From 3628fa2ceb0d49626ed61a25aeed57dffabe9ab1 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:08:32 +0000 Subject: [PATCH] feat!: failing locations impossible to miss, cursor windows per model, folder roots in the UI Upgrade the server, its schedulers, every location and every worker together: 1. Run `sqb compile` on each project with this release: it now resolves job and sensor selectors (D017), which a location only checked when publishing. 2. Upgrade the server and schedulers, then every location and worker. 3. Container health checks: use `sqb location health --allow-starting` for liveness, so a location loading its first snapshot isn't restarted. Deploy readiness checks keep the plain command and wait for exit 0. feat!: the server alone computes a location's health state, and serves it feat: a failing location shows a banner on every page, a "Location failing" item on the Overview, its state on the Locations pages, and a location_failing platform event fix: resolve job and sensor selectors at compile, as a location does when it publishes fix(cli): report starting until a restarted location's own first load finishes fix: order a location's load reports by arrival, so a later publication clears earlier failures fix: fail plans at once with the load error when a location can't load the current code fix(cli): a crashed discovered-set check discovers again, so its failure is reported fix: a location that can't get its next generation number reports a failed load fix: a full build binds cursor intrinsics to the whole cursor range instead of refusing fix: one model's planning error no longer fails the whole plan fix: clamp an explicit cursor window to each model's cursor_start fix(ui): group the catalog and overview by folders below sql/ and python/nodes/ fix(server): name cost folders as the catalog does and offer only selectable path folders fix(ui): make each Cost drill one navigation, so Back right after drilling goes up fix: compute one build status per node on the server and render it on every page fix(cli): keep publication records off sqb dev's stdout fix(deps): upgrade to SQLQuack 0.23.1 and SQLClean 0.12.1 test: fix the duckshop benchmarks for SQLClean 0.12 findings and the sql/ layout, and stale tests for the new health shape BREAKING CHANGE: location health and planning report failures they used to hide. - GET /api/control/locations/{location_id}/targets/{target}/health returns {"state": ..., "observations": [...]} instead of a bare array of observations. - `sqb location health` exits 0 only when healthy. discovery_failed, degraded and the new change_plan_failed exit 1, the new starting state exits 3 (0 with --allow-starting), and 2 still means the state couldn't be read. A location's state is ordered by when its reports arrived, not by generation number. - `sqb compile` fails with D017 on a job or sensor selector a location would refuse to publish, such as a path selector without its sql/models/ or python/nodes/ root. - `sqb plan` exits 1 when any model can't be planned; that model's row has action "error" with error {code, message, help}, and the plan has has_errors: true. Compile, validation and source errors (S4xx) still fail the whole plan. Builds still refuse a selection containing a model that can't be planned. - A non-microbatch full build no longer fails with S204 on __cursor_start()/__cursor_end(): they bind to the model's cursor_start (or the cursor type's lowest value) and the type's highest value. - An explicit --start-cursor-ts/--end-cursor-ts window is clamped to each model's cursor_start, and a model whose floor is after the window is skipped with a reason; P001 is raised only when the window leaves nothing to build across the selection. Refs CHI-1657, CHI-1659, CHI-1660, CHI-1662, CHI-1665, CHI-1666 --- Cargo.lock | 76 +++---- Cargo.toml | 26 +-- Makefile | 1 + benchmarks/duckshop-10k/README.md | 8 +- benchmarks/duckshop-10k/checksum.txt | 2 +- .../duckshop-10k/duckshop10k/__init__.py | 2 +- .../duckshop-10k/duckshop10k/manifest.py | 12 +- .../duckshop-10k/duckshop10k/workload.py | 37 ++-- .../orchestration/jobs/orders_folder_job.toml | 4 +- .../sql/models/orders/order_totals.sql | 2 +- .../project/python/nodes/loaders/_writer.py | 2 +- .../customers/int_customer_order_sequence.sql | 14 +- .../edge_cases/int_edge_amount_bit_reads.sql | 15 +- .../staging/inventory/stg_stock_movements.sql | 3 +- benchmarks/duckshop/scripts/duckdb_project.py | 2 +- clients/typescript/src/schema.d.ts | 76 ++++++- compose.yml | 5 + .../src/adhoc/_helpers/evaluation.rs | 12 +- .../adhoc/tests/test_selection_evaluation.rs | 4 +- .../sqlbuild-cli/src/argv/command_table.json | 10 + .../src/dev_screen/tests/helpers.rs | 1 - .../src/dev_session/_helpers/child.rs | 13 +- .../src/dev_session/main/run_dev_session.rs | 5 +- .../native_commands/_helpers/command/paths.rs | 3 +- .../_helpers/location/changed_build.rs | 17 ++ .../_helpers/location/compile_turn.rs | 70 +++++++ .../_helpers/location/compiler_discovery.rs | 19 +- .../_helpers/location/execution.rs | 34 ++-- .../_helpers/location/health.rs | 20 ++ .../_helpers/location/lookup_failure.rs | 53 +++++ .../native_commands/_helpers/location/mod.rs | 3 + .../src/native_commands/constants.rs | 9 + .../main/_location_changed_build.rs | 71 +++++-- .../src/native_commands/main/_run_location.rs | 39 +--- .../main/run_location_invocation.rs | 11 +- .../src/native_commands/models.rs | 28 +++ .../sqlbuild-cli/src/native_commands/tests.rs | 4 + .../src/native_commands/tests/helpers.rs | 11 ++ .../tests/test_changed_build.rs | 43 +++- .../tests/test_location_discovery.rs | 57 +++++- .../tests/test_location_health.rs | 80 ++++++++ .../tests/test_lookup_failures.rs | 77 ++++++++ .../src/native_commands/tests/test_types.rs | 33 ++++ .../sqlbuild-cli/src/native_commands/types.rs | 17 +- .../native_commands/test_location_health.rs | 16 +- .../build_command/main/plan_safety_steps.rs | 22 ++- .../sqlbuild-core/src/build_command/models.rs | 9 + .../build_command/tests/test_plan_safety.rs | 45 ++++- .../src/cli_text/_helpers/plan_sections.rs | 33 +++- .../sqlbuild-core/src/cli_text/constants.rs | 9 +- crates/sqlbuild-core/src/cli_text/models.rs | 2 + .../src/plan_display/_helpers/plan_pages.rs | 22 ++- .../sqlbuild-core/src/plan_display/models.rs | 4 + .../src/plan_display/tests/helpers.rs | 2 + .../src/plan_display/tests/test_plan_pages.rs | 30 ++- .../api/_helpers/resources/person_reads.rs | 8 +- .../src/dev_events/models.rs | 3 +- .../src/node_states/_helpers/mod.rs | 1 + .../src/node_states/_helpers/reads.rs | 93 ++++++++- .../src/node_states/_helpers/status.rs | 139 +++++++++++++ .../node_states/main/report_changed_build.rs | 7 +- .../src/node_states/models.rs | 31 ++- .../_helpers/health/current_instance.rs | 79 ++++++++ .../platform/_helpers/health/event_history.rs | 5 + .../_helpers/health/failing_locations.rs | 111 +++++++++++ .../src/platform/_helpers/health/mod.rs | 2 + .../src/platform/_helpers/health/problems.rs | 3 + .../platform/_helpers/health/recent_health.rs | 54 ++++- .../platform/_helpers/location/liveness.rs | 31 +++ .../_helpers/location/reported_generation.rs | 5 + .../_helpers/location/rule_findings.rs | 22 ++- .../platform/_helpers/maintenance/watchdog.rs | 7 +- .../platform/_helpers/plans/load_failure.rs | 86 ++++++++ .../src/platform/_helpers/plans/mod.rs | 1 + .../src/platform/constants.rs | 3 + .../main/health/load_failure_refusal.rs | 21 ++ .../src/platform/main/health/mod.rs | 1 + .../health/read_person_location_health.rs | 13 +- .../main/health/report_location_health.rs | 43 ++-- .../person_reads/read_person_plan_rows.rs | 2 + .../main/person_reads/read_person_problems.rs | 10 + .../src/platform/models.rs | 115 +++++++++-- .../src/runs/_helpers/requests/plan.rs | 5 + .../_helpers/cost_selection.rs | 31 ++- .../tests/api/test_cost_selection.rs | 24 ++- .../tests/api/test_location_health.rs | 23 ++- .../tests/api/test_node_states.rs | 72 +++++++ .../tests/api/test_person_plans.rs | 143 +++++++++++++- .../tests/api/test_person_sessions.rs | 27 ++- .../tests/api/test_types.rs | 8 + .../tests/dev_events/test_dev_events.rs | 3 +- .../tests/node_states/helpers.rs | 103 ++++++++++ .../tests/node_states/test_contracts.rs | 4 + .../tests/node_states/test_statuses.rs | 186 ++++++++++++++++++ .../tests/node_states/test_types.rs | 15 ++ .../tests/platform/helpers.rs | 117 ++++++++++- .../tests/platform/test_compile_failure.rs | 18 +- .../tests/platform/test_contracts.rs | 4 + .../tests/platform/test_failing_locations.rs | 149 ++++++++++++++ .../tests/platform/test_location_state.rs | 173 ++++++++++++++++ .../tests/platform/test_types.rs | 42 +++- .../src/native_host/_helpers/dialect.rs | 3 +- .../_helpers/compiler_enums/constants.rs | 1 + .../_helpers/planner_records/constants.rs | 3 + .../_helpers/stages/analysis.rs | 9 +- .../src/plan_output/_helpers/plan_json.rs | 26 ++- .../src/plan_output/_helpers/plan_text.rs | 67 ++++++- .../src/plan_output/main/format_plan_json.rs | 11 ++ .../planner_entries/_helpers/entries/mod.rs | 2 + .../_helpers/entries/model_entries.rs | 46 +++-- .../_helpers/entries/planning_error.rs | 127 ++++++++++++ .../_helpers/entries/window_turns.rs | 87 ++++++++ .../src/planner_entries/constants.rs | 3 + .../src/planner_entries/models.rs | 17 ++ .../src/planner_phases/constants.rs | 4 +- .../_helpers/cursor/cursor_ranges.rs | 5 +- .../_helpers/references/orchestration.rs | 64 ++++-- .../main/cursor/model_cursor_overrides.rs | 50 +++-- .../src/planner_resolution/mod.rs | 1 + .../src/planner_resolution/models.rs | 11 ++ .../src/planner_resolution/types.rs | 6 + .../src/native_host/main/mod.rs | 1 + .../src/native_host/main/sensor_selection.rs | 17 ++ .../src/project_snapshot/constants.rs | 3 + .../src/project_snapshot/main/mod.rs | 1 + .../main/orchestration_selectors.rs | 118 +++++++++++ .../_helpers/build_command/policies.rs | 14 +- deploy/README.md | 8 +- fensu.toml | 4 +- .../sqlbuild/references/docs/cli/build.md | 2 +- .../sqlbuild/references/docs/cli/dev.md | 2 - .../sqlbuild/references/docs/cli/location.md | 38 +++- .../sqlbuild/references/docs/cli/plan.md | 22 ++- .../sqlbuild/references/docs/cli/server.md | 1 + .../references/docs/concepts/incremental.md | 25 ++- .../references/docs/concepts/orchestration.md | 6 +- src/sqlbuild/_native.pyi | 7 + .../contract/classes/strict_adapter.py | 14 ++ src/sqlbuild/adapter/contract/constants.py | 5 + .../clickhouse/classes/clickhouse_adapter.py | 9 + src/sqlbuild/adapters/clickhouse/constants.py | 2 + .../adapters/sqlite/_helpers/timestamps.py | 4 +- .../executor/pipeline/_helpers/settings.py | 12 +- src/sqlbuild/executor/pipeline/main/run.py | 3 +- .../orchestration_declarations/types.py | 1 + .../cli/commands/main/build/_test_types.py | 12 ++ .../cli/commands/main/build/helpers.py | 14 ++ .../build/own_change_replay/_test_types.py | 15 ++ .../test_own_change_replay.py | 89 +++++++-- .../main/build/test_cursor_window_floors.py | 180 +++++++++++++++++ .../cli/commands/main/compile/_test_types.py | 10 + .../cli/commands/main/compile/helpers.py | 22 +++ .../test_sql_macro_relation_slots.py | 2 +- .../test_duckshop_benchmark_compile.py | 2 +- .../compile/test_orchestration_selectors.py | 98 +++++++++ .../publication/_test_types.py | 1 + .../compiled_project/publication/test_dev.py | 18 +- .../publication/test_plan_preview.py | 15 +- .../publication/test_rules_at_load.py | 4 + .../planner/main/test_build_execution_plan.py | 49 +++-- .../strict_adapter/test_strict_adapter.py | 1 + .../planner/_helpers/resolve/_test_types.py | 12 ++ .../resolve/test_cursor_intrinsics.py | 153 +++++++++++--- .../compiler/planner/main/test_execution.py | 19 +- ui/e2e/cost.spec.ts | 6 - ui/e2e/plan-browser.spec.ts | 2 +- ui/e2e/selection.spec.ts | 6 +- ui/e2e/support/fake-control.ts | 3 +- ui/src/lib/api/http-catalog.ts | 9 +- ui/src/lib/api/http-client.test.ts | 14 +- ui/src/lib/api/http-client.ts | 6 +- ui/src/lib/api/http-locations.test.ts | 48 ++--- ui/src/lib/api/http-locations.ts | 47 ++--- ui/src/lib/api/http-overview.test.ts | 20 +- ui/src/lib/api/http-overview.ts | 10 +- ui/src/lib/api/http-problems.test.ts | 9 + ui/src/lib/api/http-problems.ts | 42 ++++ ui/src/lib/api/http-runs.ts | 2 + ui/src/lib/api/mock/big-output.ts | 4 +- ui/src/lib/api/mock/build-fixtures.ts | 12 +- ui/src/lib/api/mock/build.ts | 22 ++- ui/src/lib/api/mock/cost-project.ts | 13 +- ui/src/lib/api/mock/cost-rows.ts | 6 +- ui/src/lib/api/mock/discovered.ts | 2 +- ui/src/lib/api/mock/huge-project.ts | 2 +- ui/src/lib/api/mock/large-project.ts | 4 +- ui/src/lib/api/mock/operate-graph.ts | 40 ++-- ui/src/lib/api/mock/operate.ts | 16 +- ui/src/lib/api/mock/run-detail.ts | 12 +- ui/src/lib/api/node-states.test.ts | 6 +- ui/src/lib/api/node-states.ts | 9 +- ui/src/lib/api/types.ts | 3 +- ui/src/lib/api/types/build.ts | 13 +- ui/src/lib/api/types/operate.ts | 12 +- ui/src/lib/build-area/attention-conditions.ts | 1 + ui/src/lib/build-area/folder-tree.test.ts | 43 ++-- ui/src/lib/build-area/folder-tree.ts | 39 ++-- ui/src/lib/build-area/node-status.test.ts | 94 +++++++++ ui/src/lib/build-area/node-status.ts | 30 +++ ui/src/lib/build-area/status-fixtures.ts | 23 +++ .../components/build-area/folder-tree.svelte | 12 +- ui/src/lib/lineage/catalog-graph.test.ts | 22 ++- ui/src/lib/lineage/catalog-graph.ts | 53 +++-- ui/src/lib/lineage/folder-graph.test.ts | 21 +- ui/src/lib/lineage/folder-selection.test.ts | 20 +- ui/src/lib/lineage/member-graph.test.ts | 3 +- ui/src/lib/lineage/view-summary.test.ts | 14 +- ui/src/lib/lineage/view-summary.ts | 8 +- ui/src/lib/lineage/visible-edges.test.ts | 14 +- ui/src/lib/platform/labels.ts | 13 +- ui/src/lib/project-layout.test.ts | 37 ++++ ui/src/lib/project-layout.ts | 47 +++++ ui/src/lib/run/command.test.ts | 12 +- ui/src/lib/run/command.ts | 10 +- ui/src/lib/run/plan-browser.svelte | 2 +- ui/src/lib/run/plan-index.test.ts | 37 ++++ ui/src/lib/run/plan-index.ts | 8 +- ui/src/lib/run/plan-text.ts | 5 +- ui/src/lib/run/plan-totals.ts | 8 +- ui/src/lib/selection/folders.test.ts | 18 +- ui/src/lib/selection/folders.ts | 7 +- ui/src/lib/state/catalog-feed.test.ts | 6 +- ui/src/lib/state/selection.svelte.ts | 19 +- ui/src/routes/catalog/+page.svelte | 22 ++- ui/src/routes/catalog/[name]/node-view.svelte | 11 +- .../routes/catalog/[name]/overview-tab.svelte | 3 +- ui/src/routes/cost/cost-view.svelte | 10 +- ui/src/routes/cost/utils/selector.test.ts | 3 +- ui/src/routes/cost/utils/selector.ts | 9 +- ui/src/routes/lineage/+page.svelte | 13 +- website/src/content/docs/docs/cli/build.mdx | 2 +- website/src/content/docs/docs/cli/dev.mdx | 2 - .../src/content/docs/docs/cli/location.mdx | 38 +++- website/src/content/docs/docs/cli/plan.mdx | 21 +- website/src/content/docs/docs/cli/server.mdx | 1 + .../docs/docs/concepts/incremental.mdx | 25 ++- .../docs/docs/concepts/orchestration.mdx | 6 +- 237 files changed, 5172 insertions(+), 866 deletions(-) create mode 100644 crates/sqlbuild-cli/src/native_commands/_helpers/location/compile_turn.rs create mode 100644 crates/sqlbuild-cli/src/native_commands/_helpers/location/health.rs create mode 100644 crates/sqlbuild-cli/src/native_commands/_helpers/location/lookup_failure.rs create mode 100644 crates/sqlbuild-cli/src/native_commands/tests/test_location_health.rs create mode 100644 crates/sqlbuild-cli/src/native_commands/tests/test_lookup_failures.rs create mode 100644 crates/sqlbuild-orchestration/src/node_states/_helpers/status.rs create mode 100644 crates/sqlbuild-orchestration/src/platform/_helpers/health/current_instance.rs create mode 100644 crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_locations.rs create mode 100644 crates/sqlbuild-orchestration/src/platform/_helpers/plans/load_failure.rs create mode 100644 crates/sqlbuild-orchestration/src/platform/main/health/load_failure_refusal.rs create mode 100644 crates/sqlbuild-orchestration/tests/node_states/helpers.rs create mode 100644 crates/sqlbuild-orchestration/tests/node_states/test_statuses.rs create mode 100644 crates/sqlbuild-orchestration/tests/platform/test_failing_locations.rs create mode 100644 crates/sqlbuild-orchestration/tests/platform/test_location_state.rs create mode 100644 crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/planning_error.rs create mode 100644 crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/window_turns.rs create mode 100644 crates/sqlbuild-python-planner/src/planner_resolution/types.rs create mode 100644 crates/sqlbuild-python-project/src/native_host/main/sensor_selection.rs create mode 100644 crates/sqlbuild-python-project/src/project_snapshot/main/orchestration_selectors.rs create mode 100644 tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_window_floors.py create mode 100644 tests/e2e/src/sqlbuild/cli/commands/main/compile/test_orchestration_selectors.py create mode 100644 ui/src/lib/build-area/node-status.test.ts create mode 100644 ui/src/lib/build-area/node-status.ts create mode 100644 ui/src/lib/build-area/status-fixtures.ts create mode 100644 ui/src/lib/project-layout.test.ts create mode 100644 ui/src/lib/project-layout.ts diff --git a/Cargo.lock b/Cargo.lock index 725ea314e0..770efd4846 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4875,8 +4875,8 @@ dependencies = [ [[package]] name = "sqlclean" -version = "0.12.0" -source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=8550e6a45c95a4a9e8470a570ae786d6f0deee8e#8550e6a45c95a4a9e8470a570ae786d6f0deee8e" +version = "0.12.1" +source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=462a98779a2a11ff11884ff79feefbfb190ab8d1#462a98779a2a11ff11884ff79feefbfb190ab8d1" dependencies = [ "rayon", "rustc-hash", @@ -4894,8 +4894,8 @@ dependencies = [ [[package]] name = "sqlclean-lint" -version = "0.12.0" -source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=8550e6a45c95a4a9e8470a570ae786d6f0deee8e#8550e6a45c95a4a9e8470a570ae786d6f0deee8e" +version = "0.12.1" +source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=462a98779a2a11ff11884ff79feefbfb190ab8d1#462a98779a2a11ff11884ff79feefbfb190ab8d1" dependencies = [ "rayon", "serde", @@ -4909,16 +4909,16 @@ dependencies = [ [[package]] name = "sqlclean-rules" -version = "0.12.0" -source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=8550e6a45c95a4a9e8470a570ae786d6f0deee8e#8550e6a45c95a4a9e8470a570ae786d6f0deee8e" +version = "0.12.1" +source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=462a98779a2a11ff11884ff79feefbfb190ab8d1#462a98779a2a11ff11884ff79feefbfb190ab8d1" dependencies = [ "sqlquack-syntax", ] [[package]] name = "sqlquack-derive" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "proc-macro2", "quote", @@ -4927,8 +4927,8 @@ dependencies = [ [[package]] name = "sqlquack-diagnostics" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "serde", "serde_json", @@ -4937,8 +4937,8 @@ dependencies = [ [[package]] name = "sqlquack-fingerprint" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sha2 0.10.9", "sqlquack-parse", @@ -4948,8 +4948,8 @@ dependencies = [ [[package]] name = "sqlquack-format" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "serde_json", "sqlquack-parse", @@ -4959,8 +4959,8 @@ dependencies = [ [[package]] name = "sqlquack-parse" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sqlquack-syntax", "sqlquack-syntax-bigquery", @@ -4972,8 +4972,8 @@ dependencies = [ [[package]] name = "sqlquack-semantics" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "regex", "rustc-hash", @@ -4988,8 +4988,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "serde", "serde_json", @@ -5001,8 +5001,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-bigquery" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sqlquack-syntax", "stacker", @@ -5010,8 +5010,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-clickhouse" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sqlquack-syntax", "stacker", @@ -5019,8 +5019,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-databricks" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sqlquack-syntax", "stacker", @@ -5028,8 +5028,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-duckdb" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sqlquack-syntax", "stacker", @@ -5037,8 +5037,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-postgres" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sqlquack-syntax", "stacker", @@ -5046,8 +5046,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-snowflake" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "serde", "serde_json", @@ -5060,8 +5060,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-sqlite" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sqlquack-syntax", "stacker", @@ -5069,8 +5069,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-sqlserver" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sqlquack-syntax", "sqlquack-tokenize", @@ -5079,8 +5079,8 @@ dependencies = [ [[package]] name = "sqlquack-tokenize" -version = "0.23.0" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=7a8501afa69eb846637e4eb85604d6726fc33174#7a8501afa69eb846637e4eb85604d6726fc33174" +version = "0.23.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sqlquack-syntax", "thiserror 1.0.69", diff --git a/Cargo.toml b/Cargo.toml index 121faef3b1..88ff8e5e70 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -213,24 +213,24 @@ sqlbuild-scopes = { path = "crates/sqlbuild-scopes" } sqlbuild-sqltext = { path = "crates/sqlbuild-sqltext" } sqlbuild-state = { path = "crates/sqlbuild-state" } # SQL lint Rules, quality Rules and the formatter. -sqlclean = { git = "https://github.com/sqlstack-io/sqlclean.git", rev = "8550e6a45c95a4a9e8470a570ae786d6f0deee8e" } +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 = "7a8501afa69eb846637e4eb85604d6726fc33174", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } +sqlquack-fingerprint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d", 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 = "7a8501afa69eb846637e4eb85604d6726fc33174", features = ["bigquery", "clickhouse", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } +sqlquack-semantics = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d", 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 = "7a8501afa69eb846637e4eb85604d6726fc33174" } +sqlquack-parse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } # SQLQuack's syntax tree and lossless tokens. -sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } # SQLQuack's tokenizer: lossless tokens and tokenize failures. -sqlquack-tokenize = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } -sqlquack-syntax-bigquery = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } -sqlquack-syntax-clickhouse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } -sqlquack-syntax-databricks = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } -sqlquack-syntax-duckdb = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } -sqlquack-syntax-postgres = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } -sqlquack-syntax-sqlite = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } -sqlquack-syntax-sqlserver = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "7a8501afa69eb846637e4eb85604d6726fc33174" } +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" } 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 6ced0ebdb9..df6e08f39f 100644 --- a/Makefile +++ b/Makefile @@ -184,6 +184,7 @@ E2E_DUCKDB_BUILD_INCREMENTAL_PATHS := \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_capped_microbatch_build.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_changed_builds.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_concurrent_microbatch_build.py \ + tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_window_floors.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_observations.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_runtime_failures.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_dropped_relation_rebuild.py \ diff --git a/benchmarks/duckshop-10k/README.md b/benchmarks/duckshop-10k/README.md index a16c6ff1ce..7592b76550 100644 --- a/benchmarks/duckshop-10k/README.md +++ b/benchmarks/duckshop-10k/README.md @@ -26,7 +26,9 @@ iteration. `checksum.txt` records the full profile only. The generator uses no randomness, clocks or environment: the same generator version always writes byte-identical files. `checksum.txt` holds the generator version, the file count and the SHA-256 of -`MANIFEST.sha256`, a sorted list of the SHA-256 of every generated file. +`MANIFEST.sha256`, a sorted list of the SHA-256 of every generated file. The generator writes it to +`target/MANIFEST.sha256` in the generated project, beside SQLBuild's local build output, so the +project root holds only project files. When a change alters any generated file, bump `GENERATOR_VERSION` in `duckshop10k/__init__.py` and run `python benchmarks/duckshop-10k/generate.py --update-checksum`. @@ -38,7 +40,7 @@ run `python benchmarks/duckshop-10k/generate.py --update-checksum`. | Models | 10,840 | | Staging, intermediate, marts and snapshots | 6,149 (56.7%), 2,519 (23.2%), 2,162 (19.9%), 10 | | Incremental models | 583, 112 of them with a capped automatic start and 112 renamed | -| Python export assets | 433 in 241 modules sharing one helper module | +| Python export assets | 433, each in its own `asset.py`, sharing one helper module | | Sources | 2,466 table sources and one expression source | | Unit tests and scenarios | 288 and 2 | | Dependency depth | 11 at most; 170 models at depth 7 or more | @@ -57,7 +59,7 @@ A large project also carries planning workload the layers above barely touch, so it in the proportions such projects have: an incrementally kept history of every third timestamped intermediate table, one in five of them capping how far ahead its automatic start may sit and one in five renamed from an older name with `migrate_from`, and a Python export asset for every fifth -published mart, a few per module, all sharing one helper module. A live plan reads a cursor bound for +published mart, each in its own `asset.py`, all sharing one helper module. A live plan reads a cursor bound for each incremental model, plans each rename and discovers each Python node. The models that use `HASH`, `TIMESTAMP_LTZ` or `CURRENT_TIMESTAMP()` are tagged `known_divergence`, diff --git a/benchmarks/duckshop-10k/checksum.txt b/benchmarks/duckshop-10k/checksum.txt index 12393fd21a..bb8e9b439f 100644 --- a/benchmarks/duckshop-10k/checksum.txt +++ b/benchmarks/duckshop-10k/checksum.txt @@ -1 +1 @@ -generator 4 files 11674 sha256 c3a3d8f62a23c4ae770c70ceb5437d849bb32211edb12b6017af25a76fb8d7e2 +generator 5 files 11866 sha256 d0b3847b68e1aac09af58422d804badc23d8a880607bb8e2bce2efb11ba1ae6c diff --git a/benchmarks/duckshop-10k/duckshop10k/__init__.py b/benchmarks/duckshop-10k/duckshop10k/__init__.py index 6b01c6c3dd..fd08beaad7 100644 --- a/benchmarks/duckshop-10k/duckshop10k/__init__.py +++ b/benchmarks/duckshop-10k/duckshop10k/__init__.py @@ -4,6 +4,6 @@ regenerate checksum.txt, whenever a change alters any generated file. """ -GENERATOR_VERSION = "4" +GENERATOR_VERSION = "5" SEED = 20261024 PROJECT_NAME = "duckshop_10k" diff --git a/benchmarks/duckshop-10k/duckshop10k/manifest.py b/benchmarks/duckshop-10k/duckshop10k/manifest.py index f2b3bf8809..bcafe5e5f2 100644 --- a/benchmarks/duckshop-10k/duckshop10k/manifest.py +++ b/benchmarks/duckshop-10k/duckshop10k/manifest.py @@ -7,7 +7,8 @@ from duckshop10k import GENERATOR_VERSION -MANIFEST_NAME = "MANIFEST.sha256" +# Under the project's local build output, so the project root holds only SQLBuild project files. +MANIFEST_PATH = "target/MANIFEST.sha256" def manifest(files: dict[str, str]) -> str: @@ -36,16 +37,17 @@ def write_project(files: dict[str, str], out: Path) -> None: target = out / path target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(content.encode("utf-8")) - (out / MANIFEST_NAME).write_bytes(manifest(files).encode("utf-8")) + manifest_file = out / MANIFEST_PATH + manifest_file.parent.mkdir(parents=True, exist_ok=True) + manifest_file.write_bytes(manifest(files).encode("utf-8")) def read_project(out: Path) -> dict[str, str]: - """Every generated file below `out`, skipping the manifest and local build output.""" - skipped = {MANIFEST_NAME} + """Every generated file below `out`, skipping local build output, which holds the manifest.""" local = ("target/", "logs/", ".sqlbuild/", "sqlbuild_local.toml") files: dict[str, str] = {} for path in sorted(out.rglob("*")): relative = path.relative_to(out).as_posix() - if path.is_file() and relative not in skipped and not relative.startswith(local): + if path.is_file() and not relative.startswith(local): files[relative] = path.read_bytes().decode("utf-8") return files diff --git a/benchmarks/duckshop-10k/duckshop10k/workload.py b/benchmarks/duckshop-10k/duckshop10k/workload.py index 7358522c3f..96700b15c4 100644 --- a/benchmarks/duckshop-10k/duckshop10k/workload.py +++ b/benchmarks/duckshop-10k/duckshop10k/workload.py @@ -4,7 +4,7 @@ migration for every renamed model and discovers every Python node. The layers above build few of each, so this module adds them in proportions such projects have: about one model in twenty kept incrementally, a hundred of those renamed from an older name, and a few hundred -Python exports of published marts, spread over many modules that share helper code. +Python exports of published marts, each in its own `asset.py`, sharing helper code. """ from __future__ import annotations @@ -19,8 +19,6 @@ RENAMED_EVERY = 5 #: Every this-many published mart gets a Python export asset. EXPORT_STRIDE = 5 -#: Export assets per Python module, so discovery walks many modules. -EXPORTS_PER_MODULE = 6 _TIMESTAMP = "TIMESTAMP_NTZ" _INCREMENT_FOLDER = "sql/models/intermediate/increments" _EXPORT_PACKAGE = "python/nodes/exports" @@ -130,24 +128,23 @@ def _exports(project: Project) -> None: by_folder.setdefault(model.folder.rsplit("/", 1)[-1], []).append(model) project.write(_SHARED_MODULE, SHARED_EXPORT_HELPERS) for folder, models in sorted(by_folder.items()): - for start in range(0, len(models), EXPORTS_PER_MODULE): - chunk: list[Model] = models[start : start + EXPORTS_PER_MODULE] - module: str = f"{folder}_{start // EXPORTS_PER_MODULE + 1:02d}" - project.write(f"{_EXPORT_PACKAGE}/{module}.py", _export_module(folder, chunk)) - - -def _export_module(folder: str, models: list[Model]) -> str: - assets: list[str] = [ - f'@asset(depends_on=model("{model.name}"))\n' - f"def export_{model.name}(ctx: AssetContext):\n" - f' """Send {model.name} to the {folder} partner feed."""\n' - f' metadata = feed_metadata(ctx, model("{model.name}"), "{folder}")\n' - " return ctx.result(metadata=metadata, materialized=True)\n" - for model in models - ] + for mart in models: + project.write( + f"{_EXPORT_PACKAGE}/{folder}/export_{mart.name}/asset.py", + _export_module(folder, mart), + ) + + +def _export_module(folder: str, mart: Model) -> str: + """One export asset in its own `asset.py`, as the project layout requires.""" return ( - f'"""Exports of the {folder} marts to partner feeds."""\n\n' + f'"""Export of {mart.name} to the {folder} partner feed."""\n\n' "from sqlbuild.assets import AssetContext, asset\n" "from sqlbuild.refs import model\n\n" - "from python.nodes.shared.export_feed import feed_metadata\n\n\n" + "\n\n".join(assets) + "from python.nodes.shared.export_feed import feed_metadata\n\n\n" + f'@asset(depends_on=model("{mart.name}"))\n' + f"def export_{mart.name}(ctx: AssetContext):\n" + f' """Send {mart.name} to the {folder} partner feed."""\n' + f' metadata = feed_metadata(ctx, model("{mart.name}"), "{folder}")\n' + " return ctx.result(metadata=metadata, materialized=True)\n" ) diff --git a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/jobs/orders_folder_job.toml b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/jobs/orders_folder_job.toml index 9d818a8deb..4dbb961442 100644 --- a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/jobs/orders_folder_job.toml +++ b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/jobs/orders_folder_job.toml @@ -1,4 +1,4 @@ -# A folder, an expansion, a glob, an intersection's name, a job name and a repeated name: one named node. +# A folder, an expansion, a glob, an intersection's name and a repeated name: one named node. name = "orders_folder_job" description = "Selects the orders pipeline without listing it." -select = "sql/models/orders +order_totals stg_* order_totals,tag:orders orders_listed_job order_totals" +select = "sql/models/orders +order_totals stg_* order_totals,tag:orders order_totals" diff --git a/benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/order_totals.sql b/benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/order_totals.sql index 95527d44d9..736a17057f 100644 --- a/benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/order_totals.sql +++ b/benchmarks/duckshop/edge_cases/named_selectors/sql/models/orders/order_totals.sql @@ -1,2 +1,2 @@ -MODEL (description "Synthetic orders edge case order_totals"); +MODEL (description "Synthetic orders edge case order_totals", tags [orders]); SELECT 1 AS order_id diff --git a/benchmarks/duckshop/project/python/nodes/loaders/_writer.py b/benchmarks/duckshop/project/python/nodes/loaders/_writer.py index b1b8872f65..a20ecfef4e 100644 --- a/benchmarks/duckshop/project/python/nodes/loaders/_writer.py +++ b/benchmarks/duckshop/project/python/nodes/loaders/_writer.py @@ -17,7 +17,7 @@ import yaml -SOURCES_DIR = Path(__file__).resolve().parents[2] / "sql" / "sources" +SOURCES_DIR = Path(__file__).resolve().parents[3] / "sql" / "sources" BATCH_SIZE = 500 JSON_TYPES = {"VARIANT": "", "OBJECT": "::OBJECT", "ARRAY": "::ARRAY"} diff --git a/benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_order_sequence.sql b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_order_sequence.sql index b6344f11bd..dd49a5bd56 100644 --- a/benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_order_sequence.sql +++ b/benchmarks/duckshop/project/sql/models/intermediate/customers/int_customer_order_sequence.sql @@ -27,13 +27,13 @@ WITH orders AS ( valid_orders AS ( SELECT - o.order_id, - o.customer_id, - o.placed_at, - o.placed_date_local, - o.amount_usd, - o.sales_channel - FROM orders AS o + order_id, + customer_id, + placed_at, + placed_date_local, + amount_usd, + sales_channel + FROM orders WHERE NOT @sql.is_status(@enum("order_status").CANCELLED) ), diff --git a/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_bit_reads.sql b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_bit_reads.sql index 3afd7d3382..9d0fe00156 100644 --- a/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_bit_reads.sql +++ b/benchmarks/duckshop/project/sql/models/intermediate/edge_cases/int_edge_amount_bit_reads.sql @@ -107,14 +107,13 @@ final AS ( (f.group_hash = b.group_hash)::BOOLEAN AS group_hash_is_order_free FROM checks AS c INNER JOIN group_sizes AS s - ON c.group_code = s.group_code, - group_names AS n, - hash_forward AS f, - hash_backward AS b - WHERE - n.group_code = c.group_code - AND f.group_code = c.group_code - AND b.group_code = c.group_code + ON c.group_code = s.group_code + INNER JOIN group_names AS n + ON c.group_code = n.group_code + INNER JOIN hash_forward AS f + ON c.group_code = f.group_code + INNER JOIN hash_backward AS b + ON c.group_code = b.group_code ) SELECT * diff --git a/benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_movements.sql b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_movements.sql index c279ea73b1..91e80d369f 100644 --- a/benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_movements.sql +++ b/benchmarks/duckshop/project/sql/models/staging/inventory/stg_stock_movements.sql @@ -57,8 +57,7 @@ final AS ( d.moved_at_local, @sql.json_text(d.metadata:operator) AS operator_id FROM deduplicated AS d - INNER JOIN effective_ids AS e - ON d.movement_id = e.movement_id + WHERE d.movement_id IN (SELECT e.movement_id FROM effective_ids AS e) ) SELECT * diff --git a/benchmarks/duckshop/scripts/duckdb_project.py b/benchmarks/duckshop/scripts/duckdb_project.py index dae5a579e9..34aafa41a7 100644 --- a/benchmarks/duckshop/scripts/duckdb_project.py +++ b/benchmarks/duckshop/scripts/duckdb_project.py @@ -215,7 +215,7 @@ def write_declarations(out: pathlib.Path) -> None: folders.pop() / "_sqlbuild" / "_enums" if len(folders) == 1 else out / "sql" / "enums" ) keep[folder / f"{name}.sql"] = types(enums[name].read_text()) - for gone in ("tests", "macros", "rules", "constants", "enums"): + for gone in ("tests", "rules", "sql/macros", "sql/constants", "sql/enums"): shutil.rmtree(out / gone, ignore_errors=True) for folder in ("_macros", "macros", "constants", "_constants", "enums", "_enums"): for path in list(out.glob(f"sql/models/**/_sqlbuild/{folder}")): diff --git a/clients/typescript/src/schema.d.ts b/clients/typescript/src/schema.d.ts index b6dd0d98ce..9ddea767e3 100644 --- a/clients/typescript/src/schema.d.ts +++ b/clients/typescript/src/schema.d.ts @@ -2076,7 +2076,7 @@ export interface components { changed: string[]; /** @description Nodes that run only because an upstream they read runs. */ downstream: string[]; - /** @description Why the location's plan failed, with both lists empty; absent when it planned. */ + /** @description Why the location's plan failed or which models it couldn't plan, with the nodes it did plan; absent when every model planned. */ failing?: string | null; /** * Format: int64 @@ -2093,7 +2093,7 @@ export interface components { ChangedBuildReport: { changed: string[]; downstream: string[]; - /** @description Why the plan failed, sent with empty lists. */ + /** @description Why the plan failed (empty lists) or which models it couldn't plan (the lists of the rest). */ failing?: string | null; /** Format: int64 */ generation: number; @@ -2491,6 +2491,23 @@ export interface components { /** Format: uuid */ session_id: 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. */ + error?: string | null; + /** + * Format: date-time + * @description When the failure was reported. + */ + failed_at: string; + /** Format: uuid */ + location_id: string; + location_name: string; + serving?: null | components["schemas"]["SnapshotRecord"]; + /** @description `falling_back`, `change_plan_failed`, `discovery_failed` or `degraded`. */ + state: components["schemas"]["LocationState"]; + target: string; + }; /** @description Build evidence only: no SQL, arbitrary metadata, or inference about live relation existence. */ FingerprintObservation: { definition_hash: string; @@ -2663,6 +2680,8 @@ export interface components { /** @enum {string} */ kind: "heartbeat"; } | { + /** @description Why the load failed, redacted and bounded; absent from older locations. */ + error?: string | null; /** Format: int64 */ generation: number; /** @enum {string} */ @@ -2698,6 +2717,12 @@ export interface components { /** @enum {string} */ kind: "discovery"; sets: components["schemas"]["DiscoveryHealth"][]; + } | { + /** Format: int64 */ + generation: number; + /** @enum {string} */ + kind: "change_plan_failed"; + reason: string; } | { /** Format: int64 */ generation: number; @@ -2765,6 +2790,11 @@ export interface components { message: string; path?: string | null; }; + /** + * @description One target's state from its newest health observations, as the web UI shows it. + * @enum {string} + */ + LocationState: "starting" | "healthy" | "degraded" | "falling_back" | "change_plan_failed" | "missing_secrets" | "discovery_failed" | "broken"; /** @description Only named location operations cross this boundary, never arbitrary SQL or Python. */ LocationWork: { /** @enum {string} */ @@ -3018,6 +3048,11 @@ export interface components { name: string; role: components["schemas"]["BuiltinRole"]; }; + /** + * @description Where a node stands: built and current, or why not. + * @enum {string} + */ + NodeBuildStatus: "current" | "changed" | "behind" | "failed" | "not_built" | "source"; /** @description One build's estimated query cost of one node, across every warehouse it used. */ NodeCostRecord: { /** Format: double */ @@ -3096,12 +3131,19 @@ export interface components { /** Format: uuid */ snapshot_id: string; }; - /** @description The state fields of a `CatalogNodeRecord`, with the same meaning. */ + /** @description The state fields of a `CatalogNodeRecord`, with the same meaning, and the status every page shows. */ NodeState: { checks: components["schemas"]["CatalogNodeChecks"]; definition_changed: boolean; last_build?: null | components["schemas"]["CatalogNodeBuild"]; last_outcome?: null | components["schemas"]["CatalogNodeOutcome"]; + /** @description The node's one build status, which pages show as it is. */ + status?: components["schemas"]["NodeBuildStatus"]; + /** + * Format: date-time + * @description When the status was reached: the last build, or the last run for a node without a table. + */ + status_at?: string | null; }; /** @description Every current node's state at one version; `snapshot_id` is null before the first publication. */ NodeStatesRecord: { @@ -3345,6 +3387,12 @@ export interface components { /** Format: uuid */ principal_id: string; }; + /** @description A target's health as people read it: its state, computed only here, and the newest observations it was computed from. */ + PersonLocationHealth: { + /** @description Newest first, with this server's pool-cap warning on the current snapshot. */ + observations: components["schemas"]["LocationHealthObservation"][]; + state: components["schemas"]["LocationState"]; + }; /** @description A stored platform event a person may see; the location target is absent for server-wide events. */ PersonPlatformEvent: { event: components["schemas"]["PlatformEvent"]; @@ -3606,6 +3654,18 @@ export interface components { /** Format: uuid */ location_id: string; target: string; + } | { + error?: string | null; + /** Format: date-time */ + failed_at: string; + /** @enum {string} */ + kind: "location_failing"; + /** Format: uuid */ + location_id: string; + /** Format: int64 */ + serving_generation?: number | null; + state: components["schemas"]["LocationState"]; + target: string; } | { /** Format: uuid */ claim_id: string; @@ -3656,12 +3716,14 @@ export interface components { trigger_id: string; }; /** @enum {string} */ - PlatformEventKind: "heartbeat" | "scheduler_no_leader" | "tick_overdue" | "calendar_horizon_low" | "location_broken" | "launch_failed" | "run_failed" | "trigger_skipped" | "sensor_rechecked" | "calendar_times_dropped"; + PlatformEventKind: "heartbeat" | "scheduler_no_leader" | "tick_overdue" | "calendar_horizon_low" | "location_broken" | "location_failing" | "launch_failed" | "run_failed" | "trigger_skipped" | "sensor_rechecked" | "calendar_times_dropped"; /** @description Problems derived from live state when read; nothing here is stored. */ PlatformProblems: { 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 Checking-in locations whose latest load, plan of what changed, discovery or connection check failed. */ + failing_locations?: components["schemas"]["FailingLocation"][]; /** @description Running calendar schedules whose dates run out within a day. */ low_calendars?: components["schemas"]["LowCalendar"][]; overdue_ticks: components["schemas"]["OverdueTick"][]; @@ -7122,13 +7184,13 @@ export interface operations { }; requestBody?: never; responses: { - /** @description This target's newest health observations and instance check-ins */ + /** @description This target's state and the newest health observations and instance check-ins it was computed from */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["LocationHealthObservation"][]; + "application/json": components["schemas"]["PersonLocationHealth"]; }; }; /** @description Session rejected */ @@ -7716,7 +7778,7 @@ export interface operations { parameters: { query: { /** @description The section to page */ - section: "full_refresh" | "query_changed" | "function_changed" | "config_changed" | "schema_changed" | "first_run" | "renamed" | "routine_models" | "migrations" | "column_migrations" | "table_type_conversions" | "retention" | "loader_reloads" | "loader_loads" | "source_reloads" | "source_loads" | "changed_functions" | "functions" | "first_run_seeds" | "changed_seeds" | "unchanged_seeds" | "python_nodes" | "held_back" | "unchanged" | "warnings"; + section: "planning_error" | "window_before_cursor_start" | "full_refresh" | "query_changed" | "function_changed" | "config_changed" | "schema_changed" | "first_run" | "renamed" | "routine_models" | "migrations" | "column_migrations" | "table_type_conversions" | "retention" | "loader_reloads" | "loader_loads" | "source_reloads" | "source_loads" | "changed_functions" | "functions" | "first_run_seeds" | "changed_seeds" | "unchanged_seeds" | "python_nodes" | "held_back" | "unchanged" | "warnings"; /** @description Rows to skip; 0 by default */ offset?: number; /** @description At most this many rows, capped at 1000 */ diff --git a/compose.yml b/compose.yml index d26d57fba1..93b35f1bf3 100644 --- a/compose.yml +++ b/compose.yml @@ -61,6 +61,11 @@ services: SQLBUILD_VERSION: ${SQLBUILD_VERSION:-} SQLBUILD_GIT_REVISION: ${SQLBUILD_GIT_REVISION:?Set SQLBUILD_GIT_REVISION} command: [location, serve, --server, "http://server:8000", --location-id, "${SQLBUILD_LOCATION_ID:?Set SQLBUILD_LOCATION_ID}", --target, development] + # Alive while starting: whether the new code loaded is the deploy's cutover check, not the container's. + healthcheck: + test: [CMD, sqb, location, health, --allow-starting, --server, "http://server:8000", --location-id, "${SQLBUILD_LOCATION_ID:?Set SQLBUILD_LOCATION_ID}", --target, development] + interval: 30s + start_period: 60s environment: SQLBUILD_LOCATION_TOKEN: ${SQLBUILD_LOCATION_TOKEN:-} volumes: diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs index 996646e74e..68d042c9a2 100644 --- a/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs @@ -4,6 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use sqlbuild_analysis::graph::main::parse_selector::parse_selector; use sqlbuild_analysis::graph::models::ParsedSelector; +use sqlbuild_core::constants::{MODELS_PATH, PYTHON_NODE_ROOT}; use sqlbuild_core::text::main::close_matches::close_matches; use sqlbuild_orchestration::runs::models::{ SelectionField, SelectionLocation, SelectionProblem, SelectionRefusal, SelectionVocabulary, @@ -276,7 +277,7 @@ fn kind_of(key: &str) -> &str { key.split_once(':').map_or("", |(kind, _)| kind) } -/// `models/staging/orders` and every folder above it. +/// `sql/models/staging/orders` and each folder above it that a `path:` selector accepts. fn folders(folder: &str) -> Vec { if folder.is_empty() || folder == PROJECT_FOLDER { return Vec::new(); @@ -284,9 +285,18 @@ fn folders(folder: &str) -> Vec { let parts: Vec<&str> = folder.split('/').collect(); (1..=parts.len()) .map(|depth| parts[..depth].join("/")) + .filter(|path| is_path_root_folder(path)) .collect() } +/// Whether a folder is `sql/models` or `python/nodes` or below one, never `sql` or `python` (S012). +fn is_path_root_folder(path: &str) -> bool { + [MODELS_PATH, PYTHON_NODE_ROOT].contains(&path) + || [MODELS_PATH, PYTHON_NODE_ROOT] + .iter() + .any(|root| path.starts_with(&format!("{root}/"))) +} + fn entries(counts: BTreeMap) -> Vec { counts .into_iter() 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 4881f3b611..2d0661bbcd 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs @@ -112,17 +112,15 @@ fn given_a_publication_when_its_vocabulary_is_read_then_each_value_counts_the_no expected_entries: &[("orders", 4)], }, VocabularyTestCase { - description: "a folder counts the nodes below it at any depth", + description: "a folder a path selector accepts counts the nodes below it at any depth", entries_of: |vocabulary| &vocabulary.paths, expected_entries: &[ - ("python", 4), ("python/nodes", 4), ("python/nodes/fulfillment", 1), ("python/nodes/fulfillment/carrier_sync", 1), ("python/nodes/loaders", 2), ("python/nodes/orders", 1), ("python/nodes/orders/partner_export", 1), - ("sql", 4), ("sql/models", 4), ("sql/models/marts", 3), ("sql/models/staging", 1), diff --git a/crates/sqlbuild-cli/src/argv/command_table.json b/crates/sqlbuild-cli/src/argv/command_table.json index 6c08e7760f..4ec154ae0a 100644 --- a/crates/sqlbuild-cli/src/argv/command_table.json +++ b/crates/sqlbuild-cli/src/argv/command_table.json @@ -252,6 +252,16 @@ "help": "for republish, why, as the audit log and the location record it", "group": 1 }, + { + "kind": "store_true", + "options": ["--allow-starting"], + "dest": "location_allow_starting", + "nargs": 0, + "const": true, + "default": false, + "help": "for health, exit 0 while the newest instance is starting, for container health checks", + "group": 1 + }, { "kind": "store_true", "options": ["--wait"], diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs b/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs index e4a1c23884..4596d72dbf 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs @@ -98,7 +98,6 @@ pub(super) fn connecting() -> Vec { ScreenMessage::Child(DevEvent::Published { generation: 1, snapshot_id: "b429729b5c1e".to_owned(), - record: serde_json::Value::Null, }), ScreenMessage::Triggers("41 paused".to_owned()), ScreenMessage::Started { diff --git a/crates/sqlbuild-cli/src/dev_session/_helpers/child.rs b/crates/sqlbuild-cli/src/dev_session/_helpers/child.rs index 96b33ce753..74cca2a95c 100644 --- a/crates/sqlbuild-cli/src/dev_session/_helpers/child.rs +++ b/crates/sqlbuild-cli/src/dev_session/_helpers/child.rs @@ -1,6 +1,4 @@ -//! The location child's pipes: its log lines, its publication records and the control lines sent to it. - -use std::io::{IsTerminal, Write}; +//! The location child's pipes: its log lines and the control lines sent to it. use sqlbuild_orchestration::dev_events::main::dev_control_line::dev_control_line; use sqlbuild_orchestration::dev_events::models::DevControl; @@ -22,15 +20,6 @@ pub(crate) async fn relay_logs( } } -/// Redirected stdout keeps one publication record per line, as `sqb location serve` prints them. -pub(crate) fn publish_record(record: &serde_json::Value) { - if std::io::stdout().is_terminal() { - return; - } - let mut stdout = std::io::stdout().lock(); - drop(writeln!(stdout, "{record}").and_then(|()| stdout.flush())); -} - /// Send one control line to the location child. pub(crate) async fn send_control( stdin: &mut ChildStdin, diff --git a/crates/sqlbuild-cli/src/dev_session/main/run_dev_session.rs b/crates/sqlbuild-cli/src/dev_session/main/run_dev_session.rs index 7abcb3e7d6..6afe6757e4 100644 --- a/crates/sqlbuild-cli/src/dev_session/main/run_dev_session.rs +++ b/crates/sqlbuild-cli/src/dev_session/main/run_dev_session.rs @@ -15,7 +15,7 @@ use uuid::Uuid; use crate::dev_screen::models::{ScreenAction, ScreenMessage}; use crate::dev_screen::types::DevScreenParts; -use crate::dev_session::_helpers::child::{publish_record, relay_logs, send_control}; +use crate::dev_session::_helpers::child::{relay_logs, send_control}; use crate::dev_session::_helpers::foreground::connect_in_foreground; use crate::dev_session::_helpers::runs::{SeenRuns, run_messages}; use crate::dev_session::_helpers::triggers::trigger_summary; @@ -71,8 +71,7 @@ pub(crate) async fn run_dev_session( drop(screen.send(ScreenMessage::Log(line))); continue; }; - if let DevEvent::Published { record, .. } = &event { - publish_record(record); + if let DevEvent::Published { .. } = &event { drop(screen.send(ScreenMessage::Triggers( trigger_summary(&list_triggers(&store, location_id, &dev.target).await?), ))); diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs index 77318687d8..14d3d5099a 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs @@ -16,7 +16,7 @@ use crate::native_commands::constants::{ DEVELOPMENT_CONTROL_FILE, DEVELOPMENT_OUTPUT_FOLDER, LOCATION_COMMIT_CHECK_SECONDS, }; use crate::native_commands::errors::PythonNeeded; -use crate::native_commands::models::{LocationWatch, ProjectLocation}; +use crate::native_commands::models::{GenerationLookups, LocationWatch, ProjectLocation}; use crate::replay::main::output_file_identities::output_file_identities; /// Observe the same project inputs as compiler reuse, excluding redirected command output. @@ -43,6 +43,7 @@ pub(crate) fn location_watch(root: &Path) -> LocationWatch { commit_checked_at: tokio::time::Instant::now(), checked: false, republish: None, + lookups: GenerationLookups::default(), } } diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/changed_build.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/changed_build.rs index b88a0de7c4..8d46fdf012 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/changed_build.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/changed_build.rs @@ -38,3 +38,20 @@ pub(in crate::native_commands) fn changed_build_nodes( } Ok((changed, downstream)) } + +/// `Can't plan N models: name: error; ...` for the plan's models that couldn't be planned; `None` when every model planned. +pub(in crate::native_commands) fn model_errors(document: &Value) -> Option { + let mut errors: Vec = Vec::new(); + for model in document["models"].as_array().into_iter().flatten() { + let Some(message) = model["error"]["message"].as_str() else { + continue; + }; + let name: &str = model["name"].as_str().unwrap_or("a model"); + errors.push(format!("{name}: {message}")); + } + match errors.len() { + 0 => None, + 1 => Some(format!("Can't plan 1 model: {}", errors[0])), + count => Some(format!("Can't plan {count} models: {}", errors.join("; "))), + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/compile_turn.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/compile_turn.rs new file mode 100644 index 0000000000..754f5e49fa --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/compile_turn.rs @@ -0,0 +1,70 @@ +//! One compile turn of a serving location: the next generation number, its compile, and what settles it. + +use std::future::Future; +use std::path::Path; + +use sqlbuild_orchestration::store::errors::ControlError; +use tokio::sync::{mpsc, watch}; + +use crate::native_commands::_helpers::location::execution::{ + compile_next_generation, finish_compile, +}; +use crate::native_commands::_helpers::location::lookup_failure::failed_lookup; +use crate::native_commands::models::{ + DevControlState, LocationRuntimeRequest, LocationServe, LocationWatch, +}; +use crate::native_commands::types::{CompileState, LocationSession}; + +/// Compile the next generation and settle it, with the generation it published; `None` when stopped. A failed lookup retries in 5 seconds and reports a failed load at the third in a row. +pub(crate) async fn compile_turn( + ((options, script), (bearer, client, poll), requests): ( + (&LocationServe, &Path), + LocationSession<'_>, + &mpsc::Sender, + ), + ((watch, metadata, deferred_sync), compiled_inputs): CompileState, + (controls, stopped): ( + &mut watch::Receiver, + impl Future>, + ), +) -> Result)>, ControlError> { + tokio::pin!(stopped); + let Some((next_compile, metadata, compiled_inputs)) = compile_next_generation( + (options, bearer, requests), + (metadata, compiled_inputs, &watch.observed.0), + stopped.as_mut(), + ) + .await? + else { + return Ok(None); + }; + let (load, generation) = match next_compile { + Ok(next) => next, + Err(error) => { + let retried: Option = + failed_lookup(options, (bearer, poll.session_id), (&error, watch), stopped).await?; + return Ok( + retried.map(|watch| (((watch, metadata, deferred_sync), compiled_inputs), None)) + ); + } + }; + let mut watch = watch; + watch.lookups.answered(generation); + let published: Option = match &load { + Ok(_) => Some(generation), + Err(_) => None, + }; + let settled = finish_compile( + (options, script, ((bearer, poll.session_id), client)), + (load, generation), + (watch, metadata, deferred_sync), + (controls, stopped.as_mut()), + ) + .await?; + Ok(settled.map(|(watch, metadata, deferred_sync)| { + ( + ((watch, metadata, deferred_sync), compiled_inputs), + published, + ) + })) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_discovery.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_discovery.rs index 9b9fd56ee2..b5c75d4bd8 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_discovery.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_discovery.rs @@ -52,7 +52,7 @@ pub(crate) async fn sleep_until(due: Option) { } } -/// Call the set due for its `check_every` again; republish when its result changed. Shutdown, or a request waiting out its grace, stops it. +/// Call the set due for its `check_every` again; republish when its result changed, or with discovery when the check crashed, so the publication reports the set. Shutdown, or a request waiting out its grace, stops it. pub(crate) async fn check_discovered( compiler: Option, discovery: &mut LocationDiscovery, @@ -83,17 +83,17 @@ pub(crate) async fn check_discovered( let reply: DiscoveredSetChecked = match reply { Some(Ok(reply)) => reply, unfinished => { + let crashed: bool = unfinished.is_some(); let problem: String = match unfinished { - Some(_) => format!("Checking discovered set {name} failed"), - None => format!( - "Checking discovered set {name} did not finish within {} seconds of a request waiting for it", + Some(Err(error)) => format!( + "Checking discovered set {name} failed: {error}; the location restarts its interpreter and discovers again" + ), + _ => format!( + "Checking discovered set {name} did not finish within {} seconds of a request waiting for it; the location restarts its interpreter", CHECK_GRACE.as_secs() ), }; - drop(write_output(&[( - Stream::Stderr, - &format!("{problem}; the location restarts its interpreter.\n"), - )])); + drop(write_output(&[(Stream::Stderr, &format!("{problem}.\n"))])); discovery.checked( &name, DiscoveredSetChecked { @@ -103,6 +103,9 @@ pub(crate) async fn check_discovered( Instant::now(), ); stop_location_runtime(Some(active)).await?; + if crashed { + request_republish(republish, true); + } return Ok(None); } }; 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 4d9da35442..402e372107 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs @@ -59,7 +59,7 @@ use crate::native_commands::constants::{ use crate::native_commands::constants::{ DEVELOPMENT_CONTROL_FILE, DEVELOPMENT_OUTPUT_FOLDER, PLAN_NOT_PRODUCED, }; -use crate::native_commands::constants::{OPENING_STORE, STORE_READY}; +use crate::native_commands::constants::{MAX_LOAD_ERROR_CHARS, OPENING_STORE, STORE_READY}; use crate::native_commands::errors::PythonNeeded; use crate::native_commands::main::_run_admin::run_admin; use crate::native_commands::main::_run_control::run_control; @@ -439,8 +439,6 @@ pub(crate) async fn compile_generation( dev_event_line(&DevEvent::Published { generation, snapshot_id: record.snapshot_id.to_string(), - record: serde_json::to_value(&record) - .map_err(|error| ControlError::Invalid(error.to_string()))?, }) } else { let mut output: String = serde_json::to_string(&record) @@ -970,11 +968,11 @@ pub(crate) fn location_options(namespace: &Namespace) -> Result Result, ControlError> { +) -> Result, ControlError> { match next_remote_generation( &options.server_url, bearer, @@ -983,7 +981,7 @@ pub(crate) async fn location_generation( ) .await { - Ok(generation) => Ok(Some(generation)), + Ok(generation) => Ok(Ok(generation)), Err(error) => { if matches!(&error, ClientError::Configuration(_)) || matches!(&error, ClientError::Rejected(status) if matches!(status.as_u16(), 401 | 403)) @@ -996,7 +994,7 @@ pub(crate) async fn location_generation( "Location generation lookup failed; retaining last good snapshot and retrying: {error}\n" ), )])); - Ok(None) + Ok(Err(error.to_string())) } } } @@ -1872,11 +1870,20 @@ pub(crate) async fn finish_compile( .. } = match load { Ok(published) => published, - Err((rules, _)) => { + Err((rules, error)) => { watch.retry_at = Some(Instant::now() + Duration::from_secs(30)); + let error: String = redact_error_text(&error) + .chars() + .take(MAX_LOAD_ERROR_CHARS) + .collect(); + let failed = LocationHealth::CompileFailed { + generation, + rules, + error: Some(error), + }; tokio::select! { result = &mut stopped => { result?; return Ok(None); }, - () = report_location_health(options, session.0, session.1, LocationHealth::CompileFailed { generation, rules }) => {}, + () = report_location_health(options, session.0, session.1, failed) => {}, } drop(write_output(&[( Stream::Stderr, @@ -1926,12 +1933,13 @@ pub(crate) async fn compile_next_generation( Some(state) => Some(close_metadata_reader(state).await?), None => None, }; - let generation: Option = tokio::select! { + let generation: Result = tokio::select! { result = &mut stopped => { result?; return Ok(None); }, generation = location_generation(options, bearer) => generation?, }; - let Some(generation) = generation else { - return Ok(Some((None, metadata, compiled_inputs))); + let generation: i64 = match generation { + Ok(generation) => generation, + Err(error) => return Ok(Some((Err(error), metadata, compiled_inputs))), }; drop(write_output(&[( Stream::Stderr, @@ -1945,7 +1953,7 @@ pub(crate) async fn compile_next_generation( stopped.as_mut(), ) .await?; - Ok(load.map(|load| (Some((load, generation)), metadata, compiled_inputs))) + Ok(load.map(|load| (Ok((load, generation)), metadata, compiled_inputs))) } /// The safety sync interval from the flag, then the environment, then the project; `None` when unset. diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/health.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/health.rs new file mode 100644 index 0000000000..9876d7b010 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/health.rs @@ -0,0 +1,20 @@ +//! What `sqb location health` exits with for each state. + +use sqlbuild_orchestration::platform::models::LocationState; + +use crate::native_commands::constants::STARTING_EXIT_CODE; + +/// 0 only when healthy; 1 when anything failed or is down; 3 while the newest instance's first load runs, or 0 then when `allow_starting`, as a container health check counts a starting location alive. +pub(crate) fn health_exit_code(state: LocationState, allow_starting: bool) -> i32 { + match state { + LocationState::Healthy => 0, + LocationState::Starting if allow_starting => 0, + LocationState::Starting => STARTING_EXIT_CODE, + LocationState::Broken + | LocationState::FallingBack + | LocationState::MissingSecrets + | LocationState::ChangePlanFailed + | LocationState::DiscoveryFailed + | LocationState::Degraded => 1, + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/lookup_failure.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/lookup_failure.rs new file mode 100644 index 0000000000..2bbd10611a --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/lookup_failure.rs @@ -0,0 +1,53 @@ +//! A location that checks in but can't get its next generation number can't load new code; at the third failed lookup in a row it reports a failed load. + +use std::future::Future; +use std::time::Duration; + +use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; +use sqlbuild_orchestration::platform::models::LocationHealth; +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::report_location_health; +use crate::native_commands::constants::MAX_LOAD_ERROR_CHARS; +use crate::native_commands::models::{GenerationLookups, LocationServe, LocationWatch}; + +/// Retry the lookup in 5 seconds and, at the third failure in a row, report a failed load with `error`; `None` when stopped first. +pub(crate) async fn failed_lookup( + options: &LocationServe, + (bearer, session_id): (&str, Uuid), + (error, mut watch): (&str, LocationWatch), + stopped: impl Future>, +) -> Result, ControlError> { + watch.retry_at = Some(Instant::now() + Duration::from_secs(5)); + if !watch.lookups.failed() { + return Ok(Some(watch)); + } + let error: String = redact_error_text(&format!( + "the location can't get its next generation number from the server: {error}" + )) + .chars() + .take(MAX_LOAD_ERROR_CHARS) + .collect(); + drop(write_output(&[( + Stream::Stderr, + &format!("Reporting a failed load: {error}\n"), + )])); + let failed: LocationHealth = lookup_failure_health(watch.lookups, error); + tokio::select! { + result = stopped => { result?; Ok(None) }, + () = report_location_health(options, bearer, session_id, failed) => Ok(Some(watch)), + } +} + +/// A failed load of the generation the location can't get, with `error`. +pub(crate) fn lookup_failure_health(lookups: GenerationLookups, error: String) -> LocationHealth { + LocationHealth::CompileFailed { + generation: lookups.next(), + rules: None, + error: Some(error), + } +} 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 21b7f0eb8e..a7dd6bb746 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs @@ -1,5 +1,6 @@ pub(crate) mod api_start; pub(crate) mod changed_build; +pub(crate) mod compile_turn; pub(crate) mod compiler_discovery; pub(crate) mod compiler_restart; pub(crate) mod dev_cancel; @@ -11,7 +12,9 @@ pub(crate) mod discovery_state; pub(crate) mod dynamic_resume; pub(crate) mod env_reload; pub(crate) mod execution; +pub(crate) mod health; pub(crate) mod held_copy; +pub(crate) mod lookup_failure; pub(crate) mod plan_document; pub(crate) mod plan_request; pub(crate) mod plan_reuse; diff --git a/crates/sqlbuild-cli/src/native_commands/constants.rs b/crates/sqlbuild-cli/src/native_commands/constants.rs index 46c99e2b84..ae61acdb36 100644 --- a/crates/sqlbuild-cli/src/native_commands/constants.rs +++ b/crates/sqlbuild-cli/src/native_commands/constants.rs @@ -274,3 +274,12 @@ pub(crate) const DEVELOPMENT_OUTPUT_FOLDER: &str = /// How `sqb dev` hands its location the SQLite control store file, which the watch leaves out. pub(crate) const DEVELOPMENT_CONTROL_FILE: &str = sqlbuild_core::constants::DEVELOPMENT_CONTROL_FILE_ENV; + +/// `sqb location health` while the newest location instance has not finished its first load. +pub(crate) const STARTING_EXIT_CODE: i32 = 3; + +/// Failed generation lookups in a row, while the location still checks in, after which it reports a failed load. +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; diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs index 15febaebbb..3621413439 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs @@ -14,7 +14,7 @@ use crate::argv::models::Stream; use crate::native_commands::_helpers::command::paths::location_files; use crate::native_commands::_helpers::command::terminal::write_output; use crate::native_commands::_helpers::location::changed_build::{ - changed_build_nodes, changed_build_settings, + changed_build_nodes, changed_build_settings, model_errors, }; use crate::native_commands::_helpers::location::plan_reuse::keep_plan; use crate::native_commands::main::_location_plan::plan_location; @@ -45,7 +45,14 @@ pub(super) async fn report_changed_build( Ok(settings) => settings, Err(error) => { report(&format!("Could not plan what changed: {error}\n")); - return Ok(Some(false)); + return Ok(Some( + report_failed_plan( + (options, client), + (session_id, generation), + &error.to_string(), + ) + .await, + )); } }; report("Planning what changed from the synced warehouse copy...\n"); @@ -70,36 +77,37 @@ pub(super) async fn report_changed_build( keep_plan(keep, (&document, &diffs)); if let Some(reason) = document["error"]["message"].as_str() { report(&format!("Could not plan what changed: {reason}\n")); - let request = ChangedBuildReport { - session_id, - generation, - changed: Vec::new(), - downstream: Vec::new(), - failing: Some(reason.chars().take(MAX_FAILING_REASON_CHARS).collect()), - }; - let reported = match client.report_changed_build(&options.target, &request).await { - Ok(_) => document["error"]["code"].as_str() != Some("plan_failed"), - Err(error) => { - report(&format!("Reporting the failed plan failed: {error}\n")); - false - } - }; - return Ok(Some(reported)); + let reported = + report_failed_plan((options, client), (session_id, generation), reason).await; + return Ok(Some( + reported && document["error"]["code"].as_str() != Some("plan_failed"), + )); } let (changed, downstream) = match changed_build_nodes(&document) { Ok(nodes) => nodes, Err(error) => { report(&format!("Could not plan what changed: {error}\n")); - return Ok(Some(false)); + return Ok(Some( + report_failed_plan( + (options, client), + (session_id, generation), + &error.to_string(), + ) + .await, + )); } }; let counts = format!("{} changed, {} downstream", changed.len(), downstream.len()); + let failing: Option = model_errors(&document); + if let Some(reason) = &failing { + report(&format!("Planned what changed with errors: {reason}\n")); + } let request = ChangedBuildReport { session_id, generation, changed, downstream, - failing: None, + failing: failing.map(|reason| reason.chars().take(MAX_FAILING_REASON_CHARS).collect()), }; Ok(Some( match client.report_changed_build(&options.target, &request).await { @@ -114,3 +122,28 @@ pub(super) async fn report_changed_build( }, )) } + +/// Tell the server the plan failed and why, so its health and pages show it; whether the server took it. +async fn report_failed_plan( + (options, client): (&LocationServe, &LocationWorkClient), + (session_id, generation): (Uuid, i64), + reason: &str, +) -> bool { + let request = ChangedBuildReport { + session_id, + generation, + changed: Vec::new(), + downstream: Vec::new(), + failing: Some(reason.chars().take(MAX_FAILING_REASON_CHARS).collect()), + }; + match client.report_changed_build(&options.target, &request).await { + Ok(_) => true, + Err(error) => { + drop(write_output(&[( + Stream::Stderr, + &format!("Reporting the failed plan failed: {error}\n"), + )])); + false + } + } +} 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 872d252703..dc256e329c 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs @@ -3,7 +3,6 @@ use sqlbuild_orchestration::platform::models::LocationWorkScope; use std::future::Future; use std::path::Path; -use std::time::Duration; use sqlbuild_cache::project_snapshot::models::PathStamp; use sqlbuild_orchestration::platform::main::work::connect_location_work::connect_location_work; @@ -19,9 +18,8 @@ use crate::native_commands::_helpers::command::paths::{ exclude_location_databases, location_watch, observe_location_inputs, }; use crate::native_commands::_helpers::command::terminal::write_output; -use crate::native_commands::_helpers::location::execution::{ - apply_dev_controls, compile_next_generation, finish_compile, -}; +use crate::native_commands::_helpers::location::compile_turn::compile_turn; +use crate::native_commands::_helpers::location::execution::apply_dev_controls; use crate::native_commands::_helpers::location::execution::{ dev_controls, location_clock, location_heartbeats, next_turn, }; @@ -36,7 +34,6 @@ use crate::native_commands::main::_location_work::run_location_work; use crate::native_commands::models::{ DevControlState, LocationMetadataSync, LocationRuntimeRequest, LocationServe, LocationWatch, }; -use crate::native_commands::types::LoadOutcome; pub(super) async fn run_location( options: LocationServe, @@ -133,37 +130,19 @@ async fn watch_location( (watch, work_at, metadata) = idle; continue; } - published_generation = None; - let Some(next) = compile_next_generation( - (options, bearer, &requests), - (metadata, compiled_inputs, &watch.observed.0), - stopped.as_mut(), - ) - .await? - else { - return Ok(()); - }; - let next_compile: Option<(LoadOutcome, i64)>; - (next_compile, metadata, compiled_inputs) = next; - let Some((load, generation)) = next_compile else { - watch.retry_at = Some(Instant::now() + Duration::from_secs(5)); - continue; - }; - published_generation = match &load { - Ok(_) => Some(generation), - Err(_) => None, - }; - let Some(settled) = finish_compile( - (options, script, ((bearer, poll.session_id), client)), - (load, generation), - (watch, metadata, deferred_sync), + let Some(turn) = compile_turn( + ((options, script), (bearer, client, poll), &requests), + ((watch, metadata, deferred_sync), compiled_inputs), (&mut controls, stopped.as_mut()), ) .await? else { return Ok(()); }; - (watch, metadata, deferred_sync) = settled; + ( + ((watch, metadata, deferred_sync), compiled_inputs), + published_generation, + ) = turn; } } diff --git a/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs b/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs index 1d2fb6f694..732c56b636 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs @@ -6,10 +6,12 @@ use chrono::Utc; use serde_json::json; use sqlbuild_orchestration::platform::main::work::connect_location_work::connect_location_work; use sqlbuild_orchestration::platform::models::LocationState; + +use crate::native_commands::_helpers::location::health::health_exit_code; use uuid::Uuid; use crate::argv::models::{Namespace, Stream}; -use crate::native_commands::_helpers::command::decision::text; +use crate::native_commands::_helpers::command::decision::{flag, text}; use crate::native_commands::_helpers::command::terminal::write_output; use crate::native_commands::_helpers::location::execution::location_options; use crate::native_commands::_helpers::location::republish_command::run_republish; @@ -69,7 +71,7 @@ pub(crate) fn run_location_invocation(namespace: &Namespace, script: Option<&Pat }) } -/// `sqb location health`: 0 when healthy, degraded or failing discovery, 1 when down or falling back, 2 when unanswered. +/// `sqb location health`: 0 when healthy, 1 when anything failed or is down, 2 when unanswered, 3 while starting. fn location_health(namespace: &Namespace) -> i32 { drop(write_output(&[( Stream::Stderr, @@ -82,10 +84,7 @@ fn location_health(namespace: &Namespace) -> i32 { (Stream::Stdout, &format!("{document}\n")), (Stream::Stderr, "Location health checked successfully\n"), ])); - i32::from(matches!( - state, - LocationState::Broken | LocationState::FallingBack | LocationState::MissingSecrets - )) + health_exit_code(state, flag(namespace, "location_allow_starting")) } Err(error) => { drop(write_output(&[( diff --git a/crates/sqlbuild-cli/src/native_commands/models.rs b/crates/sqlbuild-cli/src/native_commands/models.rs index 2a65c1f148..bc2648c325 100644 --- a/crates/sqlbuild-cli/src/native_commands/models.rs +++ b/crates/sqlbuild-cli/src/native_commands/models.rs @@ -315,6 +315,8 @@ pub(crate) struct LocationWatch { pub(crate) checked: bool, /// A claimed republish, owed the result of the next compile to finish. pub(crate) republish: Option, + /// The generation lookups, whose failures in a row become a reported failed load. + pub(crate) lookups: GenerationLookups, } /// What one compile published, for the watcher and any republish it owes. @@ -847,3 +849,29 @@ impl std::fmt::Debug for RepublishCaller { } } } + +/// The location's generation lookups: the last generation it got, and how many failed in a row since. It reports a failed load once per streak, at `LOOKUP_FAILURES_REPORTED`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct GenerationLookups { + failures: u32, + last: Option, +} + +impl GenerationLookups { + /// Count one failed lookup; true for the one to report. + pub(crate) fn failed(&mut self) -> bool { + self.failures += 1; + self.failures == crate::native_commands::constants::LOOKUP_FAILURES_REPORTED + } + + /// A lookup answered with `generation`: the streak ends. + pub(crate) fn answered(&mut self, generation: i64) { + self.failures = 0; + self.last = Some(generation); + } + + /// The generation after the last one the location got, or the first: the one it can't load. + pub(crate) fn next(self) -> i64 { + self.last.map_or(1, |generation| generation + 1) + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests.rs b/crates/sqlbuild-cli/src/native_commands/tests.rs index 612025842f..d64cf8e840 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests.rs @@ -12,6 +12,8 @@ mod helpers; mod init; #[path = "tests/test_location_discovery.rs"] mod location_discovery; +#[path = "tests/test_location_health.rs"] +mod location_health; #[path = "tests/test_location_metadata.rs"] mod location_metadata; #[path = "tests/test_location_plan.rs"] @@ -28,5 +30,7 @@ mod rules; mod sync_schedule; #[path = "tests/test_terminal.rs"] mod terminal; +#[path = "tests/test_lookup_failures.rs"] +mod test_lookup_failures; #[path = "tests/test_types.rs"] mod test_types; diff --git a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs index 9394f51da7..4ee37e10da 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs @@ -328,3 +328,14 @@ pub(super) fn scripted_compiler(script: &str) -> crate::native_commands::models: python_sources: Vec::new(), } } + +/// A lookup that failed, as the location loop counts it; true when it is the one to report. +pub(crate) fn failed(lookups: &mut crate::native_commands::models::GenerationLookups) -> bool { + lookups.failed() +} + +/// A lookup the server answered with generation 4; never reported. +pub(crate) fn answered(lookups: &mut crate::native_commands::models::GenerationLookups) -> bool { + lookups.answered(4); + false +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_changed_build.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_changed_build.rs index 75862ddc53..b01520351b 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_changed_build.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_changed_build.rs @@ -3,13 +3,13 @@ use serde_json::json; use sqlbuild_orchestration::warehouse_metadata::models::WarehouseHistoryKind; use crate::native_commands::_helpers::location::changed_build::{ - changed_build_nodes, changed_build_settings, + changed_build_nodes, changed_build_settings, model_errors, }; use crate::native_commands::_helpers::location::execution::metadata_sync; use crate::native_commands::models::LocationMetadataSync; use crate::native_commands::tests::helpers::{acknowledge_complete_pages, one_location}; use crate::native_commands::tests::test_types::{ - ChangedBuildNodesTestCase, ChangedBuildSettingsTestCase, ReplanTestCase, + ChangedBuildNodesTestCase, ChangedBuildSettingsTestCase, ModelErrorsTestCase, ReplanTestCase, }; #[test] @@ -121,3 +121,42 @@ fn given_completed_syncs_when_deciding_to_replan_then_a_publication_an_applied_c ); } } + +#[test] +fn given_a_plan_with_models_it_could_not_plan_when_read_then_the_reason_names_each_model() { + let test_cases = [ + ModelErrorsTestCase { + description: "every model planned", + document: json!({"models": [{"name": "orders", "action": "create_table"}]}), + expected_reason: None, + }, + ModelErrorsTestCase { + description: "one model", + document: json!({"models": [ + {"name": "orders", "action": "error", "error": {"code": "S203", "message": "model 'orders' sets full_refresh false", "help": null}}, + {"name": "totals", "action": "create_table"}, + ]}), + expected_reason: Some( + "Can't plan 1 model: orders: model 'orders' sets full_refresh false", + ), + }, + ModelErrorsTestCase { + description: "several models", + document: json!({"models": [ + {"name": "orders", "action": "error", "error": {"code": "S203", "message": "full_refresh false", "help": null}}, + {"name": "returns", "action": "error", "error": {"code": "S302", "message": "empty inputs", "help": null}}, + ]}), + expected_reason: Some( + "Can't plan 2 models: orders: full_refresh false; returns: empty inputs", + ), + }, + ]; + for test_case in test_cases { + assert_eq!( + model_errors(&test_case.document).as_deref(), + test_case.expected_reason, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_location_discovery.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_location_discovery.rs index 11f8cdb953..d53e902468 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_location_discovery.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_location_discovery.rs @@ -13,7 +13,9 @@ use crate::native_commands::tests::helpers::{PLAN_FILE, discovered_load, failed_ #[cfg(unix)] use crate::native_commands::tests::helpers::{scripted_compiler, silent_compiler}; #[cfg(unix)] -use crate::native_commands::tests::test_types::{CheckGraceTestCase, CheckShutdownTestCase}; +use crate::native_commands::tests::test_types::{ + CheckGraceTestCase, CheckShutdownTestCase, CrashedCheckTestCase, +}; use crate::native_commands::tests::test_types::{ DiscoveryCheckTestCase, DiscoveryReportTestCase, FailedCompileDiscoveryTestCase, RediscoverTestCase, @@ -377,3 +379,56 @@ fn given_a_request_waiting_on_a_check_when_the_grace_passes_then_only_an_unfinis ); } } + +#[cfg(unix)] +#[test] +fn given_a_check_whose_interpreter_crashes_when_it_ends_then_the_location_republishes_and_discovers_again() + { + let test_cases = [ + CrashedCheckTestCase { + description: "an interpreter that exits mid-check rediscovers, so the publication reports the set", + script: "read request; exit 3", + expected_rediscovers: 1, + }, + CrashedCheckTestCase { + description: "a check that answers asks for nothing", + script: r#"read request; echo '{"set":null,"changed":false}'; exec sleep 600"#, + expected_rediscovers: 0, + }, + ]; + + for test_case in test_cases { + let rediscovers: u64 = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime") + .block_on(async { + let mut load = discovered_load(&["a"]); + for set in load.discovered.values_mut() { + set.check_every_seconds = Some(0); + } + let mut discovery = LocationDiscovery::default(); + discovery.published(&load, Instant::now()); + let (republish, controls) = tokio::sync::watch::channel(Default::default()); + let (_sender, requests) = tokio::sync::mpsc::channel(1); + tokio::time::timeout( + Duration::from_secs(10), + check_discovered( + Some(scripted_compiler(test_case.script)), + &mut discovery, + ((&republish, ("synthetic", uuid::Uuid::nil())), &requests), + ), + ) + .await + .expect("the check ends") + .expect("the interpreter is usable or stopped"); + controls.borrow().rediscovers + }); + + assert_eq!( + rediscovers, test_case.expected_rediscovers, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_location_health.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_location_health.rs new file mode 100644 index 0000000000..4c1d07fd79 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_location_health.rs @@ -0,0 +1,80 @@ +//! `sqb location health` exits non-zero while a restarted location loads, so a deploy waits for the new code. + +use sqlbuild_orchestration::platform::models::LocationState; + +use crate::native_commands::_helpers::location::health::health_exit_code; +use crate::native_commands::tests::test_types::HealthExitTestCase; + +#[test] +fn given_each_location_state_when_health_exits_then_only_healthy_or_an_allowed_start_exits_zero() { + let test_cases = [ + HealthExitTestCase { + description: "the newest instance is loading", + state: LocationState::Starting, + allow_starting: false, + expected_code: 3, + }, + HealthExitTestCase { + description: "the newest instance is loading, for a container health check", + state: LocationState::Starting, + allow_starting: true, + expected_code: 0, + }, + HealthExitTestCase { + description: "its load failed, for a container health check too", + state: LocationState::FallingBack, + allow_starting: true, + expected_code: 1, + }, + HealthExitTestCase { + description: "its load failed", + state: LocationState::FallingBack, + allow_starting: false, + expected_code: 1, + }, + HealthExitTestCase { + description: "no instance checked in", + state: LocationState::Broken, + allow_starting: false, + expected_code: 1, + }, + HealthExitTestCase { + description: "a provider secret is unset", + state: LocationState::MissingSecrets, + allow_starting: false, + expected_code: 1, + }, + HealthExitTestCase { + description: "loaded", + state: LocationState::Healthy, + allow_starting: false, + expected_code: 0, + }, + HealthExitTestCase { + description: "loaded, but the connection check failed", + state: LocationState::Degraded, + allow_starting: false, + expected_code: 1, + }, + HealthExitTestCase { + description: "loaded, but a discover function failed", + state: LocationState::DiscoveryFailed, + allow_starting: false, + expected_code: 1, + }, + HealthExitTestCase { + description: "loaded, but the plan of what changed failed", + state: LocationState::ChangePlanFailed, + allow_starting: false, + expected_code: 1, + }, + ]; + for test_case in test_cases { + assert_eq!( + health_exit_code(test_case.state, test_case.allow_starting), + test_case.expected_code, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_lookup_failures.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_lookup_failures.rs new file mode 100644 index 0000000000..de57c52c1f --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_lookup_failures.rs @@ -0,0 +1,77 @@ +//! A location that checks in but can't get its next generation number reports a failed load at the third failure in a row, once per streak. + +use sqlbuild_orchestration::platform::models::LocationHealth; + +use crate::native_commands::_helpers::location::lookup_failure::lookup_failure_health; +use crate::native_commands::models::GenerationLookups; +use crate::native_commands::tests::helpers::{answered, failed}; +use crate::native_commands::tests::test_types::{ + LookupFailureHealthTestCase, LookupFailuresTestCase, +}; + +#[test] +fn given_failed_generation_lookups_when_counted_then_the_third_in_a_row_is_reported_once() { + let test_cases = [ + LookupFailuresTestCase { + description: "two failures report nothing", + lookups: &[failed, failed], + expected_reports: &[false, false], + }, + LookupFailuresTestCase { + description: "the third failure in a row reports, later ones in the streak don't", + lookups: &[failed, failed, failed, failed, failed], + expected_reports: &[false, false, true, false, false], + }, + LookupFailuresTestCase { + description: "an answered lookup ends the streak", + lookups: &[failed, failed, answered, failed, failed, failed], + expected_reports: &[false, false, false, false, false, true], + }, + ]; + for test_case in test_cases { + let mut lookups = GenerationLookups::default(); + let reports: Vec = test_case + .lookups + .iter() + .map(|lookup| lookup(&mut lookups)) + .collect(); + assert_eq!( + reports, test_case.expected_reports, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_reported_lookup_failure_when_built_then_it_is_a_failed_load_of_the_next_generation() { + let test_cases = [ + LookupFailureHealthTestCase { + description: "after generation 4, the location can't load 5", + answered: Some(4), + expected_generation: 5, + }, + LookupFailureHealthTestCase { + description: "before any generation, it can't load the first", + answered: None, + expected_generation: 1, + }, + ]; + for test_case in test_cases { + let mut lookups = GenerationLookups::default(); + test_case + .answered + .into_iter() + .for_each(|generation| lookups.answered(generation)); + assert_eq!( + lookup_failure_health(lookups, "timed out".into()), + LocationHealth::CompileFailed { + generation: test_case.expected_generation, + rules: None, + error: Some("timed out".into()), + }, + "{}: a failed load, which the server reads as falling_back", + 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 a933eb5764..393c51a8b7 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs @@ -480,3 +480,36 @@ pub(super) struct CheckGraceTestCase { pub(super) expected_within: std::time::Duration, pub(super) expected_compiler: bool, } + +pub(crate) struct HealthExitTestCase { + pub(crate) description: &'static str, + pub(crate) state: sqlbuild_orchestration::platform::models::LocationState, + pub(crate) allow_starting: bool, + pub(crate) expected_code: i32, +} + +pub(super) struct CrashedCheckTestCase { + pub(super) description: &'static str, + pub(super) script: &'static str, + pub(super) expected_rediscovers: u64, +} + +pub(super) struct ModelErrorsTestCase { + pub(super) description: &'static str, + pub(super) document: serde_json::Value, + pub(super) expected_reason: Option<&'static str>, +} + +pub(super) struct LookupFailuresTestCase { + pub(super) description: &'static str, + /// Each lookup: `failed` or `answered`, as the location loop calls them. + pub(super) lookups: + &'static [fn(&mut crate::native_commands::models::GenerationLookups) -> bool], + pub(super) expected_reports: &'static [bool], +} + +pub(super) struct LookupFailureHealthTestCase { + pub(super) description: &'static str, + pub(super) answered: Option, + pub(super) expected_generation: i64, +} diff --git a/crates/sqlbuild-cli/src/native_commands/types.rs b/crates/sqlbuild-cli/src/native_commands/types.rs index c3ce30e98b..8a62381643 100644 --- a/crates/sqlbuild-cli/src/native_commands/types.rs +++ b/crates/sqlbuild-cli/src/native_commands/types.rs @@ -11,9 +11,9 @@ pub(crate) type Settled = ( Option<(Vec, i64)>, ); -/// The next compile, if a generation number was issued, with the metadata sync and the inputs it saw. +/// The next compile, or why no generation number was issued, with the metadata sync and the inputs it saw. pub(crate) type NextGeneration = ( - Option<(LoadOutcome, i64)>, + Result<(LoadOutcome, i64), String>, Option, Option>, ); @@ -50,3 +50,16 @@ pub(crate) type DiscoveryControls<'a> = ( &'a tokio::sync::watch::Sender, (&'a str, uuid::Uuid), ); + +/// What the location carries from one compile to the next: its settled state and the inputs it last compiled. +pub(crate) type CompileState = ( + Settled, + Option>, +); + +/// A serving location's sign-in, its work client and its poll. +pub(crate) type LocationSession<'a> = ( + &'a str, + &'a sqlbuild_orchestration::platform::models::LocationWorkClient, + &'a sqlbuild_orchestration::platform::models::LocationWorkPoll, +); diff --git a/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs b/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs index 780dad3cec..815e22f739 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs @@ -24,9 +24,19 @@ fn given_location_health_reports_when_checking_health_then_down_falling_back_or_ expected_exit: 1, }, LocationHealthTestCase { - description: "a recent heartbeat", + description: "a recent heartbeat before the instance's own first load finishes", reports: &[r#"{"kind":"heartbeat"}"#], other_target_connections: 0, + expected_state: "starting", + expected_exit: 3, + }, + LocationHealthTestCase { + description: "a recent heartbeat after the instance's own load connected", + reports: &[ + r#"{"kind":"heartbeat"}"#, + r#"{"kind":"connection","generation":2,"healthy":true}"#, + ], + other_target_connections: 0, expected_state: "healthy", expected_exit: 0, }, @@ -88,14 +98,14 @@ fn given_location_health_reports_when_checking_health_then_down_falling_back_or_ ], other_target_connections: 0, expected_state: "discovery_failed", - expected_exit: 0, + expected_exit: 1, }, LocationHealthTestCase { description: "the warehouse connection check failed", reports: &[r#"{"kind":"connection","generation":2,"healthy":false}"#], other_target_connections: 0, expected_state: "degraded", - expected_exit: 0, + expected_exit: 1, }, ]; let runtime = tokio::runtime::Builder::new_current_thread() diff --git a/crates/sqlbuild-core/src/build_command/main/plan_safety_steps.rs b/crates/sqlbuild-core/src/build_command/main/plan_safety_steps.rs index ccf4f53775..c8de79dae0 100644 --- a/crates/sqlbuild-core/src/build_command/main/plan_safety_steps.rs +++ b/crates/sqlbuild-core/src/build_command/main/plan_safety_steps.rs @@ -8,17 +8,33 @@ use crate::build_command::_helpers::storage::{retention_step, snapshot_steps, ta use crate::build_command::errors::BuildCommandError; use crate::build_command::main::model_limit_error::model_limit_error; use crate::build_command::models::{ - ModelLimit, PlanSafetyFacts, PlanSafetyGates, PolicyStep, SnapshotPolicies, + ModelErrorFact, ModelLimit, PlanSafetyFacts, PlanSafetyGates, PolicyStep, SnapshotPolicies, }; -/// Migration, old-name, model-limit, snapshot, table-type and retention gates; a refusal ends the list. +/// A selected model that couldn't be planned refuses the build with its own error; several are joined under the first one's code. +fn model_error_refusal(errors: &[ModelErrorFact]) -> Option { + let first: &ModelErrorFact = errors.first()?; + let message: String = errors + .iter() + .map(|error| error.message.as_str()) + .collect::>() + .join("; "); + Some(BuildCommandError::new( + first.code.as_deref(), + message, + first.help.as_deref(), + )) +} + +/// Model-error, migration, old-name, model-limit, snapshot, table-type and retention gates; a refusal ends the list. pub fn plan_safety_steps( facts: &PlanSafetyFacts, gates: &PlanSafetyGates, (limit, snapshot_policies): (&ModelLimit, &SnapshotPolicies), ) -> Result, BuildCommandError> { let mut steps: Vec = Vec::new(); - let refusal: Option = model_migration_refusal(&facts.model_migrations) + let refusal: Option = model_error_refusal(&facts.model_errors) + .or_else(|| model_migration_refusal(&facts.model_migrations)) .or_else(|| column_migration_refusal(&facts.column_migrations)); if let Some(error) = refusal { steps.push(PolicyStep::Refuse(error)); diff --git a/crates/sqlbuild-core/src/build_command/models.rs b/crates/sqlbuild-core/src/build_command/models.rs index 6e6fe6ae4c..10c494648a 100644 --- a/crates/sqlbuild-core/src/build_command/models.rs +++ b/crates/sqlbuild-core/src/build_command/models.rs @@ -36,6 +36,14 @@ pub struct PlanWarningFact { pub message: String, } +/// A selected model that couldn't be planned, with its error. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ModelErrorFact { + pub code: Option, + pub message: String, + pub help: Option, +} + /// A snapshot model planned for a full refresh. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct SnapshotRefreshFact { @@ -65,6 +73,7 @@ pub struct PlanSafetyFacts { pub model_migrations: Vec, pub column_migrations: Vec, pub error_warnings: Vec, + pub model_errors: Vec, pub executable_model_count: usize, pub snapshot_refreshes: Vec, pub table_type_downgrades: Vec, diff --git a/crates/sqlbuild-core/src/build_command/tests/test_plan_safety.rs b/crates/sqlbuild-core/src/build_command/tests/test_plan_safety.rs index 350e3bfcc4..9d13280f0f 100644 --- a/crates/sqlbuild-core/src/build_command/tests/test_plan_safety.rs +++ b/crates/sqlbuild-core/src/build_command/tests/test_plan_safety.rs @@ -1,5 +1,6 @@ use crate::build_command::models::{ - ColumnMigrationFact, ModelMigrationFact, PlanSafetyFacts, PlanSafetyGates, PlanWarningFact, + ColumnMigrationFact, ModelErrorFact, ModelMigrationFact, PlanSafetyFacts, PlanSafetyGates, + PlanWarningFact, }; use crate::build_command::tests::helpers::{ build_gates, described_steps, missing_origin, retention, snapshot, table_type, @@ -16,6 +17,48 @@ fn given_plan_facts_when_applying_safety_gates_then_refuses_or_confirms_in_order max_models: None, expected_steps: Vec::new(), }, + PolicyTestCase { + description: "a model that can't be planned refuses before any migration, with its own error", + facts: PlanSafetyFacts { + model_errors: vec![ModelErrorFact { + code: Some("S203".to_owned()), + message: "model 'orders' sets full_refresh false".to_owned(), + help: Some("allow the rebuild".to_owned()), + }], + model_migrations: vec![ModelMigrationFact { + blocks_build: true, + decision: "conflict".to_owned(), + ..missing_origin("orders") + }], + ..PlanSafetyFacts::default() + }, + gates: build_gates(), + max_models: None, + expected_steps: vec!["refuse:S203:model 'orders' sets full_refresh false".to_owned()], + }, + PolicyTestCase { + description: "several models that can't be planned are joined under the first code", + facts: PlanSafetyFacts { + model_errors: vec![ + ModelErrorFact { + code: Some("S203".to_owned()), + message: "model 'orders' sets full_refresh false".to_owned(), + help: None, + }, + ModelErrorFact { + code: Some("S302".to_owned()), + message: "model 'customers' has empty inputs".to_owned(), + help: None, + }, + ], + ..PlanSafetyFacts::default() + }, + gates: build_gates(), + max_models: None, + expected_steps: vec![ + "refuse:S203:model 'orders' sets full_refresh false; model 'customers' has empty inputs".to_owned(), + ], + }, PolicyTestCase { description: "a hidden blocking origin refuses first", facts: PlanSafetyFacts { 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 11cccfe5ed..10f92cd260 100644 --- a/crates/sqlbuild-core/src/cli_text/_helpers/plan_sections.rs +++ b/crates/sqlbuild-core/src/cli_text/_helpers/plan_sections.rs @@ -8,11 +8,11 @@ use crate::cli_text::_helpers::layout::tree_connector; use crate::cli_text::constants::{ ALTER_DYNAMIC_ACTION, BOUNDED_BACKFILL, CHANGED_IDENTITY, COLUMN_ADDED, COLUMN_REMOVED, COLUMN_TYPE_CHANGED, CONFIG_CHANGED_REASON, CREATE_DYNAMIC_ACTION, CREATE_VIEW_ACTION, - CUSTOM_ACTION, DIFF_HEADER_MARKER, EFFECTIVE_BATCH_SIZE_TOKEN, ERROR_SEVERITY_VALUE, - FIRST_RUN_REASON, FORWARD_BACKFILL, FULL_BACKFILL, FULL_REFRESH_REASON, INFO_SEVERITY_VALUE, - NO_CHANGE_REASON, NORMAL_INCREMENTAL_REASON, QUERY_CHANGED_REASON, REASON_GROUPS, - SCHEMA_CHANGED_REASON, SKIP_ACTION, SOURCE_FRESHNESS_UNKNOWN_WARNING_TITLE, - STALE_INPUT_WARNING_TITLE, + CUSTOM_ACTION, DIFF_HEADER_MARKER, EFFECTIVE_BATCH_SIZE_TOKEN, ERROR_ACTION, + ERROR_SEVERITY_VALUE, FIRST_RUN_REASON, FORWARD_BACKFILL, FULL_BACKFILL, FULL_REFRESH_REASON, + INFO_SEVERITY_VALUE, NO_CHANGE_REASON, NORMAL_INCREMENTAL_REASON, QUERY_CHANGED_REASON, + REASON_GROUPS, SCHEMA_CHANGED_REASON, SKIP_ACTION, SOURCE_FRESHNESS_UNKNOWN_WARNING_TITLE, + STALE_INPUT_WARNING_TITLE, UNBOUNDED_RANGE, }; use crate::cli_text::models::{ CliStyle, CursorPlanText, DisplayLimit, FunctionPlanText, ModelPlanText, PlanTextReport, @@ -41,12 +41,12 @@ fn section_lines( lines } -/// Models whose action is not `skip`. +/// Models whose action is not `skip`, and skipped models with a reason to show. pub(crate) fn active_models(report: &PlanTextReport) -> Vec<&ModelPlanText> { report .models .iter() - .filter(|model| model.action != SKIP_ACTION) + .filter(|model| model.action != SKIP_ACTION || model.skip_reason.is_some()) .collect() } @@ -427,6 +427,12 @@ fn schema_change_suffix(model: &ModelPlanText) -> String { } fn action_text(model: &ModelPlanText) -> String { + if let Some(reason) = &model.skip_reason { + return reason.clone(); + } + if model.action == ERROR_ACTION { + return ERROR_ACTION.to_owned(); + } if model.action == CREATE_VIEW_ACTION { return "recreate view".to_owned(); } @@ -716,6 +722,19 @@ pub(crate) fn full_refresh_count_lines(active: &[&ModelPlanText]) -> Vec for (label, count) in counts { lines.push(format!(" {count:>3} {label}")); } + let unbounded: usize = active + .iter() + .filter(|model| { + model + .cursor + .as_ref() + .and_then(|cursor| cursor.range.as_deref()) + .is_some_and(|range| range.ends_with(UNBOUNDED_RANGE)) + }) + .count(); + if unbounded > 0 { + lines.push(format!(" {unbounded:>3} cursor range {UNBOUNDED_RANGE}")); + } lines } diff --git a/crates/sqlbuild-core/src/cli_text/constants.rs b/crates/sqlbuild-core/src/cli_text/constants.rs index bd63958abd..f642d4bab4 100644 --- a/crates/sqlbuild-core/src/cli_text/constants.rs +++ b/crates/sqlbuild-core/src/cli_text/constants.rs @@ -51,7 +51,9 @@ pub(crate) const STALE_INPUT_WARNING_TITLE: &str = "Stale inputs detected"; pub(crate) const SOURCE_FRESHNESS_UNKNOWN_WARNING_TITLE: &str = "source freshness unknown"; pub(crate) const DIFF_HEADER_MARKER: &str = "# "; pub(crate) const EFFECTIVE_BATCH_SIZE_TOKEN: &str = "effective"; -pub(crate) const REASON_GROUPS: [(&str, &str); 7] = [ +pub(crate) const REASON_GROUPS: [(&str, &str); 9] = [ + ("planning_error", "Planning failed"), + ("window_before_cursor_start", "Window before cursor_start"), ("full_refresh", "Full refresh"), ("query_changed", "Query changed"), ("function_changed", "Function changed"), @@ -61,6 +63,8 @@ pub(crate) const REASON_GROUPS: [(&str, &str); 7] = [ ("renamed", "Renamed"), ]; pub(crate) const SKIP_ACTION: &str = "skip"; +/// The row action of a model that can't be planned. +pub(crate) const ERROR_ACTION: &str = "error"; pub(crate) const CREATE_VIEW_ACTION: &str = "create_view"; pub(crate) const CUSTOM_ACTION: &str = "custom"; pub(crate) const CREATE_DYNAMIC_ACTION: &str = "create_dynamic"; @@ -99,3 +103,6 @@ pub(crate) const DBT_NO_MATCH_WARNING: &str = "No dbt or SQLBuild resources matc pub(crate) const DBT_RESOURCE_FALLBACK_TYPE: &str = "resource"; /// An inline error wraps to at most this many lines before it is truncated. pub(crate) const MAX_INLINE_ERROR_LINES: usize = 2; + +/// How a full build's unbounded cursor range ends in plan text. +pub(crate) const UNBOUNDED_RANGE: &str = "(unbounded)"; diff --git a/crates/sqlbuild-core/src/cli_text/models.rs b/crates/sqlbuild-core/src/cli_text/models.rs index 473141944c..91ec3eba16 100644 --- a/crates/sqlbuild-core/src/cli_text/models.rs +++ b/crates/sqlbuild-core/src/cli_text/models.rs @@ -326,6 +326,8 @@ pub struct ModelPlanText { pub reinitialised_by: Option, /// Whether the warehouse lists this kept dynamic model as suspended. pub paused: bool, + /// Why a skipped model is shown anyway, such as `window ends before cursor_start 2021-01-01`. + pub skip_reason: Option, } /// One planned function. diff --git a/crates/sqlbuild-core/src/plan_display/_helpers/plan_pages.rs b/crates/sqlbuild-core/src/plan_display/_helpers/plan_pages.rs index bf15c5a3eb..f59281930a 100644 --- a/crates/sqlbuild-core/src/plan_display/_helpers/plan_pages.rs +++ b/crates/sqlbuild-core/src/plan_display/_helpers/plan_pages.rs @@ -13,7 +13,12 @@ use crate::plan_display::constants::{ use crate::plan_display::models::PlanPageSection; /// Every section, in the order the plan reads, with its name in the API. -pub(crate) const SECTIONS: [(PlanPageSection, &str); 25] = [ +pub(crate) const SECTIONS: [(PlanPageSection, &str); 27] = [ + (PlanPageSection::PlanningError, "planning_error"), + ( + PlanPageSection::WindowBeforeCursorStart, + "window_before_cursor_start", + ), (PlanPageSection::FullRefresh, "full_refresh"), (PlanPageSection::QueryChanged, "query_changed"), (PlanPageSection::FunctionChanged, "function_changed"), @@ -45,7 +50,12 @@ pub(crate) const SECTIONS: [(PlanPageSection, &str); 25] = [ ]; /// A model's section by its plan reason; reasons without their own section build as routine models. -const MODEL_REASONS: [(&str, PlanPageSection); 7] = [ +const MODEL_REASONS: [(&str, PlanPageSection); 9] = [ + ("planning_error", PlanPageSection::PlanningError), + ( + "window_before_cursor_start", + PlanPageSection::WindowBeforeCursorStart, + ), ("full_refresh", PlanPageSection::FullRefresh), ("query_changed", PlanPageSection::QueryChanged), ("function_changed", PlanPageSection::FunctionChanged), @@ -154,9 +164,13 @@ impl<'document> PlanRows<'document> { } fn models(&self, section: PlanPageSection) -> Vec<&'document Value> { + let shown_anyway: bool = matches!( + section, + PlanPageSection::PlanningError | PlanPageSection::WindowBeforeCursorStart + ); self.kept("models", |model| { - text(model, "action") != SKIP_ACTION - && self.runs_node(&node_key("model", model)) + (shown_anyway || text(model, "action") != SKIP_ACTION) + && (shown_anyway || self.runs_node(&node_key("model", model))) && model_section(model) == section }) } diff --git a/crates/sqlbuild-core/src/plan_display/models.rs b/crates/sqlbuild-core/src/plan_display/models.rs index 51244eb2fb..012b1462c8 100644 --- a/crates/sqlbuild-core/src/plan_display/models.rs +++ b/crates/sqlbuild-core/src/plan_display/models.rs @@ -36,6 +36,10 @@ pub struct TimestampGrainFacts { /// A plan section a summary counts and the rows endpoint pages, in the order the plan reads. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PlanPageSection { + /// Models that couldn't be planned, with their errors. + PlanningError, + /// Models an explicit cursor window skips, as it ends before their `cursor_start`. + WindowBeforeCursorStart, /// Built models the plan rebuilds in full. FullRefresh, QueryChanged, diff --git a/crates/sqlbuild-core/src/plan_display/tests/helpers.rs b/crates/sqlbuild-core/src/plan_display/tests/helpers.rs index 612c157398..92c83300cf 100644 --- a/crates/sqlbuild-core/src/plan_display/tests/helpers.rs +++ b/crates/sqlbuild-core/src/plan_display/tests/helpers.rs @@ -95,6 +95,8 @@ pub(super) fn full_plan() -> serde_json::Value { planned_model("events", ("incremental_merge", "normal_incremental")), planned_model("skipped_model", ("skip", "no_change")), planned_model("not_run", ("create_view", "no_change")), + planned_model("unplannable", ("error", "planning_error")), + planned_model("late_feed", ("skip", "window_before_cursor_start")), ], "seeds": [ {"name": "countries", "reason": "first_run"}, diff --git a/crates/sqlbuild-core/src/plan_display/tests/test_plan_pages.rs b/crates/sqlbuild-core/src/plan_display/tests/test_plan_pages.rs index ace9bf29fd..a6054d4b8f 100644 --- a/crates/sqlbuild-core/src/plan_display/tests/test_plan_pages.rs +++ b/crates/sqlbuild-core/src/plan_display/tests/test_plan_pages.rs @@ -14,6 +14,16 @@ use crate::plan_display::tests::test_types::{ #[test] fn given_a_plan_when_paging_each_section_then_every_section_pages_its_rows_in_plan_order() { let test_cases = [ + SectionTestCase { + description: "models that can't be planned, though --changed doesn't run them", + section: PlanPageSection::PlanningError, + expected_rows: &["unplannable"], + }, + SectionTestCase { + description: "models an explicit window skips, though skipped and not run by --changed", + section: PlanPageSection::WindowBeforeCursorStart, + expected_rows: &["late_feed"], + }, SectionTestCase { description: "full refresh", section: PlanPageSection::FullRefresh, @@ -339,28 +349,38 @@ fn given_model_pages_when_read_then_rows_carry_diff_counts_runs_warnings_and_win fn given_a_plan_when_summarised_then_sections_are_counts_and_no_row_list_is_left() { let test_cases = [ SummaryFieldTestCase { - description: "the first section", + description: "models that can't be planned first", pointer: "/sections/0/section", + expected_value: json!("planning_error"), + }, + SummaryFieldTestCase { + description: "then models the window skips", + pointer: "/sections/1/section", + expected_value: json!("window_before_cursor_start"), + }, + SummaryFieldTestCase { + description: "then full refresh", + pointer: "/sections/2/section", expected_value: json!("full_refresh"), }, SummaryFieldTestCase { description: "routine models after the changes", - pointer: "/sections/7/section", + pointer: "/sections/9/section", expected_value: json!("routine_models"), }, SummaryFieldTestCase { description: "warnings last", - pointer: "/sections/24/section", + pointer: "/sections/26/section", expected_value: json!("warnings"), }, SummaryFieldTestCase { description: "no section beyond the plan's", - pointer: "/sections/25", + pointer: "/sections/27", expected_value: Value::Null, }, SummaryFieldTestCase { description: "a section's size", - pointer: "/sections/5/total", + pointer: "/sections/7/total", expected_value: json!(2), }, SummaryFieldTestCase { 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 8f6f33e738..61df78a37f 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs @@ -30,9 +30,7 @@ use crate::node_states::models::{NodeStateCache, NodeStatesRecord}; use crate::platform::main::health::read_person_location_health::read_person_location_health; use crate::platform::main::person_reads::list_person_platform_events::list_person_platform_events; use crate::platform::main::person_reads::read_person_problems::read_person_problems; -use crate::platform::models::{ - LocationHealthObservation, PersonPlatformEventPage, PlatformProblems, -}; +use crate::platform::models::{PersonLocationHealth, PersonPlatformEventPage, PlatformProblems}; use crate::run_output::main::download_person_output::download_person_output; use crate::run_output::main::read_person_output_index::read_person_output_index; use crate::run_output::main::read_person_output_page::read_person_output_page; @@ -820,7 +818,7 @@ pub(crate) async fn snapshots( #[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/health", operation_id = "readPersonLocationHealth", params(("location_id" = Uuid, Path), ("target" = String, Path)), - responses((status = 200, body = Vec, description = "This target's newest health observations and instance check-ins"), + responses((status = 200, body = PersonLocationHealth, description = "This target's state and the newest health observations and instance check-ins it was computed from"), (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), security(("session" = []), ("cliSession" = [])))] pub(crate) async fn health( @@ -828,7 +826,7 @@ pub(crate) async fn health( (Extension(default_role), Extension(facts)): (Extension, Extension), Path((location_id, target)): Path<(Uuid, String)>, Extension(AuthenticatedPerson(principal, _)): Extension, -) -> Result>, ApiError> { +) -> Result, ApiError> { Ok(Json( read_person_location_health( &store, diff --git a/crates/sqlbuild-orchestration/src/dev_events/models.rs b/crates/sqlbuild-orchestration/src/dev_events/models.rs index ef60d461c7..31722bd2d0 100644 --- a/crates/sqlbuild-orchestration/src/dev_events/models.rs +++ b/crates/sqlbuild-orchestration/src/dev_events/models.rs @@ -54,11 +54,10 @@ pub enum DevEvent { Changed { paths: Vec, more: usize }, /// The interpreter restarted because Python sources changed. Restarted { reason: String }, - /// A generation was published; `record` is the publication record `sqb location serve` prints. + /// A generation was published as `snapshot_id`. Published { generation: i64, snapshot_id: String, - record: serde_json::Value, }, /// A generation failed; the last good generation keeps serving. Failed { diff --git a/crates/sqlbuild-orchestration/src/node_states/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/node_states/_helpers/mod.rs index a2ec04a89f..76cf267091 100644 --- a/crates/sqlbuild-orchestration/src/node_states/_helpers/mod.rs +++ b/crates/sqlbuild-orchestration/src/node_states/_helpers/mod.rs @@ -2,4 +2,5 @@ pub(crate) mod authorized; pub(crate) mod bodies; pub(crate) mod checks; pub(crate) mod reads; +pub(crate) mod status; pub(crate) mod views; diff --git a/crates/sqlbuild-orchestration/src/node_states/_helpers/reads.rs b/crates/sqlbuild-orchestration/src/node_states/_helpers/reads.rs index c319ace18d..887cd2c1cc 100644 --- a/crates/sqlbuild-orchestration/src/node_states/_helpers/reads.rs +++ b/crates/sqlbuild-orchestration/src/node_states/_helpers/reads.rs @@ -1,11 +1,12 @@ //! One read-only transaction reads the current snapshot's catalog, unless it is already held, and every node's state. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; use serde_json::{Map, Value}; use uuid::Uuid; +use crate::node_states::_helpers::status::{StatusNode, apply_statuses}; use crate::node_states::models::{ChangedBuild, ChangedBuildNodes, NodeState, SnapshotCatalog}; use crate::snapshots::main::reads::read_current_record::read_current_record; use crate::snapshots::main::reads::read_snapshot_nodes::read_snapshot_nodes; @@ -19,10 +20,17 @@ use crate::warehouse_metadata::main::node_reads::{ destination::destination, last_outcome::last_outcome, latest_attempts::latest_attempts, latest_fingerprints::latest_fingerprints, }; -use crate::warehouse_metadata::models::{CatalogNodeBuild, DefinitionEvidence, FingerprintQuery}; +use crate::warehouse_metadata::models::{ + CatalogNodeBuild, CatalogNodeOutcome, DefinitionEvidence, FingerprintQuery, +}; -/// The definition fields node states read: the name and destination of builds, and the planner identity. -const STATE_FIELDS: [&str; 3] = ["name", "destination", "planner_identity"]; +/// The definition fields node states read: build name and destination, planner identity, a source's loader entry. +const STATE_FIELDS: [&str; 4] = ["name", "destination", "planner_identity", "entry"]; +/// The snapshot node kinds of a Python loader, which runs under the key of each source it loads, and a source. +const LOADER_KIND: &str = "loader"; +const SOURCE_KIND: &str = "source"; +const VIEW_MATERIALIZATION: &str = "view"; +const FAILED_OUTCOME: &str = "failed"; /// A target's read: its catalog, every node's state, and the changed build planned for the current snapshot. pub(crate) type TargetRead = ( @@ -48,8 +56,7 @@ pub(crate) async fn read_target( (transaction, Arc::new(snapshot_catalog(snapshot_id, nodes))) } }; - let (transaction, states) = - node_states(transaction, (location_id, target), &catalog.inputs).await?; + let (transaction, states) = node_states(transaction, (location_id, target), &catalog).await?; let (transaction, changed_build) = changed_build(transaction, (location_id, target)).await?; commit(transaction).await?; Ok((catalog, states, changed_build)) @@ -121,12 +128,13 @@ fn snapshot_catalog(snapshot_id: Uuid, nodes: BTreeMap) -> } } -/// Builds are batched indexed seeks; attempts and check results are one read each. +/// Builds are batched indexed seeks; attempts and check results are one read each. Statuses are worked out last, over every node. async fn node_states( transaction: ControlTransaction, (location_id, target): (Uuid, &str), - nodes: &[(String, SnapshotNode)], + catalog: &SnapshotCatalog, ) -> Result<(ControlTransaction, BTreeMap), ControlError> { + let nodes: &[(String, SnapshotNode)] = &catalog.inputs; let mut positions: Vec = Vec::new(); let mut queries: Vec = Vec::new(); for (position, (_, node)) in nodes.iter().enumerate() { @@ -137,7 +145,8 @@ async fn node_states( } let (transaction, found) = latest_fingerprints(transaction, (location_id, target, &queries)).await?; - let (transaction, mut attempts) = latest_attempts(transaction, (location_id, target)).await?; + let (transaction, attempts) = latest_attempts(transaction, (location_id, target)).await?; + let loaded: HashMap<&str, Vec<&str>> = loaded_sources(nodes); let (transaction, mut checks) = read_node_check_counts(transaction, (location_id, target)).await?; let (transaction, evidences) = definition_evidences( @@ -159,11 +168,19 @@ async fn node_states( version_hash: record.version_hash, }); } + let tables: Vec = { + let mut tables = vec![false; nodes.len()]; + positions + .iter() + .for_each(|position| tables[*position] = true); + tables + }; let states: BTreeMap = nodes .iter() .zip(builds.into_iter().zip(changed)) .map(|((key, node), (last_build, definition_changed))| { - let last_outcome = last_outcome(attempts.remove(key.as_str()), last_build.as_ref()); + let attempt = newest_attempt(&attempts, key, node, &loaded); + let last_outcome = last_outcome(attempt, last_build.as_ref()); let checks = checks .remove(key.as_str()) .or_else(|| checks.remove(&format!("{}:{key}", node.kind))) @@ -175,9 +192,65 @@ async fn node_states( last_outcome, definition_changed, checks, + ..NodeState::default() }, ) }) .collect(); + let listed: HashSet<&str> = nodes.iter().map(|(key, _)| key.as_str()).collect(); + let status_nodes: Vec> = nodes + .iter() + .zip(&catalog.records) + .zip(tables) + .map(|(((key, node), record), has_table)| StatusNode { + key, + kind: &node.kind, + has_table, + view: record.materialization.as_deref() == Some(VIEW_MATERIALIZATION), + upstream: listed_upstream(&record.dependencies, &listed), + }) + .collect(); + let states = apply_statuses(&status_nodes, states); Ok((transaction, states)) } + +/// The dependencies that are themselves listed, as the catalog draws them. +fn listed_upstream<'a>(dependencies: &'a [String], listed: &HashSet<&str>) -> Vec<&'a str> { + dependencies + .iter() + .map(String::as_str) + .filter(|upstream| listed.contains(upstream)) + .collect() +} + +/// Each loader's name and the keys of the sources it loads, whose runs record its work. +pub(crate) fn loaded_sources(nodes: &[(String, SnapshotNode)]) -> HashMap<&str, Vec<&str>> { + let mut loaded: HashMap<&str, Vec<&str>> = HashMap::new(); + for (key, node) in nodes.iter().filter(|(_, node)| node.kind == SOURCE_KIND) { + if let Some(loader) = node.definition["entry"]["loader"].as_str() { + loaded.entry(loader).or_default().push(key); + } + } + loaded +} + +/// A node's newest attempt; a loader's is the newest of the sources it loads, a failure first on a tie. +pub(crate) fn newest_attempt( + attempts: &HashMap, + key: &str, + node: &SnapshotNode, + loaded: &HashMap<&str, Vec<&str>>, +) -> Option { + let own = attempts.get(key); + let sources = (node.kind == LOADER_KIND) + .then(|| node.definition["name"].as_str()) + .flatten() + .and_then(|name| loaded.get(name)) + .into_iter() + .flatten() + .filter_map(|source| attempts.get(*source)); + own.into_iter() + .chain(sources) + .max_by_key(|attempt| (attempt.at, attempt.status == FAILED_OUTCOME)) + .cloned() +} diff --git a/crates/sqlbuild-orchestration/src/node_states/_helpers/status.rs b/crates/sqlbuild-orchestration/src/node_states/_helpers/status.rs new file mode 100644 index 0000000000..50a893d944 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/node_states/_helpers/status.rs @@ -0,0 +1,139 @@ +//! Each node's one build status, worked out once over a target's states so every page shows the same. + +use std::cell::RefCell; +use std::collections::{BTreeMap, HashMap}; + +use chrono::{DateTime, Utc}; + +use crate::node_states::models::{NodeBuildStatus, NodeState}; + +/// What a node's status depends on apart from its own state. +pub(crate) struct StatusNode<'a> { + pub(crate) key: &'a str, + /// The snapshot node kind, such as `model`, `source` or `asset`. + pub(crate) kind: &'a str, + /// Whether it builds a warehouse object whose builds are fingerprinted. + pub(crate) has_table: bool, + /// A view reads its upstream when queried, so it is never behind. + pub(crate) view: bool, + /// The listed nodes it reads. + pub(crate) upstream: Vec<&'a str>, +} + +/// A status and when it was reached. +type Status = (NodeBuildStatus, Option>); + +const SOURCE_KIND: &str = "source"; +const FAILED_OUTCOME: &str = "failed"; +const SUCCEEDED_OUTCOMES: [&str; 2] = ["success", "warn"]; + +/// When the data each node reads last changed, worked out once per node; a cycle reads as no data. +struct DataTimes<'a> { + nodes: HashMap<&'a str, &'a StatusNode<'a>>, + states: &'a BTreeMap, + known: RefCell>>>, +} + +impl<'a> DataTimes<'a> { + /// A node's own last build, or for a view the newest data behind it. + fn at(&self, key: &'a str) -> Option> { + if let Some(known) = self.known.borrow().get(key) { + return *known; + } + self.known.borrow_mut().insert(key, None); + let time = match self.nodes.get(key) { + Some(node) if node.view => node.upstream.iter().filter_map(|up| self.at(up)).max(), + _ => self + .states + .get(key) + .and_then(|state| state.last_build.as_ref()) + .map(|build| build.observed_at), + }; + self.known.borrow_mut().insert(key, time); + time + } + + /// Whether an upstream node has newer data than this node's last build; views and unbuilt nodes never are. + fn behind(&self, node: &'a StatusNode<'a>, state: &NodeState) -> bool { + let Some(build) = state + .last_build + .as_ref() + .filter(|_| node.has_table && !node.view) + else { + return false; + }; + node.upstream + .iter() + .any(|upstream| self.at(upstream).is_some_and(|at| at > build.observed_at)) + } +} + +/// `states` with every node's `status` and `status_at` set. +pub(crate) fn apply_statuses( + nodes: &[StatusNode<'_>], + states: BTreeMap, +) -> BTreeMap { + let statuses: HashMap = { + let times = DataTimes { + nodes: nodes.iter().map(|node| (node.key, node)).collect(), + states: &states, + known: RefCell::default(), + }; + nodes + .iter() + .filter_map(|node| { + let state = states.get(node.key)?; + Some(( + node.key.to_owned(), + status_of(node, state, times.behind(node, state)), + )) + }) + .collect() + }; + states + .into_iter() + .map(|(key, state)| { + let (status, status_at) = statuses + .get(&key) + .copied() + .unwrap_or((state.status, state.status_at)); + ( + key, + NodeState { + status, + status_at, + ..state + }, + ) + }) + .collect() +} + +/// A node's status and when it was reached, given whether it is behind its upstream. +fn status_of(node: &StatusNode<'_>, state: &NodeState, behind: bool) -> Status { + if node.kind == SOURCE_KIND { + return (NodeBuildStatus::Source, None); + } + let outcome = state.last_outcome.as_ref(); + if let Some(failed) = outcome.filter(|outcome| outcome.status == FAILED_OUTCOME) { + return (NodeBuildStatus::Failed, Some(failed.at)); + } + if !node.has_table { + return outcome + .filter(|outcome| SUCCEEDED_OUTCOMES.contains(&outcome.status.as_str())) + .map_or((NodeBuildStatus::NotBuilt, None), |outcome| { + (NodeBuildStatus::Current, Some(outcome.at)) + }); + } + let Some(build) = &state.last_build else { + return (NodeBuildStatus::NotBuilt, None); + }; + let status = if state.definition_changed { + NodeBuildStatus::Changed + } else if behind { + NodeBuildStatus::Behind + } else { + NodeBuildStatus::Current + }; + (status, Some(build.observed_at)) +} diff --git a/crates/sqlbuild-orchestration/src/node_states/main/report_changed_build.rs b/crates/sqlbuild-orchestration/src/node_states/main/report_changed_build.rs index 93b32c5858..f41123943f 100644 --- a/crates/sqlbuild-orchestration/src/node_states/main/report_changed_build.rs +++ b/crates/sqlbuild-orchestration/src/node_states/main/report_changed_build.rs @@ -27,13 +27,10 @@ pub async fn report_changed_build( )); } if report.failing.as_ref().is_some_and(|reason| { - reason.trim().is_empty() - || reason.chars().count() > MAX_FAILING_REASON_CHARS - || !report.changed.is_empty() - || !report.downstream.is_empty() + reason.trim().is_empty() || reason.chars().count() > MAX_FAILING_REASON_CHARS }) { return Err(ControlError::Invalid( - "a failing changed build carries a bounded reason and no nodes".into(), + "a failing changed build carries a bounded reason".into(), )); } let mut transaction = begin_ingestion( diff --git a/crates/sqlbuild-orchestration/src/node_states/models.rs b/crates/sqlbuild-orchestration/src/node_states/models.rs index 5ed2ec93b3..ffb9059f01 100644 --- a/crates/sqlbuild-orchestration/src/node_states/models.rs +++ b/crates/sqlbuild-orchestration/src/node_states/models.rs @@ -15,13 +15,38 @@ use crate::warehouse_metadata::models::{ CatalogNodeBuild, CatalogNodeChecks, CatalogNodeOutcome, CatalogNodeRecord, }; -/// The state fields of a `CatalogNodeRecord`, with the same meaning. +/// The state fields of a `CatalogNodeRecord`, with the same meaning, and the status every page shows. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] pub struct NodeState { pub last_build: Option, pub last_outcome: Option, pub definition_changed: bool, pub checks: CatalogNodeChecks, + /// The node's one build status, which pages show as it is. + #[serde(default)] + pub status: NodeBuildStatus, + /// When the status was reached: the last build, or the last run for a node without a table. + #[serde(default)] + pub status_at: Option>, +} + +/// Where a node stands: built and current, or why not. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum NodeBuildStatus { + /// Built, or run successfully for a node without a table, and up to date. + Current, + /// Its definition changed since its last build. + Changed, + /// An upstream node has newer data than its last build. + Behind, + /// Its last attempt failed. + Failed, + /// Never built, or never run for a node without a table. + #[default] + NotBuilt, + /// A source, which SQLBuild reads but never builds. + Source, } /// Every current node's state at one version; `snapshot_id` is null before the first publication. @@ -46,7 +71,7 @@ pub struct ChangedBuild { pub changed: Vec, /// Nodes that run only because an upstream they read runs. pub downstream: Vec, - /// Why the location's plan failed, with both lists empty; absent when it planned. + /// Why the location's plan failed or which models it couldn't plan, with the nodes it did plan; absent when every model planned. #[serde(default, skip_serializing_if = "Option::is_none")] pub failing: Option, } @@ -68,7 +93,7 @@ pub struct ChangedBuildReport { pub generation: i64, pub changed: Vec, pub downstream: Vec, - /// Why the plan failed, sent with empty lists. + /// Why the plan failed (empty lists) or which models it couldn't plan (the lists of the rest). #[serde(default, skip_serializing_if = "Option::is_none")] pub failing: Option, } diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/current_instance.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/current_instance.rs new file mode 100644 index 0000000000..7da035ad53 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/current_instance.rs @@ -0,0 +1,79 @@ +//! The newest location instance and whether its own first load has finished, from one target's observations. + +use chrono::{DateTime, TimeDelta, Utc}; +use uuid::Uuid; + +use crate::platform::constants::{LOCATION_RETENTION_DAYS, RECENT_HEALTH_LIMIT}; +use crate::platform::models::{LocationHealth, LocationHealthObservation}; + +/// Where the newest live instance of a target stands. +pub(crate) enum CurrentInstance { + /// Its first load has not finished: judge nothing from earlier instances. + Starting, + /// Its first load finished; its own reports from that load on are its health. + Loaded(Uuid), + /// The observations can't tell: an older location, or one whose start has left the history. + Unknown, +} + +/// The newest live instance, by its time-ordered session ID, and whether its first load finished. +pub(crate) fn current_instance( + (own, read): (&[&LocationHealthObservation], usize), + (silence, now): (TimeDelta, DateTime), +) -> CurrentInstance { + let Some(session) = own + .iter() + .filter(|observation| is_check_in(&observation.report.health)) + .filter(|observation| now - observation.received_at <= silence) + .map(|observation| observation.report.session_id) + .max() + else { + return CurrentInstance::Unknown; + }; + if own.iter().any(|observation| { + observation.report.session_id == session && is_load_outcome(&observation.report.health) + }) { + return CurrentInstance::Loaded(session); + } + let Some(started) = session_started(session) else { + return CurrentInstance::Unknown; + }; + if history_covers((own, read), (started, now)) { + CurrentInstance::Starting + } else { + CurrentInstance::Unknown + } +} + +/// A check-in: the instance's liveness row, which holds its newest heartbeat. +fn is_check_in(health: &LocationHealth) -> bool { + matches!(health, LocationHealth::Heartbeat {}) +} + +/// A report that ends a load: a failed compile, or the connection check that follows a publication. +fn is_load_outcome(health: &LocationHealth) -> bool { + matches!( + health, + LocationHealth::CompileFailed { .. } | LocationHealth::Connection { .. } + ) +} + +/// When the process that made a time-ordered (v7) session ID started; none for other IDs. +fn session_started(session: Uuid) -> Option> { + let (seconds, nanos) = session.get_timestamp()?.to_unix(); + DateTime::from_timestamp(i64::try_from(seconds).unwrap_or(i64::MAX), nanos) +} + +/// Whether the history reaches back to `started`: none of the `read` observations was cut off, or an older one is kept. +fn history_covers( + (own, read): (&[&LocationHealthObservation], usize), + (started, now): (DateTime, DateTime), +) -> bool { + if now - started > TimeDelta::days(LOCATION_RETENTION_DAYS) { + return false; + } + read < RECENT_HEALTH_LIMIT + || own.iter().any(|observation| { + !is_check_in(&observation.report.health) && observation.received_at <= started + }) +} diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/event_history.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/event_history.rs index 1744e52d75..fec91e0389 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/health/event_history.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/event_history.rs @@ -62,6 +62,11 @@ fn person_event( location_id, target, .. + } + | PlatformEvent::LocationFailing { + location_id, + target, + .. } => Some((*location_id, target.clone())), PlatformEvent::TickOverdue { trigger_id, .. } | PlatformEvent::CalendarHorizonLow { trigger_id, .. } diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_locations.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_locations.rs new file mode 100644 index 0000000000..1ad31d980b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_locations.rs @@ -0,0 +1,111 @@ +//! Checking-in locations whose latest load, plan of what changed, discovery or connection check failed. + +use chrono::TimeDelta; +use uuid::Uuid; + +use crate::discovered_sets::models::DiscoveredSetStatus; +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, +}; +use crate::snapshots::main::reads::read_current_record::read_current_record; +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 fact a degraded location reports, which carries no text of its own. +const CONNECTION_FAILED: &str = "the warehouse connection check after its last load failed"; + +/// 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> { + let now = transaction.now; + let (mut transaction, rows) = query( + transaction, + "SELECT DISTINCT i.location_id, l.name AS location_name, i.target \ + FROM sqb_location_instances i JOIN sqb_locations l ON l.location_id=i.location_id \ + WHERE l.archived_at IS NULL AND i.last_seen_at>=$1 ORDER BY l.name, i.target", + vec![Parameter::Time( + now - TimeDelta::seconds(LOCATION_SILENCE_SECONDS), + )], + ) + .await?; + let mut failing: Vec = Vec::new(); + for row in rows { + let LiveTarget { + location_id, + location_name, + target, + } = decode_row(row)?; + let target: &str = ⌖ + let observations; + (transaction, observations) = recent_health(transaction, location_id, Some(target)).await?; + let state = LocationState::of(&observations, (target, now)); + let Some((failed_at, error)) = deciding_report(&observations, state) else { + continue; + }; + let serving; + (transaction, serving) = read_current_record(transaction, (location_id, target)).await?; + failing.push(FailingLocation { + location_id, + location_name, + target: target.to_owned(), + state, + failed_at, + error, + serving, + }); + } + Ok((transaction, failing)) +} + +/// When the failure that decided `state` was reported and its text; `None` for a state that isn't a failure here. +fn deciding_report( + observations: &[LocationHealthObservation], + state: LocationState, +) -> Option<(chrono::DateTime, Option)> { + observations.iter().find_map(|observation| { + let at = observation.received_at; + match (&observation.report.health, state) { + (LocationHealth::CompileFailed { error, .. }, LocationState::FallingBack) => { + Some((at, error.clone())) + } + (LocationHealth::ChangePlanFailed { reason, .. }, LocationState::ChangePlanFailed) => { + Some((at, Some(reason.clone()))) + } + (LocationHealth::Discovery { sets, .. }, LocationState::DiscoveryFailed) => { + Some((at, Some(failed_sets(sets)?))) + } + (LocationHealth::Connection { healthy: false, .. }, LocationState::Degraded) => { + Some((at, Some(CONNECTION_FAILED.to_owned()))) + } + _ => None, + } + }) +} + +/// `name: error` of each failed set, joined; `None` when none failed. +fn failed_sets(sets: &[DiscoveryHealth]) -> Option { + let mut failed: Vec = Vec::new(); + for set in sets { + if set.status != DiscoveredSetStatus::Failed { + continue; + } + failed.push(match &set.error { + Some(error) => format!("{}: {error}", set.name), + None => set.name.clone(), + }); + } + (!failed.is_empty()).then(|| failed.join("; ")) +} + +/// A live location target, as the query reads it. +#[derive(serde::Deserialize)] +struct LiveTarget { + location_id: Uuid, + location_name: String, + target: String, +} diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/mod.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/mod.rs index 5e31e7e225..2f3b98c7b1 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/health/mod.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/mod.rs @@ -1,6 +1,8 @@ //! Health observations, live problems and the platform event history. +pub(crate) mod current_instance; pub(crate) mod event_history; +pub(crate) mod failing_locations; 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 8570fa1d55..e789c8561f 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/health/problems.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/problems.rs @@ -4,6 +4,7 @@ use chrono::{DateTime, TimeDelta, Utc}; use uuid::Uuid; use crate::declarations::models::Schedule; +use crate::platform::_helpers::health::failing_locations::failing_locations; use crate::platform::constants::LOCATION_SILENCE_SECONDS; use std::collections::BTreeSet; @@ -59,6 +60,7 @@ pub(crate) async fn scan_problems(store: &ControlStore) -> Result = schedules .into_iter() @@ -90,6 +92,7 @@ pub(crate) async fn scan_problems(store: &ControlStore) -> Result>()?, + failing, 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 7800fbbf9c..9cfabbef7c 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/health/recent_health.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/recent_health.rs @@ -2,8 +2,8 @@ use uuid::Uuid; -use crate::platform::constants::LOCATION_RETENTION_DAYS; -use crate::platform::models::LocationHealthObservation; +use crate::platform::constants::{LOCATION_RETENTION_DAYS, RECENT_HEALTH_LIMIT}; +use crate::platform::models::{LocationHealth, LocationHealthObservation, LocationHealthReport}; use crate::store::errors::ControlError; use crate::store::main::decode_row::decode_row; use crate::store::main::query::query; @@ -82,6 +82,54 @@ pub(crate) async fn recent_health( .collect::, _>>()?, ); observations.sort_by_key(|observation| std::cmp::Reverse(observation.received_at)); - observations.truncate(100); + observations.truncate(RECENT_HEALTH_LIMIT); + let Some(target) = target else { + return Ok((transaction, observations)); + }; + let (transaction, failed_plan) = failed_change_plan(transaction, (location_id, target)).await?; + if let Some(failed_plan) = failed_plan { + observations.push(failed_plan); + observations.sort_by_key(|observation| std::cmp::Reverse(observation.received_at)); + } Ok((transaction, observations)) } + +/// The location's plan of what changed on the current snapshot, as health when it failed: the server derives it, so the history's bound never drops it. +async fn failed_change_plan( + transaction: ControlTransaction, + (location_id, target): (Uuid, &str), +) -> Result<(ControlTransaction, Option), ControlError> { + let (transaction, rows) = query( + transaction, + "SELECT b.generation, b.reported_at, b.report_json->>'failing' AS failing FROM sqb_changed_builds b \ + JOIN sqb_current_snapshots c ON c.location_id=b.location_id AND c.target=b.target \ + JOIN sqb_snapshots s ON s.snapshot_id=c.snapshot_id \ + WHERE b.location_id=$1 AND b.target=$2 AND s.generation=b.generation", + vec![Parameter::Id(location_id), Parameter::Text(target.to_owned())], + ) + .await?; + let Some(row) = rows.into_iter().next() else { + return Ok((transaction, None)); + }; + let (Some(reason), Some(generation)) = (row["failing"].as_str(), row["generation"].as_i64()) + else { + return Ok((transaction, None)); + }; + let received_at = serde_json::from_value(row["reported_at"].clone()) + .map_err(|error| ControlError::Invalid(format!("stored changed build: {error}")))?; + Ok(( + transaction, + Some(LocationHealthObservation { + received_at, + report: LocationHealthReport { + event_id: Uuid::nil(), + session_id: Uuid::nil(), + target: target.to_owned(), + health: LocationHealth::ChangePlanFailed { + generation, + reason: reason.to_owned(), + }, + }, + }), + )) +} diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/location/liveness.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/location/liveness.rs index e3cf68e442..9e847be678 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/location/liveness.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/location/liveness.rs @@ -3,6 +3,7 @@ use chrono::TimeDelta; use uuid::Uuid; +use crate::platform::_helpers::health::failing_locations::failing_locations; use crate::platform::_helpers::health::observations::observe; use crate::platform::constants::LOCATION_SILENCE_SECONDS; use crate::platform::models::{PlatformEvent, WatchdogLocation}; @@ -63,3 +64,33 @@ pub(crate) async fn scan_location_page( commit(transaction).await?; Ok(next) } + +/// Every failing location once per failure: the time it was reported tells one failure from the next. +pub(crate) async fn observe_failing_locations( + store: &ControlStore, + installation_id: Uuid, +) -> Result<(), ControlError> { + let (mut transaction, failing) = + failing_locations(begin(store, TransactionMode::Write).await?).await?; + for location in failing { + let incident = Some(location.failed_at); + transaction = observe( + transaction, + installation_id, + ( + PlatformEvent::LocationFailing { + location_id: location.location_id, + target: location.target, + state: location.state, + failed_at: location.failed_at, + error: location.error, + serving_generation: location.serving.map(|snapshot| snapshot.generation), + }, + incident, + ), + ) + .await?; + } + commit(transaction).await?; + Ok(()) +} 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 130cbf2554..8f6adda9fa 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs @@ -24,6 +24,11 @@ pub(crate) fn reported_generation( "the server derives pool_capped health; a location cannot report it".into(), )); } + LocationHealth::ChangePlanFailed { .. } => { + return Err(ControlError::Invalid( + "the server derives change_plan_failed health; a location cannot report it".into(), + )); + } }; if generation.is_some_and(|generation| generation < 1) { return Err(ControlError::Invalid( diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/location/rule_findings.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/location/rule_findings.rs index c3349394db..f99ffd0f4f 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/location/rule_findings.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/location/rule_findings.rs @@ -1,15 +1,25 @@ //! The bounds a location's reported rule findings must stay within. -use crate::platform::constants::{MAX_REPORTED_RULE_FINDINGS, MAX_RULE_FINDING_CHARS}; +use crate::platform::constants::{ + MAX_PUBLISH_ERROR_CHARS, MAX_REPORTED_RULE_FINDINGS, MAX_RULE_FINDING_CHARS, +}; use crate::platform::models::{LocationHealth, LocationHealthReport}; use crate::store::errors::ControlError; -/// Refuse a compile failure whose rule findings exceed the reported bounds. +/// Refuse a compile failure whose error or rule findings exceed the reported bounds. pub(crate) fn check_rule_findings(report: &LocationHealthReport) -> Result<(), ControlError> { - let LocationHealth::CompileFailed { - rules: Some(rules), .. - } = &report.health - else { + let LocationHealth::CompileFailed { rules, error, .. } = &report.health else { + return Ok(()); + }; + if error + .as_deref() + .is_some_and(|error| error.chars().count() > MAX_PUBLISH_ERROR_CHARS) + { + return Err(ControlError::Invalid( + "location load error exceeds the reported bounds".into(), + )); + } + let Some(rules) = rules else { return Ok(()); }; let oversized = |text: &str| text.chars().count() > MAX_RULE_FINDING_CHARS; diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/watchdog.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/watchdog.rs index 5d217455cb..7c93f05fc3 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/watchdog.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/watchdog.rs @@ -6,7 +6,9 @@ use uuid::Uuid; use crate::platform::_helpers::health::observations::observe; use crate::platform::_helpers::health::problems::calendar_low; -use crate::platform::_helpers::location::liveness::scan_location_page; +use crate::platform::_helpers::location::liveness::{ + observe_failing_locations, scan_location_page, +}; use crate::platform::models::{InstallationHealth, PlatformEvent, WatchdogTrigger}; use crate::store::errors::ControlError; use crate::store::main::begin::begin; @@ -51,6 +53,9 @@ pub(crate) async fn scan_health( } tokio::task::yield_now().await; } + if !*shutdown.borrow() { + observe_failing_locations(store, health.installation_id).await?; + } let mut after = None; while !*shutdown.borrow() { after = scan_trigger_page(store, health.installation_id, after).await?; diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/plans/load_failure.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/plans/load_failure.rs new file mode 100644 index 0000000000..0f30588101 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/plans/load_failure.rs @@ -0,0 +1,86 @@ +//! A plan can't wait for a location that can't load the current code: it fails with the load's error. + +use serde_json::json; +use uuid::Uuid; + +use crate::platform::models::{ + LocationHealth, LocationHealthObservation, LocationHealthReport, LocationWorkOutcome, + LocationWorkResult, +}; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{ControlTransaction, Parameter}; + +/// The plan error's code when the location's newest load failed. +pub(crate) const LOAD_FAILED_CODE: &str = "location_load_failed"; +/// The error of a load from an older location, which reports no error text. +const UNREPORTED_LOAD_ERROR: &str = "the location's output has the error"; + +/// Why a plan can't run: the location's newest load failed, with its error. +pub(crate) fn load_failure_message(error: Option<&str>) -> String { + format!( + "the location can't load the current code, so it can't plan: {}", + error.unwrap_or(UNREPORTED_LOAD_ERROR) + ) +} + +/// The error of the newest failed load among `observations`, newest first. +pub(crate) fn newest_load_error(observations: &[LocationHealthObservation]) -> Option<&str> { + observations + .iter() + .find_map(|observation| match &observation.report.health { + LocationHealth::CompileFailed { error, .. } => Some(error.as_deref()), + _ => None, + }) + .flatten() +} + +/// Finish every plan still waiting on the target with the failed load's error, as if the location had answered it. +pub(crate) async fn fail_waiting_plans( + transaction: ControlTransaction, + (location_id, target, session_id): (Uuid, &str, Uuid), + error: Option<&str>, +) -> Result { + let message = load_failure_message(error); + let result = LocationWorkResult { + claim_id: Uuid::nil(), + session_id, + outcome: LocationWorkOutcome::Plan { + document: json!({"error": {"code": LOAD_FAILED_CODE, "message": message}}), + diffs: Default::default(), + }, + }; + let now = transaction.now; + let (transaction, _) = query( + transaction, + "UPDATE sqb_location_work SET result_json=$4, completed_at=$5 \ + WHERE location_id=$1 AND target=$2 AND completed_at IS NULL AND expires_at>$3 \ + AND request_json->'work'->>'kind'='plan'", + vec![ + Parameter::Id(location_id), + Parameter::Text(target.to_owned()), + Parameter::Time(now), + Parameter::Json(json!(result)), + Parameter::Time(now), + ], + ) + .await?; + Ok(transaction) +} + +/// `fail_waiting_plans` when `report` is a failed load; other reports leave plans waiting. +pub(crate) async fn fail_plans_on_failed_load( + transaction: ControlTransaction, + location_id: Uuid, + report: &LocationHealthReport, +) -> Result { + let LocationHealth::CompileFailed { error, .. } = &report.health else { + return Ok(transaction); + }; + fail_waiting_plans( + transaction, + (location_id, &report.target, report.session_id), + error.as_deref(), + ) + .await +} diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/plans/mod.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/plans/mod.rs index 200629012f..fbcff37f16 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/plans/mod.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/plans/mod.rs @@ -1,4 +1,5 @@ //! Who may read a person's plan, and the model diffs stored beside it. +pub(crate) mod load_failure; pub(crate) mod plan_access; pub(crate) mod plan_diffs; diff --git a/crates/sqlbuild-orchestration/src/platform/constants.rs b/crates/sqlbuild-orchestration/src/platform/constants.rs index 68208c86af..df0ee1a34e 100644 --- a/crates/sqlbuild-orchestration/src/platform/constants.rs +++ b/crates/sqlbuild-orchestration/src/platform/constants.rs @@ -44,6 +44,9 @@ pub(crate) const PLAN_EXPIRY_SECONDS: i64 = 600; /// Unfinished plans one target accepts across everyone; each person may have one. pub(crate) const PLAN_QUEUE_LIMIT: i64 = 4; +/// The most health observations a read keeps, newest first. +pub(crate) const RECENT_HEALTH_LIMIT: usize = 100; + /// A location instance unseen for longer than this cannot take a plan; locations report every 30 seconds. pub(crate) const LOCATION_SILENCE_SECONDS: i64 = 90; diff --git a/crates/sqlbuild-orchestration/src/platform/main/health/load_failure_refusal.rs b/crates/sqlbuild-orchestration/src/platform/main/health/load_failure_refusal.rs new file mode 100644 index 0000000000..ff852b7646 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/main/health/load_failure_refusal.rs @@ -0,0 +1,21 @@ +//! A plan can't wait for a location that can't load the current code. + +use uuid::Uuid; + +use crate::platform::_helpers::health::recent_health::recent_health; +use crate::platform::_helpers::plans::load_failure::{load_failure_message, newest_load_error}; +use crate::platform::models::LocationState; +use crate::store::errors::ControlError; +use crate::store::models::ControlTransaction; + +/// The error a plan request fails with while the target's newest load failed; `None` while it loads. +pub(crate) async fn load_failure_refusal( + transaction: ControlTransaction, + (location_id, target): (Uuid, &str), +) -> Result<(ControlTransaction, Option), ControlError> { + let now = transaction.now; + let (transaction, observations) = recent_health(transaction, location_id, Some(target)).await?; + let refusal = (LocationState::of(&observations, (target, now)) == LocationState::FallingBack) + .then(|| load_failure_message(newest_load_error(&observations))); + Ok((transaction, refusal)) +} diff --git a/crates/sqlbuild-orchestration/src/platform/main/health/mod.rs b/crates/sqlbuild-orchestration/src/platform/main/health/mod.rs index 4e744280bb..6d8568f032 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/health/mod.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/health/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod load_failure_refusal; pub mod location_health; pub mod missing_provider_secrets; pub mod read_person_connection_test; diff --git a/crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs b/crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs index 37771872c6..786e00135b 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/health/read_person_location_health.rs @@ -10,19 +10,19 @@ use crate::platform::_helpers::health::pool_cap_warnings::{ pool_cap_observation, pool_cap_warnings, }; use crate::platform::_helpers::health::recent_health::recent_health; -use crate::platform::models::LocationHealthObservation; +use crate::platform::models::{LocationState, PersonLocationHealth}; use crate::snapshots::main::reads::read_current_record::read_current_record; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit}; use crate::store::models::{ControlStore, TransactionMode}; -/// The location's newest observations for this target only, newest first, with this server's pool-cap warning on the current snapshot. +/// The target's state and its newest observations for this target only, newest first, with this server's pool-cap warning on the current snapshot. pub async fn read_person_location_health( store: &ControlStore, (context, credentials): (&AuditContext, Uuid), (location_id, target): (Uuid, &str), (default_role, caps): (DefaultRole, &ServerPoolCaps), -) -> Result, ControlError> { +) -> Result { let (transaction, _) = authorize_listing( begin(store, TransactionMode::Write).await?, (context, credentials), @@ -30,8 +30,10 @@ pub async fn read_person_location_health( default_role, ) .await?; + let now = transaction.now; let (transaction, mut observations) = recent_health(transaction, location_id, Some(target)).await?; + let state = LocationState::of(&observations, (target, now)); let (transaction, snapshot) = read_current_record(transaction, (location_id, target)).await?; let (transaction, jobs) = current_jobs(transaction, (location_id, target), caps).await?; commit(transaction).await?; @@ -41,5 +43,8 @@ pub async fn read_person_location_health( observations.push(warning); observations.sort_by_key(|observation| std::cmp::Reverse(observation.received_at)); } - Ok(observations) + Ok(PersonLocationHealth { + state, + observations, + }) } 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 1d8606121b..32682eb088 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 @@ -1,5 +1,6 @@ //! Append scoped location observations without turning health into mutable lifecycle state. +use chrono::{DateTime, Utc}; use serde_json::json; use uuid::Uuid; @@ -7,6 +8,7 @@ use crate::platform::_helpers::location::location_heartbeat::location_heartbeat; use crate::platform::_helpers::location::published_generation::require_published_generation; 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::store::errors::ControlError; use crate::store::main::append_control_event::append_control_event; @@ -28,17 +30,15 @@ pub async fn report_location_health( commit(transaction).await?; return Ok(applied); } - let invocation_id = format!("location/{location_id}/{}", transaction.now.date_naive()); - let event_id = Uuid::new_v5(&location_id, report.event_id.as_bytes()); - let payload = json!({"location_id": location_id, "report": report}); + let event = health_event(location_id, report, transaction.now); let (transaction, previous) = query( transaction, "SELECT payload FROM recall_events WHERE event_id=$1 LIMIT 1", - vec![Parameter::Text(event_id.to_string())], + vec![Parameter::Text(event.event_id.to_string())], ) .await?; if let Some(previous) = previous.first() { - if previous.get("payload") != Some(&payload) { + if previous.get("payload") != Some(&event.payload) { return Err(ControlError::Invalid( "location health event ID already has different content".into(), )); @@ -56,25 +56,30 @@ pub async fn report_location_health( return Err(ControlError::Invalid("active location is required".into())); } let transaction = require_published_generation(transaction, location_id, report).await?; - let occurred_at = transaction.now; - let (transaction, outcome) = append_control_event( - transaction, - ControlEvent { - event_id, - invocation_id, - event_type: "location_health", - producer: "location", - occurred_at, - run_id: None, - payload, - }, - ) - .await?; + let (transaction, outcome) = append_control_event(transaction, event).await?; if outcome.conflict.is_some() { return Err(ControlError::Invalid( "location health conflicts with a durable fact".into(), )); } + let transaction = fail_plans_on_failed_load(transaction, location_id, report).await?; commit(transaction).await?; Ok(true) } + +/// The durable event of a report: one ID per location and report, so a retried report is the same event. +fn health_event( + location_id: Uuid, + report: &LocationHealthReport, + now: DateTime, +) -> ControlEvent<'static> { + ControlEvent { + event_id: Uuid::new_v5(&location_id, report.event_id.as_bytes()), + invocation_id: format!("location/{location_id}/{}", now.date_naive()), + event_type: "location_health", + producer: "location", + occurred_at: now, + run_id: None, + payload: json!({"location_id": location_id, "report": report}), + } +} diff --git a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_plan_rows.rs b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_plan_rows.rs index ab8e0209b0..3ce5acc057 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_plan_rows.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_plan_rows.rs @@ -51,6 +51,8 @@ pub async fn read_person_plan_rows( /// The plan display's section for the API's. fn page_section(section: PlanRowSection) -> PlanPageSection { match section { + PlanRowSection::PlanningError => PlanPageSection::PlanningError, + PlanRowSection::WindowBeforeCursorStart => PlanPageSection::WindowBeforeCursorStart, PlanRowSection::FullRefresh => PlanPageSection::FullRefresh, PlanRowSection::QueryChanged => PlanPageSection::QueryChanged, PlanRowSection::FunctionChanged => PlanPageSection::FunctionChanged, 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 43a7818ff8..e26518951f 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 @@ -23,6 +23,11 @@ pub async fn read_person_problems( .broken .iter() .map(|location| (location.location_id, location.target.clone())) + .chain( + scan.failing + .iter() + .map(|location| (location.location_id, location.target.clone())), + ) .chain(scan.late_targets.iter().cloned()) .chain( scan.low_calendars @@ -69,6 +74,11 @@ pub async fn read_person_problems( .into_iter() .filter(|location| listed.contains(&(location.location_id, location.target.clone()))) .collect(), + failing_locations: scan + .failing + .into_iter() + .filter(|location| listed.contains(&(location.location_id, location.target.clone()))) + .collect(), 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 0e5e4355b2..68e80b10ff 100644 --- a/crates/sqlbuild-orchestration/src/platform/models.rs +++ b/crates/sqlbuild-orchestration/src/platform/models.rs @@ -4,6 +4,7 @@ use crate::api::models::ControlClient; 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::sensors::models::{SensorEvaluationRequest, SensorFunctionOutcome}; use crate::snapshots::models::{SnapshotRecord, SnapshotRetention}; @@ -46,6 +47,9 @@ pub enum LocationHealth { /// The configured rules' findings when they failed the load; absent for other failures and from older locations. #[serde(default, skip_serializing_if = "Option::is_none")] rules: Option, + /// Why the load failed, redacted and bounded; absent from older locations. + #[serde(default, skip_serializing_if = "Option::is_none")] + error: Option, }, Connection { generation: i64, @@ -70,6 +74,11 @@ pub enum LocationHealth { generation: i64, sets: Vec, }, + /// The location's plan of what changed on the current snapshot failed, derived by the server from that plan, never reported by a location. + ChangePlanFailed { + generation: i64, + reason: String, + }, /// Jobs and groups this server's `pool_caps` clamp, derived by the server, never reported by a location. PoolCapped { generation: i64, @@ -189,15 +198,27 @@ pub struct LocationHealthObservation { pub report: LocationHealthReport, } +/// A target's health as people read it: its state, computed only here, and the newest observations it was computed from. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct PersonLocationHealth { + pub state: LocationState, + /// Newest first, with this server's pool-cap warning on the current snapshot. + pub observations: Vec, +} + /// One target's state from its newest health observations, as the web UI shows it. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "snake_case")] pub enum LocationState { + /// The newest instance has not finished its first load; it reports nothing yet, and earlier instances don't count. + Starting, Healthy, /// The warehouse connection check after the last load failed. Degraded, /// The last load failed, so runs use the previous snapshot. FallingBack, + /// The plan of what changed on the current snapshot failed, so what needs building is unknown. + ChangePlanFailed, /// A provider secret is unset in the location's environment, so runs that use the provider fail. MissingSecrets, /// A discover function failed at the last publication, so its set serves its last good items or none. @@ -207,7 +228,7 @@ pub enum LocationState { } impl LocationState { - /// `target`'s state at `now` from observations that may cover several targets: down without a recent check-in, then a failed load, then missing provider secrets, then a failed discover function, then a failed connection. + /// `target`'s state at `now`: down without a recent check-in, starting until the newest instance's first load finishes, then from that instance's reports a failed load (the newest load report by arrival decides, as failed loads keep the generation they tried), missing secrets, the server's record of a failed plan of what changed, a failed discover function, then a failed connection. #[must_use] pub fn of( observations: &[LocationHealthObservation], @@ -225,24 +246,34 @@ impl LocationState { }) { return Self::Broken; } - let mut failed: Option<(DateTime, i64)> = None; - let mut connection: Option<(DateTime, i64, bool)> = None; + let change_plan_failed: bool = own.iter().any(|observation| { + matches!( + observation.report.health, + LocationHealth::ChangePlanFailed { .. } + ) + }); + let own: Vec<&LocationHealthObservation> = + match current_instance((&own, observations.len()), (silence, now)) { + CurrentInstance::Starting => return Self::Starting, + CurrentInstance::Loaded(session) => own + .into_iter() + .filter(|observation| observation.report.session_id == session) + .collect(), + CurrentInstance::Unknown => own, + }; + let mut load: Option<(DateTime, LoadReport)> = None; let mut secrets: Option<(DateTime, u64)> = None; let mut discovery: Option<(DateTime, bool)> = None; for observation in own { let seen = observation.received_at; match observation.report.health { - LocationHealth::CompileFailed { generation, .. } - if failed.is_none_or(|(at, _)| seen > at) => - { - failed = Some((seen, generation)); + LocationHealth::CompileFailed { .. } if load.is_none_or(|(at, _)| seen > at) => { + load = Some((seen, LoadReport::Failed)); } - LocationHealth::Connection { - generation, - healthy, - .. - } if connection.is_none_or(|(at, _, _)| seen > at) => { - connection = Some((seen, generation, healthy)); + LocationHealth::Connection { healthy, .. } + if load.is_none_or(|(at, _)| seen > at) => + { + load = Some((seen, LoadReport::Published { connected: healthy })); } LocationHealth::ProviderSecrets { missing, .. } if secrets.is_none_or(|(at, _)| seen > at) => @@ -260,19 +291,24 @@ impl LocationState { _ => {} } } - match (failed, connection, secrets) { - (Some((_, failed)), Some((_, connected, _)), _) if failed >= connected => { - Self::FallingBack - } - (Some(_), None, _) => Self::FallingBack, - (_, _, Some((_, missing))) if missing > 0 => Self::MissingSecrets, + match (load.map(|(_, report)| report), secrets) { + (Some(LoadReport::Failed), _) => Self::FallingBack, + (_, Some((_, missing))) if missing > 0 => Self::MissingSecrets, + _ if change_plan_failed => Self::ChangePlanFailed, _ if discovery.is_some_and(|(_, failing)| failing) => Self::DiscoveryFailed, - (_, Some((_, _, false)), _) => Self::Degraded, + (Some(LoadReport::Published { connected: false }), _) => Self::Degraded, _ => Self::Healthy, } } } +/// How the newest load a location reported ended. +#[derive(Clone, Copy)] +enum LoadReport { + Failed, + Published { connected: bool }, +} + /// Only named location operations cross this boundary, never arbitrary SQL or Python. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] @@ -445,6 +481,7 @@ pub enum PlatformEventKind { TickOverdue, CalendarHorizonLow, LocationBroken, + LocationFailing, LaunchFailed, RunFailed, TriggerSkipped, @@ -461,6 +498,7 @@ impl PlatformEventKind { Self::TickOverdue => "tick_overdue", Self::CalendarHorizonLow => "calendar_horizon_low", Self::LocationBroken => "location_broken", + Self::LocationFailing => "location_failing", Self::LaunchFailed => "launch_failed", Self::RunFailed => "run_failed", Self::TriggerSkipped => "trigger_skipped", @@ -494,6 +532,15 @@ pub enum PlatformEvent { target: String, last_seen_at: DateTime, }, + /// A checking-in location's latest load, plan of what changed, discovery or connection check failed; `serving_generation` is what runs use instead. + LocationFailing { + location_id: Uuid, + target: String, + state: LocationState, + failed_at: DateTime, + error: Option, + serving_generation: Option, + }, /// A launch attempt or its response failed; the worker may still start or finish. LaunchFailed { run_id: Uuid, @@ -541,6 +588,7 @@ impl PlatformEvent { Self::TickOverdue { .. } => PlatformEventKind::TickOverdue, Self::CalendarHorizonLow { .. } => PlatformEventKind::CalendarHorizonLow, Self::LocationBroken { .. } => PlatformEventKind::LocationBroken, + Self::LocationFailing { .. } => PlatformEventKind::LocationFailing, Self::LaunchFailed { .. } => PlatformEventKind::LaunchFailed, Self::RunFailed { .. } => PlatformEventKind::RunFailed, Self::TriggerSkipped { .. } => PlatformEventKind::TriggerSkipped, @@ -557,6 +605,7 @@ impl PlatformEvent { Self::TickOverdue { .. } => "platform_tick_overdue", Self::CalendarHorizonLow { .. } => "platform_calendar_horizon_low", Self::LocationBroken { .. } => "platform_location_broken", + Self::LocationFailing { .. } => "platform_location_failing", Self::LaunchFailed { .. } => "platform_launch_failed", Self::RunFailed { .. } => "platform_run_failed", Self::TriggerSkipped { .. } => "platform_trigger_skipped", @@ -636,6 +685,9 @@ pub struct PlatformProblems { /// When the last scheduler lease ran out, or will run out; absent until a server first leads. pub scheduler_lease_expires_at: Option>, pub broken_locations: Vec, + /// Checking-in locations whose latest load, plan of what changed, discovery or connection check failed. + #[serde(default)] + pub failing_locations: Vec, pub overdue_ticks: Vec, /// Running calendar schedules whose dates run out within a day. #[serde(default)] @@ -741,6 +793,22 @@ pub struct BrokenLocation { pub last_seen_at: DateTime, } +/// A checking-in location whose latest load, plan of what changed, discovery or connection check failed, and what it serves instead. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct FailingLocation { + pub location_id: Uuid, + pub location_name: String, + pub target: String, + /// `falling_back`, `change_plan_failed`, `discovery_failed` or `degraded`. + pub state: LocationState, + /// When the failure was reported. + pub failed_at: DateTime, + /// What failed, redacted; absent when an older location reported no text. + pub error: Option, + /// The snapshot the target serves; absent before its first publication. + pub serving: Option, +} + /// A running schedule whose next tick is more than 30 seconds late. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] pub struct OverdueTick { @@ -769,6 +837,7 @@ pub(crate) struct ProblemScan { pub(crate) now: DateTime, pub(crate) lease: Option, pub(crate) broken: Vec, + pub(crate) failing: Vec, pub(crate) late_targets: std::collections::BTreeSet<(Uuid, String)>, pub(crate) low_calendars: Vec, pub(crate) skipped_triggers: Vec, @@ -881,6 +950,10 @@ pub struct LocationRuleFinding { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "snake_case")] pub enum PlanRowSection { + /// Models that couldn't be planned, with their errors. + PlanningError, + /// Models an explicit cursor window skips, as it ends before their `cursor_start`. + WindowBeforeCursorStart, /// Built models the plan rebuilds in full. FullRefresh, QueryChanged, diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/plan.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/plan.rs index 3589234274..90329796eb 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/plan.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/plan.rs @@ -7,6 +7,7 @@ use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::platform::constants::{LOCATION_SILENCE_SECONDS, PLAN_EXPIRY_SECONDS, PLAN_QUEUE_LIMIT}; +use crate::platform::main::health::load_failure_refusal::load_failure_refusal; use crate::platform::main::work::enqueue_location_work::enqueue_location_work; use crate::platform::main::work::read_location_work::read_location_work; use crate::platform::models::{LocationWork, LocationWorkRequest, PlanRequest}; @@ -99,6 +100,10 @@ pub(in crate::runs) async fn request_plan_in( "no sqb location serve has reported for {target} in the last {LOCATION_SILENCE_SECONDS} seconds; start it and plan again" ))); } + let (transaction, refusal) = load_failure_refusal(transaction, (location_id, target)).await?; + if let Some(refusal) = refusal { + return Err(ControlError::Invalid(refusal)); + } if count("mine") > 0 { return Err(ControlError::Invalid( "your previous plan for this target is still running".into(), diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_selection.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_selection.rs index 63b8a5f060..9b0b1c6cb2 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_selection.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/cost_selection.rs @@ -3,6 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use chrono::{DateTime, Duration, NaiveDate, Utc}; +use sqlbuild_core::constants::{MODELS_PATH, PYTHON_NODE_ROOT, SQL_DIRECTORY}; use uuid::Uuid; use crate::credentials::models::{AuditContext, DefaultRole}; @@ -19,8 +20,8 @@ use crate::warehouse_history::_helpers::costs::{ /// The folder of nodes whose path the publication doesn't give, such as nodes no longer deployed. pub(crate) const OTHER_FOLDER: &str = "other"; -/// The layout root of SQL models, which folders leave out. -const MODELS_ROOT: &str = "sql/models"; +/// The folder Python nodes group under, in place of their `python/nodes` root. +const PYTHON_FOLDER: &str = "python"; /// A period of whole UTC days ending today, and the one before it. pub(crate) struct CostPeriod { @@ -91,22 +92,36 @@ pub(crate) struct SelectionCosts { pub(crate) pending_runs: BTreeSet, } -/// A node's folder: its directory, without `sql/models/` (empty at its top); other roots as published. +/// A node's folder as the catalog groups it: below `sql/models/`, below `sql/`, or `python/`. pub(crate) fn cost_folder(path: Option<&str>) -> String { let Some(path) = path else { return OTHER_FOLDER.to_owned(); }; let directory: &str = path.rsplit_once('/').map_or("", |(directory, _)| directory); - if directory == MODELS_ROOT { - return String::new(); + if let Some(folder) = below(directory, MODELS_PATH) { + return folder.to_owned(); } - directory - .strip_prefix(MODELS_ROOT) - .and_then(|rest| rest.strip_prefix('/')) + if let Some(folder) = below(directory, PYTHON_NODE_ROOT) { + return if folder.is_empty() { + PYTHON_FOLDER.to_owned() + } else { + format!("{PYTHON_FOLDER}/{folder}") + }; + } + below(directory, SQL_DIRECTORY) + .filter(|folder| !folder.is_empty()) .unwrap_or(directory) .to_owned() } +/// `directory` below `root`: empty when it is the root, `None` outside it. +fn below<'a>(directory: &'a str, root: &str) -> Option<&'a str> { + if directory == root { + return Some(""); + } + directory.strip_prefix(root)?.strip_prefix('/') +} + /// The period of the last `days` whole UTC days to now, and the selection's cost rows over it. pub(crate) async fn selection_costs_in_days( store: &ControlStore, diff --git a/crates/sqlbuild-orchestration/tests/api/test_cost_selection.rs b/crates/sqlbuild-orchestration/tests/api/test_cost_selection.rs index c57a117813..8e096eba26 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_cost_selection.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_cost_selection.rs @@ -256,9 +256,29 @@ fn given_published_paths_when_costs_are_grouped_then_each_node_is_in_its_folder( expected_folder: "", }, CostFolderTestCase { - description: "a Python node keeps its root", + description: "a Python node under python/ in place of python/nodes", path: Some("python/nodes/exports/asset.py"), - expected_folder: "python/nodes/exports", + expected_folder: "python/exports", + }, + CostFolderTestCase { + description: "a Python node at the top of python/nodes", + path: Some("python/nodes/asset.py"), + expected_folder: "python", + }, + CostFolderTestCase { + description: "a seed by its path below sql", + path: Some("sql/seeds/geo/countries.csv"), + expected_folder: "seeds/geo", + }, + CostFolderTestCase { + description: "a scoped declaration stays in its owner's folder", + path: Some("sql/models/staging/_sqlbuild/functions/clean.sql"), + expected_folder: "staging/_sqlbuild/functions", + }, + CostFolderTestCase { + description: "a path outside the layout's roots as published", + path: Some("legacy/orders.sql"), + expected_folder: "legacy", }, CostFolderTestCase { description: "a node no longer published", diff --git a/crates/sqlbuild-orchestration/tests/api/test_location_health.rs b/crates/sqlbuild-orchestration/tests/api/test_location_health.rs index 0bd69d9ce9..a976039fda 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_location_health.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_location_health.rs @@ -5,6 +5,7 @@ use crate::platform::main::health::read_person_location_health::read_person_loca use crate::platform::main::health::report_remote_location_health::report_remote_location_health; use crate::platform::models::{ ConnectionCheckTrigger, LocationHealth, LocationHealthObservation, LocationHealthReport, + LocationState, }; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; use crate::store::main::migrate_store::migrate_store; @@ -199,15 +200,20 @@ fn given_scoped_location_observations_when_retried_or_read_then_history_and_auth (DefaultRole::None, &no_caps), ) }; + let read = person_read("preview #1").await.expect("person health"); assert_eq!( - person_read("preview #1").await.expect("person health"), - observations, - "a person sees the same observations for the reporting target" + (read.observations.clone(), read.state), + ( + observations.clone(), + LocationState::of(&observations, ("preview #1", Utc::now())) + ), + "a person sees the same observations for the reporting target, and the server's state of them" ); assert!( person_read("another target") .await .expect("other target health") + .observations .is_empty(), "another target's read leaves this target's observations out" ); @@ -223,7 +229,10 @@ fn given_scoped_location_observations_when_retried_or_read_then_history_and_auth .await .expect("aged report"); commit(transaction).await.expect("aged report committed"); - let reports = person_read("preview #1").await.expect("aged health"); + let reports = person_read("preview #1") + .await + .expect("aged health") + .observations; assert_eq!( reports .iter() @@ -289,7 +298,8 @@ fn given_scoped_location_observations_when_retried_or_read_then_history_and_auth assert_eq!( person_read("preview #1") .await - .expect("quiet target health"), + .expect("quiet target health") + .observations, observations, "a busier target's newer observations do not push out this target's" ); @@ -399,7 +409,8 @@ fn given_pool_amounts_above_this_servers_caps_when_reading_health_then_a_pool_ca (DefaultRole::None, &caps), ) .await - .expect("health"); + .expect("health") + .observations; let capped = pool_capped(&observations); assert!( diff --git a/crates/sqlbuild-orchestration/tests/api/test_node_states.rs b/crates/sqlbuild-orchestration/tests/api/test_node_states.rs index e2c8a234ca..ee255388c0 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_node_states.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_node_states.rs @@ -19,6 +19,9 @@ use crate::node_states::_helpers::views::{current_view, refresh_view, target_cac use crate::node_states::main::report_changed_build::report_changed_build; use crate::node_states::main::start_node_states::start_node_states; use crate::node_states::models::ChangedBuildReport; +use crate::platform::main::health::location_health::location_health; +use crate::platform::main::health::report_location_health::report_location_health; +use crate::platform::models::{LocationHealth, LocationHealthReport, LocationState}; use crate::runs::main::requests::request_job_run::request_job_run; use crate::runs::models::JobRunRequest; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; @@ -399,6 +402,75 @@ fn given_changed_build_reports_when_people_read_node_states_then_only_the_curren "{}: a failed plan replaces the count with its reason", test_case.description ); + report_location_health( + store, + location, + &LocationHealthReport { + event_id: Uuid::now_v7(), + session_id, + target: "development".into(), + health: LocationHealth::Connection { + generation: 2, + healthy: true, + trigger: None, + elapsed_millis: None, + }, + }, + ) + .await + .expect("published"); + let health = location_health(store, (location, Some("development"))) + .await + .expect("health"); + assert_eq!( + ( + health + .iter() + .find_map(|observation| match &observation.report.health { + LocationHealth::ChangePlanFailed { generation, reason } => { + Some((*generation, reason.clone())) + } + _ => None, + }), + LocationState::of(&health, ("development", chrono::Utc::now())), + ), + ( + Some((2, "Model orders cannot plan a full rebuild".to_owned())), + LocationState::ChangePlanFailed + ), + "{}: a failed plan of what changed is the location's health, not only a log line", + test_case.description + ); + let partial = ChangedBuildReport { + session_id, + generation: 2, + changed: vec!["model:totals".into()], + downstream: Vec::new(), + failing: Some( + "Can't plan 1 model: orders: model 'orders' sets full_refresh false".into(), + ), + }; + report_changed_build(store, (location, "development"), &partial) + .await + .expect("partial changed build"); + next_notice(&mut feed).await.expect("node status"); + assert_eq!( + changed_build().await, + json!({"generation": 2, "changed": ["model:totals"], "downstream": [], "failing": "Can't plan 1 model: orders: model 'orders' sets full_refresh false"}), + "{}: a plan with models it couldn't plan keeps the rest and names those models", + test_case.description + ); + assert_eq!( + LocationState::of( + &location_health(store, (location, Some("development"))) + .await + .expect("health"), + ("development", chrono::Utc::now()) + ), + LocationState::ChangePlanFailed, + "{}: models it couldn't plan count as a failed plan of what changed", + test_case.description + ); assert!( matches!( report_changed_build( diff --git a/crates/sqlbuild-orchestration/tests/api/test_person_plans.rs b/crates/sqlbuild-orchestration/tests/api/test_person_plans.rs index e22447fc35..a94c36b8e6 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_person_plans.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_person_plans.rs @@ -7,12 +7,15 @@ use sqlbuild_core::plan_display::main::detach_model_diffs::detach_model_diffs; use uuid::Uuid; use crate::api::tests::plans_helpers::{ask, person, plan_request, register_instance, run_rows}; -use crate::api::tests::test_types::{PlanDiffTestCase, PlanTestCase, PlanTimingsReadTestCase}; +use crate::api::tests::test_types::{ + PlanDiffTestCase, PlanLoadFailureTestCase, PlanTestCase, PlanTimingsReadTestCase, +}; use crate::api::tests::work_helpers::execute; use crate::authorization::main::people::bootstrap_user::bootstrap_user; use crate::credentials::models::{AuditContext, BuiltinRole}; use crate::credentials::tests::location_helpers::create_location; use crate::platform::_helpers::maintenance::retention::retain; +use crate::platform::main::health::report_location_health::report_location_health; use crate::platform::main::person_reads::read_person_plan::read_person_plan; use crate::platform::main::person_reads::read_person_plan_diff::read_person_plan_diff; use crate::platform::main::person_reads::read_person_plan_rows::read_person_plan_rows; @@ -21,8 +24,9 @@ use crate::platform::main::work::claim_location_work::claim_location_work; use crate::platform::main::work::complete_location_work::complete_location_work; use crate::platform::main::work::request_location_work::request_location_work; use crate::platform::models::{ - LocationWork, LocationWorkOutcome, LocationWorkRequest, LocationWorkResult, PlanModelDiff, - PlanRequest, PlanRowSection, PlanRowsQuery, PlanTimingStep, PlanTimings, + LocationHealth, LocationHealthReport, LocationWork, LocationWorkOutcome, LocationWorkRequest, + LocationWorkResult, PlanModelDiff, PlanRequest, PlanRowSection, PlanRowsQuery, PlanTimingStep, + PlanTimings, }; use crate::runs::tests::helpers::snapshot; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; @@ -807,3 +811,136 @@ fn given_a_plan_with_timings_when_its_summary_is_read_then_timings_of_another_sh }); } } + +#[test] +fn given_a_location_whose_load_fails_when_planning_then_waiting_and_new_plans_fail_with_its_error() +{ + let test_cases = [ + PlanLoadFailureTestCase { + description: "SQLite, the load error reported", + backend: Backend::Sqlite, + load_error: Some("job loaders_job: path selectors require an explicit root"), + expected_message: "the location can't load the current code, so it can't plan: job loaders_job: path selectors require an explicit root", + }, + PlanLoadFailureTestCase { + description: "PostgreSQL, from a location that reports no error", + backend: Backend::Postgres, + load_error: None, + expected_message: "the location can't load the current code, so it can't plan: the location's output has the error", + }, + ]; + 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 context = AuditContext { + actor: "control-store-owner".into(), + granting_role: "control-store-owner".into(), + request_id: Uuid::now_v7(), + ip_address: None, + }; + let admin = bootstrap_user(store, &context, "orders-admin") + .await + .expect("bootstrap"); + let location = create_location(store, "orders", "test-owner") + .await + .expect("location"); + publish_snapshot(store, &snapshot(location)) + .await + .expect("publish"); + let viewer = person( + store, + (&context, admin), + ("orders-viewer", location), + &[BuiltinRole::Viewer], + ) + .await; + let poll = register_instance(store, location).await; + let waiting = plan_request(&["build", "customers"]); + assert_eq!( + ask(store, (&context, viewer), location, &waiting) + .await + .ok(), + Some(true), + "{}: a plan waits while the location loads", + test_case.description + ); + let reported = |health: LocationHealth| LocationHealthReport { + event_id: Uuid::now_v7(), + session_id: poll.session_id, + target: "development".into(), + health, + }; + report_location_health( + store, + location, + &reported(LocationHealth::CompileFailed { + generation: 2, + rules: None, + error: test_case.load_error.map(str::to_owned), + }), + ) + .await + .expect("failed load"); + let answered = read_person_plan( + store, + (&context, viewer), + (location, "development", waiting.request_id), + ) + .await + .expect("read plan") + .and_then(|record| record.result_json); + let Some(LocationWorkOutcome::Plan { document, .. }) = + answered.map(|result| result.outcome) + else { + panic!("{}: the waiting plan failed", test_case.description); + }; + assert_eq!( + document["error"]["message"], test_case.expected_message, + "{}: the waiting plan carries the load error", + test_case.description + ); + let refused = ask( + store, + (&context, viewer), + location, + &plan_request(&["build", "orders"]), + ) + .await; + assert!( + matches!(&refused, Err(ControlError::Invalid(message)) if message == test_case.expected_message), + "{}: a new plan fails at once, got {refused:?}", + test_case.description + ); + report_location_health( + store, + location, + &reported(LocationHealth::Connection { + generation: 1, + healthy: true, + trigger: None, + elapsed_millis: None, + }), + ) + .await + .expect("publication"); + assert_eq!( + ask( + store, + (&context, viewer), + location, + &plan_request(&["build", "orders"]) + ) + .await + .ok(), + Some(true), + "{}: once a load publishes, plans are accepted again", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs b/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs index 62ff34face..5155b9e9d5 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs @@ -306,12 +306,37 @@ fn given_browser_session_roles_when_work_is_requested_then_scope_revocation_and_ format!("/api/control/locations/{location}/targets/development/jobs"), format!("/api/control/locations/{location}/targets/development/triggers"), format!("/api/control/locations/{location}/targets/development/snapshots"), - format!("/api/control/locations/{location}/targets/development/health"), format!( "/api/control/locations/{location}/targets/development/triggers/{}/ticks", trigger.trigger_id ), ]; + let health_path = + format!("/api/control/locations/{location}/targets/development/health"); + let health = request( + &provider.client, + session, + (Method::GET, &health_path), + (&Value::Null, &session.csrf), + ) + .await; + assert_eq!( + health.status().as_u16(), + role_case.expected_metadata, + "{health_path}" + ); + let health: Value = health.json().await.expect("health response"); + assert_eq!( + ( + health["state"].is_string(), + health["observations"].is_array() + ), + ( + role_case.expected_metadata == StatusCode::OK.as_u16(), + role_case.expected_metadata == StatusCode::OK.as_u16() + ), + "{health_path}: {health}" + ); let unknown_reads = [ format!("{metadata}/{}/nodes", Uuid::now_v7()), format!( diff --git a/crates/sqlbuild-orchestration/tests/api/test_types.rs b/crates/sqlbuild-orchestration/tests/api/test_types.rs index c61a9205e3..59623dfbd3 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_types.rs @@ -726,3 +726,11 @@ pub(crate) struct CostFolderTestCase { pub(crate) path: Option<&'static str>, pub(crate) expected_folder: &'static str, } + +pub(crate) struct PlanLoadFailureTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + /// The error the location reports with its failed load; absent from an older location. + pub(crate) load_error: Option<&'static str>, + pub(crate) expected_message: &'static str, +} diff --git a/crates/sqlbuild-orchestration/tests/dev_events/test_dev_events.rs b/crates/sqlbuild-orchestration/tests/dev_events/test_dev_events.rs index cc3cb7fa98..105415e140 100644 --- a/crates/sqlbuild-orchestration/tests/dev_events/test_dev_events.rs +++ b/crates/sqlbuild-orchestration/tests/dev_events/test_dev_events.rs @@ -36,11 +36,10 @@ fn given_each_event_when_encoding_then_one_prefixed_line_reads_back_unchanged() expected_newlines: 1, }, RoundTripTestCase { - description: "a publication keeps its whole record on the same line", + description: "a publication keeps its generation and snapshot", event: DevEvent::Published { generation: 2, snapshot_id: "b429729b".to_owned(), - record: serde_json::json!({"snapshot_id": "b429729b", "generation": 2}), }, expected_newlines: 1, }, diff --git a/crates/sqlbuild-orchestration/tests/node_states/helpers.rs b/crates/sqlbuild-orchestration/tests/node_states/helpers.rs new file mode 100644 index 0000000000..25e840431b --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/node_states/helpers.rs @@ -0,0 +1,103 @@ +//! Node states for status tests: builds and runs at hours after one fixed start. + +use std::collections::BTreeMap; + +use chrono::{DateTime, Duration, TimeZone, Utc}; + +use crate::node_states::_helpers::status::{StatusNode, apply_statuses}; +use crate::node_states::models::NodeState; +use crate::warehouse_metadata::models::{CatalogNodeBuild, CatalogNodeOutcome}; + +pub(crate) fn at(hours: i64) -> DateTime { + Utc.with_ymd_and_hms(2026, 11, 24, 0, 0, 0) + .single() + .expect("a valid fixture start") + + Duration::hours(hours) +} + +pub(crate) fn built(hours: i64) -> Option { + Some(CatalogNodeBuild { + observed_at: at(hours), + run_id: "run".to_owned(), + version_hash: "hash".to_owned(), + }) +} + +pub(crate) fn outcome(status: &str, hours: i64) -> Option { + Some(CatalogNodeOutcome { + status: status.to_owned(), + at: at(hours), + run_id: None, + }) +} + +pub(crate) fn state( + last_build: Option, + last_outcome: Option, + changed: bool, +) -> NodeState { + NodeState { + last_build, + last_outcome, + definition_changed: changed, + ..NodeState::default() + } +} + +/// A small project: tables, views and nodes without a table, with builds and runs at different hours. +pub(crate) fn project_statuses() -> BTreeMap { + let node = |key, kind, has_table, view, upstream: &[&'static str]| StatusNode { + key, + kind, + has_table, + view, + upstream: upstream.to_vec(), + }; + let nodes = [ + node("source:raw", "source", false, false, &[]), + node("model:fresh", "model", true, false, &[]), + node("model:old", "model", true, false, &["model:fresh"]), + node("model:view", "model", true, true, &["model:fresh"]), + node("model:over_view", "model", true, false, &["model:view"]), + node("model:edited", "model", true, false, &[]), + node("model:edited_failed", "model", true, false, &[]), + node("model:unbuilt", "model", true, false, &[]), + node("model:unbuilt_failed", "model", true, false, &[]), + node("asset:ran", "asset", false, false, &["model:fresh"]), + node("asset:warned", "asset", false, false, &[]), + node("asset:failed", "asset", false, false, &[]), + node("asset:never", "asset", false, false, &[]), + node("model:loop_a", "model", true, true, &["model:loop_b"]), + node("model:loop_b", "model", true, true, &["model:loop_a"]), + ]; + let states: BTreeMap = BTreeMap::from( + [ + ("source:raw", state(None, outcome("success", 1), false)), + ("model:fresh", state(built(5), outcome("success", 5), false)), + ("model:old", state(built(2), outcome("success", 2), false)), + ("model:view", state(built(1), outcome("success", 1), false)), + ( + "model:over_view", + state(built(3), outcome("success", 3), false), + ), + ("model:edited", state(built(4), outcome("success", 4), true)), + ( + "model:edited_failed", + state(built(4), outcome("failed", 6), true), + ), + ("model:unbuilt", state(None, None, false)), + ( + "model:unbuilt_failed", + state(None, outcome("failed", 6), false), + ), + ("asset:ran", state(None, outcome("success", 7), false)), + ("asset:warned", state(None, outcome("warn", 8), false)), + ("asset:failed", state(None, outcome("failed", 9), false)), + ("asset:never", state(None, None, false)), + ("model:loop_a", state(built(1), None, false)), + ("model:loop_b", state(built(1), None, false)), + ] + .map(|(key, state)| (key.to_owned(), state)), + ); + apply_statuses(&nodes, states) +} diff --git a/crates/sqlbuild-orchestration/tests/node_states/test_contracts.rs b/crates/sqlbuild-orchestration/tests/node_states/test_contracts.rs index 6098b127c9..8a29267292 100644 --- a/crates/sqlbuild-orchestration/tests/node_states/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/node_states/test_contracts.rs @@ -1,4 +1,8 @@ +#[path = "helpers.rs"] +pub(crate) mod helpers; #[path = "test_held_checks.rs"] mod test_held_checks; +#[path = "test_statuses.rs"] +mod test_statuses; #[path = "test_types.rs"] mod test_types; diff --git a/crates/sqlbuild-orchestration/tests/node_states/test_statuses.rs b/crates/sqlbuild-orchestration/tests/node_states/test_statuses.rs new file mode 100644 index 0000000000..85876f0ddb --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/node_states/test_statuses.rs @@ -0,0 +1,186 @@ +//! Every node gets one build status on the server, from its build, its last run when it has no table, and its upstream. + +use std::collections::HashMap; + +use serde_json::json; + +use crate::node_states::_helpers::reads::{loaded_sources, newest_attempt}; +use crate::node_states::models::NodeBuildStatus; +use crate::node_states::tests::helpers::{at, outcome, project_statuses}; +use crate::node_states::tests::test_types::{LoaderAttemptTestCase, NodeStatusTestCase}; +use crate::snapshots::models::SnapshotNode; +use crate::warehouse_metadata::models::CatalogNodeOutcome; + +#[test] +fn given_node_states_when_statuses_are_worked_out_then_each_node_has_one() { + let test_cases = [ + NodeStatusTestCase { + description: "a source is a source, whatever ran", + node_key: "source:raw", + expected_status: NodeBuildStatus::Source, + expected_status_at: None, + }, + NodeStatusTestCase { + description: "a table built after its upstream is current", + node_key: "model:fresh", + expected_status: NodeBuildStatus::Current, + expected_status_at: Some(5), + }, + NodeStatusTestCase { + description: "a table built before its upstream's newer build is behind", + node_key: "model:old", + expected_status: NodeBuildStatus::Behind, + expected_status_at: Some(2), + }, + NodeStatusTestCase { + description: "a view reads its upstream when queried, so it is never behind", + node_key: "model:view", + expected_status: NodeBuildStatus::Current, + expected_status_at: Some(1), + }, + NodeStatusTestCase { + description: "a table over a view is behind the data behind the view", + node_key: "model:over_view", + expected_status: NodeBuildStatus::Behind, + expected_status_at: Some(3), + }, + NodeStatusTestCase { + description: "a definition changed since the build is changed", + node_key: "model:edited", + expected_status: NodeBuildStatus::Changed, + expected_status_at: Some(4), + }, + NodeStatusTestCase { + description: "a failed attempt outranks a changed definition", + node_key: "model:edited_failed", + expected_status: NodeBuildStatus::Failed, + expected_status_at: Some(6), + }, + NodeStatusTestCase { + description: "a table never built is not built", + node_key: "model:unbuilt", + expected_status: NodeBuildStatus::NotBuilt, + expected_status_at: None, + }, + NodeStatusTestCase { + description: "a table whose only attempt failed is failed", + node_key: "model:unbuilt_failed", + expected_status: NodeBuildStatus::Failed, + expected_status_at: Some(6), + }, + NodeStatusTestCase { + description: "a node without a table that ran successfully is current, as of its run", + node_key: "asset:ran", + expected_status: NodeBuildStatus::Current, + expected_status_at: Some(7), + }, + NodeStatusTestCase { + description: "a run with warnings succeeded", + node_key: "asset:warned", + expected_status: NodeBuildStatus::Current, + expected_status_at: Some(8), + }, + NodeStatusTestCase { + description: "a node without a table whose run failed is failed", + node_key: "asset:failed", + expected_status: NodeBuildStatus::Failed, + expected_status_at: Some(9), + }, + NodeStatusTestCase { + description: "a node without a table that never ran is not built", + node_key: "asset:never", + expected_status: NodeBuildStatus::NotBuilt, + expected_status_at: None, + }, + NodeStatusTestCase { + description: "views reading each other end the walk", + node_key: "model:loop_a", + expected_status: NodeBuildStatus::Current, + expected_status_at: Some(1), + }, + ]; + let states = project_statuses(); + for test_case in test_cases { + let state = &states[test_case.node_key]; + assert_eq!( + (state.status, state.status_at), + ( + test_case.expected_status, + test_case.expected_status_at.map(at) + ), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_loader_when_its_sources_ran_then_its_attempt_is_theirs() { + let test_cases = [ + LoaderAttemptTestCase { + description: "a loader's run is recorded under the source it loads", + attempts: &[("source:raw__orders", "success", 2)], + expected_attempt: Some(("success", 2)), + }, + LoaderAttemptTestCase { + description: "the newest of its sources' attempts", + attempts: &[ + ("source:raw__orders", "failed", 1), + ("source:raw__customers", "success", 3), + ], + expected_attempt: Some(("success", 3)), + }, + LoaderAttemptTestCase { + description: "a failure first when its sources ran at once", + attempts: &[ + ("source:raw__orders", "success", 4), + ("source:raw__customers", "failed", 4), + ], + expected_attempt: Some(("failed", 4)), + }, + LoaderAttemptTestCase { + description: "another loader's source is not its own", + attempts: &[("source:other", "success", 5)], + expected_attempt: None, + }, + ]; + let source = |loader: &str| SnapshotNode { + kind: "source".to_owned(), + definition: json!({"name": "source", "entry": {"loader": loader}}), + raw_sql: None, + compiled_sql: None, + python_source: None, + }; + let loader = SnapshotNode { + kind: "loader".to_owned(), + definition: json!({"name": "raw"}), + raw_sql: None, + compiled_sql: None, + python_source: None, + }; + let nodes = vec![ + ("source:raw__orders".to_owned(), source("raw")), + ("source:raw__customers".to_owned(), source("raw")), + ("source:other".to_owned(), source("other")), + ]; + let loaded = loaded_sources(&nodes); + for test_case in test_cases { + let attempts: HashMap = test_case + .attempts + .iter() + .map(|(key, status, hours)| { + let attempt = outcome(status, *hours).expect("an outcome for every attempt"); + ((*key).to_owned(), attempt) + }) + .collect(); + let found = newest_attempt(&attempts, "loader:raw", &loader, &loaded); + assert_eq!( + found.map(|attempt| (attempt.status, attempt.at)), + test_case + .expected_attempt + .map(|(status, hours)| (status.to_owned(), at(hours))), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/node_states/test_types.rs b/crates/sqlbuild-orchestration/tests/node_states/test_types.rs index 48d00bd953..bfe191f234 100644 --- a/crates/sqlbuild-orchestration/tests/node_states/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/node_states/test_types.rs @@ -3,3 +3,18 @@ pub(crate) struct HeldChecksTestCase { pub(crate) signals_during_read: usize, pub(crate) expected_held: Option<&'static str>, } + +pub(crate) struct NodeStatusTestCase { + pub(crate) description: &'static str, + pub(crate) node_key: &'static str, + pub(crate) expected_status: crate::node_states::models::NodeBuildStatus, + /// Hours after the fixture's start, or none. + pub(crate) expected_status_at: Option, +} + +pub(crate) struct LoaderAttemptTestCase { + pub(crate) description: &'static str, + /// Each attempt: the node key it was recorded under, its status and hours after the start. + pub(crate) attempts: &'static [(&'static str, &'static str, i64)], + pub(crate) expected_attempt: Option<(&'static str, i64)>, +} diff --git a/crates/sqlbuild-orchestration/tests/platform/helpers.rs b/crates/sqlbuild-orchestration/tests/platform/helpers.rs index 21000b3d54..1cf689184c 100644 --- a/crates/sqlbuild-orchestration/tests/platform/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/platform/helpers.rs @@ -7,7 +7,10 @@ use axum::extract::State; use axum::http::{HeaderMap, StatusCode}; use axum::response::IntoResponse; -use crate::platform::models::{PlatformEvent, PlatformEventEnvelope}; +use crate::platform::models::{ + LocationHealth, LocationHealthObservation, LocationHealthReport, PlatformEvent, + PlatformEventEnvelope, +}; use crate::runs::main::execution::claim_next_run::claim_next_run; use crate::runs::main::execution::publish_run_recall::publish_run_recall; use crate::runs::models::{RecallBatch, RecallRecord}; @@ -22,7 +25,9 @@ use sqlbuild_recall::schema::models::Table; use tokio::task::JoinHandle; use uuid::Uuid; -use crate::platform::tests::test_types::{Observation, WebhookReceiver}; +use crate::platform::tests::test_types::{ + Instance, Observation, Reported, ReportedHealth, WebhookReceiver, +}; use crate::runs::tests::helpers::{queue, request}; use crate::scheduler::tests::contracts::helpers::acquire_lease; @@ -235,3 +240,111 @@ pub(crate) async fn retained_platform_facts(store: &ControlStore) -> Vec ( + Vec, + chrono::DateTime, +) { + let now: chrono::DateTime = + chrono::DateTime::from_timestamp(1_795_000_000, 0).expect("a valid read time"); + // One session ID per instance: v7, stamped with when its process started, except the unordered one. + let v7 = |started: chrono::DateTime| -> Uuid { + let seconds = u64::try_from(started.timestamp()).expect("a time after 1970"); + Uuid::new_v7(uuid::Timestamp::from_unix(uuid::NoContext, seconds, 0)) + }; + let sessions: [Uuid; 4] = [ + v7(now - TimeDelta::hours(3)), + v7(now - TimeDelta::seconds(25)), + v7(now - TimeDelta::days(8)), + Uuid::from_u128(0x5_0000_0000_4000_8000_0000_0000_0000), + ]; + let sessions: std::collections::BTreeMap = [ + Instance::Previous, + Instance::Restarted, + Instance::LongRunning, + Instance::Unordered, + ] + .into_iter() + .zip(sessions) + .collect(); + let observation = |reported: &Reported| LocationHealthObservation { + received_at: now - TimeDelta::seconds(reported.seconds_ago), + report: LocationHealthReport { + event_id: Uuid::now_v7(), + session_id: sessions[&reported.instance], + target: "production".into(), + health: (reported.health.0)(reported.health.1), + }, + }; + let later = (0..later_reports).map(|index| Reported { + instance: Instance::Previous, + seconds_ago: 20 - i64::try_from(index % 20).expect("a small index"), + health: ReportedHealth(secrets, 0), + }); + let mut observations: Vec = reported + .iter() + .map(observation) + .chain(later.map(|reported| observation(&reported))) + .collect(); + observations.sort_by_key(|observation| std::cmp::Reverse(observation.received_at)); + observations.truncate(crate::platform::constants::RECENT_HEALTH_LIMIT); + (observations, now) +} + +/// One report in a health history. +pub(crate) const fn reported( + instance: Instance, + seconds_ago: i64, + health: ReportedHealth, +) -> Reported { + Reported { + instance, + seconds_ago, + health, + } +} + +/// The instance's liveness row. +pub(crate) const fn check_in(_generation: i64) -> LocationHealth { + LocationHealth::Heartbeat {} +} + +/// A publication of the generation, then its healthy connection check. +pub(crate) const fn published(generation: i64) -> LocationHealth { + LocationHealth::Connection { + generation, + healthy: true, + trigger: None, + elapsed_millis: None, + } +} + +/// A failed load of the generation. +pub(crate) fn failed(generation: i64) -> LocationHealth { + LocationHealth::CompileFailed { + generation, + rules: None, + error: Some(format!("generation {generation} failed to load")), + } +} + +/// The server's record that the plan of what changed on the generation failed. +pub(crate) fn change_plan_failed(generation: i64) -> LocationHealth { + LocationHealth::ChangePlanFailed { + generation, + reason: "Model orders cannot plan a full rebuild".into(), + } +} + +/// A provider check without missing secrets. +pub(crate) const fn secrets(_generation: i64) -> LocationHealth { + LocationHealth::ProviderSecrets { + generation: 1, + missing: 0, + providers: Vec::new(), + } +} diff --git a/crates/sqlbuild-orchestration/tests/platform/test_compile_failure.rs b/crates/sqlbuild-orchestration/tests/platform/test_compile_failure.rs index d03a3e721a..3771e5a510 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_compile_failure.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_compile_failure.rs @@ -12,14 +12,15 @@ use crate::store::tests::store_helpers::{close_test_store, open_test_store, run} use crate::store::tests::store_test_types::Backend; #[test] -fn given_rule_findings_when_a_location_reports_a_failed_load_then_only_bounded_lists_are_accepted() -{ +fn given_rule_findings_and_an_error_when_a_location_reports_a_failed_load_then_only_bounded_reports_are_accepted() + { let test_cases = [ CompileFailureTestCase { description: "one finding", finding_count: 1, listed: 1, message_chars: 60, + error_chars: 80, expected_accepted: true, }, CompileFailureTestCase { @@ -27,6 +28,7 @@ fn given_rule_findings_when_a_location_reports_a_failed_load_then_only_bounded_l finding_count: 222, listed: 50, message_chars: 500, + error_chars: 4000, expected_accepted: true, }, CompileFailureTestCase { @@ -34,6 +36,7 @@ fn given_rule_findings_when_a_location_reports_a_failed_load_then_only_bounded_l finding_count: 51, listed: 51, message_chars: 60, + error_chars: 80, expected_accepted: false, }, CompileFailureTestCase { @@ -41,6 +44,15 @@ fn given_rule_findings_when_a_location_reports_a_failed_load_then_only_bounded_l finding_count: 1, listed: 2, message_chars: 60, + error_chars: 80, + expected_accepted: false, + }, + CompileFailureTestCase { + description: "an over-long load error", + finding_count: 1, + listed: 1, + message_chars: 60, + error_chars: 4001, expected_accepted: false, }, CompileFailureTestCase { @@ -48,6 +60,7 @@ fn given_rule_findings_when_a_location_reports_a_failed_load_then_only_bounded_l finding_count: 1, listed: 1, message_chars: 501, + error_chars: 80, expected_accepted: false, }, ]; @@ -83,6 +96,7 @@ fn given_rule_findings_when_a_location_reports_a_failed_load_then_only_bounded_l finding_count: test_case.finding_count, findings: vec![finding; test_case.listed], }), + error: Some("e".repeat(test_case.error_chars)), }, }; assert_eq!( diff --git a/crates/sqlbuild-orchestration/tests/platform/test_contracts.rs b/crates/sqlbuild-orchestration/tests/platform/test_contracts.rs index b373e75fce..e4d424b344 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_contracts.rs @@ -4,8 +4,12 @@ mod helpers; #[path = "test_compile_failure.rs"] mod test_compile_failure; +#[path = "test_failing_locations.rs"] +mod test_failing_locations; #[path = "test_installation.rs"] mod test_installation; +#[path = "test_location_state.rs"] +mod test_location_state; #[path = "test_problems.rs"] mod test_problems; #[path = "test_provider_secrets.rs"] diff --git a/crates/sqlbuild-orchestration/tests/platform/test_failing_locations.rs b/crates/sqlbuild-orchestration/tests/platform/test_failing_locations.rs new file mode 100644 index 0000000000..eb23711152 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/platform/test_failing_locations.rs @@ -0,0 +1,149 @@ +//! A checking-in location whose latest load failed is a problem people see and a platform event alerts receive, once. + +use uuid::Uuid; + +use crate::authorization::main::people::bootstrap_user::bootstrap_user; +use crate::credentials::models::{AuditContext, DefaultRole}; +use crate::credentials::tests::location_helpers::create_location; +use crate::platform::_helpers::location::liveness::observe_failing_locations; +use crate::platform::main::health::report_location_health::report_location_health; +use crate::platform::main::person_reads::read_person_problems::read_person_problems; +use crate::platform::models::{LocationHealth, LocationHealthReport, LocationState}; +use crate::platform::tests::test_types::FailingLocationTestCase; +use crate::runs::tests::helpers::snapshot; +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::main::query::query; +use crate::store::models::{Parameter, 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_a_location_whose_latest_load_failed_when_problems_are_read_then_it_is_a_problem_and_one_event() + { + let test_cases = [ + FailingLocationTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_error: "job loaders_job: path selectors require an explicit root", + }, + FailingLocationTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_error: "job loaders_job: path selectors require an explicit root", + }, + ]; + 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 context = AuditContext { + actor: "control-store-owner".into(), + granting_role: "control-store-owner".into(), + request_id: Uuid::now_v7(), + ip_address: None, + }; + let admin = bootstrap_user(store, &context, "orders-admin") + .await + .expect("administrator"); + let location = create_location(store, "orders", "test-admin") + .await + .expect("location"); + let published = publish_snapshot(store, &snapshot(location)) + .await + .expect("publish"); + let session_id = Uuid::now_v7(); + for health in [ + LocationHealth::Heartbeat {}, + LocationHealth::CompileFailed { + generation: 2, + rules: None, + error: Some(test_case.expected_error.to_owned()), + }, + ] { + report_location_health( + store, + location, + &LocationHealthReport { + event_id: Uuid::now_v7(), + session_id, + target: "development".into(), + health, + }, + ) + .await + .expect("report"); + } + let problems = read_person_problems(store, admin, DefaultRole::None) + .await + .expect("problems"); + let failing: Vec<(LocationState, Option, Option)> = problems + .failing_locations + .iter() + .map(|failing| { + ( + failing.state, + failing.error.clone(), + failing.serving.as_ref().map(|snapshot| snapshot.generation), + ) + }) + .collect(); + assert_eq!( + failing, + [( + LocationState::FallingBack, + Some(test_case.expected_error.to_owned()), + Some(published.generation) + )], + "{}: the failure, its error and the generation served instead", + test_case.description + ); + let installation = { + let transaction = begin(store, TransactionMode::Read).await.expect("begin"); + let (transaction, rows) = query( + transaction, + "SELECT installation_id FROM sqb_installation", + Vec::new(), + ) + .await + .expect("installation"); + commit(transaction).await.expect("commit"); + rows[0]["installation_id"] + .as_str() + .and_then(|id| id.parse::().ok()) + .expect("an installation") + }; + observe_failing_locations(store, installation) + .await + .expect("scan"); + observe_failing_locations(store, installation) + .await + .expect("scan again"); + let transaction = begin(store, TransactionMode::Read).await.expect("begin"); + let (transaction, events) = query( + transaction, + "SELECT payload FROM recall_events WHERE event_type=$1", + vec![Parameter::Text("platform_location_failing".into())], + ) + .await + .expect("events"); + commit(transaction).await.expect("commit"); + let states: Vec<&str> = events + .iter() + .filter_map(|row| row["payload"]["platform"]["state"].as_str()) + .collect(); + assert_eq!( + states, + ["falling_back"], + "{}: one platform event per failure, however often the watchdog scans", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/platform/test_location_state.rs b/crates/sqlbuild-orchestration/tests/platform/test_location_state.rs new file mode 100644 index 0000000000..f5dcdb8f98 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/platform/test_location_state.rs @@ -0,0 +1,173 @@ +//! A location's health is its newest instance's: starting until that instance's first load ends, then from that load. + +use crate::platform::models::LocationState; +use crate::platform::tests::helpers::{ + change_plan_failed, check_in, failed, health_history, published, reported, +}; +use crate::platform::tests::test_types::{ + Instance, LocationStateTestCase, Reported, ReportedHealth, +}; + +const PREVIOUS_PUBLISHED: Reported = + reported(Instance::Previous, 10_000, ReportedHealth(published, 11)); +const PREVIOUS_CHECKED_IN: Reported = reported(Instance::Previous, 30, ReportedHealth(check_in, 0)); +const RESTARTED_CHECKED_IN: Reported = + reported(Instance::Restarted, 5, ReportedHealth(check_in, 0)); + +#[test] +fn given_a_location_restart_when_reading_health_then_the_newest_instance_decides() { + let test_cases = [ + LocationStateTestCase { + description: "a restarted instance loading its first snapshot is starting, though the previous one published", + reported: vec![ + PREVIOUS_PUBLISHED, + PREVIOUS_CHECKED_IN, + RESTARTED_CHECKED_IN, + ], + later_reports: 0, + expected_state: LocationState::Starting, + }, + LocationStateTestCase { + description: "its first load failed: falling back to the previous snapshot", + reported: vec![ + PREVIOUS_PUBLISHED, + RESTARTED_CHECKED_IN, + reported(Instance::Restarted, 4, ReportedHealth(failed, 12)), + ], + later_reports: 0, + expected_state: LocationState::FallingBack, + }, + LocationStateTestCase { + description: "its first load published: healthy, though the previous instance's last load failed", + reported: vec![ + PREVIOUS_PUBLISHED, + reported(Instance::Previous, 600, ReportedHealth(failed, 12)), + RESTARTED_CHECKED_IN, + reported(Instance::Restarted, 4, ReportedHealth(published, 13)), + ], + later_reports: 0, + expected_state: LocationState::Healthy, + }, + LocationStateTestCase { + description: "the newest instance's start is no longer kept: its location's newest reports decide", + reported: vec![ + reported(Instance::LongRunning, 5, ReportedHealth(check_in, 0)), + reported(Instance::Previous, 600, ReportedHealth(failed, 12)), + ], + later_reports: 0, + expected_state: LocationState::FallingBack, + }, + LocationStateTestCase { + description: "the history was cut after the newest instance started: its location's newest reports decide", + reported: vec![ + PREVIOUS_PUBLISHED, + PREVIOUS_CHECKED_IN, + RESTARTED_CHECKED_IN, + ], + later_reports: 100, + expected_state: LocationState::Healthy, + }, + LocationStateTestCase { + description: "a session ID without a start time: its location's newest reports decide", + reported: vec![ + PREVIOUS_PUBLISHED, + reported(Instance::Unordered, 5, ReportedHealth(check_in, 0)), + ], + later_reports: 0, + expected_state: LocationState::Healthy, + }, + LocationStateTestCase { + description: "no instance checked in for 90 seconds: broken, never starting", + reported: vec![ + PREVIOUS_PUBLISHED, + reported(Instance::Restarted, 120, ReportedHealth(check_in, 0)), + ], + later_reports: 0, + expected_state: LocationState::Broken, + }, + ]; + for test_case in test_cases { + let (observations, now) = health_history(&test_case.reported, test_case.later_reports); + assert_eq!( + LocationState::of(&observations, ("production", now)), + test_case.expected_state, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_loads_of_one_generation_when_reading_health_then_the_latest_to_arrive_decides() { + let test_cases = [ + LocationStateTestCase { + description: "failed attempts at a generation, then its publication: healthy", + reported: vec![ + reported(Instance::Restarted, 20, ReportedHealth(failed, 12)), + reported(Instance::Restarted, 15, ReportedHealth(failed, 12)), + RESTARTED_CHECKED_IN, + reported(Instance::Restarted, 4, ReportedHealth(published, 12)), + ], + later_reports: 0, + expected_state: LocationState::Healthy, + }, + LocationStateTestCase { + description: "a generation's publication, then a failed reload at it: falling back", + reported: vec![ + reported(Instance::Restarted, 20, ReportedHealth(published, 12)), + RESTARTED_CHECKED_IN, + reported(Instance::Restarted, 4, ReportedHealth(failed, 12)), + ], + later_reports: 0, + expected_state: LocationState::FallingBack, + }, + LocationStateTestCase { + description: "a published generation whose plan of what changed failed: not healthy", + reported: vec![ + RESTARTED_CHECKED_IN, + reported(Instance::Restarted, 10, ReportedHealth(published, 12)), + reported( + Instance::Restarted, + 4, + ReportedHealth(change_plan_failed, 12), + ), + ], + later_reports: 0, + expected_state: LocationState::ChangePlanFailed, + }, + LocationStateTestCase { + description: "a failed load outranks a failed plan of what changed", + reported: vec![ + RESTARTED_CHECKED_IN, + reported( + Instance::Restarted, + 10, + ReportedHealth(change_plan_failed, 12), + ), + reported(Instance::Restarted, 4, ReportedHealth(failed, 12)), + ], + later_reports: 0, + expected_state: LocationState::FallingBack, + }, + LocationStateTestCase { + description: "a previous instance's failures at the generation the next one published, with its start no longer kept", + reported: vec![ + reported(Instance::Previous, 600, ReportedHealth(failed, 12)), + reported(Instance::Previous, 300, ReportedHealth(failed, 12)), + reported(Instance::LongRunning, 5, ReportedHealth(check_in, 0)), + reported(Instance::LongRunning, 4, ReportedHealth(published, 12)), + ], + later_reports: 0, + expected_state: LocationState::Healthy, + }, + ]; + for test_case in test_cases { + let (observations, now) = health_history(&test_case.reported, test_case.later_reports); + assert_eq!( + LocationState::of(&observations, ("production", now)), + test_case.expected_state, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/platform/test_types.rs b/crates/sqlbuild-orchestration/tests/platform/test_types.rs index 65c064cc1f..496cebf9b4 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_types.rs @@ -1,6 +1,6 @@ use std::sync::{Arc, Mutex}; -use crate::platform::models::{PlatformEvent, PlatformEventEnvelope, StorageKind}; +use crate::platform::models::{LocationHealth, PlatformEvent, PlatformEventEnvelope, StorageKind}; use chrono::{DateTime, Utc}; use serde::Deserialize; @@ -70,6 +70,8 @@ pub(crate) struct CompileFailureTestCase { pub(crate) finding_count: u64, pub(crate) listed: usize, pub(crate) message_chars: usize, + /// The load error's length. + pub(crate) error_chars: usize, pub(crate) expected_accepted: bool, } @@ -81,3 +83,41 @@ pub(crate) struct ProviderSecretsHealthTestCase { pub(crate) expected_missing: u64, pub(crate) expected_state: crate::platform::models::LocationState, } + +/// A location instance in a health history, by when its process started. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Instance { + /// Started three hours before the read. + Previous, + /// Started 25 seconds before the read. + Restarted, + /// Started eight days before the read, before the history kept. + LongRunning, + /// An instance whose session ID carries no start time. + Unordered, +} + +/// One report in a health history: the instance, how many seconds before the read, and what it said. +pub(crate) struct Reported { + pub(crate) instance: Instance, + pub(crate) seconds_ago: i64, + pub(crate) health: ReportedHealth, +} + +/// What an instance said: a report of the generation, built by a health helper such as `published`. +#[derive(Clone, Copy)] +pub(crate) struct ReportedHealth(pub(crate) fn(i64) -> LocationHealth, pub(crate) i64); + +pub(crate) struct LocationStateTestCase { + pub(crate) description: &'static str, + pub(crate) reported: Vec, + /// Provider checks the previous instance sent after the restart, filling the history. + pub(crate) later_reports: usize, + pub(crate) expected_state: crate::platform::models::LocationState, +} + +pub(crate) struct FailingLocationTestCase { + pub(crate) description: &'static str, + pub(crate) backend: crate::store::tests::store_test_types::Backend, + pub(crate) expected_error: &'static str, +} diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/dialect.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/dialect.rs index 9b5326f8c7..00861df819 100644 --- a/crates/sqlbuild-python-base/src/native_host/_helpers/dialect.rs +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/dialect.rs @@ -3,11 +3,12 @@ /// Adapter attributes that only write SQL or describe the dialect, by prefix. const SYNTAX_PREFIXES: [&str; 3] = ["render_", "_render_", "supports_"]; /// Adapter attributes that only describe the dialect or its defaults; none takes a connection. -const SYNTAX_ATTRIBUTES: [&str; 33] = [ +const SYNTAX_ATTRIBUTES: [&str; 34] = [ "adapter_name", "allows_implicit_managed_write_schema", "build_cursor_filter", "collection_rendering", + "cursor_type_range", "default_database", "default_promotion_strategy", "default_schema", diff --git a/crates/sqlbuild-python-base/src/records/_helpers/compiler_enums/constants.rs b/crates/sqlbuild-python-base/src/records/_helpers/compiler_enums/constants.rs index b995105a6d..474d876e9d 100644 --- a/crates/sqlbuild-python-base/src/records/_helpers/compiler_enums/constants.rs +++ b/crates/sqlbuild-python-base/src/records/_helpers/compiler_enums/constants.rs @@ -606,6 +606,7 @@ const E_PLAN_REASON: EnumSpec = EnumSpec { ("DISABLED", "disabled"), ("SOURCE_FRESHNESS_ERROR", "source_freshness_error"), ("EXTERNAL_UPSTREAM_FAILED", "external_upstream_failed"), + ("WINDOW_BEFORE_CURSOR_START", "window_before_cursor_start"), ], }; const E_INCREMENTAL_STRATEGY: EnumSpec = EnumSpec { 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 1d3f2765ea..bc42bb4dbd 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 @@ -675,6 +675,8 @@ const R_MODEL_PLAN_ENTRY: RecordSpec = RecordSpec { FieldSpec::new("refresh_on_build", FieldDefault::False), FieldSpec::new("dynamic_readers", FieldDefault::EmptyTuple), FieldSpec::new("dynamic_paused", FieldDefault::False), + FieldSpec::new("planning_error", FieldDefault::None), + FieldSpec::new("skip_reason", FieldDefault::None), ], }; const R_CLONE_SOURCE_PLAN_ENTRY: RecordSpec = RecordSpec { @@ -1248,6 +1250,7 @@ const R_PLAN_WARNING: RecordSpec = RecordSpec { FieldSpec::required("severity"), FieldSpec::required("message"), FieldSpec::new("code", FieldDefault::None), + FieldSpec::new("help", FieldDefault::None), ], }; const R_COLUMN_RENAME_HINT: RecordSpec = RecordSpec { diff --git a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/analysis.rs b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/analysis.rs index 89cbcc4650..6951e27198 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/analysis.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/analysis.rs @@ -39,6 +39,7 @@ use sqlbuild_python_project::planner_identity::main::execution_cycle::execution_ use sqlbuild_python_project::planner_selection::main::reject_unit_test_selectors::reject_unit_test_selectors; use sqlbuild_python_project::planner_selection::main::select_project_graph::select_project_graph; use sqlbuild_python_project::project_snapshot::main::job_group_cycles::job_group_cycles; +use sqlbuild_python_project::project_snapshot::main::orchestration_selectors::orchestration_selectors; use sqlbuild_rules::lint_text::main::counts_toward_exit::counts_toward_exit; use std::time::Instant; @@ -232,10 +233,16 @@ fn analyzed<'py>( early_lint_wait_ms = early_lint.borrow().stop(py)?.into_pyobject(py)?.into_any(); } else { let compiled: &Bound<'py, CompiledProjectGraph> = graph.cast()?; + let native = compiled.get().native(py); + orchestration_selectors( + &options.project_dir, + (&project, &discovered), + native.get().graph(), + )?; job_group_cycles( &options.project_dir, (&project, &discovered), - compiled.get().native(py).get().graph(), + native.get().graph(), )?; } let (lineage, lineage_ms): (Bound<'py, PyAny>, u64) = driver.lineage(&graph, &dialect)?; 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 186f30f55c..55ef877fc6 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 @@ -29,6 +29,10 @@ const CHANGED_IDENTITY: &str = "changed"; /// The plan document field saying audit failures hold nothing back; present only when they do. pub(crate) const IGNORE_AUDIT_FAILURES_KEY: &str = "ignore_audit_failures"; +/// The row action and reason of a model that can't be planned. +pub(crate) const ERROR_ACTION: &str = "error"; +pub(crate) const PLANNING_ERROR_REASON: &str = "planning_error"; + fn token<'py>(bound: Bound<'py, PyAny>) -> PyResult> { Ok(PyString::new(bound.py(), &sentinel_to_token(&bound)?).into_any()) } @@ -288,6 +292,26 @@ pub(crate) fn model_json<'py>(entry: &Bound<'py, PyAny>) -> PyResult = native_field(entry, "skip_reason")?; + if !skip_reason.is_none() { + model.set_item("skip_reason", skip_reason)?; + } + let planning_error: Bound<'py, PyAny> = native_field(entry, "planning_error")?; + if !planning_error.is_none() { + model.set_item("action", ERROR_ACTION)?; + model.set_item("reason", PLANNING_ERROR_REASON)?; + model.set_item( + "error", + dict( + py, + vec![ + ("code", native_field(&planning_error, "code")?), + ("message", native_field(&planning_error, "message")?), + ("help", native_field(&planning_error, "help")?), + ], + )?, + )?; + } Ok(model.into_any()) } @@ -397,7 +421,7 @@ pub(crate) fn warning_json<'py>(warning: &Bound<'py, PyAny>) -> PyResult = native_field(warning, key)?; if !value.is_none() { item.set_item(key, value)?; 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 c3cfba3a6d..b25899025c 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 @@ -25,6 +25,7 @@ use crate::plan_output::_helpers::display::format_waiting_on_empty_inputs; use crate::plan_output::_helpers::display::model_materialization_label; use crate::plan_output::_helpers::migrations::pre_build_lines; use crate::plan_output::_helpers::plan_json::unified_diff; +use crate::plan_output::_helpers::plan_json::{ERROR_ACTION, PLANNING_ERROR_REASON}; use crate::plan_output::_helpers::python_identity::definition_source_text; use crate::plan_output::_helpers::python_identity::dependency_source_text; use crate::plan_output::_helpers::values::optional_text; @@ -43,6 +44,10 @@ const SKIP_ACTION: &str = "skip"; const QUERY_CHANGED: &str = "query_changed"; const CONFIG_CHANGED: &str = "config_changed"; const MICROBATCH_MODE: &str = "microbatch"; +const ERROR_SEVERITY: &str = "error"; +const CREATE_TABLE_ACTION: &str = "create_table"; +/// An unbounded end of a full build's cursor range. +const UNBOUNDED_RANGE_END: &str = "(unbounded)"; const CHANGED_IDENTITY: &str = "changed"; pub(crate) const PLAN_OPTIONS: (&[&str], &[&str]) = ( &["plan"], @@ -94,6 +99,19 @@ fn cursor_range(entry: &Bound<'_, PyAny>, bounds: &Bound<'_, PyAny>) -> PyResult Ok(format!("{start} \u{2192} {end}")) } +/// A non-microbatch full build's range: its `cursor_start` floor, or unbounded, to unbounded; `None` for other builds. +fn full_build_range(entry: &Bound<'_, PyAny>, runtime_owned: bool) -> PyResult> { + if runtime_owned + || native_field(entry, "incremental_mode")?.eq(MICROBATCH_MODE)? + || !native_field(&native_field(entry, "action")?, "value")?.eq(CREATE_TABLE_ACTION)? + { + return Ok(None); + } + let start: String = optional_text(&native_field(entry, "cursor_start")?)? + .unwrap_or_else(|| UNBOUNDED_RANGE_END.to_owned()); + Ok(Some(format!("{start} \u{2192} {UNBOUNDED_RANGE_END}"))) +} + fn cursor_text(entry: &Bound<'_, PyAny>, details: CursorDetails<'_>) -> PyResult { let empty_inputs_window: Option = if details.empty_inputs.is_truthy()? { Some(if details.waiting_on_empty_inputs { @@ -104,11 +122,10 @@ fn cursor_text(entry: &Bound<'_, PyAny>, details: CursorDetails<'_>) -> PyResult } else { None }; - let range: Option = details - .resolved_bounds - .as_ref() - .map(|bounds| cursor_range(entry, bounds)) - .transpose()?; + let range: Option = match &details.resolved_bounds { + Some(bounds) => Some(cursor_range(entry, bounds)?), + None => full_build_range(entry, details.runtime_owned)?, + }; Ok(CursorPlanText { column: optional_text(&native_field(entry, "cursor_column")?)?.unwrap_or_default(), cursor_type: optional_text(&native_field(entry, "cursor_type")?)?, @@ -209,15 +226,43 @@ fn coloured(diff: Option>) -> Option> { diff.map(|lines| format_query_diff(&lines, CliStyle { use_color: true })) } +/// A model's planning error as `sqb` prints errors: `error[CODE]: message`, then its help. +fn planning_error_text(warning: &Bound<'_, PyAny>) -> PyResult { + let message: String = text(&native_field(warning, "message")?)?; + let code: Option = optional_text(&native_field(warning, "code")?)?; + let help: Option = optional_text(&native_field(warning, "help")?)?; + let mut lines: String = match code { + Some(code) => format!("error[{code}]: {message}"), + None => message, + }; + if let Some(help) = help { + lines.push_str(&format!("\nhelp: {help}")); + } + Ok(PlanWarningText { + severity: ERROR_SEVERITY.to_owned(), + message: lines, + model_name: optional_text(&native_field(warning, "model_name")?)?, + }) +} + fn model_text(entry: &Bound<'_, PyAny>) -> PyResult { let action: String = text(&native_field(&native_field(entry, "action")?, "value")?)?; let reason: String = text(&native_field(&native_field(entry, "reason")?, "value")?)?; let name: String = text(&native_field(entry, "name")?)?; + if !native_field(entry, "planning_error")?.is_none() { + return Ok(ModelPlanText { + name, + action: ERROR_ACTION.to_owned(), + reason: PLANNING_ERROR_REASON.to_owned(), + ..ModelPlanText::default() + }); + } if action == SKIP_ACTION { return Ok(ModelPlanText { name, action, reason, + skip_reason: optional_text(&native_field(entry, "skip_reason")?)?, ..ModelPlanText::default() }); } @@ -256,6 +301,7 @@ fn model_text(entry: &Bound<'_, PyAny>) -> PyResult { query_diff: coloured(model_query_diff(entry, &reason)?), reinitialised_by: optional_text(&native_field(entry, "reinitialised_by")?)?, paused: native_field(entry, "dynamic_paused")?.is_truthy()?, + skip_reason: None, name, action, reason, @@ -493,7 +539,18 @@ pub(crate) fn report(arguments: &KeywordArguments<'_>) -> PyResult = native_field(&plan, "metadata")?; let mut warnings: Vec = Vec::new(); + let mut planning_errors: Vec> = Vec::new(); + for entry in items(&native_field(&plan, "model_entries")?)? { + let planning_error: Bound<'_, PyAny> = native_field(&entry, "planning_error")?; + if !planning_error.is_none() { + planning_errors.push(planning_error); + } + } for warning in items(&native_field(&plan, "warnings")?)? { + if planning_errors.iter().any(|error| error.is(&warning)) { + warnings.push(planning_error_text(&warning)?); + continue; + } warnings.push(PlanWarningText { severity: text(&native_field( &native_field(&warning, "severity")?, 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 f50619bc11..38f688be75 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 @@ -102,6 +102,7 @@ pub fn format_plan_json(py: Python<'_>, options: Option>) -> P "warnings", mapped(&native_field(&plan, "warnings")?, warning_json)?, ), + ("has_errors", any(py, plan_has_errors(&plan)?)?), ("retention", retention_json(&plan)?), ("table_type_conversions", table_type_json(&plan)?), ("migrations", migrations_json(&plan)?), @@ -196,3 +197,13 @@ fn mark_renames(result: &Bound<'_, PyDict>) -> PyResult<()> { } Ok(()) } + +/// Whether any plan finding has error severity, such as a model that can't be planned. +fn plan_has_errors(plan: &Bound<'_, PyAny>) -> PyResult { + for warning in native_field(plan, "warnings")?.try_iter()? { + if native_field(&native_field(&warning?, "severity")?, "value")?.eq("error")? { + return Ok(true); + } + } + Ok(false) +} diff --git a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/mod.rs b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/mod.rs index 8147db06b4..90ab9f4774 100644 --- a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/mod.rs +++ b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/mod.rs @@ -1,5 +1,7 @@ pub(crate) mod contexts; pub(crate) mod getters; pub(crate) mod model_entries; +pub(crate) mod planning_error; pub(crate) mod relations; pub(crate) mod values; +pub(crate) mod window_turns; diff --git a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/model_entries.rs b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/model_entries.rs index 3885247bdc..ef162e2123 100644 --- a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/model_entries.rs +++ b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/model_entries.rs @@ -4,6 +4,8 @@ use crate::planner_changes::main::replaces_incremental_relation::replaces_increm use crate::planner_entries::_helpers::entries::values::{ MICROBATCH_CONCURRENCY_MESSAGE, error_of, native, none, planner_type, replaced, string, }; +use crate::planner_entries::_helpers::entries::window_turns::window_turn; +use crate::planner_entries::models::WindowTally; use crate::planner_entries::models::{ ModelPlanContext, PlanEntriesRequest, PlanEntryBuildInputs, PlannerRelationsContext, }; @@ -16,7 +18,6 @@ use crate::planner_resolution::main::cursor::config_str::config_str; use crate::planner_resolution::main::cursor::cursor_safety_configs::cursor_safety_configs; use crate::planner_resolution::main::cursor::empty_cursor_inputs::empty_cursor_inputs; use crate::planner_resolution::main::cursor::microbatch_range::microbatch_range; -use crate::planner_resolution::main::cursor::model_cursor_overrides::model_cursor_overrides; use crate::planner_resolution::main::cursor::plan_cursor_bounds::plan_cursor_bounds; use crate::planner_resolution::main::cursor::with_cursor_safety_warnings::with_cursor_safety_warnings; use crate::planner_resolution::main::references::model_hook_entries::model_hook_entries; @@ -464,6 +465,7 @@ pub(crate) fn plan_entries<'py>( let microbatch = enum_member(py, RecordId::IncrementalMode, "MICROBATCH")?; let mut entries: Vec> = Vec::new(); let mut warnings: Vec> = Vec::new(); + let mut tally = WindowTally::default(); for key in &scope_data.order { let name = &key.1; if !scope_data.selected.contains(key) || !models.contains(name)? { @@ -473,24 +475,31 @@ pub(crate) fn plan_entries<'py>( continue; }; let resolved = models.get_item(name)?; - let overrides = model_cursor_overrides( + let turn = window_turn( &model, - &cursor_overrides, - (start_override.clone(), end_override.clone()), - )?; - let effective_full_refresh = - resolve_model_full_refresh(&model, full_refresh.applies(name))?; - let (mut entry, entry_warnings) = plan_model_from_change(&ModelPlanRequest { - model: model.clone(), - snapshot: snapshot.clone(), - context: &reads, - sql_analysis_enabled, - full_refresh: effective_full_refresh, - overrides, - change_result: native_field(&resolved, "change")?, - protect_full_refresh: !freshness_blocked.contains(name)? - && !external_blocked.contains(name)?, - })?; + ( + &cursor_overrides, + (start_override.clone(), end_override.clone()), + ), + |overrides| { + plan_model_from_change(&ModelPlanRequest { + model: model.clone(), + snapshot: snapshot.clone(), + context: &reads, + sql_analysis_enabled, + full_refresh: resolve_model_full_refresh(&model, full_refresh.applies(name))?, + overrides, + change_result: native_field(&resolved, "change")?, + protect_full_refresh: !freshness_blocked.contains(name)? + && !external_blocked.contains(name)?, + }) + }, + ); + let Some((mut entry, entry_warnings)) = + tally.take((&mut entries, &mut warnings), &model, turn)? + else { + continue; + }; let entry_name = native_field(&entry, "name")?; if freshness_blocked.contains(&entry_name)? { entry = replaced( @@ -537,6 +546,7 @@ pub(crate) fn plan_entries<'py>( warnings.push(warning?); } } + tally.refuse_empty_window(py)?; if let Some(warning) = check_microbatch_concurrency(&project, &dialect, &entries, concurrency)? { warnings.push(warning); diff --git a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/planning_error.rs b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/planning_error.rs new file mode 100644 index 0000000000..07cd40053b --- /dev/null +++ b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/planning_error.rs @@ -0,0 +1,127 @@ +//! One model that can't be planned becomes an error row, so the rest of the plan still plans. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyErr, PyResult, Python}; +use sqlbuild_python_base::records::main::construct::enum_member::enum_member; +use sqlbuild_python_base::records::main::construct::error_class::error_class; +use sqlbuild_python_base::records::main::construct::new_record_with::new_record_with; +use sqlbuild_python_base::records::main::fields::field::field as native_field; +use sqlbuild_python_base::records::types::{ErrorId, RecordId}; +use sqlbuild_python_project::compiled_views::main::compiled_models::destination::destination; +use sqlbuild_python_project::compiled_views::main::compiled_models::model_key::model_key; +use sqlbuild_python_project::compiled_views::main::compiled_models::name_object::name_object; + +use crate::planner_entries::_helpers::entries::values::{planner_model, planner_type, string}; +use crate::planner_entries::constants::SOURCE_VALIDATION_CODE_PREFIX; +use crate::planner_resolution::models::WindowFit; +use crate::planner_strategy::main::strategy::materialization_of::materialization_of; + +/// The model's error row and its error-severity warning, or `error` itself when it isn't a planning error: a compile or validation error, such as a capped watermark edge (P001) or a source that breaks its contract (S4xx), still fails the plan. +pub(crate) fn planning_error<'py>( + model: &Bound<'py, PyAny>, + error: PyErr, +) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>)> { + let py: Python<'py> = model.py(); + let value: Bound<'py, PyAny> = error.value(py).clone().into_any(); + let attribute = |name: &str| -> PyResult> { + Ok(value + .getattr_opt(name)? + .unwrap_or_else(|| py.None().into_bound(py))) + }; + let code: String = attribute("code")?.str()?.to_string(); + if !value.is_instance(&error_class(py, ErrorId::PlannerInput)?)? + || code.starts_with(SOURCE_VALIDATION_CODE_PREFIX) + { + return Err(error); + } + let message: Bound<'py, PyAny> = match attribute("message")? { + message if message.is_truthy()? => message, + _ => value.str()?.into_any(), + }; + let warning: Bound<'py, PyAny> = new_record_with( + py, + RecordId::PlanWarning, + &[ + ("model_name", name_object(model)?), + ( + "severity", + enum_member(py, RecordId::WarningSeverity, "ERROR")?, + ), + ("message", message), + ("code", attribute("code")?), + ("help", attribute("help")?), + ], + )?; + let entry = skipped_entry(model, ("NO_CHANGE", ("planning_error", warning.clone())))?; + Ok((entry, warning)) +} + +/// The row of a model whose explicit cursor window ends at or before its `cursor_start` `floor`: skipped, with that as its reason. +pub(crate) fn window_skip<'py>( + model: &Bound<'py, PyAny>, + floor: &str, +) -> PyResult> { + let reason = string( + model.py(), + &format!("window ends before cursor_start {floor}"), + ); + skipped_entry( + model, + ("WINDOW_BEFORE_CURSOR_START", ("skip_reason", reason)), + ) +} + +/// A skipped model row with `reason` and one extra field, which runs nothing. +fn skipped_entry<'py>( + model: &Bound<'py, PyAny>, + (reason, extra): (&str, (&str, Bound<'py, PyAny>)), +) -> PyResult> { + let py: Python<'py> = model.py(); + planner_model( + py, + RecordId::ModelPlanEntry, + &[ + ("key", model_key(model)?), + ("name", name_object(model)?), + ("relative_path", native_field(model, "relative_path")?), + ("materialization_type", materialization_of(model)?), + ("action", planner_type(py, RecordId::PlanAction, "SKIP")?), + ("reason", planner_type(py, RecordId::PlanReason, reason)?), + ("destination", destination(model)?), + ("fingerprint_query_sql", string(py, "")), + ("resolved_sql", string(py, "")), + ("logical_ddl", string(py, "")), + extra, + ], + ) +} + +/// The warning on a model whose explicit cursor window started before its `cursor_start`, which starts it there; `None` for any other fit. +pub(crate) fn window_clamp_warning<'py>( + model: &Bound<'py, PyAny>, + fit: &WindowFit, +) -> PyResult>> { + let WindowFit::Clamped { requested, floor } = fit else { + return Ok(None); + }; + let py: Python<'py> = model.py(); + Ok(Some(new_record_with( + py, + RecordId::PlanWarning, + &[ + ("model_name", name_object(model)?), + ( + "severity", + enum_member(py, RecordId::WarningSeverity, "WARNING")?, + ), + ( + "message", + string( + py, + &format!( + "explicit start {requested} is before cursor_start {floor}; the window starts at {floor}" + ), + ), + ), + ], + )?)) +} diff --git a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/window_turns.rs b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/window_turns.rs new file mode 100644 index 0000000000..99e53a6d9c --- /dev/null +++ b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/window_turns.rs @@ -0,0 +1,87 @@ +//! An explicit cursor window fitted to each model's floor: planned, clamped with a warning, skipped, or a planning error; nothing to build at all is P001. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; +use sqlbuild_python_base::records::main::construct::new_plain_error::new_plain_error; +use sqlbuild_python_base::records::types::ErrorId; + +use crate::planner_entries::_helpers::entries::planning_error::{ + planning_error, window_clamp_warning, window_skip, +}; +use crate::planner_entries::models::{WindowTally, WindowTurn}; +use crate::planner_resolution::main::cursor::config_str::config_str; +use crate::planner_resolution::main::cursor::model_cursor_overrides::model_cursor_overrides; +use crate::planner_resolution::models::WindowFit; +use sqlbuild_python_project::compiled_views::main::compiled_models::name_object::name_object; + +/// Fit the explicit window to `model`'s floor, then plan it with `plan` unless the window ends before the floor. +pub(crate) fn window_turn<'py>( + model: &Bound<'py, PyAny>, + (cursor_overrides, overrides): (&Bound<'py, PyAny>, (Bound<'py, PyAny>, Bound<'py, PyAny>)), + plan: impl FnOnce( + (Bound<'py, PyAny>, Bound<'py, PyAny>), + ) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>)>, +) -> PyResult> { + let (window, fit) = model_cursor_overrides(model, cursor_overrides, overrides)?; + if let WindowFit::BeforeFloor { floor, window } = &fit { + return Ok(WindowTurn::Skipped( + window_skip(model, floor)?, + (floor.clone(), window.clone()), + )); + } + let clamped = window_clamp_warning(model, &fit)?; + Ok(WindowTurn::Planned(plan(window)?, clamped)) +} + +impl WindowTally { + /// The planned row and its warnings to finish; a skipped or failed model's row goes straight to `entries`, and `None`. + pub(crate) fn take<'py>( + &mut self, + (entries, warnings): (&mut Vec>, &mut Vec>), + model: &Bound<'py, PyAny>, + turn: PyResult>, + ) -> PyResult, Bound<'py, PyAny>)>> { + match turn { + Ok(WindowTurn::Planned(planned, clamped)) => { + warnings.extend(clamped); + self.cursor_models_planned += usize::from(!config_str(model, "cursor")?.is_none()); + Ok(Some(planned)) + } + Ok(WindowTurn::Skipped(entry, (floor, window))) => { + let name = name_object(model)?.str()?.to_string(); + entries.push(entry); + self.window_skips + .push((format!("{name} (cursor_start {floor})"), window)); + Ok(None) + } + Err(error) => { + let (entry, warning) = planning_error(model, error)?; + entries.push(entry); + warnings.push(warning); + Ok(None) + } + } + } + + /// P001 when the explicit window skipped every selected cursor model, naming the window and each one's floor. + pub(crate) fn refuse_empty_window(&self, py: Python<'_>) -> PyResult<()> { + let Some((_, window)) = self.window_skips.first() else { + return Ok(()); + }; + if self.cursor_models_planned > 0 { + return Ok(()); + } + let floors: Vec<&str> = self + .window_skips + .iter() + .map(|(model, _)| model.as_str()) + .collect(); + Err(new_plain_error( + py, + ErrorId::CompileInput, + &format!( + "the explicit cursor window {window} leaves nothing to build: it ends at or before the cursor_start of every selected cursor model: {}", + floors.join(", ") + ), + )) + } +} diff --git a/crates/sqlbuild-python-planner/src/planner_entries/constants.rs b/crates/sqlbuild-python-planner/src/planner_entries/constants.rs index c55b87786f..5d3a8ef847 100644 --- a/crates/sqlbuild-python-planner/src/planner_entries/constants.rs +++ b/crates/sqlbuild-python-planner/src/planner_entries/constants.rs @@ -24,3 +24,6 @@ pub const GETTERS: &[GetterEntry] = &[ read: read_planner_relations_context, }, ]; + +/// The code family of source checks against the warehouse (a missing source, a contract the source breaks); they validate the project, so they fail the plan rather than one model's row. +pub const SOURCE_VALIDATION_CODE_PREFIX: &str = "S4"; diff --git a/crates/sqlbuild-python-planner/src/planner_entries/models.rs b/crates/sqlbuild-python-planner/src/planner_entries/models.rs index 4136195d77..06dc1147ca 100644 --- a/crates/sqlbuild-python-planner/src/planner_entries/models.rs +++ b/crates/sqlbuild-python-planner/src/planner_entries/models.rs @@ -101,3 +101,20 @@ pub struct PlanEntryBuildInputs { pub max_microbatches_is_override: bool, pub microbatch_limit_action: Py, } + +/// One model's turn under an explicit cursor window: planned, with a clamp warning when the window started before its floor, or skipped because the window ends at or before it. +pub(crate) enum WindowTurn<'py> { + Planned( + (Bound<'py, PyAny>, Bound<'py, PyAny>), + Option>, + ), + /// The skip row, and the floor and window that skipped it. + Skipped(Bound<'py, PyAny>, (String, String)), +} + +/// What an explicit cursor window did across the selection: how many cursor models planned, and which it skipped (`model (cursor_start floor)`, and the window). +#[derive(Debug, Default)] +pub(crate) struct WindowTally { + pub(crate) cursor_models_planned: usize, + pub(crate) window_skips: Vec<(String, String)>, +} diff --git a/crates/sqlbuild-python-planner/src/planner_phases/constants.rs b/crates/sqlbuild-python-planner/src/planner_phases/constants.rs index d44d8393a1..c1b2d1ca40 100644 --- a/crates/sqlbuild-python-planner/src/planner_phases/constants.rs +++ b/crates/sqlbuild-python-planner/src/planner_phases/constants.rs @@ -28,8 +28,8 @@ pub(crate) const DOWNGRADE_HISTORY_DAYS: i64 = 90; pub(crate) const FULL_REFRESH_DISABLED_REBUILD_CODE: &str = "S203"; -/// A FULL backfill of a non-microbatch model whose SQL reads the cursor intrinsics. -pub(crate) const FULL_BACKFILL_WITHOUT_INTERVAL_CODE: &str = "S204"; +/// Marks an unbounded end of a full build's cursor intrinsics in compiled SQL. +pub(crate) const UNBOUNDED_CURSOR_MARK: &str = "/* (unbounded) */"; pub(crate) const MISSING_UPSTREAM_CODE: &str = "S301"; diff --git a/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/cursor/cursor_ranges.rs b/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/cursor/cursor_ranges.rs index 3664304ecf..aa349bc0ed 100644 --- a/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/cursor/cursor_ranges.rs +++ b/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/cursor/cursor_ranges.rs @@ -493,9 +493,10 @@ pub(crate) fn resolve_cursor_overrides<'py>( start_cursor_override: Bound<'py, PyAny>, end_cursor_override: Bound<'py, PyAny>, ) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>)> { - model_cursor_overrides( + let (window, _) = model_cursor_overrides( model, cursor_overrides, (start_cursor_override, end_cursor_override), - ) + )?; + Ok(window) } diff --git a/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/references/orchestration.rs b/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/references/orchestration.rs index 30fcbb6af1..9434900e9e 100644 --- a/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/references/orchestration.rs +++ b/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/references/orchestration.rs @@ -1,14 +1,15 @@ //! Model, function and SQL-hook orchestration through adapter-owned rendering. -use crate::planner_phases::constants::FULL_BACKFILL_WITHOUT_INTERVAL_CODE; +use crate::planner_phases::constants::UNBOUNDED_CURSOR_MARK; use crate::planner_resolution::_helpers::cursor::cursor_model::{ compute_model_cursor_bounds, unbounded, }; +use crate::planner_resolution::constants::CURSOR_START; use crate::planner_resolution::main::references::model_hook_entries::model_hook_entries; use crate::planner_resolution::models::Resolution; use crate::planner_resolution::models::{CursorFiltering, ModelSqlRequest}; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; -use pyo3::types::{PyDict, PyDictMethods, PyString, PyTuple}; +use pyo3::types::{PyDict, PyString, PyTuple}; use pyo3::{PyErr, pyfunction}; use sqlbuild_model_config::config_values::models::ConfigNode; use sqlbuild_python_base::boundary::main::call_with::call_with; @@ -19,7 +20,10 @@ use sqlbuild_python_base::records::main::construct::error_class::error_class; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::ErrorId; use sqlbuild_python_front::attachments::main::resolve_cursor_intrinsics::resolve_cursor_intrinsics; +use sqlbuild_python_front::cursor::main::scalars::render_value::render_value; use sqlbuild_python_front::cursor::main::scalars::sentinel_to_token::sentinel_to_token; +use sqlbuild_python_front::cursor::main::scalars::try_parse::try_parse; +use sqlbuild_python_front::model_config::main::config::config_cursor_bound::config_cursor_bound; use sqlbuild_python_front::model_config::main::config::config_node_of::config_node_of; use sqlbuild_python_front::model_config::main::config::config_text_is::config_text_is; use sqlbuild_python_front::model_config::main::config::config_text_object::config_text_object; @@ -120,7 +124,12 @@ pub(crate) fn resolve_model_sql<'py>( { unbounded(py)? } - _ => return Err(unresolved_bounds_error(py, &name, cause.as_deref())?), + _ if cause.is_some() => { + sql = full_build_bounds(&sql, model, &cursor_type, &resolution.dialect)?; + resolution.assert_resolved(&sql, &format!("Model '{name}'"))?; + return Ok(sql); + } + _ => return Err(unresolved_bounds_error(py, &name)?), }; sql = intrinsic_bounds(&sql, &bounds, &cursor_type, &resolution.dialect)?; } @@ -167,19 +176,46 @@ fn intrinsic_bounds<'py>( Ok(resolve_cursor_intrinsics(py, sql, Some(&start_sql), Some(&end_sql))?.0) } -fn unresolved_bounds_error(py: Python<'_>, name: &str, cause: Option<&str>) -> PyResult { +fn unresolved_bounds_error(py: Python<'_>, name: &str) -> PyResult { let error = error_class(py, ErrorId::PlannerInput)?; - let kwargs = PyDict::new(py); - let message = if let Some(cause) = cause { - kwargs.set_item("code", FULL_BACKFILL_WITHOUT_INTERVAL_CODE)?; - kwargs.set_item("help", "rebuild it with an explicit cursor interval (--start-cursor-ts and --end-cursor-ts, or the -int forms), or make it a microbatch model so a full rebuild can run batch by batch")?; - format!( - "Model '{name}' was given a FULL backfill ({cause}), but it uses cursor intrinsics and a non-microbatch full rebuild has no cursor interval" - ) - } else { - format!("Model '{name}' uses cursor intrinsics, but cursor bounds could not be resolved") + let message = + format!("Model '{name}' uses cursor intrinsics, but cursor bounds could not be resolved"); + Ok(PyErr::from_value(error.call1((message,))?)) +} + +/// A non-microbatch full build's intrinsics: the model's `cursor_start` floor or the cursor type's lowest value, to its highest. +fn full_build_bounds<'py>( + sql: &str, + model: &Bound<'py, PyAny>, + cursor_type: &Bound<'py, PyAny>, + dialect: &Bound<'py, Dialect>, +) -> PyResult { + let py = model.py(); + let (lowest, highest): (String, String) = call_with( + &dialect.syntax("cursor_type_range")?, + &[("cursor_type", cursor_type.clone())], + )? + .extract()?; + let literal = |value: &str| -> PyResult { + call_with( + &dialect.syntax("render_cursor_bound_literal")?, + &[ + ("value", PyString::new(py, value).into_any()), + ("cursor_type", cursor_type.clone()), + ], + )? + .extract() + }; + let floor = match config_cursor_bound(py, &model_values(model)?, CURSOR_START)? { + Some(floor) => try_parse(&floor, cursor_type)?, + None => None, + }; + let start = match floor { + Some(floor) => literal(&render_value(&floor)?)?, + None => format!("{} {UNBOUNDED_CURSOR_MARK}", literal(&lowest)?), }; - Ok(PyErr::from_value(error.call((message,), Some(&kwargs))?)) + let end = format!("{} {UNBOUNDED_CURSOR_MARK}", literal(&highest)?); + Ok(resolve_cursor_intrinsics(py, sql, Some(&start), Some(&end))?.0) } #[pyfunction] diff --git a/crates/sqlbuild-python-planner/src/planner_resolution/main/cursor/model_cursor_overrides.rs b/crates/sqlbuild-python-planner/src/planner_resolution/main/cursor/model_cursor_overrides.rs index 12a86e1137..b9e91a640e 100644 --- a/crates/sqlbuild-python-planner/src/planner_resolution/main/cursor/model_cursor_overrides.rs +++ b/crates/sqlbuild-python-planner/src/planner_resolution/main/cursor/model_cursor_overrides.rs @@ -7,18 +7,20 @@ use crate::planner_resolution::_helpers::cursor::cursor_ranges::config_bound; use crate::planner_resolution::_helpers::cursor::cursor_ranges::order; use crate::planner_resolution::_helpers::cursor::cursor_ranges::token; use crate::planner_resolution::main::cursor::config_str::config_str; +use crate::planner_resolution::models::WindowFit; +use crate::planner_resolution::types::CursorBounds; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_front::cursor::models::CursorSession; use sqlbuild_python_project::compiled_views::main::compiled_models::name_object::name_object; use std::cmp::Ordering; -/// Resolve typed cursor overrides to generic start/end for one model. +/// Resolve typed cursor overrides to generic start/end for one model, fitted to its `cursor_start` floor: a window that starts before the floor starts at it, and one that ends at or before it builds nothing. pub fn model_cursor_overrides<'py>( model: &Bound<'py, PyAny>, cursor_overrides: &Bound<'py, PyAny>, (start, end): (Bound<'py, PyAny>, Bound<'py, PyAny>), -) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyAny>)> { +) -> PyResult<(CursorBounds<'py>, WindowFit)> { let py = model.py(); let cursor_type = config_str(model, "cursor_type")?; let (mut resolved_start, mut resolved_end) = (start, end); @@ -45,18 +47,36 @@ pub fn model_cursor_overrides<'py>( let name = name_object(model)?.str()?; let cursor_start = config_bound(model, "cursor_start")?; let cursor_end = config_bound(model, "cursor_end")?; - if !resolved_start.is_none() - && !cursor_start.is_none() - && order(&session, (&resolved_start, &cursor_start), &cursor_type)? == Ordering::Less - { - return Err(compile_input_error( - py, - format!( - "model '{name}': explicit start {} is before cursor_start {}", - resolved_start.str()?, - cursor_start.str()? - ), - )); + let mut fit = WindowFit::Inside; + if !cursor_start.is_none() { + let floor = cursor_start.clone(); + let before = |value: &Bound<'py, PyAny>, ending: bool| -> PyResult { + Ok(!value.is_none() + && match order(&session, (value, &floor), &cursor_type)? { + Ordering::Less => true, + Ordering::Equal => ending, + Ordering::Greater => false, + }) + }; + if before(&resolved_end, true)? { + let shown = |value: &Bound<'py, PyAny>| -> PyResult { + Ok(if value.is_none() { + "the start".to_owned() + } else { + value.str()?.to_string() + }) + }; + fit = WindowFit::BeforeFloor { + floor: floor.str()?.to_string(), + window: format!("{} to {}", shown(&resolved_start)?, shown(&resolved_end)?), + }; + } else if before(&resolved_start, false)? { + fit = WindowFit::Clamped { + requested: resolved_start.str()?.to_string(), + floor: floor.str()?.to_string(), + }; + resolved_start = floor; + } } if !cursor_end.is_none() { for (value, label) in [(&resolved_start, "start"), (&resolved_end, "end")] { @@ -74,5 +94,5 @@ pub fn model_cursor_overrides<'py>( } } } - Ok((resolved_start, resolved_end)) + Ok(((resolved_start, resolved_end), fit)) } diff --git a/crates/sqlbuild-python-planner/src/planner_resolution/mod.rs b/crates/sqlbuild-python-planner/src/planner_resolution/mod.rs index e8dd7a3eda..50dc5cab33 100644 --- a/crates/sqlbuild-python-planner/src/planner_resolution/mod.rs +++ b/crates/sqlbuild-python-planner/src/planner_resolution/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-planner/src/planner_resolution/models.rs b/crates/sqlbuild-python-planner/src/planner_resolution/models.rs index f9835adfd0..177bf03b8a 100644 --- a/crates/sqlbuild-python-planner/src/planner_resolution/models.rs +++ b/crates/sqlbuild-python-planner/src/planner_resolution/models.rs @@ -166,3 +166,14 @@ impl<'py> Resolution<'py> { Ok(value) } } + +/// How an explicit cursor window fits one model's `cursor_start` floor. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WindowFit { + /// The window starts at or after the floor, or names no start before it. + Inside, + /// The window starts before the floor and ends after it: the model starts at the floor. + Clamped { requested: String, floor: String }, + /// The window, as `start to end`, ends at or before the floor: the model has nothing to build in it. + BeforeFloor { floor: String, window: String }, +} diff --git a/crates/sqlbuild-python-planner/src/planner_resolution/types.rs b/crates/sqlbuild-python-planner/src/planner_resolution/types.rs new file mode 100644 index 0000000000..53f33dd81e --- /dev/null +++ b/crates/sqlbuild-python-planner/src/planner_resolution/types.rs @@ -0,0 +1,6 @@ +//! Public type aliases of planner resolution. + +use pyo3::prelude::{Bound, PyAny}; + +/// A model's resolved cursor start and end; either may be `None`. +pub type CursorBounds<'py> = (Bound<'py, PyAny>, Bound<'py, PyAny>); diff --git a/crates/sqlbuild-python-project/src/native_host/main/mod.rs b/crates/sqlbuild-python-project/src/native_host/main/mod.rs index 2ec2d3d7aa..b41c539748 100644 --- a/crates/sqlbuild-python-project/src/native_host/main/mod.rs +++ b/crates/sqlbuild-python-project/src/native_host/main/mod.rs @@ -5,5 +5,6 @@ pub mod register_runs_state; pub mod report_synced_catalog; pub mod run_recorder; pub mod sensor_declaration; +pub(crate) mod sensor_selection; pub mod target_location; pub mod write_stderr_line; diff --git a/crates/sqlbuild-python-project/src/native_host/main/sensor_selection.rs b/crates/sqlbuild-python-project/src/native_host/main/sensor_selection.rs new file mode 100644 index 0000000000..b8801f83f9 --- /dev/null +++ b/crates/sqlbuild-python-project/src/native_host/main/sensor_selection.rs @@ -0,0 +1,17 @@ +//! A sensor condition's selectors, resolved as publication resolves them. + +use pyo3::PyResult; +use serde_json::Value; +use sqlbuild_analysis::graph::models::ProjectGraph; + +use crate::graph::models::ProjectSelection; +use crate::native_host::_helpers::orchestration_triggers::sensor_nodes; + +/// The published node keys `selectors` name for the condition `field`, or why they name none. +pub(crate) fn sensor_selection( + project: (&ProjectGraph, &ProjectSelection), + selectors: &[String], + field: &str, +) -> PyResult { + sensor_nodes(project, selectors, field) +} diff --git a/crates/sqlbuild-python-project/src/project_snapshot/constants.rs b/crates/sqlbuild-python-project/src/project_snapshot/constants.rs index 6aa3ef83d2..5df13dabfe 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/constants.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/constants.rs @@ -5,6 +5,9 @@ use crate::project_snapshot::models::RunsIn; /// The code a node fails with when a provider it uses is missing secrets, as `sqb build` reports it. pub(crate) const MISSING_SECRET_CODE: &str = "D012"; +/// The sensor condition field of `executed_successfully` selectors, as publication names it. +pub(crate) const EXECUTED_SUCCESSFULLY: &str = "executed_successfully"; + /// Snapshot node kinds a provider consumer can run inside. pub(crate) const MODEL_NODE_KIND: &str = "model"; pub(crate) const SOURCE_NODE_KIND: &str = "source"; diff --git a/crates/sqlbuild-python-project/src/project_snapshot/main/mod.rs b/crates/sqlbuild-python-project/src/project_snapshot/main/mod.rs index cfeeda589d..5a47fd1776 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/main/mod.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/main/mod.rs @@ -3,6 +3,7 @@ pub mod compile_declarations; pub mod compile_project_roles; pub mod job_group_cycles; pub mod model_nodes; +pub mod orchestration_selectors; pub mod providers_document; pub mod python_declarations; pub mod register_snapshot; diff --git a/crates/sqlbuild-python-project/src/project_snapshot/main/orchestration_selectors.rs b/crates/sqlbuild-python-project/src/project_snapshot/main/orchestration_selectors.rs new file mode 100644 index 0000000000..3498c0cf57 --- /dev/null +++ b/crates/sqlbuild-python-project/src/project_snapshot/main/orchestration_selectors.rs @@ -0,0 +1,118 @@ +//! Refuse a compile whose job or sensor selectors would not resolve at publish, as `OrchestrationDeclarationError` (D017). + +use std::path::Path; + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; +use sqlbuild_analysis::graph::models::ProjectGraph; +use sqlbuild_discovery::orchestration_files::models::{FilePosition, OrchestrationInventory}; +use sqlbuild_python_base::orchestration_reads::main::declared_at::declared_at; +use sqlbuild_python_base::orchestration_reads::main::imported_declarations::imported_declarations; +use sqlbuild_python_base::orchestration_reads::models::AuthoredSensor; +use sqlbuild_python_base::records::main::fields::field::field; +use sqlbuild_python_front::discovery::main::sources::orchestration_declarations::orchestration_declarations; +use sqlbuild_python_front::discovery::main::sources::orchestration_failure::orchestration_failure; + +use crate::graph::models::ProjectSelection; +use crate::native_host::main::sensor_selection::sensor_selection; +use crate::project_snapshot::_helpers::snapshot::snapshot_declarations::declared_for; +use crate::project_snapshot::constants::EXECUTED_SUCCESSFULLY; +use crate::project_snapshot::main::python_declarations::python_declarations; + +/// Every job and sensor selector declared for the project's target, resolved as publication resolves them; one error names each that fails. +pub fn orchestration_selectors( + project_dir: &Bound<'_, PyAny>, + (project, discovered_inputs): (&Bound<'_, PyAny>, &Bound<'_, PyAny>), + graph: &ProjectGraph, +) -> PyResult<()> { + let py = project_dir.py(); + let inventory: OrchestrationInventory = orchestration_declarations(project_dir)?; + if inventory.jobs.is_empty() && inventory.sensors.is_empty() { + return Ok(()); + } + let target: String = field(project, "effective_target_name")? + .extract::>()? + .unwrap_or_default(); + let selected = ProjectSelection::new(project, discovered_inputs)?; + let mut failures: Vec = job_failures(&inventory, &target, (graph, &selected)); + if !inventory.sensors.is_empty() { + let root: std::path::PathBuf = project_dir.extract()?; + let declarations = python_declarations(py, &root, &inventory)?; + let sensors: Vec = imported_declarations(py, declarations)?.sensors; + failures.extend(sensor_failures( + (py, &root), + sensors, + &target, + (graph, &selected), + )?); + } + if failures.is_empty() { + return Ok(()); + } + Err(orchestration_failure(py, failures.join("\n"))) +} + +/// `path:line:column: job NAME: error` for each job whose `select` or `exclude` does not resolve. +fn job_failures( + inventory: &OrchestrationInventory, + target: &str, + (graph, selected): (&ProjectGraph, &ProjectSelection), +) -> Vec { + let tokens = |value: &str| { + value + .split_whitespace() + .map(str::to_owned) + .collect::>() + }; + inventory + .jobs + .iter() + .filter(|(_, job)| declared_for(&job.run.targets, target)) + .filter_map(|(path, job)| { + let exclude: &str = job.exclude.as_ref().map_or("", |exclude| &exclude.value); + let error = selected + .run_keys(graph, &tokens(&job.select.value), &tokens(exclude)) + .err()?; + let FilePosition { line, column } = job.select.position; + Some(format!( + "{path}:{line}:{column}: job {}: {error}", + job.run.name.value + )) + }) + .collect() +} + +/// `path:line: sensor NAME: error` for each sensor whose condition selectors do not resolve. +fn sensor_failures( + (py, project_dir): (Python<'_>, &Path), + sensors: Vec, + target: &str, + graph: (&ProjectGraph, &ProjectSelection), +) -> PyResult> { + let mut failures: Vec = Vec::new(); + for sensor in sensors { + let (Some(name), Some(when)) = (sensor.name, sensor.when) else { + continue; + }; + if !sensor.targets.is_empty() && !sensor.targets.iter().any(|value| value == target) { + continue; + } + let site: String = declared_at(project_dir, sensor.declared_at)? + .map_or_else(String::new, |at| format!("{}:{}: ", at.path, at.line)); + let mut checks: Vec<(Vec, String)> = Vec::new(); + if let Some(select) = when.select { + checks.push(( + select.split_whitespace().map(str::to_owned).collect(), + when.kind, + )); + } + if let Some(selectors) = when.executed_successfully { + checks.push((selectors, EXECUTED_SUCCESSFULLY.to_owned())); + } + for (selectors, field_name) in checks { + if let Err(error) = sensor_selection(graph, &selectors, &field_name) { + failures.push(format!("{site}sensor {name}: {}", error.value(py))); + } + } + } + Ok(failures) +} diff --git a/crates/sqlbuild-python/src/bindings/_helpers/build_command/policies.rs b/crates/sqlbuild-python/src/bindings/_helpers/build_command/policies.rs index c73dffaed4..11d3a84bbf 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/build_command/policies.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/build_command/policies.rs @@ -11,9 +11,9 @@ use sqlbuild_core::build_command::main::model_limit_error::model_limit_error; use sqlbuild_core::build_command::main::plan_safety_steps::plan_safety_steps; use sqlbuild_core::build_command::main::render_confirmation_prompt::render_confirmation_prompt; use sqlbuild_core::build_command::models::{ - ColumnMigrationFact, ModelLimit, ModelMigrationFact, PlanSafetyFacts, PlanSafetyGates, - PlanWarningFact, PolicyStep, RetentionFact, SnapshotPolicies, SnapshotRefreshFact, - TableTypeFact, + ColumnMigrationFact, ModelErrorFact, ModelLimit, ModelMigrationFact, PlanSafetyFacts, + PlanSafetyGates, PlanWarningFact, PolicyStep, RetentionFact, SnapshotPolicies, + SnapshotRefreshFact, TableTypeFact, }; use sqlbuild_python_base::records::main::construct::new_error::new_error; @@ -137,6 +137,14 @@ fn plan_facts(plan: &Bound<'_, PyAny>) -> PyResult { } } for entry in entries(plan, "model_entries")? { + let planning_error: Bound<'_, PyAny> = native_field(&entry, "planning_error")?; + if !planning_error.is_none() { + facts.model_errors.push(ModelErrorFact { + code: optional_text(&planning_error, "code")?, + message: text(&planning_error, "message")?, + help: optional_text(&planning_error, "help")?, + }); + } if optional_text(&entry, "materialization_type")?.as_deref() == Some(SNAPSHOT_VALUE) && text(&entry, "reason")? == FULL_REFRESH_REASON { diff --git a/deploy/README.md b/deploy/README.md index 87153aeb20..61527959a9 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -86,8 +86,10 @@ hashes before writing. The warehouse persists in its named volume, and so does r folder with PostgreSQL in this image, so recreating the server keeps it. `docker compose down --volumes` deletes both. -Check the location the way a container health check would; it exits 1 when the location is down -or its last load failed: +Check the location the way a deploy's cutover check would; it exits 0 only when the newest instance +loaded the current code, 3 while it is still starting, and 1 when the location is down or its last +load failed. The container's own health check passes `--allow-starting`, so a starting location +counts as alive: ```sh docker compose exec location sqb location health --server http://server:8000 --location-id "$SQLBUILD_LOCATION_ID" --target development @@ -257,7 +259,7 @@ Network=sqlbuild.network Volume=sqlbuild-warehouse:/warehouse Secret=sqlbuild-orders-location-token,type=env,target=SQLBUILD_LOCATION_TOKEN Exec=location serve --server http://sqlbuild-server:8000 --location-id 00000000-0000-0000-0000-000000000001 --target development -HealthCmd=sqb location health --server http://sqlbuild-server:8000 --location-id 00000000-0000-0000-0000-000000000001 --target development +HealthCmd=sqb location health --allow-starting --server http://sqlbuild-server:8000 --location-id 00000000-0000-0000-0000-000000000001 --target development HealthInterval=30s HealthStartPeriod=60s PodmanArgs=--cpus 2 --memory 1g diff --git a/fensu.toml b/fensu.toml index 2690f8e1b6..8fd49c7291 100644 --- a/fensu.toml +++ b/fensu.toml @@ -1734,8 +1734,8 @@ select = [ [[targets.rust.threshold_overrides]] paths = ["crates/sqlbuild-python/Cargo.toml"] -thresholds = { max_crate_code_lines = 51311 } -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. The cap stays near its current size; lower it as code moves out." +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." [[targets.rust.threshold_overrides]] paths = ["crates/sqlbuild-python/src/bindings/_helpers"] 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 d21c7e6b79..cc8cb52570 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/build.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/build.md @@ -74,7 +74,7 @@ own option. `--version` works only directly after `sqb`, as in `sqb --version`: | `--verbose`, `-v` | Show lifecycle SQL inline after each model | | `--start-cursor` | Override the start cursor, typed from the selected incremental models' cursor type; fails with `S303` if the selection mixes timestamp and integer cursors. With no cursor model selected, an integer value is read as an integer cursor and anything else as an ISO timestamp | | `--end-cursor` | Override the end cursor, typed the same way as `--start-cursor` | -| `--start-cursor-ts` | Override start cursor for timestamp incremental models (ISO format) | +| `--start-cursor-ts` | Override start cursor for timestamp incremental models (ISO format); each model fits the window to its own [`cursor_start`](../concepts/incremental.md#explicit-cursor-windows) | | `--end-cursor-ts` | Override end cursor for timestamp incremental models (ISO format) | | `--start-cursor-int` | Override start cursor for integer incremental models | | `--end-cursor-int` | Override end cursor for integer incremental models | diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dev.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dev.md index af91883f1d..0a41167924 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dev.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/dev.md @@ -237,8 +237,6 @@ sqb dev shop · target dev · sqb 0.256.0 Warnings, such as a failed warehouse read, a stopped warehouse sync or unset provider secrets, are printed as warning blocks. -When stdout is redirected, it receives one JSON record per published version. - ## Run scheduled jobs locally Triggers start paused, so a schedule never runs on your machine by accident. Resume a trigger in diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/location.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/location.md index fcc739f30b..cb71cf12cc 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/location.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/location.md @@ -44,27 +44,53 @@ sqb location health --server https://control.example.com --location-id "$LOCATIO | `state` | Meaning | Exit code | | --- | --- | --- | +| `starting` | The newest instance checked in but hasn't finished its first load | `3` | | `healthy` | An instance checked in within 90 seconds and its last load published | `0` | -| `degraded` | The warehouse connection check after the last load failed | `0` | +| `degraded` | The warehouse connection check after the last load failed | `1` | | `missing_secrets` | A provider [secret](../concepts/python-nodes/providers.md#secrets) is unset in the location's environment, and the target's [`allow_missing_secrets`](../concepts/project-configuration.md#allowed-missing-secrets) doesn't list the provider, so runs that use it fail | `1` | -| `discovery_failed` | A [discover function](../concepts/python-nodes/discovered-nodes.md) failed at the last publication, so its set serves its last good items, or none | `0` | +| `change_plan_failed` | The location's plan of what changed on the current snapshot failed, so the UI's **Build what changed** and the nodes' changed state are unknown | `1` | +| `discovery_failed` | A [discover function](../concepts/python-nodes/discovered-nodes.md) failed at the last publication, so its set serves its last good items, or none | `1` | | `falling_back` | The last load failed, so runs use the previous snapshot | `1` | | `broken` | No instance has checked in for 90 seconds | `1` | -The command exits `2` when it cannot read the state: the server is unreachable, or the token is +Only `healthy` exits `0`. The command exits `2` when it cannot read the state: the server is unreachable, or the token is missing, expired or for another location. It needs the location's token, not a person's sign-in. -A Compose health check for the location service: +The state is the newest instance's: the one that started last among those that checked in within +90 seconds. Until its first load finishes it is `starting`, whatever an earlier instance loaded, so a +deploy that restarts the location and polls `sqb location health` until it exits `0` waits for the +new code. Once that load finishes, the state comes from it: `falling_back` if it failed, otherwise +`healthy` or one of the states above. For an instance that started more than 7 days ago, whose +first reports are no longer kept, the state comes from the location's newest reports of any instance. + +A container health check asks whether the location is alive, not whether the newest code has +loaded: pass `--allow-starting`, which exits `0` while the state is `starting` and leaves every other +exit code as it is. Whether a deploy's new code loaded is the deploy's cutover check: poll +`sqb location health` without the flag until it exits `0`. A Compose health check for the location +service, as the shipped `compose.yml` has: ```yaml healthcheck: - test: [CMD, sqb, location, health, --server, "http://server:8000", --location-id, "${SQLBUILD_LOCATION_ID}", --target, development] + test: [CMD, sqb, location, health, --allow-starting, --server, "http://server:8000", --location-id, "${SQLBUILD_LOCATION_ID}", --target, development] interval: 30s start_period: 60s ``` +A Quadlet unit uses the same command in `HealthCmd=`. + A `falling_back` location still runs scheduled jobs from its last good snapshot. Restarting it -does not fix the failed load; fix the project and deploy it again. +does not fix the failed load; fix the project and deploy it again. A location that keeps checking in +but can't get its next generation number from the server can't load new code either: after three +failed lookups in a row it reports a failed load with the lookup's error, so it is `falling_back` +until a later publication succeeds. Plan previews on it fail at once +with the load's error instead of waiting for the location. + +A location that checks in but is `falling_back`, `change_plan_failed`, `discovery_failed` or +`degraded` is a problem everyone who can view its target sees: a banner on every page of the UI +names the location and target, the error, and the generation it serves instead with when that was +published; the Overview lists it under **Needs attention**; and the server sends a +[`location_failing` platform event](server.md#receive-platform-events) once per failure, so a +platform webhook or a [`platform_event` sensor](../concepts/orchestration.md) with `PlatformEventKind.LOCATION_FAILING` can alert on it. Loading a project is a full compile, as [`sqb compile`](compile.md) runs it, including the configured [Rules](../concepts/rules.md). A Rule finding fails the load like any other compile 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 7f2d480411..430f95aa37 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/plan.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/plan.md @@ -14,6 +14,7 @@ Online: https://sqlbuild.com/docs/cli/plan/ - Nodes that can't run - Timings - Exit codes +- Models that can't be planned - Missing upstream dependencies - Missing source tables @@ -176,7 +177,7 @@ Plan timings seconds share `sqb plan` exits `0` when the plan is ready, including plans that only have warnings. It exits `1` when the plan has an error-severity finding that `sqb build` would refuse, such as an `M114` name -claim; the final line then reads `✗ Plan failed with errors`. `sqb plan --json` uses the same exit +claim or a model that can't be planned; the final line then reads `✗ Plan failed with errors`. `sqb plan --json` uses the same exit codes, so CI can gate on either form. When `sqb plan --json` fails before it can produce a plan, for example on an unknown selector, it @@ -185,6 +186,25 @@ still exits `1` and prints its coded error on stderr, and prints the error as JS Release note: earlier versions printed `Plan complete with errors` and exited `0` for such plans. +## Models that can't be planned + +A model whose planning fails, for example a `full_refresh false` model the plan would rebuild +(`S203`), doesn't stop the rest of the plan. Its row is listed under **Planning failed** with the +action `error`, the `Errors` section prints its error as `error[CODE]: message` with its help, and +every other model plans as usual. In `sqb plan --json` the model's row has `"action": "error"`, +`"reason": "planning_error"` and an `error` object with `code`, `message` and `help`, and the +plan has `"has_errors": true`; the plan exits `1`. + +Only planning errors become error rows: a model the plan can't decide how to build, such as `S203`, +a cursor input error (`S302`) or a cursor safety limit. Compile and validation errors still fail the +whole plan with their code, as before: an invalid project edge such as a capped watermark input +(`P001`), and source checks against the warehouse (`S4xx`), such as a missing source or a source +column that breaks an enforced contract. + +`sqb build` refuses a selection that contains a model that can't be planned, with that model's +error; select around it or fix it. A location's plan of what changed keeps the models it could +plan and reports the others, so the location's health is `change_plan_failed`, naming them. + ## Missing upstream dependencies Planning a scoped selection whose upstream inputs were never built in the target fails with `S301` rather than producing a plan that would break at build time: 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 bad1fef717..b64c6cde37 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md @@ -364,6 +364,7 @@ seconds, stops delivery and retries the same event. Deduplicate by `event_id`, w | `tick_overdue` | A schedule tick is late | `trigger_id`, `scheduled_for` | | `calendar_horizon_low` | A running calendar schedule has a day or less of dates left | `trigger_id`, `refresh_at`, `horizon_end` | | `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` | | `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` | diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/incremental.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/incremental.md index 1015a2a290..86d9970079 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/incremental.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/incremental.md @@ -189,9 +189,28 @@ Cursors define the incremental replay boundary. SQLBuild queries `MAX(cursor)` f | `cursor` | Output column used to track incremental position | | `cursor_type` | `timestamp` or `integer` | | `cursor_grain` | Time grain for timestamp cursors: `second`, `minute`, `hour`, `day`, `month`, `year` | -| `cursor_start` | Lower bound floor; the cursor will never replay before this value | +| `cursor_start` | Lower bound floor; the cursor will never replay before this value, even inside an [explicit cursor window](#explicit-cursor-windows) | | `cursor_inputs` | Map of upstream ref/source names to their cursor columns | +### Explicit cursor windows + +`--start-cursor-ts` and `--end-cursor-ts` (or the `-int` forms, or `--start-cursor` and +`--end-cursor`) give every selected cursor model the same window, and each model fits it to its own +`cursor_start`: + +- A window that starts before a model's `cursor_start` and ends after it starts that model at its + `cursor_start`. The plan warns on that model: + `explicit start 2020-06-01 is before cursor_start 2021-01-01; the window starts at 2021-01-01`. +- A window that ends at or before a model's `cursor_start` skips that model. The plan lists it under + **Window before cursor_start** with the reason `window ends before cursor_start 2021-01-01`; in + `sqb plan --json` its row has `"action": "skip"`, `"reason": "window_before_cursor_start"` and + that reason as `skip_reason`. +- When the window skips every selected cursor model, there is nothing to build and the plan fails + with `P001`, naming the window and each model's `cursor_start`. Selected models without a cursor + don't count. + +A window that reaches a model's exclusive `cursor_end` still fails the plan with `P001`. + ### cursor_inputs When a model references multiple upstream inputs, `cursor_inputs` is required to tell SQLBuild which column on each input carries the cursor: @@ -263,7 +282,9 @@ WHERE ordered_at >= __cursor_start() AND ordered_at < __cursor_end() ``` -`__cursor_start()` is the effective inclusive start and `__cursor_end()` is the effective exclusive end after cursor floors, lookback, replay policy, and command-line overrides have been applied. The intrinsics accept no arguments and are only valid in built-in cursor incremental model query SQL. They are rejected in functions, hooks, audits, SQL tests and scenarios, source expressions, non-incremental or cursorless models, custom materializations, and non-microbatch full refreshes. A non-microbatch model planned as a FULL backfill, for example by `--full-refresh`, fails planning with `S204`, naming the cause; pass an explicit interval with `--start-cursor-ts` and `--end-cursor-ts` (or the `-int` forms) to rebuild it. +`__cursor_start()` is the effective inclusive start and `__cursor_end()` is the effective exclusive end after cursor floors, lookback, replay policy, and command-line overrides have been applied. The intrinsics accept no arguments and are only valid in built-in cursor incremental model query SQL. They are rejected in functions, hooks, audits, SQL tests and scenarios, source expressions, non-incremental or cursorless models, and custom materializations. + +A non-microbatch full build (the first run, `--full-refresh`, or `replay_on_change full`) has no cursor interval, so the intrinsics span every value: `__cursor_start()` is the model's `cursor_start` floor, or the cursor type's lowest value without one, and `__cursor_end()` is the type's highest value. They render as typed literals, each unbounded end followed by `/* (unbounded) */` in the compiled SQL, and `sqb plan` shows the range as `(unbounded)`. Timestamps span `0001-01-01 00:00:00` to `9999-12-31 23:59:59.999999`, except on ClickHouse, where DateTime64 spans `1900-01-01 00:00:00` to `2299-12-31 23:59:59.999999`; integers span the 64-bit range. Because `__cursor_end()` is exclusive, a row whose cursor is exactly the highest value is left out. An explicit interval (`--start-cursor-ts` and `--end-cursor-ts`, or the `-int` forms) still bounds a full build. In microbatch mode, the intrinsics resolve to each batch's concrete bounds. A microbatch full refresh discovers its range from current inputs while ignoring the old destination watermark. 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 3991713343..93416dde7b 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md @@ -423,10 +423,14 @@ Rename model stg_orders -> stg_orders_clean ## Errors Every problem with an orchestration file is a `D017` error at its file, line and column, reported by -`sqb compile` and every other command that reads the project. +`sqb compile` and every other command that reads the project. `sqb compile` resolves every job's +`select` and `exclude`, and every sensor condition's selectors, for the target it compiles, as a +location does when it publishes, so a selector the location would refuse fails the compile first. | Error | Fix | | --- | --- | +| `orchestration/jobs/orders_job.toml:3:10: job orders_job: path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'` | Start the path at `sql/models/` or `python/nodes/` | +| `orchestration/sensors/raw_sensor.py:4: sensor raw_sensor: source_new_data: path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'` | The same, in the sensor's condition | | ``orchestration/jobs/nightly_orders_job.toml:4:11: unknown variant `coalesce`, expected `queue` or `skip` `` | Use one of the listed values | | `files cannot sit directly in orchestration/` | Move jobs and groups to TOML files in `orchestration/jobs/` or `orchestration/job_groups/` | | `` `job` was removed from sqlbuild.orchestration`` | Declare the job in TOML and start it with `RunRequest(job="...")` | diff --git a/src/sqlbuild/_native.pyi b/src/sqlbuild/_native.pyi index e9a8bd9bc7..ff6c1298b1 100644 --- a/src/sqlbuild/_native.pyi +++ b/src/sqlbuild/_native.pyi @@ -1065,12 +1065,14 @@ class PlanWarning(NativeRecord): severity: WarningSeverity message: str code: str | None + help: str | None def __init__( self, model_name: str | None, severity: WarningSeverity, message: str, code: str | None = ..., + help: str | None = ..., ) -> None: ... def __replace__(self, **changes: Any) -> PlanWarning: ... @@ -13599,6 +13601,7 @@ class PlanReason(StrEnum): DISABLED = "disabled" SOURCE_FRESHNESS_ERROR = "source_freshness_error" EXTERNAL_UPSTREAM_FAILED = "external_upstream_failed" + WINDOW_BEFORE_CURSOR_START = "window_before_cursor_start" class IncrementalStrategy(StrEnum): APPEND = "append" @@ -14181,6 +14184,8 @@ class ModelPlanEntry(NativeRecord): refresh_on_build: bool dynamic_readers: tuple[str, ...] dynamic_paused: bool + planning_error: PlanWarning | None + skip_reason: str | None def __init__( self, key: CompiledObjectKey, @@ -14277,6 +14282,8 @@ class ModelPlanEntry(NativeRecord): refresh_on_build: bool = ..., dynamic_readers: tuple[str, ...] = ..., dynamic_paused: bool = ..., + planning_error: PlanWarning | None = ..., + skip_reason: str | None = ..., ) -> None: ... class CloneSourcePlanEntry(NativeRecord): diff --git a/src/sqlbuild/adapter/contract/classes/strict_adapter.py b/src/sqlbuild/adapter/contract/classes/strict_adapter.py index 1222e2b74c..5c4972e127 100644 --- a/src/sqlbuild/adapter/contract/classes/strict_adapter.py +++ b/src/sqlbuild/adapter/contract/classes/strict_adapter.py @@ -12,6 +12,12 @@ from sqlbuild.adapter.contract.classes.materialization import MaterializationMixin from sqlbuild.adapter.contract.classes.schema import SchemaMixin from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder +from sqlbuild.adapter.contract.constants import ( + HIGHEST_INTEGER_CURSOR, + HIGHEST_TIMESTAMP_CURSOR, + LOWEST_INTEGER_CURSOR, + LOWEST_TIMESTAMP_CURSOR, +) from sqlbuild.adapter.contract.exceptions import AdapterUserError from sqlbuild.adapter.contract.models import ( ColumnInfo, @@ -31,6 +37,7 @@ TemporaryFunction, ) from sqlbuild.adapter.contract.types import ( + CursorKind, DynamicListing, DynamicOperation, FrameworkType, @@ -181,6 +188,13 @@ def render_cursor_text(self, *, expression: str, cursor_type: str) -> str: del cursor_type return f"CAST({expression} AS VARCHAR)" + def cursor_type_range(self, *, cursor_type: str | None) -> tuple[str, str]: + """Optional: the lowest and highest `cursor_type` values a full build's intrinsics span.""" + + if cursor_type == CursorKind.INTEGER: + return (LOWEST_INTEGER_CURSOR, HIGHEST_INTEGER_CURSOR) + return (LOWEST_TIMESTAMP_CURSOR, HIGHEST_TIMESTAMP_CURSOR) + def render_create_temporary_function( self, *, name: str, definition: FunctionDefinition ) -> TemporaryFunction | None: diff --git a/src/sqlbuild/adapter/contract/constants.py b/src/sqlbuild/adapter/contract/constants.py index 6e00b10343..3cac3985e5 100644 --- a/src/sqlbuild/adapter/contract/constants.py +++ b/src/sqlbuild/adapter/contract/constants.py @@ -25,3 +25,8 @@ LATEST_DUCKDB_STORAGE_VERSION: str = "latest" QUOTED_IDENTIFIER_DELIMITER: str = '"' MIN_QUOTED_IDENTIFIER_LENGTH: int = 3 + +LOWEST_TIMESTAMP_CURSOR: str = "0001-01-01 00:00:00" +HIGHEST_TIMESTAMP_CURSOR: str = "9999-12-31 23:59:59.999999" +LOWEST_INTEGER_CURSOR: str = str(-(2**63)) +HIGHEST_INTEGER_CURSOR: str = str(2**63 - 1) diff --git a/src/sqlbuild/adapters/clickhouse/classes/clickhouse_adapter.py b/src/sqlbuild/adapters/clickhouse/classes/clickhouse_adapter.py index 863016705c..31f3a3752d 100644 --- a/src/sqlbuild/adapters/clickhouse/classes/clickhouse_adapter.py +++ b/src/sqlbuild/adapters/clickhouse/classes/clickhouse_adapter.py @@ -124,6 +124,8 @@ EXPECTED_OUTPUT_COLUMNS_CONFIG_KEY, FRESH_GENERATION_CLAUSE, GENERATION_COMMENT_PREFIX, + HIGHEST_TIMESTAMP_CURSOR, + LOWEST_TIMESTAMP_CURSOR, MAX_IDENTIFIER_LENGTH, MAX_QUERY_SIZE_BYTES, MODEL_NAME_CONFIG_KEY, @@ -678,6 +680,13 @@ def render_source_expression_cast( ) -> str: return f"CAST({expression} AS {nullable_type(target_type)}) AS {alias}" + def cursor_type_range(self, *, cursor_type: str | None) -> tuple[str, str]: + """Timestamp cursors span DateTime64's range here, which the bound literals parse into.""" + + if cursor_type == CursorKind.INTEGER: + return super().cursor_type_range(cursor_type=cursor_type) + return (LOWEST_TIMESTAMP_CURSOR, HIGHEST_TIMESTAMP_CURSOR) + def render_cursor_bound_literal(self, *, value: str, cursor_type: str | None) -> str: if cursor_type == CursorKind.INTEGER: return value diff --git a/src/sqlbuild/adapters/clickhouse/constants.py b/src/sqlbuild/adapters/clickhouse/constants.py index 12b05306d1..ce4f0cd2b3 100644 --- a/src/sqlbuild/adapters/clickhouse/constants.py +++ b/src/sqlbuild/adapters/clickhouse/constants.py @@ -135,3 +135,5 @@ EXACT_ROW_COUNT_ENGINES: frozenset[str] = frozenset( {"MergeTree", "ReplicatedMergeTree", "SharedMergeTree"} ) +LOWEST_TIMESTAMP_CURSOR: str = "1900-01-01 00:00:00" +HIGHEST_TIMESTAMP_CURSOR: str = "2299-12-31 23:59:59.999999" diff --git a/src/sqlbuild/adapters/sqlite/_helpers/timestamps.py b/src/sqlbuild/adapters/sqlite/_helpers/timestamps.py index 1e246012e1..2ade26ffe1 100644 --- a/src/sqlbuild/adapters/sqlite/_helpers/timestamps.py +++ b/src/sqlbuild/adapters/sqlite/_helpers/timestamps.py @@ -11,7 +11,7 @@ def canonical_timestamp_text(value: str) -> str: - """Rewrite an ISO-8601 date-time so text comparison orders it like SQLite timestamps.""" + """Rewrite an ISO-8601 date-time, its year padded to four digits, to sort like SQLite's.""" if _DATE_TIME.match(value) is None: return value @@ -21,7 +21,7 @@ def canonical_timestamp_text(value: str) -> str: return value if parsed.tzinfo is not None: parsed = parsed.astimezone(UTC).replace(tzinfo=None) - text: str = parsed.strftime(TIMESTAMP_TEXT_FORMAT) + text: str = f"{parsed.year:04d}" + parsed.strftime(TIMESTAMP_TEXT_FORMAT.removeprefix("%Y")) if parsed.microsecond: text += f".{parsed.microsecond:06d}".rstrip("0") return text diff --git a/src/sqlbuild/executor/pipeline/_helpers/settings.py b/src/sqlbuild/executor/pipeline/_helpers/settings.py index f640d45d49..8284f7c78a 100644 --- a/src/sqlbuild/executor/pipeline/_helpers/settings.py +++ b/src/sqlbuild/executor/pipeline/_helpers/settings.py @@ -4,7 +4,7 @@ from dataclasses import replace -from sqlbuild._native import SettingsConfig +from sqlbuild._native import PlannerInputError, PlanOutput, PlanWarning, SettingsConfig from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter from sqlbuild.adapter.contract.types import TablePromotionMode from sqlbuild.executor.build.models import ( @@ -57,3 +57,13 @@ def resolve_build_inputs( customizations=customizations if customizations is not None else BuildCustomizations(), initial_state=initial_state if initial_state is not None else BuildInitialState(), ) + + +def plannable_plan(plan: PlanOutput) -> PlanOutput: + """The plan, or the first model's planning error, so no run silently skips that model.""" + + for entry in plan.model_entries: + error: PlanWarning | None = entry.planning_error + if error is not None: + raise PlannerInputError(error.message, code=error.code, help=error.help) + return plan diff --git a/src/sqlbuild/executor/pipeline/main/run.py b/src/sqlbuild/executor/pipeline/main/run.py index c5fdbf65be..1acbf2c814 100644 --- a/src/sqlbuild/executor/pipeline/main/run.py +++ b/src/sqlbuild/executor/pipeline/main/run.py @@ -45,7 +45,7 @@ from sqlbuild.executor.pipeline._helpers.seeding import ( run_seed_pipeline as run_seed_pipeline, ) -from sqlbuild.executor.pipeline._helpers.settings import resolve_build_inputs +from sqlbuild.executor.pipeline._helpers.settings import plannable_plan, resolve_build_inputs from sqlbuild.executor.pipeline._helpers.testing import ( run_test_pipeline as run_test_pipeline, ) @@ -75,6 +75,7 @@ def run_build_pipeline( ) -> BuildExecutionResult: """Execute a full build pipeline: resolve settings, open connections, run plan, close.""" + plan = plannable_plan(plan) with run_scope(runtime.run_id) as identity: dispatcher: EventDispatcher | None = current_event_dispatcher() started: float = time.monotonic() diff --git a/src/sqlbuild/orchestration_declarations/types.py b/src/sqlbuild/orchestration_declarations/types.py index 87c75fc9ae..8db75aab4a 100644 --- a/src/sqlbuild/orchestration_declarations/types.py +++ b/src/sqlbuild/orchestration_declarations/types.py @@ -16,6 +16,7 @@ class PlatformEventKind(StrEnum): TICK_OVERDUE = "tick_overdue" CALENDAR_HORIZON_LOW = "calendar_horizon_low" LOCATION_BROKEN = "location_broken" + LOCATION_FAILING = "location_failing" LAUNCH_FAILED = "launch_failed" RUN_FAILED = "run_failed" TRIGGER_SKIPPED = "trigger_skipped" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py index 214337f048..49f85648ac 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py @@ -1780,3 +1780,15 @@ class DiscoveredNodesE2ETestCase: expected_exit_code: int expected_output_patterns: tuple[str, ...] expected_runs: tuple[str, ...] + + +@dataclass(frozen=True) +class CursorWindowFloorTestCase: + description: str + select: tuple[str, ...] + window: tuple[str, str] + expected_returncode: int + expected_output_fragments: tuple[str, ...] + expected_json_rows: dict[str, dict[str, str]] + expected_warning_fragments: dict[str, str] + expected_rows: dict[str, tuple[str, ...]] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py index 64a77f056b..02f008ecda 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py @@ -1772,3 +1772,17 @@ def node_results_in(*, db_path: Path, schema: str, node_type: str) -> list[tuple f"WHERE node_type = '{node_type}' ORDER BY node_name" ), ) + + +def picked_plan_fields(row: dict[str, Any], keys: tuple[str, ...]) -> dict[str, Any]: + """The given keys of one plan JSON row.""" + return {key: row.get(key) for key in keys} + + +def window_floor_event_dates(project_dir: Path, model: str) -> tuple[str, ...]: + """The event dates a model holds, in order.""" + rows: list[tuple[Any, ...]] = query_duckdb( + db_path=project_dir / "events.duckdb", + sql=f"SELECT event_date FROM main.{model} ORDER BY event_date", + ) + return tuple(str(row[0]) for row in rows) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/_test_types.py index 5fd99769ce..6ed8c4bac2 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/_test_types.py @@ -41,6 +41,21 @@ class RefusedPlanTestCase: expected_fragments: tuple[str, ...] +@dataclass(frozen=True) +class FullRefreshIntrinsicTestCase: + description: str + expected_plan_fragments: tuple[str, ...] + + +@dataclass(frozen=True) +class PlanningErrorRowTestCase: + description: str + expected_code: str + expected_error_model: str + expected_planned_model: str + expected_text_fragments: tuple[str, ...] + + @dataclass(frozen=True) class UpstreamContractFailureTestCase: description: str diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/test_own_change_replay.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/test_own_change_replay.py index 1e1ff5036b..2e5b7b374e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/test_own_change_replay.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/own_change_replay/test_own_change_replay.py @@ -11,8 +11,10 @@ import pytest from tests.e2e.src.sqlbuild.cli.commands.main.build.own_change_replay._test_types import ( + FullRefreshIntrinsicTestCase, FunctionCallerReplayTestCase, OwnChangePlanBuildTestCase, + PlanningErrorRowTestCase, RefusedPlanTestCase, RenamePlanBuildTestCase, ) @@ -33,10 +35,12 @@ merge_downstream_files, plan, plan_models, + relation_rows, relation_types, rename_upstream_with_cli, rename_upstream_with_migrate_from, ) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import run_sqb _REPLAYED_TAIL: list[tuple[Any, ...]] = [ (2, date(2026, 9, 2)), @@ -341,35 +345,88 @@ def test_given_full_refresh_false_caller_when_function_forces_full_rebuild_then_ @pytest.mark.parametrize( "test_case", [ - RefusedPlanTestCase( - description="explicit full refresh of a cursor-intrinsic merge names the FULL cause", - expected_fragments=( - "error[S204]", - "Model 'downstream' was given a FULL backfill (--full-refresh)", - "non-microbatch full rebuild has no cursor interval", - "--start-cursor-ts", + PlanningErrorRowTestCase( + description="a model that can't be planned is an error row and the rest still plans", + expected_code="S203", + expected_error_model="order_amounts", + expected_planned_model="order_totals", + expected_text_fragments=( + "Planning failed", + "error[S203]: model 'order_amounts' sets full_refresh false", + "Plan failed with errors", ), ) ], ids=lambda case: case.description, ) -def test_given_full_refresh_flag_on_cursor_intrinsic_merge_when_planning_then_names_full_cause( - test_case: RefusedPlanTestCase, tmp_path: Path +def test_given_one_model_that_cannot_be_planned_when_planning_then_it_is_an_error_row_and_builds_refuse( + test_case: PlanningErrorRowTestCase, tmp_path: Path +) -> None: + project_dir: Path = build_function_project( + tmp_path=tmp_path, caller_config=" replay_on_change full,\n full_refresh false,\n" + ) + totals_before: list[tuple[Any, ...]] = relation_rows( + project_dir=project_dir, relation=test_case.expected_planned_model + ) + + planned_json: subprocess.CompletedProcess[str] = plan(project_dir=project_dir, args=("--json",)) + planned_text: subprocess.CompletedProcess[str] = plan(project_dir=project_dir) + built: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "build"), project_dir=project_dir + ) + + document: dict[str, Any] = json.loads(planned_json.stdout) + models: dict[str, dict[str, Any]] = {model["name"]: model for model in document["models"]} + assert planned_json.returncode == 1, planned_json.stdout + planned_json.stderr + assert document["has_errors"] is True + assert models[test_case.expected_error_model]["action"] == "error" + assert models[test_case.expected_error_model]["error"]["code"] == test_case.expected_code + assert models[test_case.expected_planned_model]["action"] != "error" + assert "error" not in models[test_case.expected_planned_model] + assert planned_text.returncode == 1 + assert all(fragment in planned_text.stdout for fragment in test_case.expected_text_fragments), ( + planned_text.stdout + ) + assert built.returncode != 0, built.stdout + built.stderr + assert f"error[{test_case.expected_code}]" in built.stdout + built.stderr + assert ( + relation_rows(project_dir=project_dir, relation=test_case.expected_planned_model) + == totals_before + ) + + +@pytest.mark.parametrize( + "test_case", + [ + FullRefreshIntrinsicTestCase( + description="explicit full refresh of a cursor-intrinsic merge spans every value", + expected_plan_fragments=("(unbounded)",), + ) + ], + ids=lambda case: case.description, +) +def test_given_full_refresh_flag_on_cursor_intrinsic_merge_when_building_then_rebuilds_every_row( + test_case: FullRefreshIntrinsicTestCase, tmp_path: Path ) -> None: project_dir: Path = build_event_project( tmp_path=tmp_path, extra_files=merge_downstream_files(extra_config="") ) + before: list[tuple[Any, ...]] = relation_rows(project_dir=project_dir, relation="downstream") - assert_plan_fails( + planned: subprocess.CompletedProcess[str] = plan( + project_dir=project_dir, args=("--full-refresh", "--select", "downstream") + ) + rebuilt: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "build", "--full-refresh", "--select", "downstream"), project_dir=project_dir, - args=("--full-refresh", "--select", "downstream"), - expected=test_case.expected_fragments, ) - refused: subprocess.CompletedProcess[str] = plan( - project_dir=project_dir, args=("--json", "--full-refresh", "--select", "downstream") + + assert planned.returncode == 0, planned.stdout + planned.stderr + assert all(fragment in planned.stdout for fragment in test_case.expected_plan_fragments), ( + planned.stdout ) - assert refused.returncode != 0, refused.stdout + refused.stderr - assert json.loads(refused.stdout)["error"]["code"] == "S204", refused.stdout + refused.stderr + assert rebuilt.returncode == 0, rebuilt.stdout + rebuilt.stderr + assert relation_rows(project_dir=project_dir, relation="downstream") == before @pytest.mark.parametrize( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_window_floors.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_window_floors.py new file mode 100644 index 0000000000..7657239c1a --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_window_floors.py @@ -0,0 +1,180 @@ +"""DuckDB E2E coverage: an explicit cursor window is fitted to each model's own cursor_start (CHI-1662).""" + +import json +import subprocess +from pathlib import Path +from textwrap import dedent +from typing import Any + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import CursorWindowFloorTestCase +from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import ( + picked_plan_fields, + window_floor_event_dates, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( + prepare_inline_project, + run_sqb, +) + +_MODEL: str = dedent( + """ + MODEL ( + description "Events from {floor} on", + materialized incremental, + incremental_strategy delete_insert, + incremental_mode microbatch, + microbatch_strategy watermark, + cursor_watermark_mode all, + cursor event_date, + cursor_type timestamp, + cursor_grain day, + cursor_inputs ( + events (column event_date, roles [filter, watermark]), + ), + batch_size 1mo, + cursor_start "{floor}", + columns ( + event_date (type DATE), + value (type INTEGER), + ), + ); + + SELECT + CAST(event_date AS DATE) AS event_date, + CAST(value AS INTEGER) AS value + FROM __seed("events") + """ +).strip() + +_PROJECT_FILES: dict[str, str] = { + "sqlbuild_project.toml": 'name = "window_floors"\nadapter = "duckdb"\n\n' + '[connection]\ndatabase = "events.duckdb"\n', + "sql/seeds/seeds.yml": ( + "seeds:\n- name: events\n description: Test seed events.\n columns:\n" + " - name: event_date\n type: DATE\n - name: value\n type: INTEGER\n" + ), + "sql/seeds/events.csv": "event_date,value\n2020-06-01,1\n2021-06-01,2\n", + "sql/models/staging/stg_events_early.sql": _MODEL.format(floor="2019-12-01") + "\n", + "sql/models/staging/stg_events_late.sql": _MODEL.format(floor="2021-01-01") + "\n", + "sql/models/staging/event_count.sql": ( + "MODEL (description 'Events counted.', materialized table);\n\n" + 'SELECT COUNT(*) AS events FROM __seed("events")\n' + ), +} + + +@pytest.mark.parametrize( + "test_case", + [ + CursorWindowFloorTestCase( + description="a window overlapping the late floor starts the late model there, with a warning", + select=("stg_events_early", "stg_events_late"), + window=("2020-06-01", "2021-07-01"), + expected_returncode=0, + expected_output_fragments=("explicit start 2020-06-01",), + expected_json_rows={}, + expected_warning_fragments={ + "stg_events_late": "is before cursor_start 2021-01-01; the window starts at" + }, + expected_rows={ + "stg_events_early": ("2020-06-01", "2021-06-01"), + "stg_events_late": ("2021-06-01",), + }, + ), + CursorWindowFloorTestCase( + description="a window that ends at the late floor skips the late model, and the early one builds", + select=("stg_events_early", "stg_events_late"), + window=("2019-12-01", "2021-01-01"), + expected_returncode=0, + expected_output_fragments=( + "Window before cursor_start", + "window ends before cursor_start 2021-01-01", + ), + expected_json_rows={ + "stg_events_late": { + "action": "skip", + "reason": "window_before_cursor_start", + "skip_reason": "window ends before cursor_start 2021-01-01", + } + }, + expected_warning_fragments={}, + expected_rows={"stg_events_early": ("2020-06-01",)}, + ), + CursorWindowFloorTestCase( + description="one model whose window ends before its floor has nothing to build", + select=("stg_events_late",), + window=("2019-12-01", "2021-01-01"), + expected_returncode=1, + expected_output_fragments=( + "error[P001]", + "2019-12-01 to 2021-01-01 leaves nothing to build", + "stg_events_late (cursor_start 2021-01-01)", + ), + expected_json_rows={}, + expected_warning_fragments={}, + expected_rows={}, + ), + CursorWindowFloorTestCase( + description="every cursor model skipped is nothing to build, whatever non-cursor models run", + select=("stg_events_early", "stg_events_late", "event_count"), + window=("2019-01-01", "2019-12-01"), + expected_returncode=1, + expected_output_fragments=( + "error[P001]", + "stg_events_early (cursor_start 2019-12-01)", + "stg_events_late (cursor_start 2021-01-01)", + ), + expected_json_rows={}, + expected_warning_fragments={}, + expected_rows={}, + ), + ], + ids=lambda case: case.description, +) +def test_given_an_explicit_window_and_per_model_floors_when_building_then_each_model_is_clamped_or_skipped( + test_case: CursorWindowFloorTestCase, tmp_path: Path +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, project_name="window_floors", repo_files=_PROJECT_FILES + ) + seeded: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "build", "--select", "events"), project_dir=project_dir + ) + window: tuple[str, ...] = ( + "--start-cursor-ts", + test_case.window[0], + "--end-cursor-ts", + test_case.window[1], + ) + selection: tuple[str, ...] = ("--select", *test_case.select, *window) + + planned_json: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "plan", "--json", *selection), project_dir=project_dir + ) + built: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "build", *selection), project_dir=project_dir + ) + + output: str = built.stdout + built.stderr + assert seeded.returncode == 0, seeded.stdout + seeded.stderr + assert built.returncode == test_case.expected_returncode, output + assert all(fragment in output for fragment in test_case.expected_output_fragments), output + document: dict[str, Any] = json.loads(planned_json.stdout) + rows: dict[str, dict[str, Any]] = {model["name"]: model for model in document.get("models", [])} + assert { + name: picked_plan_fields(rows[name], tuple(expected)) + for name, expected in test_case.expected_json_rows.items() + } == test_case.expected_json_rows, planned_json.stdout + warnings: dict[str, str] = { + warning.get("model_name", ""): warning["message"] + for warning in document.get("warnings", []) + } + assert all( + fragment in warnings.get(name, "") + for name, fragment in test_case.expected_warning_fragments.items() + ), planned_json.stdout + assert { + name: window_floor_event_dates(project_dir, name) for name in test_case.expected_rows + } == test_case.expected_rows 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 2cf2c765a6..e819e745d9 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 @@ -1463,6 +1463,16 @@ class JobGroupCyclesCase: expected_messages: tuple[str, ...] +@dataclass(frozen=True) +class OrchestrationSelectorCompileTestCase: + """Orchestration files whose selectors publication would refuse, the errors, and their fix.""" + + description: str + files: dict[str, str] + expected_messages: tuple[str, ...] + fixed_files: dict[str, str] + + @dataclass(frozen=True) class DynamicCompileE2ETestCase: """A project with dynamic models, its exit code and text its compile output contains.""" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/helpers.py index 3253a9da12..060fc10f4f 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/helpers.py @@ -5616,3 +5616,25 @@ def orders_job_project(job_values: str) -> dict[str, str]: 'name = "orders_job"\ndescription = "Orders."\n' + job_values ), } + + +def orchestration_job(name: str, select: str, exclude: str = "") -> str: + """A job file selecting `select` and excluding `exclude`, which may be empty.""" + + return ( + f'name = "{name}"\ndescription = "Build {name}."\n' + f'select = "{select}"\nexclude = "{exclude}"\n' + ) + + +def orchestration_sensor(select: str) -> str: + """A sensor file whose `source_new_data` condition selects `select`.""" + + return ( + "from sqlbuild.orchestration import RunRequest, SensorContext, sensor, " + "source_new_data\n\n\n" + "@sensor(description='Build orders on new data.', " + f"when=source_new_data(select='{select}'))\n" + "def regions_sensor(ctx: SensorContext):\n" + " return RunRequest(job='orders_job')\n" + ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_relation_slots.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_relation_slots.py index 3e1dfad346..5f5fb3cfbf 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_relation_slots.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_relation_slots.py @@ -323,7 +323,7 @@ def test_given_wrong_slot_mappings_when_compiling_then_the_error_names_the_slot( command=("compile",), expected_returncode=1, expected_fragments=( - "SQLCLEAN016]: Expression is aliased to its existing name", + "SQLCLEAN016]: Expression is aliased to an exact copy of its name", "--> sql/macros/sql/order_columns.sql:6:", ), ), 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 d6ba97e067..de95a80121 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 @@ -109,7 +109,7 @@ def test_given_benchmark_project_when_inspecting_test_plan_then_every_unit_test_ expected_errors=0, expected_warnings=0, expected_compiled_checksum=( - "7661e2ad98b33b8230c9df9c6c780e959cb7e18398b14a2cef36e12d19bd0bb6" + "6ca545b44f2e75e2473d716ebabbf439ccb080c1cc22671f0a3fbce7e557125c" ), ) ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_orchestration_selectors.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_orchestration_selectors.py new file mode 100644 index 0000000000..c60830f4ad --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_orchestration_selectors.py @@ -0,0 +1,98 @@ +"""E2E coverage for orchestration selectors: compile resolves them as publication does, with each site.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.compile._test_types import ( + OrchestrationSelectorCompileTestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.main.compile.helpers import ( + orchestration_job, + orchestration_sensor, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb +from tests.integration.src.sqlbuild.compiler.compiled_project.helpers import GROUP_CYCLE_NODES + +_ROOT_ERROR: str = "path selectors require an explicit root: use 'sql/models/' or 'python/nodes/'" +_ORDERS_JOB: str = "orchestration/jobs/orders_job.toml" +_REPORT_JOB: str = "orchestration/jobs/report_job.toml" +_SENSOR: str = "orchestration/sensors/regions_sensor.py" + + +@pytest.mark.parametrize( + "test_case", + [ + OrchestrationSelectorCompileTestCase( + description="root-less path selectors in jobs fail compile at their select lines", + files={ + _ORDERS_JOB: orchestration_job("orders_job", "path:models"), + _REPORT_JOB: orchestration_job( + "report_job", "region_report", exclude="path:python/loaders" + ), + }, + expected_messages=( + f"{_ORDERS_JOB}:3:10: job orders_job: {_ROOT_ERROR}", + f"{_REPORT_JOB}:3:10: job report_job: {_ROOT_ERROR}", + ), + fixed_files={ + _ORDERS_JOB: orchestration_job("orders_job", "path:sql/models"), + _REPORT_JOB: orchestration_job("report_job", "region_report", exclude="orders"), + }, + ), + OrchestrationSelectorCompileTestCase( + description="a job selecting a node the project lacks fails compile", + files={_ORDERS_JOB: orchestration_job("orders_job", "missing_orders")}, + expected_messages=(f"{_ORDERS_JOB}:3:10: job orders_job:", "missing_orders"), + fixed_files={_ORDERS_JOB: orchestration_job("orders_job", "orders")}, + ), + OrchestrationSelectorCompileTestCase( + description="a sensor condition with a root-less path selector fails compile at its decorator", + files={ + _ORDERS_JOB: orchestration_job("orders_job", "orders"), + "sql/sources/raw.yml": ( + "sources:\n - name: raw__regions\n description: Raw regions\n" + " columns:\n - name: id\n type: INTEGER\n" + ), + _SENSOR: orchestration_sensor("path:raw"), + }, + expected_messages=( + f"{_SENSOR}:4: sensor regions_sensor: source_new_data: {_ROOT_ERROR}", + ), + fixed_files={_SENSOR: orchestration_sensor("raw__regions")}, + ), + ], + ids=lambda case: case.description, +) +def test_given_orchestration_selectors_publication_refuses_when_compiling_then_each_fails_until_fixed( + tmp_path: Path, + test_case: OrchestrationSelectorCompileTestCase, +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="orchestration_selectors", + repo_files={ + "sqlbuild_project.toml": 'name = "orchestration_selectors"\nadapter = "duckdb"\n', + **GROUP_CYCLE_NODES, + **test_case.files, + }, + ) + + failed: subprocess.CompletedProcess[str] = run_sqb( + command=("compile",), project_dir=project_dir + ) + + assert failed.returncode == 1, failed.stdout + failed.stderr + assert "error[D017]" in failed.stderr + for message in test_case.expected_messages: + assert message in failed.stderr, failed.stderr + + for path, text in test_case.fixed_files.items(): + (project_dir / path).write_text(text, encoding="utf-8") + fixed: subprocess.CompletedProcess[str] = run_sqb(command=("compile",), project_dir=project_dir) + + assert fixed.returncode == 0, fixed.stdout + fixed.stderr + assert "D017" not in fixed.stderr 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 68de974712..4c5415f511 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 @@ -732,6 +732,7 @@ class FailedPlanTestCase: edited_file: str edit: tuple[str, str] selection: list[str] + expected_error_model: str expected_code: str expected_reason: str diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py index 5ac4ab5586..9c88305f4c 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py @@ -125,7 +125,7 @@ def test_given_development_when_reloaded_and_restarted_then_local_scope_and_paus } _ = environment.pop("SQLBUILD_PLATFORM_WEBHOOK_URL", None) log: Path = tmp_path / "development.log" - output: Path = tmp_path / "publications.jsonl" + output: Path = tmp_path / "development.stdout" with location_process(arguments, log, output, env=environment) as process: url, identity = wait_for_development_ready(process, log) api: SnapshotApi = SnapshotApi(url, identity, "local-development") @@ -229,8 +229,10 @@ def test_given_development_when_reloaded_and_restarted_then_local_scope_and_paus assert connection.execute("SELECT count(*) FROM sqb_development_locations").fetchone() == ( 1, ) - for line in output.read_text().splitlines(): - assert json.loads(line)["location_id"] == identity + # sqb dev's output is its screen: no raw JSON line, such as a publication record, on stdout or in + # the plain lines. + lines: list[str] = output.read_text().splitlines() + log.read_text().splitlines() + assert not any(line.lstrip().startswith(("{", "[")) for line in lines), output.read_text() @pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") @@ -264,7 +266,7 @@ def test_given_development_start_when_location_is_ready_then_project_python_is_d ) executable: str = str(Path(sys.executable).with_name("sqb")) log: Path = tmp_path / "development.log" - output: Path = tmp_path / "publications.jsonl" + output: Path = tmp_path / "development.stdout" arguments: list[str] = [executable, "dev", "--project-dir", str(project), "--port", "0"] environment: dict[str, str] = dict(os.environ) _ = environment.pop("SQLBUILD_PLATFORM_WEBHOOK_URL", None) @@ -312,7 +314,7 @@ def test_given_plain_development_when_a_warehouse_read_fails_then_a_warning_line environment: dict[str, str] = dict(os.environ) _ = environment.pop("SQLBUILD_PLATFORM_WEBHOOK_URL", None) with location_process( - arguments, log, tmp_path / "publications.jsonl", env=environment + arguments, log, tmp_path / "development.stdout", env=environment ) as process: url, identity = wait_for_development_ready(process, log) api: SnapshotApi = SnapshotApi(url, identity, "local-development") @@ -377,7 +379,7 @@ def test_given_a_missing_secret_when_it_is_added_to_the_env_file_then_the_next_r "SQLBUILD_CONTROL_DATABASE_URL": str(project / ".sqlbuild/control.sqlite3") } log: Path = tmp_path / "development.log" - output: Path = tmp_path / "publications.jsonl" + output: Path = tmp_path / "development.stdout" arguments: list[str] = [executable, "dev", "--project-dir", str(project), "--port", "0"] with location_process(arguments, log, output, env=environment) as process: url, identity = wait_for_development_ready(process, log) @@ -447,7 +449,7 @@ def test_given_an_unparsable_env_file_when_a_run_starts_then_its_reason_names_th "SQLBUILD_CONTROL_DATABASE_URL": str(project / ".sqlbuild/control.sqlite3") } log: Path = tmp_path / "development.log" - output: Path = tmp_path / "publications.jsonl" + output: Path = tmp_path / "development.stdout" arguments: list[str] = [executable, "dev", "--project-dir", str(project), "--port", "0"] with location_process(arguments, log, output, env=environment) as process: url, identity = wait_for_development_ready(process, log) @@ -497,7 +499,7 @@ def test_given_an_opened_development_server_when_started_then_it_publishes_takes executable: str = str(Path(sys.executable).with_name("sqb")) arguments: list[str] = [executable, "dev", "--project-dir", str(project), "--port", "0"] log: Path = tmp_path / "development.log" - output: Path = tmp_path / "publications.jsonl" + output: Path = tmp_path / "development.stdout" with location_process(arguments + list(test_case.arguments), log, output) as process: url, identity = wait_for_development_ready(process, log) api: SnapshotApi = SnapshotApi(url, identity, "local-development") diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_plan_preview.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_plan_preview.py index 352338af56..7c72b2942c 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_plan_preview.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_plan_preview.py @@ -635,13 +635,14 @@ def test_given_a_synced_copy_when_a_preview_reads_source_freshness_then_it_is_un edited_file="sql/functions/sql/udf__adjust_amount.sql", edit=("amount + 1", "amount + 100"), selection=["model:order_amounts"], + expected_error_model="order_amounts", expected_code="S203", expected_reason="model 'order_amounts' sets full_refresh false", ), ], ids=lambda case: case.description, ) -def test_given_a_plan_that_fails_when_the_location_plans_it_then_its_own_error_is_stored( +def test_given_a_model_that_cannot_be_planned_when_the_location_plans_it_then_its_error_row_is_stored( test_case: FailedPlanTestCase, tmp_path: Path ) -> None: project: Path = tmp_path / "project" @@ -655,10 +656,16 @@ def test_given_a_plan_that_fails_when_the_location_plans_it_then_its_own_error_i published, plan = changed_build_and_plan_from_copy(tmp_path, project, test_case.selection) - assert plan["error"]["code"] == test_case.expected_code, plan - assert test_case.expected_reason in plan["error"]["message"], plan + rows: dict[str, dict[str, Any]] = {model["name"]: model for model in plan["models"]} + error: dict[str, Any] = rows[test_case.expected_error_model]["error"] + assert plan["has_errors"] is True, plan + assert rows[test_case.expected_error_model]["action"] == "error", plan + assert error["code"] == test_case.expected_code, plan + assert test_case.expected_reason in error["message"], plan assert published["changed"] == [] and published["downstream"] == [], published - assert published["failing"] == plan["error"]["message"], published + assert published["failing"] == ( + f"Can't plan 1 model: {test_case.expected_error_model}: {error['message']}" + ), published @pytest.mark.parametrize( diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rules_at_load.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rules_at_load.py index 819464881a..eae4d8c889 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rules_at_load.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rules_at_load.py @@ -40,6 +40,10 @@ expected_health={ "kind": "compile_failed", "generation": 1, + "error": ( + "configured rules failed with 1 finding(s); first: SQBRMODEL102 " + "SELECT * is allowed only inside dependency import CTEs" + ), "rules": { "finding_count": 1, "findings": [ diff --git a/tests/integration/src/sqlbuild/compiler/planner/main/test_build_execution_plan.py b/tests/integration/src/sqlbuild/compiler/planner/main/test_build_execution_plan.py index addaa79155..300cc87f30 100644 --- a/tests/integration/src/sqlbuild/compiler/planner/main/test_build_execution_plan.py +++ b/tests/integration/src/sqlbuild/compiler/planner/main/test_build_execution_plan.py @@ -1,5 +1,6 @@ from __future__ import annotations +import re from dataclasses import replace from typing import Any @@ -14,7 +15,6 @@ LocalConfig, ModelPlanEntry, PlanAction, - PlannerInputError, PlanOutput, PlanReason, PlanWarning, @@ -555,7 +555,7 @@ def test_given_view_and_table_with_target_default_when_assembling_plan_then_only ], ids=lambda case: case.description, ) -def test_given_missing_source_cursor_input_column_when_building_plan_then_raises_planner_error( +def test_given_missing_source_cursor_input_column_when_building_plan_then_reports_planner_error( test_case: SourceCursorInputPlanErrorTestCase, adapter: DuckDbAdapter, connection: Any, @@ -566,13 +566,18 @@ def test_given_missing_source_cursor_input_column_when_building_plan_then_raises project: Any = build_project_from_source_cursor_input_test_case(test_case) - with pytest.raises(PlannerInputError, match=test_case.expected_error_fragment): - build_execution_plan_from_kwargs( - project=project, - adapter=adapter, - connection=connection, - full_refresh=False, - ) + plan: PlanOutput = build_execution_plan_from_kwargs( + project=project, + adapter=adapter, + connection=connection, + full_refresh=False, + ) + + errors: list[PlanWarning] = list( + filter(None, (entry.planning_error for entry in plan.model_entries)) + ) + assert [error.model_name for error in errors] == [test_case.model_name] + assert test_case.expected_error_fragment in errors[0].message @pytest.mark.parametrize( @@ -994,14 +999,18 @@ def test_given_future_upstream_and_error_policy_when_building_real_plan_then_fai connection.execute("CREATE TABLE raw.events (occurred_at TIMESTAMP)") connection.execute("INSERT INTO raw.events VALUES (TIMESTAMP '2500-01-01')") - with pytest.raises(PlannerInputError, match=test_case.expected_error_fragment): - build_execution_plan_from_kwargs( - project=project, - adapter=adapter, - connection=connection, - project_config=ProjectConfig( - name="future_cursor", - adapter="duckdb", - cursors=CursorsConfig(future=FutureCursorsConfig("1d", FutureCursorAction.ERROR)), - ), - ) + plan: PlanOutput = build_execution_plan_from_kwargs( + project=project, + adapter=adapter, + connection=connection, + project_config=ProjectConfig( + name="future_cursor", + adapter="duckdb", + cursors=CursorsConfig(future=FutureCursorsConfig("1d", FutureCursorAction.ERROR)), + ), + ) + + errors: list[PlanWarning] = list( + filter(None, (entry.planning_error for entry in plan.model_entries)) + ) + assert re.search(test_case.expected_error_fragment, errors[0].message), errors diff --git a/tests/unit/src/sqlbuild/adapter/contract/classes/strict_adapter/test_strict_adapter.py b/tests/unit/src/sqlbuild/adapter/contract/classes/strict_adapter/test_strict_adapter.py index 3abf99bd12..34976636ad 100644 --- a/tests/unit/src/sqlbuild/adapter/contract/classes/strict_adapter/test_strict_adapter.py +++ b/tests/unit/src/sqlbuild/adapter/contract/classes/strict_adapter/test_strict_adapter.py @@ -88,6 +88,7 @@ def test_given_first_class_adapters_when_checking_contract_then_no_method_comes_ expected_optional_methods=frozenset( { "create_sql_test_output", + "cursor_type_range", "drop_sql_test_output", "dynamic_listing", "render_alter_dynamic", diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/_test_types.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/_test_types.py index 5793219d9f..4fed6b4bb4 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/_test_types.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/_test_types.py @@ -2,10 +2,12 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass, field from datetime import date, datetime from sqlbuild._native import CursorBounds, CursorOverrides, ModelCursorSnapshot, SourceEntry +from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter from sqlbuild.adapter.contract.models import ColumnInfo @@ -66,6 +68,16 @@ class CursorIntrinsicResolutionTestCase: expected_error_fragment: str | None = None +@dataclass(frozen=True) +class FullBuildIntrinsicTestCase: + description: str + adapter: Callable[[], BaseAdapter] + model_config: dict[str, object] + full_refresh: bool + full_rebuild_cause: str | None + expected_sql: str + + @dataclass(frozen=True) class SourceResolutionTestCase: description: str diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/test_cursor_intrinsics.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/test_cursor_intrinsics.py index ff549ce031..bf702e0e76 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/test_cursor_intrinsics.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/resolve/test_cursor_intrinsics.py @@ -8,20 +8,34 @@ CursorOverridePair, Dialect, ModelCursorSnapshot, - PlannerInputError, WarehouseSnapshot, resolve_model_sql, ) +from sqlbuild.adapters.clickhouse.classes.clickhouse_adapter import ClickHouseAdapter from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter +from sqlbuild.adapters.snowflake.classes.snowflake_adapter import SnowflakeAdapter +from sqlbuild.adapters.sqlite.classes.sqlite_adapter import SqliteAdapter from sqlbuild.compiler.compile.types import CompiledModelView from tests.unit.src.sqlbuild.compiler.planner._helpers.resolve._test_types import ( CursorIntrinsicResolutionTestCase, + FullBuildIntrinsicTestCase, ) from tests.unit.src.sqlbuild.compiler.planner._helpers.resolve.helpers import ( build_cursor_intrinsic_model, build_empty_model_plan_context, ) +_TIMESTAMP: dict[str, object] = { + "materialized": "incremental", + "cursor": "event_time", + "cursor_type": "timestamp", +} +_INTEGER: dict[str, object] = { + "materialized": "incremental", + "cursor": "event_id", + "cursor_type": "integer", +} + @pytest.mark.parametrize( "test_case", @@ -86,35 +100,124 @@ def test_given_cursor_interval_when_resolving_then_renders_expected_sql( @pytest.mark.parametrize( "test_case", [ - CursorIntrinsicResolutionTestCase( - description="rejects non-microbatch full refresh", - model_config={ - "materialized": "incremental", - "cursor": "event_time", - "cursor_type": "timestamp", - }, + FullBuildIntrinsicTestCase( + description="DuckDB --full-refresh spans every timestamp", + adapter=DuckDbAdapter, + model_config=_TIMESTAMP, full_refresh=True, - cursor_snapshots={}, - expected_error_fragment=( - r"given a FULL backfill \(--full-refresh\).*full rebuild has no cursor interval" + full_rebuild_cause=None, + expected_sql=( + "SELECT TIMESTAMP '0001-01-01 00:00:00' /* (unbounded) */ AS batch_start, TIMESTAMP '9999-12-31 23:59:59.999999' /* (unbounded) */ AS batch_end" + ), + ), + FullBuildIntrinsicTestCase( + description="DuckDB first run spans every timestamp", + adapter=DuckDbAdapter, + model_config=_TIMESTAMP, + full_refresh=False, + full_rebuild_cause="the destination doesn't exist", + expected_sql=( + "SELECT TIMESTAMP '0001-01-01 00:00:00' /* (unbounded) */ AS batch_start, TIMESTAMP '9999-12-31 23:59:59.999999' /* (unbounded) */ AS batch_end" + ), + ), + FullBuildIntrinsicTestCase( + description="DuckDB cursor_start floor starts the span", + adapter=DuckDbAdapter, + model_config={**_TIMESTAMP, "cursor_start": "2024-01-01"}, + full_refresh=True, + full_rebuild_cause=None, + expected_sql=( + "SELECT TIMESTAMP '2024-01-01' AS batch_start, TIMESTAMP '9999-12-31 23:59:59.999999' /* (unbounded) */ AS batch_end" + ), + ), + FullBuildIntrinsicTestCase( + description="DuckDB integer cursor spans the 64-bit range", + adapter=DuckDbAdapter, + model_config=_INTEGER, + full_refresh=True, + full_rebuild_cause=None, + expected_sql=( + "SELECT -9223372036854775808 /* (unbounded) */ AS batch_start, 9223372036854775807 /* (unbounded) */ AS batch_end" + ), + ), + FullBuildIntrinsicTestCase( + description="DuckDB integer floor starts the span", + adapter=DuckDbAdapter, + model_config={**_INTEGER, "cursor_start": 100}, + full_refresh=True, + full_rebuild_cause=None, + expected_sql=( + "SELECT 100 AS batch_start, 9223372036854775807 /* (unbounded) */ AS batch_end" + ), + ), + FullBuildIntrinsicTestCase( + description="DuckDB date-grain cursor spans every timestamp", + adapter=DuckDbAdapter, + model_config={**_TIMESTAMP, "cursor_grain": "day"}, + full_refresh=True, + full_rebuild_cause=None, + expected_sql=( + "SELECT TIMESTAMP '0001-01-01 00:00:00' /* (unbounded) */ AS batch_start, TIMESTAMP '9999-12-31 23:59:59.999999' /* (unbounded) */ AS batch_end" + ), + ), + FullBuildIntrinsicTestCase( + description="Snowflake --full-refresh spans every timestamp", + adapter=SnowflakeAdapter, + model_config=_TIMESTAMP, + full_refresh=True, + full_rebuild_cause=None, + expected_sql=( + "SELECT '0001-01-01 00:00:00' /* (unbounded) */ AS batch_start, '9999-12-31 23:59:59.999999' /* (unbounded) */ AS batch_end" + ), + ), + FullBuildIntrinsicTestCase( + description="Snowflake integer cursor spans the 64-bit range", + adapter=SnowflakeAdapter, + model_config=_INTEGER, + full_refresh=True, + full_rebuild_cause=None, + expected_sql=( + "SELECT -9223372036854775808 /* (unbounded) */ AS batch_start, 9223372036854775807 /* (unbounded) */ AS batch_end" + ), + ), + FullBuildIntrinsicTestCase( + description="ClickHouse spans DateTime64's range", + adapter=ClickHouseAdapter, + model_config=_TIMESTAMP, + full_refresh=True, + full_rebuild_cause=None, + expected_sql=( + "SELECT parseDateTime64BestEffort('1900-01-01 00:00:00', 6, 'UTC') /* (unbounded) */ AS batch_start, parseDateTime64BestEffort('2299-12-31 23:59:59.999999', 6, 'UTC') /* (unbounded) */ AS batch_end" + ), + ), + FullBuildIntrinsicTestCase( + description="SQLite spans every timestamp as sortable text", + adapter=SqliteAdapter, + model_config=_TIMESTAMP, + full_refresh=True, + full_rebuild_cause=None, + expected_sql=( + "SELECT '0001-01-01 00:00:00' /* (unbounded) */ AS batch_start, '9999-12-31 23:59:59.999999' /* (unbounded) */ AS batch_end" ), - ) + ), ], ids=lambda case: case.description, ) -def test_given_missing_cursor_interval_when_resolving_then_rejects_intrinsics( - test_case: CursorIntrinsicResolutionTestCase, +def test_given_a_full_build_when_resolving_then_intrinsics_span_the_cursor_range( + test_case: FullBuildIntrinsicTestCase, ) -> None: model: CompiledModelView = build_cursor_intrinsic_model(config_values=test_case.model_config) - with pytest.raises(PlannerInputError, match=test_case.expected_error_fragment) as raised: - resolve_model_sql( - dialect=Dialect(DuckDbAdapter()), - model=model, - snapshot=WarehouseSnapshot(), - context=build_empty_model_plan_context(), - backfill=BackfillResult(action=BackfillAction.FORWARD_ONLY), - full_refresh=test_case.full_refresh, - cursor_overrides=CursorOverridePair(), - ) - assert raised.value.code == "S204" + resolved_sql: str = resolve_model_sql( + dialect=Dialect(test_case.adapter()), + model=model, + snapshot=WarehouseSnapshot(), + context=build_empty_model_plan_context(), + backfill=BackfillResult(action=BackfillAction.FORWARD_ONLY), + full_refresh=test_case.full_refresh, + cursor_overrides=CursorOverridePair(), + replaces_relation=True, + full_rebuild_cause=test_case.full_rebuild_cause, + ) + + assert resolved_sql == test_case.expected_sql diff --git a/tests/unit/src/sqlbuild/compiler/planner/main/test_execution.py b/tests/unit/src/sqlbuild/compiler/planner/main/test_execution.py index 7a5a095a33..d6feb6bda1 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/main/test_execution.py +++ b/tests/unit/src/sqlbuild/compiler/planner/main/test_execution.py @@ -10,9 +10,9 @@ DiscoveredHookFunction, ModelPlanEntry, PlanAction, - PlannerInputError, PlanOutput, PlanReason, + PlanWarning, project_with, ) from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter @@ -199,14 +199,15 @@ def test_given_unblocked_protected_model_when_planning_then_full_rebuild_is_refu connection: Any = adapter.connect({"database": ":memory:"}) try: create_protected_model_state(adapter=adapter, connection=connection) - with pytest.raises(PlannerInputError) as raised: - build_execution_plan_from_kwargs( - project=build_protected_schema_replay_project(), - adapter=adapter, - connection=connection, - external_blocked_model_names=test_case.external_blocked_model_names, - ) + plan_output: PlanOutput = build_execution_plan_from_kwargs( + project=build_protected_schema_replay_project(), + adapter=adapter, + connection=connection, + external_blocked_model_names=test_case.external_blocked_model_names, + ) finally: adapter.close(connection) - assert raised.value.code == test_case.expected_action + error: PlanWarning | None = plan_output.model_entries[0].planning_error + assert error is not None + assert error.code == test_case.expected_action diff --git a/ui/e2e/cost.spec.ts b/ui/e2e/cost.spec.ts index 94d8242af3..8c199a29dd 100644 --- a/ui/e2e/cost.spec.ts +++ b/ui/e2e/cost.spec.ts @@ -8,11 +8,6 @@ test.use({ viewport: { width: 1600, height: 1000 } }); const crumbs = (page: Page) => page.getByRole('navigation', { name: 'Breadcrumb' }); const rows = (page: Page) => page.locator('.drill tbody tr[data-kind]'); -/** - * A drill's URL is first a shallow entry (pushState), then made a real one by the selection's - * replacing navigation. Back before that lands is overwritten by it, so wait for the real entry. - */ -const settled = (page: Page) => page.waitForFunction(() => !history.state?.['sveltekit:pageurl']); async function open(page: Page, path: string) { await page.goto(path); @@ -41,7 +36,6 @@ test('a job’s name drills in by selecting it, and the breadcrumb and Back go u // A folder narrows the selection to the job's models in it. await rows(page).first().locator('.row-name').click(); await expect(page).toHaveURL(/path%3Asql%2Fmodels%2F/); - await settled(page); await page.goBack(); await expect(crumbs(page).getByRole('link')).toHaveCount(1); await crumbs(page).getByRole('link', { name: 'All' }).click(); diff --git a/ui/e2e/plan-browser.spec.ts b/ui/e2e/plan-browser.spec.ts index 2bf2bd36f0..cb85d822f0 100644 --- a/ui/e2e/plan-browser.spec.ts +++ b/ui/e2e/plan-browser.spec.ts @@ -234,7 +234,7 @@ test('seeds sit with the models of the same reason: first runs, changes and unch }); test('a small plan reads as a short index', async ({ page }) => { - await openPlan(page, `/plan?mock&cmd=${encodeURIComponent('sqb build -s path:models/marts')}`); + await openPlan(page, `/plan?mock&cmd=${encodeURIComponent('sqb build -s path:sql/models/marts')}`); const entries = page.locator('.index .entry'); expect(await entries.count()).toBeGreaterThanOrEqual(1); expect(await entries.count()).toBeLessThanOrEqual(3); diff --git a/ui/e2e/selection.spec.ts b/ui/e2e/selection.spec.ts index c94465582c..8b33c4c59e 100644 --- a/ui/e2e/selection.spec.ts +++ b/ui/e2e/selection.spec.ts @@ -107,7 +107,7 @@ test('a job page shows its selection as chips that open in Lineage', async ({ pa test('a job selecting folders opens in Lineage without an error', async ({ page }) => { await page.goto('/jobs/core_build?mock'); - await expect(page.locator('.sel-chips .sel-chip')).toHaveText([/path:models\/staging/, /path:models\/marts/]); + await expect(page.locator('.sel-chips .sel-chip')).toHaveText([/path:sql\/models\/staging/, /path:sql\/models\/marts/]); await page.locator('.sel-chips').getByRole('link', { name: 'Open in Lineage' }).click(); await page.waitForURL(/\/lineage\?/); await expect(page.locator('.sb-count')).toHaveText(/^\d+ nodes?$/); @@ -119,8 +119,8 @@ test('a folder on the Overview opens in the catalog as a path selection', async const marts = page.locator('a.group-row', { hasText: 'marts' }).first(); await marts.click(); await page.waitForURL(/\/catalog\?/); - expect(new URL(page.url()).searchParams.get('select')).toBe('path:models/marts'); - await expect(page.locator('.selection-bar .sel-chip')).toHaveText([/path:models\/marts/]); + expect(new URL(page.url()).searchParams.get('select')).toBe('path:sql/models/marts'); + await expect(page.locator('.selection-bar .sel-chip')).toHaveText([/path:sql\/models\/marts/]); await expect(page.getByRole('alert')).toHaveCount(0); await expect(page.getByRole('button', { name: /^Folder/ })).toHaveCount(0); }); diff --git a/ui/e2e/support/fake-control.ts b/ui/e2e/support/fake-control.ts index 9ab02dbb25..7b774739ab 100644 --- a/ui/e2e/support/fake-control.ts +++ b/ui/e2e/support/fake-control.ts @@ -200,7 +200,8 @@ export class FakeControl { elapsed_millis: 10, progress: { position: target.sync === 'running' ? 1 : 2, kinds: 2, rows: 5, elapsed_millis: 20, completed: target.sync !== 'running' } }; - return [{ received_at: at, report: { event_id: '0190d1a0-0000-7000-8000-0000000000dd', session_id: '0190d1a0-0000-7000-8000-0000000000ee', target: 'dev', health } }]; + // The server computes the state; a sync report alone leaves the target healthy. + return { state: 'healthy', observations: [{ received_at: at, report: { event_id: '0190d1a0-0000-7000-8000-0000000000dd', session_id: '0190d1a0-0000-7000-8000-0000000000ee', target: 'dev', health } }] }; } #failedRun(name: TargetName) { diff --git a/ui/src/lib/api/http-catalog.ts b/ui/src/lib/api/http-catalog.ts index e8b0d1e306..d80deb5e31 100644 --- a/ui/src/lib/api/http-catalog.ts +++ b/ui/src/lib/api/http-catalog.ts @@ -50,7 +50,10 @@ export function toCatalogNode(wire: Wire['CatalogNodeRecord']): CatalogNode | nu ? [{ reason: 'changed', change: 'definition', detail: 'The definition changed since it was last built here.', since: state.lastBuild.builtAt }] : [], sourceFreshness: null, - checks: state.checks + checks: state.checks, + // The listing carries no state; the node-states read sets it. + status: null, + statusAt: null }; } @@ -64,7 +67,9 @@ export function toNodeState(wire: Wire['NodeState']): NodeState { lastOutcome: outcome === 'success' || outcome === 'warn' || outcome === 'failed' ? outcome : null, definitionChanged: wire.definition_changed, // A recording from an older server, such as the static demo's, has no counts: unknown, not zero. - checks: wire.checks ?? null + checks: wire.checks ?? null, + status: 'status' in wire ? (wire.status ?? null) : null, + statusAt: 'status_at' in wire ? (wire.status_at ?? null) : null }; } diff --git a/ui/src/lib/api/http-client.test.ts b/ui/src/lib/api/http-client.test.ts index 78d7040645..ca88d28f0c 100644 --- a/ui/src/lib/api/http-client.test.ts +++ b/ui/src/lib/api/http-client.test.ts @@ -197,7 +197,7 @@ describe('HttpChangeFeed', () => { const signals: ChangedSignal[] = []; changes.subscribe((signal) => signals.push(signal)); changes.follow(ORDERS); - const state = { last_build: { observed_at: '2026-01-02T00:00:00Z', run_id: 'r2', version_hash: 'h2' }, last_outcome: { at: '2026-01-02T00:00:00Z', status: 'failed' }, definition_changed: false, checks: { total: 1, passing: 0, warning: 0, failing: 1 } }; + const state = { last_build: { observed_at: '2026-01-02T00:00:00Z', run_id: 'r2', version_hash: 'h2' }, last_outcome: { at: '2026-01-02T00:00:00Z', status: 'failed' }, definition_changed: false, checks: { total: 1, passing: 0, warning: 0, failing: 1 }, status: 'failed', status_at: '2026-01-02T00:00:00Z' }; const send = (notice: unknown) => latest().listeners.get('changed')!(new MessageEvent('changed', { data: JSON.stringify(notice) })); send({ topic: 'node_status:development', version: 8, previous_version: 7, states: { 'model:orders': state } }); send({ topic: 'node_status:development', version: 9, previous_version: 8, full: true }); @@ -211,7 +211,9 @@ describe('HttpChangeFeed', () => { lastBuild: { fingerprintRunId: 'r2', runId: null, jobKey: null, builtAt: '2026-01-02T00:00:00Z', fingerprint: 'h2' }, lastOutcome: 'failed', definitionChanged: false, - checks: { total: 1, passing: 0, warning: 0, failing: 1 } + checks: { total: 1, passing: 0, warning: 0, failing: 1 }, + status: 'failed', + statusAt: '2026-01-02T00:00:00Z' } } }, @@ -369,7 +371,7 @@ describe('node listing and states', () => { vi.fn(async (request: Request) => { const path = new URL(request.url).pathname; if (path.endsWith('/node-states')) { - return Response.json({ snapshot_id: record.snapshot_id, version: 3, states: { 'model:orders': { definition_changed: false, checks: record.checks, last_outcome: { at: '2026-01-02T00:00:00Z', status: 'failed' } } } }); + return Response.json({ snapshot_id: record.snapshot_id, version: 3, states: { 'model:orders': { definition_changed: false, checks: record.checks, last_outcome: { at: '2026-01-02T00:00:00Z', status: 'failed' }, status: 'failed', status_at: '2026-01-02T00:00:00Z' } } }); } if (path.endsWith('/column-lineage')) { return Response.json({ nodes: [{ node_key: 'model:orders', columns: [] }], edges: [{ source_key: 'model:orders', source_column: 'id', target_key: 'model:orders', target_column: 'order_id', transform: 'direct' }] }); @@ -581,7 +583,7 @@ describe('locations', () => { overdue_ticks: [] }); if (path.includes('/targets/preview/')) return Response.json({ error: 'refused' }, { status: 403 }); - if (path.endsWith('/health')) return Response.json([report('s-2', 10), report('s-1', 400), report('s-2', 20)]); + if (path.endsWith('/health')) return Response.json({ state: 'healthy', observations: [report('s-2', 10), report('s-1', 400), report('s-2', 20)] }); return Response.json([]); }) ); @@ -606,7 +608,7 @@ describe('locations', () => { expect(paths.some((p) => p.endsWith('/health'))).toBe(false); }); - it('counts open problems per location target', async () => { + it("counts open problems per location target, with the server's state of each", async () => { const listed = await server().client.listLocations(); expect(listed.map((l) => [l.id, l.activeProblems, l.health])).toEqual([ ['0191f0aa-orders:development', 1, 'healthy'], @@ -1091,7 +1093,7 @@ describe('listWarehouseConnections', () => { if (path.endsWith('/bootstrap')) return Response.json({ login_mode: 'password', access: { name: 'ada', principal_id: 'p', actions: [], locations: [access('development'), access('preview')] } }); if (path.endsWith('/health')) { health.push(path); - return path.includes('/targets/preview/') ? Response.json({ error: 'refused' }, { status: 403 }) : Response.json([]); + return path.includes('/targets/preview/') ? Response.json({ error: 'refused' }, { status: 403 }) : Response.json({ state: 'healthy', observations: [] }); } return Response.json([]); }) diff --git a/ui/src/lib/api/http-client.ts b/ui/src/lib/api/http-client.ts index ad40fd68c0..c4661647ed 100644 --- a/ui/src/lib/api/http-client.ts +++ b/ui/src/lib/api/http-client.ts @@ -767,7 +767,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/health', { params: { path: { location_id: locationId, target } } }); if (response.status === 401) onUnauthorized(); if (!data) throw new ApiError(errorText(error, response), response.status); - return warehouseSyncOf(data); + return warehouseSyncOf(data.observations); }, /** The location takes the request within seconds; the sync's result arrives as a `warehouse_sync` change. */ async requestWarehouseSync(scope: Scope): Promise { @@ -907,7 +907,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, locations.map(async (location) => { const [{ data, response }, snapshot] = await locationHealth(location.id); if (response.status === 403) healthRefused.add(location.id); - return data ? [toWarehouseConnection(location, data, snapshot)] : []; + return data ? [toWarehouseConnection(location, data.observations, snapshot)] : []; }) ); return read.flat(); @@ -1070,7 +1070,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, attentionAcknowledgementsOf(scope), // Missing provider secrets come from the target's own health; a refused or failed read leaves the item out and judges nothing. locationHealth(scope.locationId) - .then(([health]) => (health.data ? { read: true, event: missingSecretsEventOf(scope.locationId, health.data) } : { read: false, event: null })) + .then(([health]) => (health.data ? { read: true, event: missingSecretsEventOf(scope.locationId, health.data.observations) } : { read: false, event: null })) .catch(() => ({ read: false, event: null })), listedTriggers(scope) ]); diff --git a/ui/src/lib/api/http-locations.test.ts b/ui/src/lib/api/http-locations.test.ts index e1172e8c47..eabb5219ad 100644 --- a/ui/src/lib/api/http-locations.test.ts +++ b/ui/src/lib/api/http-locations.test.ts @@ -1,17 +1,17 @@ import { describe, expect, it } from 'vitest'; -import { connectionDetailsOf, connectionTestOf, firstSyncPending, healthOf, instancesOf, missingSecretsEventOf, missingSecretsOf, poolCapWarningsOf, toLocationDetail, toWarehouseConnection, warehouseSyncOf } from './http-locations'; +import { checkInsOf, connectionDetailsOf, connectionTestOf, firstSyncPending, instancesOf, missingSecretsEventOf, missingSecretsOf, poolCapWarningsOf, toLocationDetail, toWarehouseConnection, warehouseSyncOf } from './http-locations'; const now = Date.parse('2026-11-08T12:00:00Z'); const at = (secondsAgo: number) => new Date(now - secondsAgo * 1000).toISOString(); -type Health = Parameters[0][number]['report']['health']; +type Health = Parameters[0][number]['report']['health']; const seen = (secondsAgo: number, health: Health, session = 's-1') => ({ received_at: at(secondsAgo), report: { event_id: `e-${secondsAgo}`, session_id: session, target: 'prod', health } }); describe('location health', () => { - it('is broken without a check-in in the last 90 seconds, whatever was reported before', () => { - expect(healthOf([seen(91, { kind: 'heartbeat' })], now)).toEqual({ health: 'broken', liveInstances: 0, lastSeenAt: at(91) }); + it('counts no live instance without a check-in in the last 90 seconds', () => { + expect(checkInsOf([seen(91, { kind: 'heartbeat' })], now)).toEqual({ liveInstances: 0, lastSeenAt: at(91) }); }); it("reads the server's newest pool-cap warning, job by job", () => { @@ -23,25 +23,12 @@ describe('location health', () => { it("doesn't count the server's pool-cap warning as a location check-in", () => { const capped = seen(5, { kind: 'pool_capped', generation: 2, jobs: [] }, '00000000-0000-0000-0000-000000000000'); - expect(healthOf([capped, seen(91, { kind: 'heartbeat' })], now)).toEqual({ health: 'broken', liveInstances: 0, lastSeenAt: at(91) }); + expect(checkInsOf([capped, seen(91, { kind: 'heartbeat' })], now)).toEqual({ liveInstances: 0, lastSeenAt: at(91) }); }); it('counts each live instance once', () => { const observations = [seen(10, { kind: 'heartbeat' }), seen(20, { kind: 'connection', generation: 2, healthy: true }), seen(30, { kind: 'heartbeat' }, 's-2')]; - expect(healthOf(observations, now)).toMatchObject({ health: 'healthy', liveInstances: 2, lastSeenAt: at(10) }); - }); - - it('falls back after a failed load until a newer generation connects', () => { - const failed = seen(20, { kind: 'compile_failed', generation: 3 }); - expect(healthOf([seen(5, { kind: 'heartbeat' }), failed, seen(40, { kind: 'connection', generation: 2, healthy: true })], now).health).toBe('falling_back'); - expect(healthOf([seen(5, { kind: 'connection', generation: 4, healthy: true }), failed], now).health).toBe('healthy'); - }); - - it('reports missing provider secrets ahead of a failed connection until a newer report finds none', () => { - const missing = seen(10, { kind: 'provider_secrets', generation: 2, missing: 1, providers: [] }); - const unhealthy = seen(10, { kind: 'connection', generation: 2, healthy: false }); - expect(healthOf([missing, unhealthy], now).health).toBe('missing_secrets'); - expect(healthOf([seen(5, { kind: 'provider_secrets', generation: 3, missing: 0, providers: [] }), missing], now).health).toBe('healthy'); + expect(checkInsOf(observations, now)).toEqual({ liveInstances: 2, lastSeenAt: at(10) }); }); it('lists the newest check\'s providers missing secrets, the target\'s allowed ones last, and raises only the others', () => { @@ -68,19 +55,10 @@ describe('location health', () => { ); const allowedOnly = seen(5, { kind: 'provider_secrets', generation: 3, missing: 0, providers: [bucket] }); expect(missingSecretsEventOf('loc-1:prod', [allowedOnly, newest])).toBeNull(); - expect(healthOf([allowedOnly], now).health).toBe('healthy'); - }); - - it('reports a failed discover function ahead of a failed connection until a newer publish discovers it', () => { - const failed = seen(10, { kind: 'discovery', generation: 2, sets: [{ name: 'orders_plan', status: 'failed', error: 'ssh timeout', items: 11 }] }); - const unhealthy = seen(10, { kind: 'connection', generation: 2, healthy: false }); - expect(healthOf([failed, unhealthy], now).health).toBe('discovery_failed'); - expect(healthOf([seen(5, { kind: 'discovery', generation: 3, sets: [{ name: 'orders_plan', status: 'ok', items: 12 }] }), failed], now).health).toBe('healthy'); }); - it('needs attention when the latest connection check failed', () => { + it('records a failed connection check', () => { const observations = [seen(5, { kind: 'connection', generation: 2, healthy: false }), seen(60, { kind: 'connection', generation: 1, healthy: true })]; - expect(healthOf(observations, now).health).toBe('degraded'); expect(connectionTestOf(observations)).toMatchObject({ outcome: 'failed', at: at(5) }); }); @@ -110,20 +88,20 @@ describe('location processes', () => { describe('toLocationDetail', () => { const location = { id: 'loc:prod', name: 'orders', health: null, lastSeenAt: null, target: { name: 'prod', adapter: null, connectionSummary: null }, warehouseSync: { lastSyncedAt: null, lastError: null } }; - it('shows a failed reload as its health, without inventing a failed deploy or error text', () => { - const detail = toLocationDetail(location, [seen(5, { kind: 'heartbeat' }), seen(20, { kind: 'compile_failed', generation: 3 }), seen(40, { kind: 'connection', generation: 2, healthy: true })], null, now); + it("shows the server's state, without inventing a failed deploy or error text", () => { + const detail = toLocationDetail(location, { state: 'falling_back', observations: [seen(5, { kind: 'heartbeat' }), seen(20, { kind: 'compile_failed', generation: 3 }), seen(40, { kind: 'connection', generation: 2, healthy: true })] }, null, now); expect([detail.health, detail.failedDeploy, detail.lastLoadError, detail.snapshot]).toEqual(['falling_back', null, null, null]); }); it('lists the rule findings that failed the load, as sqb compile prints them', () => { const rules = { finding_count: 3, findings: [{ code: 'SQBRMODEL102', message: 'SELECT * is allowed only inside dependency import CTEs', path: 'models/orders.sql', line: 2 }] }; - const detail = toLocationDetail(location, [seen(20, { kind: 'compile_failed', generation: 3, rules })], null, now); + const detail = toLocationDetail(location, { state: 'falling_back', observations: [seen(20, { kind: 'compile_failed', generation: 3, rules })] }, null, now); expect(detail.lastLoadError).toBe('Compile failed: 3 rule findings\nmodels/orders.sql:2 [SQBRMODEL102] SELECT * is allowed only inside dependency import CTEs\n… and 2 more'); }); - it('is healthy again once a newer generation connects', () => { - const detail = toLocationDetail(location, [seen(5, { kind: 'connection', generation: 4, healthy: true }), seen(20, { kind: 'compile_failed', generation: 3 })], null, now); - expect([detail.health, detail.connectionTest?.outcome]).toEqual(['healthy', 'ok']); + it('shows no load error once the server reads the location healthy again', () => { + const detail = toLocationDetail(location, { state: 'healthy', observations: [seen(5, { kind: 'connection', generation: 4, healthy: true }), seen(20, { kind: 'compile_failed', generation: 3, error: 'job x: unknown' })] }, null, now); + expect([detail.health, detail.lastLoadError, detail.connectionTest?.outcome]).toEqual(['healthy', null, 'ok']); }); }); diff --git a/ui/src/lib/api/http-locations.ts b/ui/src/lib/api/http-locations.ts index 582e7a269a..9b28166798 100644 --- a/ui/src/lib/api/http-locations.ts +++ b/ui/src/lib/api/http-locations.ts @@ -12,28 +12,16 @@ function latestOf(observations: Wire[' return observations.find((o) => o.report.health.kind === kind) as (Wire['LocationHealthObservation'] & { report: { health: Extract } }) | undefined; } -/** Health from the newest observations: down without a recent check-in, then load failures, then missing provider secrets, then failed discover functions, then connection failures. */ -export function healthOf(observations: Wire['LocationHealthObservation'][], now: number): { health: LocationHealth; liveInstances: number; lastSeenAt: string | null } { - // The server's own pool-cap warning is not a location check-in. - const reported = observations.filter((o) => o.report.health.kind !== 'pool_capped'); +/** + * How many instances checked in within the live window, and the newest check-in. The server's own + * pool-cap warning and failed-plan record are not check-ins. The target's health is the server's + * `state`; it is never worked out here. + */ +export function checkInsOf(observations: Wire['LocationHealthObservation'][], now: number): { liveInstances: number; lastSeenAt: string | null } { + const reported = observations.filter((o) => o.report.health.kind !== 'pool_capped' && o.report.health.kind !== 'change_plan_failed'); const live = new Set(reported.filter((o) => now - Date.parse(o.received_at) <= LIVE_WINDOW_MS).map((o) => o.report.session_id)); const lastSeenAt = reported.reduce((latest, o) => (!latest || o.received_at > latest ? o.received_at : latest), null); - const failed = latestOf(observations, 'compile_failed'); - const connection = latestOf(observations, 'connection'); - const secrets = latestOf(observations, 'provider_secrets'); - const discovery = latestOf(observations, 'discovery'); - const health: LocationHealth = !live.size - ? 'broken' - : failed && (!connection || failed.report.health.generation >= connection.report.health.generation) - ? 'falling_back' - : secrets && secrets.report.health.missing > 0 - ? 'missing_secrets' - : discovery && discovery.report.health.sets.some((set) => set.status === 'failed') - ? 'discovery_failed' - : connection && !connection.report.health.healthy - ? 'degraded' - : 'healthy'; - return { health, liveInstances: live.size, lastSeenAt }; + return { liveInstances: live.size, lastSeenAt }; } /** The providers the newest provider check found missing secrets, problems before those the target allows. */ @@ -130,15 +118,16 @@ export function snapshotOf(published: Wire['PublishedSnapshot'] | null): Snapsho : null; } -/** `observations` is null when the person may not list the whole target; `activeProblems` counts the problems read's events. */ +/** `read` is null when the person may not list the whole target; `activeProblems` counts the problems read's events. */ export function toLocationSummary( location: Location, - observations: Wire['LocationHealthObservation'][] | null, + read: Wire['PersonLocationHealth'] | null, published: Wire['PublishedSnapshot'] | null, activeProblems: number, now: number ): LocationSummary { - const known = observations ? healthOf(observations, now) : { health: null, liveInstances: 0, lastSeenAt: null }; + const observations = read?.observations ?? null; + const known = read ? { health: read.state, ...checkInsOf(read.observations, now) } : { health: null, liveInstances: 0, lastSeenAt: null }; return { id: location.id, name: location.name, @@ -170,19 +159,19 @@ export function poolCapWarningsOf(observations: Wire['LocationHealthObservation' return (latestOf(observations, 'pool_capped')?.report.health.jobs ?? []).map((w) => ({ jobKey: w.job_key, kind: w.kind === 'group' ? 'group' : 'job', pool: w.pool, amount: w.amount, cap: w.cap, message: w.message })); } -/** A location's page from its health observations and newest snapshot; locations never send compile error text, so a failed reload shows only as its health. */ -/** The rule findings that failed the newest load, as `sqb compile` prints them; null when that load had none or a newer one connected. */ +/** Why the newest load failed: the location's error, or its rule findings as `sqb compile` prints them; null when it isn't falling back. */ export function loadErrorOf(observations: Wire['LocationHealthObservation'][], health: LocationHealth): string | null { - const rules = health === 'falling_back' ? latestOf(observations, 'compile_failed')?.report.health.rules : undefined; - if (!rules) return null; + const failed = health === 'falling_back' ? latestOf(observations, 'compile_failed')?.report.health : undefined; + const rules = failed?.rules; + if (!rules) return failed?.error ?? null; const noun = rules.finding_count === 1 ? 'rule finding' : 'rule findings'; const lines = rules.findings.map((f) => `${f.path ? `${f.path}${f.line ? `:${f.line}` : ''} ` : ''}[${f.code}] ${f.message}`); const more = rules.finding_count - rules.findings.length; return [`Compile failed: ${rules.finding_count} ${noun}`, ...lines, ...(more > 0 ? [`… and ${more} more`] : [])].join('\n'); } -export function toLocationDetail(location: Location, observations: Wire['LocationHealthObservation'][], published: Wire['PublishedSnapshot'] | null, now: number): LocationDetail { - const { health } = healthOf(observations, now); +export function toLocationDetail(location: Location, read: Wire['PersonLocationHealth'], published: Wire['PublishedSnapshot'] | null, now: number): LocationDetail { + const { observations, state: health } = read; return { id: location.id, name: location.name, diff --git a/ui/src/lib/api/http-overview.test.ts b/ui/src/lib/api/http-overview.test.ts index 4ef0b9094f..18b4bf750f 100644 --- a/ui/src/lib/api/http-overview.test.ts +++ b/ui/src/lib/api/http-overview.test.ts @@ -1,3 +1,4 @@ +import { withServerStatus } from '$lib/build-area/status-fixtures'; import { describe, expect, it } from 'vitest'; import { overviewOf } from './http-overview'; import type { CatalogNode, Check, NodeChange, PlatformEvent, Run, SnapshotChange, StaleReason } from './types'; @@ -10,7 +11,7 @@ function run(id: string, status: Run['status'], queuedHoursAgo: number, endedHou } const node = (key: string, kind: CatalogNode['kind'], path: string, stale: StaleReason['reason'][] = [], extra: Partial = {}) => - ({ key, kind, path, group: null, lastOutcome: null, lastBuild: null, stale: stale.map((reason) => ({ reason })), ...extra }) as CatalogNode; + withServerStatus({ key, kind, path, group: null, lastOutcome: null, lastBuild: null, stale: stale.map((reason) => ({ reason })), ...extra } as CatalogNode); const built = { lastBuild: { builtAt: hoursAgo(1) } } as Partial; const check = (id: string, outcome: string | null) => ({ id, latest: outcome ? { outcome } : null }) as unknown as Check; const change = (publishedHoursAgo: number, nodes: [NodeChange['op'], string][]) => @@ -42,12 +43,12 @@ describe('overview from live reads', () => { runs, checks: [check('a', 'pass'), check('b', 'fail'), check('c', 'error'), check('d', 'warn'), check('e', null)], nodes: [ - node('model:orders', 'table', 'models/marts/core/orders.sql', ['changed', 'behind'], built), - node('model:totals', 'view', 'models/marts/totals.sql', [], built), - node('model:returns', 'table', 'models/marts/returns.sql', [], { ...built, lastOutcome: 'failed' }), - node('model:events', 'incremental', 'models/staging/events.sql', ['behind'], built), - node('source:raw', 'source', 'models/staging/sources.yml'), - node('seed:regions', 'seed', 'seeds/regions.csv') + node('model:orders', 'table', 'sql/models/marts/core/orders.sql', ['changed', 'behind'], built), + node('model:totals', 'view', 'sql/models/marts/totals.sql', [], built), + node('model:returns', 'table', 'sql/models/marts/returns.sql', [], { ...built, lastOutcome: 'failed' }), + node('model:events', 'incremental', 'sql/models/staging/events.sql', ['behind'], built), + node('source:raw', 'source', 'sql/sources/raw.yml'), + node('seed:regions', 'seed', 'sql/seeds/regions.csv') ], changes: [change(1, [['added', 'model:orders'], ['added', 'seed:regions'], ['removed', 'model:old']]), change(24 * 8, [['added', 'model:totals']])], events: [event('scheduler', true), event('cleared', false)], @@ -59,7 +60,8 @@ describe('overview from live reads', () => { it('counts the nodes it builds by top-level folder, leaving sources out', () => { expect(overview.groups).toEqual([ - { group: 'marts', total: 3, current: 1, changed: 1, behind: 1, failed: 1 }, + // Each node counts once, by its status: orders is changed, whatever else it is. + { group: 'marts', total: 3, current: 1, changed: 1, behind: 0, failed: 1 }, { group: 'seeds', total: 1, current: 0, changed: 0, behind: 0, failed: 0 }, { group: 'staging', total: 1, current: 0, changed: 0, behind: 1, failed: 0 } ]); @@ -103,7 +105,7 @@ describe('overview from live reads', () => { }); it('leaves parts without a server read empty instead of zero', () => { - const unknown = overviewOf({ runs: [], checks: [], nodes: [{ ...node('model:a', 'table', 'models/a.sql'), stale: null }], changes: [], events: [], triggers: [], acknowledgements: new Map(), conditions: { snoozeSeconds: 86_400, acknowledgements: [] }, scopeKey: 'loc-1:dev', now }); + const unknown = overviewOf({ runs: [], checks: [], nodes: [{ ...node('model:a', 'table', 'sql/models/a.sql'), stale: null }], changes: [], events: [], triggers: [], acknowledgements: new Map(), conditions: { snoozeSeconds: 86_400, acknowledgements: [] }, scopeKey: 'loc-1:dev', now }); expect(unknown.groups).toBeNull(); }); }); diff --git a/ui/src/lib/api/http-overview.ts b/ui/src/lib/api/http-overview.ts index fa243cfefa..0a36b21fe4 100644 --- a/ui/src/lib/api/http-overview.ts +++ b/ui/src/lib/api/http-overview.ts @@ -1,3 +1,4 @@ +import { countStatus } from '$lib/build-area/node-status'; import { topFolder } from '$lib/lineage/catalog-graph'; import { recentDeploys } from '$lib/build-area/overview-panels'; import { clearedAcknowledgements, visibleEventKey, withConditions } from '$lib/build-area/attention-conditions'; @@ -53,19 +54,14 @@ export function problemRunsOf(topLevel: Run[], now: number): Run[] { const attentionRun = ({ id, jobKey, kind, status, statusReason, nodeCounts, startedAt, endedAt }: Run): AttentionRun => ({ id, jobKey, kind, status, statusReason, nodeCounts, startedAt, endedAt }); -/** Build state per top-level folder, for the nodes SQLBuild builds; a node can be both changed and behind. */ +/** Build state per top-level folder, for the nodes SQLBuild builds, by the server's status of each. */ export function groupStatusOf(nodes: CatalogNode[]): GroupStatus[] { const groups = new Map(); for (const n of nodes) { if (n.kind === 'source') continue; const group = topFolder(n); const g = groups.get(group) ?? { group, total: 0, current: 0, changed: 0, behind: 0, failed: 0 }; - const stale = n.stale ?? []; - g.total += 1; - if (n.lastOutcome === 'failed') g.failed += 1; - if (stale.some((s) => s.reason !== 'behind')) g.changed += 1; - if (stale.some((s) => s.reason === 'behind')) g.behind += 1; - if (!stale.length && n.lastOutcome !== 'failed' && n.lastBuild) g.current += 1; + countStatus(g, n); groups.set(group, g); } return [...groups.values()].sort((a, b) => a.group.localeCompare(b.group)); diff --git a/ui/src/lib/api/http-problems.test.ts b/ui/src/lib/api/http-problems.test.ts index a17ef4afd5..bd1a36b1f5 100644 --- a/ui/src/lib/api/http-problems.test.ts +++ b/ui/src/lib/api/http-problems.test.ts @@ -12,6 +12,15 @@ const tick = (name: string, location: string, scheduledFor: string) => ({ }); describe('toPlatformEvents', () => { + it('makes a location whose latest load failed a critical problem with its error and the snapshot it serves', () => { + const serving = { snapshot_id: 's-11', location_id: 'l1', target: 'production', generation: 11, manifest_digest: 'd', published_at: '2026-11-08T09:00:00Z' }; + const failing = (state: 'falling_back' | 'degraded', error: string | null) => ({ location_id: 'l1', location_name: 'orders', target: 'production', state, failed_at: '2026-11-08T11:59:00Z', error, serving }); + const [failed, degraded] = toPlatformEvents({ scheduler_leader: true, broken_locations: [], overdue_ticks: [], failing_locations: [failing('falling_back', 'job loaders_job: path selectors require an explicit root'), failing('degraded', null)] }, NOW); + expect([failed.kind, failed.severity, failed.active, failed.occurredAt]).toEqual(['location_failing', 'critical', true, '2026-11-08T11:59:00Z']); + expect(failed.message).toMatch(/^orders · production: latest code failed to load: job loaders_job: path selectors require an explicit root\. Serving generation 11, published /); + expect([degraded.severity, degraded.message.split('. ')[0]]).toEqual(['warning', 'orders · production: the warehouse connection check failed']); + }); + 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([]); }); diff --git a/ui/src/lib/api/http-problems.ts b/ui/src/lib/api/http-problems.ts index 94afacf427..d160b56a1e 100644 --- a/ui/src/lib/api/http-problems.ts +++ b/ui/src/lib/api/http-problems.ts @@ -1,4 +1,5 @@ import type { components } from '$control/schema.d.ts'; +import { formatStamp } from '$lib/format/time'; import { locationKey as keyOf } from './http-client'; import type { PlatformEvent } from './types'; import type { PlatformEventRecord, PlatformHealth } from './types/platform'; @@ -9,6 +10,23 @@ const placeOf = (name: string, target: string) => `${name} · ${target}`; /** Dropped calendar times a message names before `and N more`. */ const DROPPED_TIMES_NAMED = 10; +/** What failed, by state, for a failing location's banner. */ +const FAILED: Record = { + falling_back: 'latest code failed to load', + change_plan_failed: 'planning what changed failed', + discovery_failed: 'a discover function failed', + degraded: 'the warehouse connection check failed' +}; + +/** `place: what failed: error. Serving generation N, published at T.`, or what it serves before any publication. */ +function failingMessage(place: string, location: Wire['FailingLocation']): string { + const error = location.error ? `: ${location.error}` : ''; + const serving = location.serving + ? `Serving generation ${location.serving.generation}, published ${formatStamp(location.serving.published_at)}.` + : 'No snapshot published yet.'; + return `${place}: ${FAILED[location.state] ?? location.state}${error}. ${serving}`; +} + /** Live problems as active banner events: a stopped scheduler, each broken location, and late schedules, low calendars, skipped triggers, sensors checked again from scratch and calendars' dropped times per location. */ export function toPlatformEvents(problems: Wire['PlatformProblems'], now: number): PlatformEvent[] { const events: PlatformEvent[] = []; @@ -40,6 +58,21 @@ export function toPlatformEvents(problems: Wire['PlatformProblems'], now: number message: `${placeOf(location.location_name, location.target)} stopped checking in, so its scheduled runs aren’t starting.` }); } + for (const location of problems.failing_locations ?? []) { + const place = placeOf(location.location_name, location.target); + events.push({ + id: `failing:${keyOf(location.location_id, location.target)}`, + kind: 'location_failing', + severity: location.state === 'degraded' ? 'warning' : 'critical', + occurredAt: location.failed_at, + // The failure's report time tells one failure from the next. + occurrence: location.failed_at, + active: true, + locationId: keyOf(location.location_id, location.target), + subject: place, + message: failingMessage(place, location) + }); + } const late = new Map(); for (const tick of problems.overdue_ticks) { const key = keyOf(tick.location_id, tick.target); @@ -195,6 +228,15 @@ function storedRecord(wire: Wire['PersonPlatformEvent'], names: Map = { + planning_error: 'models', + window_before_cursor_start: 'models', full_refresh: 'models', query_changed: 'models', function_changed: 'models', diff --git a/ui/src/lib/api/mock/big-output.ts b/ui/src/lib/api/mock/big-output.ts index e9c5d888e0..039c72e7b5 100644 --- a/ui/src/lib/api/mock/big-output.ts +++ b/ui/src/lib/api/mock/big-output.ts @@ -139,10 +139,10 @@ export const V2_TRACEBACK = [ ' File "/app/.venv/lib/python3.12/site-packages/sqlbuild/executor/task.py", line 201, in _call', ' return node.fn(ctx)', ' ^^^^^^^^^^^^', - ' File "/app/models/ml/score_customers_v2.py", line 41, in score_customers_v2', + ' File "/app/python/nodes/ml/score_customers_v2.py", line 41, in score_customers_v2', ' features = build_features(customers, segments)', ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^', - ' File "/app/models/ml/score_customers_v2.py", line 26, in build_features', + ' File "/app/python/nodes/ml/score_customers_v2.py", line 26, in build_features', ' joined["segment_weight"] = joined["customer_segment"].map(SEGMENT_WEIGHTS)', ' ~~~~~~^^^^^^^^^^^^^^^^^^^^', ' File "/app/.venv/lib/python3.12/site-packages/pandas/core/frame.py", line 4102, in __getitem__', diff --git a/ui/src/lib/api/mock/build-fixtures.ts b/ui/src/lib/api/mock/build-fixtures.ts index e3ee730092..3b2089ac69 100644 --- a/ui/src/lib/api/mock/build-fixtures.ts +++ b/ui/src/lib/api/mock/build-fixtures.ts @@ -196,7 +196,7 @@ export const NODE_SPECS: Record = { export const PYTHON_SOURCE: Record = { score_customers_v2: { - file: 'models/ml/score_customers_v2.py', + file: 'python/nodes/ml/score_customers_v2.py', source: `import numpy as np import pandas as pd from sqlbuild.tasks import task @@ -241,7 +241,7 @@ def score_customers_v2(ctx): ctx.write("customer_scores_v2", model.predict(features))` }, notebook_runner: { - file: 'models/ml/notebook_runner.py', + file: 'python/nodes/ml/notebook_runner.py', source: `from sqlbuild.tasks import task from shop.notebooks import run_notebook @@ -255,7 +255,7 @@ def notebook_runner(ctx): ctx.log.info(f"Notebook finished: {result.cells} cells, {result.rows_written:,} rows written")` }, raw_events: { - file: 'models/ingest/raw_events.py', + file: 'python/nodes/ingest/raw_events.py', source: `import logging from sqlbuild.loaders import loader @@ -279,7 +279,7 @@ def raw_events(ctx: LoaderContext): page += 1` }, score_customers: { - file: 'models/ml/score_customers.py', + file: 'python/nodes/ml/score_customers.py', source: `import pandas as pd from sqlbuild.tasks import task @@ -296,7 +296,7 @@ def score_customers(ctx): print(f"Scored {len(customers):,} customers")` }, raw__orders: { - file: 'python/raw__orders.py', + file: 'python/nodes/raw__orders.py', source: `from sqlbuild.loaders import loader from sqlbuild.executor.load.models import LoaderContext @@ -309,7 +309,7 @@ def raw__orders(ctx: LoaderContext): return fetch_since(ctx.current_cursor_value)` }, export_revenue_csv: { - file: 'python/export_revenue_csv.py', + file: 'python/nodes/export_revenue_csv.py', source: `from sqlbuild.assets import asset from shop.file_drop import upload_csv diff --git a/ui/src/lib/api/mock/build.ts b/ui/src/lib/api/mock/build.ts index e2ee71c759..00764ad966 100644 --- a/ui/src/lib/api/mock/build.ts +++ b/ui/src/lib/api/mock/build.ts @@ -413,11 +413,13 @@ export class MockBuild { #catalogNode(state: NodeState, checks: Check[]): CatalogNode & Pick { const { sn, lastBuild, lastOutcome, stale } = state; const spec = NODE_SPECS[sn.key]; + const { status, statusAt } = mockStatus(state); return { key: sn.key, kind: sn.kind, materialization: spec?.materialization ?? null, - group: sn.group, + // The server declares no groups: pages group by the folders of the node's path. + group: null, tags: [...sn.tags], description: spec?.description ?? '', path: sn.path, @@ -428,7 +430,9 @@ export class MockBuild { lastOutcome, stale: structuredClone(stale), sourceFreshness: this.#freshness[sn.key] ?? null, - checks: countChecks(checks.filter((c) => c.node === sn.key)) + checks: countChecks(checks.filter((c) => c.node === sn.key)), + status, + statusAt }; } @@ -693,3 +697,17 @@ function synthRunId(seed: string, i: number): string { function invocationIdLike(seed: string): string { return synthRunId(seed, 0); } + +/** Python nodes keep no table: the fake server, as the real one, takes their status from their last run. */ +const WITHOUT_TABLE: ReadonlySet = new Set(['asset', 'loader']); + +/** The fake server's status of a node, by the real server's rule: failed, then not built, changed, behind or current. */ +function mockStatus({ sn, lastBuild, lastOutcome, entries, stale }: NodeState): Pick { + const ranAt = entries[0]?.startedAt ?? null; + if (sn.kind === 'source') return { status: 'source', statusAt: null }; + if (lastOutcome === 'failed') return { status: 'failed', statusAt: ranAt ?? lastBuild?.builtAt ?? null }; + if (WITHOUT_TABLE.has(sn.kind) && !lastBuild) return lastOutcome ? { status: 'current', statusAt: ranAt } : { status: 'not_built', statusAt: null }; + if (!lastBuild) return { status: 'not_built', statusAt: null }; + const status = stale.some((r) => r.reason === 'changed') ? 'changed' : stale.some((r) => r.reason === 'behind') ? 'behind' : 'current'; + return { status, statusAt: lastBuild.builtAt }; +} diff --git a/ui/src/lib/api/mock/cost-project.ts b/ui/src/lib/api/mock/cost-project.ts index 92945f2dbc..faa294c7de 100644 --- a/ui/src/lib/api/mock/cost-project.ts +++ b/ui/src/lib/api/mock/cost-project.ts @@ -5,10 +5,11 @@ import type { ApiClient } from '../client'; import type { CostFact, CostSelection, CostSelectionQuery, CostSeriesGroup, NodeBuildCost, RunStatus, Scope, SelectionEvaluation, SelectionProblem, SelectionVocabulary, VocabularyEntry } from '../types'; +import { dirOfFolder } from '$lib/project-layout'; import { costPeriod, inCostGroup } from './cost-rows'; -/** A folder as `path:` selects it: models under `sql/models/`, Python nodes under their own root. */ -const pathOf = (folder: string) => (folder.startsWith('python/') ? folder : `sql/models/${folder}`); +/** A folder's directory, as `path:` selects it: `marts` is `sql/models/marts`, `python/loaders` is `python/nodes/loaders`. */ +const pathOf = (folder: string) => dirOfFolder(folder); /** Leaf folders, their model count and model name prefix: 2,281 models. */ const FOLDERS: [string, number, string][] = [ @@ -46,8 +47,8 @@ const FOLDERS: [string, number, string][] = [ ['reporting/daily', 80, 'rpt'], ['reporting/exports', 60, 'rpt'], ['snapshots', 56, 'snap'], - ['python/nodes/loaders', 18, 'py'], - ['python/nodes/checks', 12, 'py'] + ['python/loaders', 18, 'py'], + ['python/checks', 12, 'py'] ]; const ENTITIES = ['orders', 'order_lines', 'customers', 'sessions', 'events', 'payments', 'refunds', 'invoices', 'products', 'inventory', 'shipments', 'returns', 'campaigns', 'clicks', 'impressions', 'subscriptions', 'accounts', 'users', 'devices', 'pageviews', 'carts', 'promotions', 'suppliers', 'stores', 'warehouses', 'forecasts', 'features', 'experiments', 'ledger', 'fx_rates', 'tickets', 'reviews']; const SUFFIXES = ['', '_daily', '_hourly', '_enriched', '_latest', '_history', '_by_region', '_by_channel', '_scd', '_rollup', '_v2', '_agg', '_dedup', '_flat', '_wide', '_weekly']; @@ -74,7 +75,7 @@ const JOBS: [string, number, number, string, string[]][] = [ ['campaigns_daily', 1, 2.9, 'Small', ['marketing/campaigns', 'marketing/audiences']], ['exports_daily', 1, 1.4, 'X-Small', ['reporting/exports']], ['fx_rates_hourly', 24, 0.04, 'X-Small', ['finance/fx']], - ['partner_loaders', 12, 0.12, 'X-Small', ['python/nodes/loaders', 'staging/partners/feeds']], + ['partner_loaders', 12, 0.12, 'X-Small', ['python/loaders', 'staging/partners/feeds']], ['shipments_4h', 6, 0.7, 'Small', ['staging/orders', 'intermediate/orders']], ['returns_daily', 1, 1.1, 'X-Small', ['intermediate/orders', 'marts/core']], ['experiments_daily', 1, 3.3, 'Small', ['product/experiments']], @@ -86,7 +87,7 @@ const JOBS: [string, number, number, string, string[]][] = [ ['marts_weekly_rebuild', 1 / 7, 72, 'Large', ['marts', 'intermediate']], ['forecasts_daily', 1, 7.5, 'Medium', ['ml/scoring', 'finance/revenue']], ['suppliers_weekly', 1 / 7, 3.1, 'Small', ['staging/partners']], - ['data_quality', 4, 0.6, 'Small', ['python/nodes/checks', 'marts/core']] + ['data_quality', 4, 0.6, 'Small', ['python/checks', 'marts/core']] ]; /** What runs started by hand or from the CLI built. */ const MANUAL_FOLDERS = ['marts/core', 'intermediate/pricing']; diff --git a/ui/src/lib/api/mock/cost-rows.ts b/ui/src/lib/api/mock/cost-rows.ts index fd86e70762..16176a92e7 100644 --- a/ui/src/lib/api/mock/cost-rows.ts +++ b/ui/src/lib/api/mock/cost-rows.ts @@ -2,6 +2,7 @@ // period before, job by node, and daily series by job, top-level folder or any group. Pure. import type { CostFact, CostSelection, CostSeriesGroup, SelectionProblem } from '../types'; +import { folderOfDir } from '$lib/project-layout'; /** One selected node's cost in one build. */ export type CostRowIn = { runId: string; job: string | null; nodeKey: string; folder: string; startedAt: number; pending: boolean; credits: number; usd: number | null; seconds: number; queries: number; bytes: number }; @@ -16,11 +17,10 @@ export function costPeriod(days: number, now: number) { return { first, previous: first - days * DAY, dates, day }; } -/** A node's folder from its published path: without `sql/models/` (or `models/`), other roots as published. */ +/** A node's folder from its published path, as the server's cost folder and the catalog group it (`folderOfDir`). */ export function costFolder(path: string | undefined): string { if (!path) return 'other'; - const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''; - return dir.replace(/^(sql\/)?models(\/|$)/, ''); + return folderOfDir(path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''); } const addUsd = (a: number | null, b: number | null) => (a === null || b === null ? null : a + b); diff --git a/ui/src/lib/api/mock/discovered.ts b/ui/src/lib/api/mock/discovered.ts index 527a44b894..8e681363f4 100644 --- a/ui/src/lib/api/mock/discovered.ts +++ b/ui/src/lib/api/mock/discovered.ts @@ -68,7 +68,7 @@ export const DISCOVERED_PLANS: Plan[] = [ ]; const stepKey = (asset: string, step: string) => `asset:${asset}[${step}]`; -const pathOf = (asset: string) => `src/forecast_pipelines/definitions/models/regions/${asset.split('_')[1]}/discovered_model_steps.py`; +const pathOf = (asset: string) => `python/nodes/forecast/${asset.split('_')[1]}/discovered_model_steps.py`; /** Every step node, in the snapshot's shape. */ export const DISCOVERED_NODES: SnapshotNode[] = DISCOVERED_PLANS.flatMap((p) => { diff --git a/ui/src/lib/api/mock/huge-project.ts b/ui/src/lib/api/mock/huge-project.ts index dd8a70e41d..820f88375a 100644 --- a/ui/src/lib/api/mock/huge-project.ts +++ b/ui/src/lib/api/mock/huge-project.ts @@ -38,7 +38,7 @@ export function hugeProjectNodes(template: CatalogNode): CatalogNode[] { key, kind: 'table', group: null, - path: `models/${folder}/${sub}/${key}.sql`, + path: `sql/models/${folder}/${sub}/${key}.sql`, upstream: [], description: `${folder} ${sub.replace('/', ' ')} ${NOUNS[i % NOUNS.length]}`, stale, diff --git a/ui/src/lib/api/mock/large-project.ts b/ui/src/lib/api/mock/large-project.ts index 549fef1250..ea4c76586b 100644 --- a/ui/src/lib/api/mock/large-project.ts +++ b/ui/src/lib/api/mock/large-project.ts @@ -31,9 +31,9 @@ export function largeProjectNodes(template: CatalogNode): CatalogNode[] { const staging = Array.from({ length: PER_SUBFOLDER }, (_, i) => `${folder}__stg__${NOUNS[i % NOUNS.length]}`); const mart = Array.from({ length: PER_SUBFOLDER }, (_, i) => `${folder}__mart__${NOUNS[i % NOUNS.length]}`); staging.forEach((key, i) => - nodes.push({ ...template, key, group: `${folder}/staging`, path: `models/${folder}/staging/${key}.sql`, upstream: feeds.length ? [feeds[i % feeds.length]] : [], description: `Staged ${folder} data` }) + nodes.push({ ...template, key, group: `${folder}/staging`, path: `sql/models/${folder}/staging/${key}.sql`, upstream: feeds.length ? [feeds[i % feeds.length]] : [], description: `Staged ${folder} data` }) ); - mart.forEach((key, i) => nodes.push({ ...template, key, group: `${folder}/marts`, path: `models/${folder}/marts/${key}.sql`, upstream: [staging[i], staging[(i + 1) % staging.length]], description: `${folder} mart` })); + mart.forEach((key, i) => nodes.push({ ...template, key, group: `${folder}/marts`, path: `sql/models/${folder}/marts/${key}.sql`, upstream: [staging[i], staging[(i + 1) % staging.length]], description: `${folder} mart` })); marts.set(folder, mart); // Finance also reconciles against the orders marts directly, a read across five layers. if (folder === 'finance') nodes.find((n) => n.key === staging[0])!.upstream.push(marts.get('orders')![0]); diff --git a/ui/src/lib/api/mock/operate-graph.ts b/ui/src/lib/api/mock/operate-graph.ts index 3c82163a70..82d348bb55 100644 --- a/ui/src/lib/api/mock/operate-graph.ts +++ b/ui/src/lib/api/mock/operate-graph.ts @@ -4,6 +4,7 @@ import type { NodeKind, SnapshotNode } from '../types'; 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'; function node( key: string, @@ -15,12 +16,12 @@ function node( const path = options.path ?? (kind === 'source' - ? 'models/sources.yml' + ? `${SQL_ROOT}/sources/${key.split('__')[0]}.yml` : kind === 'seed' - ? `seeds/${key}.csv` + ? `${SQL_ROOT}/seeds/${key}.csv` : kind === 'asset' || kind === 'loader' - ? `python/${key}.py` - : `models/${group}/${key}.sql`); + ? `${PYTHON_NODES_ROOT}/${key}.py` + : `${MODELS_ROOT}/${group}/${key}.sql`); return { key, kind, group, tags: options.tags ?? [], path, cursor: options.cursor ?? null, upstream }; } @@ -63,17 +64,17 @@ export const SNAPSHOT_NODES: SnapshotNode[] = [ node('agg_delivery_times', 'table', 'fulfillment', ['fct_shipments']), node('rpt_late_deliveries', 'table', 'fulfillment', ['agg_delivery_times', 'dim_customers']), // Python nodes (CHI-1591): a loader that prints its paging, and a task that warns. - node('raw_events', 'loader', 'ingest', [], { cursor: 'timestamp', path: 'models/ingest/raw_events.py' }), - node('score_customers', 'asset', 'ml', ['dim_customers'], { path: 'models/ml/score_customers.py' }), + node('raw_events', 'loader', 'ingest', [], { cursor: 'timestamp', path: 'python/nodes/ingest/raw_events.py' }), + node('score_customers', 'asset', 'ml', ['dim_customers'], { path: 'python/nodes/ml/score_customers.py' }), // Several checks on one node (CHI-1591): all passing, one warning, two warnings, and a failure with warnings. node('stg_sessions', 'view', 'staging', ['raw__customers']), node('fct_payment_daily', 'table', 'finance', ['stg_payments']), node('fct_order_lines', 'table', 'marts', ['stg_orders', 'stg_payments']), node('fct_refunds', 'table', 'finance', ['stg_payments', 'fact_orders']), // A Python task that fails with a pandas KeyError traceback after printing a few thousand lines. - node('score_customers_v2', 'asset', 'ml', ['dim_customers'], { path: 'models/ml/score_customers_v2.py' }), + node('score_customers_v2', 'asset', 'ml', ['dim_customers'], { path: 'python/nodes/ml/score_customers_v2.py' }), // A notebook runner that prints about 2 million lines (CHI-1597). - node('notebook_runner', 'asset', 'ml', ['fact_orders'], { path: 'models/ml/notebook_runner.py' }), + node('notebook_runner', 'asset', 'ml', ['fact_orders'], { path: 'python/nodes/ml/notebook_runner.py' }), // Discovered steps of two forecast plans (discovered.ts). ...DISCOVERED_NODES ]; @@ -180,11 +181,18 @@ function selectorKind(n: SnapshotNode): string { return MODEL_KINDS.has(n.kind) ? 'model' : n.kind; } -/** The folder a node's file is in, such as `models/marts`. */ -function folderOf(n: SnapshotNode): string { +/** The directory a node's file is in, such as `sql/models/marts`. */ +function dirOf(n: SnapshotNode): string { return n.path.includes('/') ? n.path.slice(0, n.path.lastIndexOf('/')) : ''; } +/** `path:`, as SQLBuild resolves it: the nodes in the directory or below it, from `sql/models` or `python/nodes` only. */ +function inDir(n: SnapshotNode, dir: string): boolean { + const at = dir.replace(/^\/+|\/+$/g, ''); + const rooted = PATH_SELECTOR_ROOTS.some((root) => at === root || at.startsWith(`${root}/`)); + return rooted && (dirOf(n) === at || dirOf(n).startsWith(`${at}/`)); +} + /** `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[]) { @@ -200,7 +208,7 @@ function matchPart(part: string): Set | null { const jobKeys = type === 'job' ? new Set(jobNodesOf(value)) : 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' ? folderOf(n) === value.replace(/^sql\//, '') || folderOf(n).startsWith(`${value.replace(/^sql\//, '')}/`) : n.key === value + type === 'tag' ? n.tags.includes(value) : type === 'kind' ? selectorKind(n) === value : type === 'path' ? inDir(n, value) : n.key === value ); if (!base.length) return null; const out = new Set(base.map((n) => n.key)); @@ -249,10 +257,16 @@ export function mockVocabulary(): Omit a.localeCompare(b)).map(([value, count]) => ({ value, count })); }; - const folders = (n: SnapshotNode) => folderOf(n).split('/').filter(Boolean).map((_, i, parts) => parts.slice(0, i + 1).join('/')); + // Every directory above a node that a `path:` selector accepts, as the server's vocabulary lists them. + const folders = (n: SnapshotNode) => + dirOf(n) + .split('/') + .filter(Boolean) + .map((_, i, parts) => parts.slice(0, i + 1).join('/')) + .filter((dir) => PATH_SELECTOR_ROOTS.some((root) => dir === root || dir.startsWith(`${root}/`))); return { tags: counted(SNAPSHOT_NODES.flatMap((n) => n.tags)), - paths: counted(SNAPSHOT_NODES.filter((n) => n.kind !== 'source' && n.kind !== 'seed').flatMap(folders)), + paths: counted(SNAPSHOT_NODES.flatMap(folders)), sources: counted(SNAPSHOT_NODES.filter((n) => 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)) diff --git a/ui/src/lib/api/mock/operate.ts b/ui/src/lib/api/mock/operate.ts index a35f52f0e2..0fb76c53fe 100644 --- a/ui/src/lib/api/mock/operate.ts +++ b/ui/src/lib/api/mock/operate.ts @@ -95,7 +95,7 @@ export const JOB_DEFS: JobDef[] = [ key: 'core_build', kind: 'job', description: 'Staging and marts models', - select: 'path:models/staging path:models/marts', + select: 'path:sql/models/staging path:sql/models/marts', exclude: [], members: [], overlap: 'skip', @@ -114,7 +114,7 @@ export const JOB_DEFS: JobDef[] = [ `core_build = job( "core_build", description="Staging and marts models", - select=["path:models/staging", "path:models/marts"], + select=["path:sql/models/staging", "path:sql/models/marts"], overlap="skip", on_failure=on_failure(retries=2, retry_delay_seconds=600), pools={"warehouse_heavy": 1}, @@ -156,7 +156,7 @@ export const JOB_DEFS: JobDef[] = [ key: 'marts_only', kind: 'job', description: 'Marts models only, reading the current staging layer', - select: 'path:models/marts', + select: 'path:sql/models/marts', exclude: [], members: [], overlap: 'queue', @@ -174,7 +174,7 @@ export const JOB_DEFS: JobDef[] = [ `marts_only = job( "marts_only", description="Marts models only, reading the current staging layer", - select="path:models/marts", + select="path:sql/models/marts", targets=["prod", "staging"], owner="analytics", )` @@ -184,7 +184,7 @@ export const JOB_DEFS: JobDef[] = [ key: 'activity_microbatch', kind: 'job', description: 'Incremental activity models, four microbatches at a time', - select: 'path:models/activity', + select: 'path:sql/models/activity', exclude: [], members: [], overlap: 'queue', @@ -202,7 +202,7 @@ export const JOB_DEFS: JobDef[] = [ `activity_microbatch = job( "activity_microbatch", description="Incremental activity models, four microbatches at a time", - select="path:models/activity", + select="path:sql/models/activity", settings={"--max-microbatches": 4}, owner="analytics", schedule=schedule(cron="{cron:activity_microbatch}", timezone="UTC", @@ -271,7 +271,7 @@ export const JOB_DEFS: JobDef[] = [ key: 'reporting_exports', kind: 'job', description: 'Reporting tables and the revenue export', - select: 'path:models/reporting export_revenue_csv', + select: 'path:sql/models/reporting export_revenue_csv', exclude: [], members: [], overlap: 'queue', @@ -289,7 +289,7 @@ export const JOB_DEFS: JobDef[] = [ `reporting_exports = job( "reporting_exports", description="Reporting tables and the revenue export", - select=["path:models/reporting", "export_revenue_csv"], + select=["path:sql/models/reporting", "export_revenue_csv"], pools={"warehouse_heavy": 1}, priority=10, targets=["prod"], diff --git a/ui/src/lib/api/mock/run-detail.ts b/ui/src/lib/api/mock/run-detail.ts index 80fdc96715..26ab80c4c8 100644 --- a/ui/src/lib/api/mock/run-detail.ts +++ b/ui/src/lib/api/mock/run-detail.ts @@ -253,11 +253,11 @@ export function auditSample(nodeKey: string, statementId: string, count: number) /** A Python node's exception: where it was raised in the node's own code, and the whole traceback. */ function pythonFailureDetail(): Pick { - return { errorLocation: { file: 'models/ml/score_customers_v2.py', line: 26 }, errorDetail: V2_TRACEBACK.join('\n') }; + return { errorLocation: { file: 'python/nodes/ml/score_customers_v2.py', line: 26 }, errorDetail: V2_TRACEBACK.join('\n') }; } function checkFailureDetail(key: string): Pick { - const file = (snapshotNode(key)?.path ?? `models/${key}.sql`).replace(/\.sql$/, '.yml'); + const file = (snapshotNode(key)?.path ?? `sql/models/${key}.sql`).replace(/\.sql$/, '.yml'); return { errorLocation: { file, line: 12 }, errorDetail: ['check unique(order_id) failed: 14 duplicate rows (severity error)', ` --> ${file}:12`, '', 'The table was built, then its error-severity check failed, so the node failed and its downstream was skipped.'].join('\n') @@ -266,7 +266,7 @@ function checkFailureDetail(key: string): Pick { - const file = snapshotNode(key)?.path ?? `models/${key}.sql`; + const file = snapshotNode(key)?.path ?? `sql/models/${key}.sql`; const line = 4 + (hash(key) % 30); const queryId = queryIdOf(statementIdOf(run, key)); return { @@ -421,7 +421,7 @@ export function sqlFor(key: string, kind: string, target: string): string { if (kind === 'create_view') return `create or replace view ${rel} as\nselect *\nfrom ${src}`; if (kind === 'merge') return `merge into ${rel} as t\nusing (\n select * from ${src}\n where updated_at >= :start_cursor and updated_at < :end_cursor\n) as s\non t.id = s.id\nwhen matched then update set *\nwhen not matched then insert *`; - if (kind === 'load_seed') return `insert into ${rel}\nselect * from read_csv('seeds/${key}.csv')`; + if (kind === 'load_seed') return `insert into ${rel}\nselect * from read_csv('sql/seeds/${key}.csv')`; if (kind === 'loader_insert') return `insert into ${rel}\nselect * from staging.${key}__batch`; return `create or replace table ${rel}__sqb_stage as\nselect *\nfrom ${from.join('\njoin ') || src};\n\nalter table ${rel}__sqb_stage swap with ${rel}`; } @@ -588,7 +588,7 @@ function pythonOutput(key: string, s: number, e: number | null, now: number, out [ 'WARNING shop.events: page 4 failed, retrying in 5s', 'Traceback (most recent call last):', - ' File "/app/models/ingest/raw_events.py", line 18, in raw_events', + ' File "/app/python/nodes/ingest/raw_events.py", line 18, in raw_events', ' rows = fetch_page(since=ctx.current_cursor_value, page=page)', ' File "/app/shop/events_api.py", line 41, in fetch_page', ' resp.raise_for_status()', @@ -619,7 +619,7 @@ function pythonOutput(key: string, s: number, e: number | null, now: number, out 1_400, 'stderr', [ - '/app/models/ml/score_customers.py:11: FutureWarning: DataFrame.fillna with \'method\' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead.', + '/app/python/nodes/ml/score_customers.py:11: FutureWarning: DataFrame.fillna with \'method\' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead.', ' features = features.fillna(method="ffill")' ].join('\n') ); diff --git a/ui/src/lib/api/node-states.test.ts b/ui/src/lib/api/node-states.test.ts index 452bd68d4e..b19a03e86c 100644 --- a/ui/src/lib/api/node-states.test.ts +++ b/ui/src/lib/api/node-states.test.ts @@ -18,7 +18,9 @@ function node(key: string, upstream: string[] = [], builtAt: string | null = '20 lastOutcome: builtAt ? 'success' : null, stale: [], sourceFreshness: null, - checks: { total: 0, passing: 0, warning: 0, failing: 0 } + checks: { total: 0, passing: 0, warning: 0, failing: 0 }, + status: builtAt ? 'current' : 'not_built', + statusAt: builtAt }; } @@ -27,6 +29,8 @@ const built = (key: string, builtAt: string, extra: Partial = {}): No lastOutcome: 'success', definitionChanged: false, checks: { total: 1, passing: 1, warning: 0, failing: 0 }, + status: 'current', + statusAt: builtAt, ...extra }); diff --git a/ui/src/lib/api/node-states.ts b/ui/src/lib/api/node-states.ts index 7930854153..0da203d4b0 100644 --- a/ui/src/lib/api/node-states.ts +++ b/ui/src/lib/api/node-states.ts @@ -10,7 +10,9 @@ export function stateOf(node: CatalogNode): NodeState { lastBuild: node.lastBuild, lastOutcome: node.lastOutcome, definitionChanged: !!node.stale?.some((r) => r.reason === 'changed'), - checks: node.checks + checks: node.checks, + status: node.status, + statusAt: node.statusAt }; } @@ -24,7 +26,7 @@ function changedReason(node: CatalogNode, state: NodeState): StaleReason[] { /** A node with `state` in place of its own; behind is left to `withBehind`, which needs every node. */ function withState(node: CatalogNode, state: NodeState): CatalogNode { const kept = (node.stale ?? []).filter((r) => r.reason !== 'changed'); - return { ...node, lastBuild: state.lastBuild, lastOutcome: state.lastOutcome, checks: state.checks, stale: [...changedReason(node, state), ...kept] }; + return { ...node, lastBuild: state.lastBuild, lastOutcome: state.lastOutcome, checks: state.checks, status: state.status, statusAt: state.statusAt, stale: [...changedReason(node, state), ...kept] }; } /** @@ -69,7 +71,8 @@ function behindOf(node: CatalogNode, dataAt: (key: string) => number | null): St const behindKey = (reasons: StaleReason[]) => JSON.stringify(reasons.filter((r) => r.reason === 'behind')); /** - * Nodes with "behind" worked out again from upstream build times. A node whose behind reasons + * Nodes with the "behind" reason worked out again from upstream build times, for its explanation + * (which upstream, since when); whether a node is behind is the server's `status`. A node whose behind reasons * did not change is returned as it was, so views keyed on it do not redraw. */ export function withBehind(nodes: CatalogNode[]): CatalogNode[] { diff --git a/ui/src/lib/api/types.ts b/ui/src/lib/api/types.ts index 9996f6ff98..04d3b4166e 100644 --- a/ui/src/lib/api/types.ts +++ b/ui/src/lib/api/types.ts @@ -89,7 +89,7 @@ export type LocationTarget = { connectionSummary: string | null; }; -export type LocationHealth = 'healthy' | 'degraded' | 'missing_secrets' | 'discovery_failed' | 'falling_back' | 'broken'; +export type LocationHealth = 'starting' | 'healthy' | 'degraded' | 'missing_secrets' | 'change_plan_failed' | 'discovery_failed' | 'falling_back' | 'broken'; /** A project deployed against exactly one target. Staging and dev are separate locations. */ export type Location = { /** Opaque server-generated UUID; the name is a mutable label. */ @@ -130,6 +130,7 @@ export type PlatformEventKind = | 'calendar_times_dropped' | 'scheduler_no_leader' | 'location_broken' + | 'location_failing' | 'location_missing_secrets' | 'launch_failed' | 'connection_test_failed' diff --git a/ui/src/lib/api/types/build.ts b/ui/src/lib/api/types/build.ts index 7911b66f13..c8167c6282 100644 --- a/ui/src/lib/api/types/build.ts +++ b/ui/src/lib/api/types/build.ts @@ -79,6 +79,10 @@ export type CatalogNode = { sourceFreshness: SourceFreshness | null; /** Null when the server does not report check counts. */ checks: CheckCounts | null; + /** The server's one status for the node (`NodeState.status`); null until its state is read. */ + status: NodeBuildStatus | null; + /** When the status was reached; null when not built. */ + statusAt: Iso | null; }; // ---- discovered sets ---- @@ -111,13 +115,20 @@ export type NodeState = { /** The definition differs from the one the last build recorded. */ definitionChanged: boolean; checks: CheckCounts | null; + /** The server's one status for the node, which every page shows as it is; null from an older server. */ + status: NodeBuildStatus | null; + /** When the status was reached: the last build, or the last run for a node without a table. */ + statusAt: Iso | null; }; +/** Where a node stands, as the server works it out once for every page. */ +export type NodeBuildStatus = 'current' | 'changed' | 'behind' | 'failed' | 'not_built' | 'source'; + /** Every node's state at one status version of a snapshot. */ /** * What `sqb build --changed` with default options runs, as the location planned it from the synced copy * after its last publication or sync: nodes changed themselves, and nodes downstream of them, as keys. - * `failing` is why that plan failed, with both lists empty; a failed plan is never shown as a count. + * `failing` is why that plan failed (both lists empty) or which models it couldn't plan (the lists name the rest). */ export type ChangedBuild = { generation: number; changed: string[]; downstream: string[]; failing: string | null }; diff --git a/ui/src/lib/api/types/operate.ts b/ui/src/lib/api/types/operate.ts index 5ae81298fc..d4712122ad 100644 --- a/ui/src/lib/api/types/operate.ts +++ b/ui/src/lib/api/types/operate.ts @@ -415,7 +415,7 @@ export type CostFact = { /** Null for builds no server run started (by hand or from the command line). */ job: string | null; nodeKey: string; - /** The node's folder: without `sql/models/` for SQL models (empty at its top), other roots as published, `other` when unknown. */ + /** The node's folder as the catalog groups it: below `sql/models/` for SQL models (empty at its top), below `sql/` for other SQL resources, `python/` for Python nodes, `other` when unknown. */ folder: string; credits: number; previousCredits: number; @@ -755,7 +755,7 @@ export type VocabularyEntry = { value: string; count: number }; export type SelectionVocabulary = { snapshotId: string | null; tags: VocabularyEntry[]; - /** Folders such as `models/staging`, counting the nodes below each at any depth. */ + /** Folders a `path:` selector accepts, such as `sql/models/staging`, counting the nodes below each at any depth. */ paths: VocabularyEntry[]; jobs: VocabularyEntry[]; sources: VocabularyEntry[]; @@ -825,6 +825,10 @@ export type PlanModel = { old_name?: PlanOldName | null; /** A paged row's diff counts in place of its diff text, which `planDiff` reads on demand. */ diff_stats?: { query?: PlanDiffStats; config?: PlanDiffStats }; + /** Why a skipped model is listed anyway, such as `window ends before cursor_start 2021-01-01`. */ + skip_reason?: string; + /** Why the model couldn't be planned, on a row whose action is `error`; a build of it is refused. */ + error?: { code: string | null; message: string; help: string | null }; }; /** A diff's changed lines; `whitespace_only` when they read the same with all whitespace taken out (a case change is a change). */ @@ -902,6 +906,8 @@ type PlanFields = { functions: { name: string; language: string; reason?: string }[]; python_nodes: { name: string; kind: string; phase: string; identity_status: string }[]; warnings: PlanWarning[]; + /** Whether any finding is an error, such as a model that couldn't be planned; a build of the plan is refused. */ + has_errors?: boolean; migrations: PlanMigration[]; column_migrations: PlanColumnMigration[]; table_type_conversions: PlanTableTypeConversion[]; @@ -944,6 +950,8 @@ export type PlanCantRun = { /** Every plan section a server summary counts and pages, in plan order. */ export type PlanPageSection = + | 'planning_error' + | 'window_before_cursor_start' | 'full_refresh' | 'query_changed' | 'function_changed' diff --git a/ui/src/lib/build-area/attention-conditions.ts b/ui/src/lib/build-area/attention-conditions.ts index 6fd11bcbcd..b4371ad2b3 100644 --- a/ui/src/lib/build-area/attention-conditions.ts +++ b/ui/src/lib/build-area/attention-conditions.ts @@ -148,6 +148,7 @@ export function visibleEventKey(key: string, scopeKey: string, healthRead = fals if (key.startsWith('sensor:')) return true; const kinds = [ 'location_broken', + 'location_failing', 'tick_overdue', 'calendar_horizon_low', 'trigger_skipped', diff --git a/ui/src/lib/build-area/folder-tree.test.ts b/ui/src/lib/build-area/folder-tree.test.ts index 71c752c71a..b67ef6ccae 100644 --- a/ui/src/lib/build-area/folder-tree.test.ts +++ b/ui/src/lib/build-area/folder-tree.test.ts @@ -1,57 +1,58 @@ +import { withServerStatus } from '$lib/build-area/status-fixtures'; import { describe, expect, it } from 'vitest'; import type { CatalogNode, StaleReason } from '$lib/api'; import { folderPaths, folderTree, visibleTreeRows, type TreeRow } from './folder-tree'; const behind = [{ reason: 'behind', upstream: [], detail: '', since: '2026-11-18T00:00:00Z' }] as StaleReason[]; const node = (key: string, path: string, extra: Partial = {}): CatalogNode => - ({ key, kind: 'table', path, group: null, upstream: [], stale: [], lastOutcome: 'success', lastBuild: { builtAt: '2026-11-18T00:00:00Z' }, ...extra }) as CatalogNode; + withServerStatus({ key, kind: 'table', path, group: null, upstream: [], stale: [], lastOutcome: 'success', lastBuild: { builtAt: '2026-11-18T00:00:00Z' }, ...extra } as CatalogNode); const nodes = [ - node('card_events', 'models/payments/providers/card/card_events.sql', { stale: behind }), - node('card_daily', 'models/payments/providers/card/card_daily.sql'), - node('bank_events', 'models/payments/providers/bank/bank_events.sql'), - node('settled', 'models/payments/settlement/settled.sql', { lastOutcome: 'failed' }), - node('payments_summary', 'models/payments/payments_summary.sql'), - node('orders', 'models/orders/marts/orders.sql'), - node('raw_orders', 'sources/shop.yml', { kind: 'source' }) + node('card_events', 'sql/models/payments/providers/card/card_events.sql', { stale: behind }), + node('card_daily', 'sql/models/payments/providers/card/card_daily.sql'), + node('bank_events', 'sql/models/payments/providers/bank/bank_events.sql'), + node('settled', 'sql/models/payments/settlement/settled.sql', { lastOutcome: 'failed' }), + node('payments_summary', 'sql/models/payments/payments_summary.sql'), + node('orders', 'sql/models/orders/marts/orders.sql'), + node('raw_orders', 'sql/sources/shop.yml', { kind: 'source' }) ]; const label = (r: TreeRow) => (r.kind === 'folder' ? `${' '.repeat(r.folder.depth)}${r.folder.group}${r.expandable ? (r.expanded ? ' v' : ' >') : ''}` : r.kind === 'node' ? `${' '.repeat(r.depth)}· ${r.node.key}` : `${' '.repeat(r.folder.depth + 1)}+${r.hidden} more`); const rows = (opts: Partial[1]> = {}) => visibleTreeRows(folderTree(nodes), { expanded: new Set(), sort: 'urgency', reverse: false, attentionOnly: false, listNodes: false, ...opts }).map(label); describe('the catalog folder tree', () => { - it('selects a folder by path only when that selects exactly what it counts, and only under models/ or python/', () => { + it('selects a folder by path only when that selects exactly what it counts, and only under sql/models/ or python/nodes/', () => { const tree = folderTree([ - node('orders', 'models/shop/orders/orders.sql'), + node('orders', 'sql/models/shop/orders/orders.sql'), // A source declared in the folder: a path would select it, though the folder doesn't count it. - node('raw_returns', 'models/shop/returns/sources.yml', { kind: 'source' }), - node('returns', 'models/shop/returns/returns.sql'), + node('raw_returns', 'sql/models/shop/returns/sources.yml', { kind: 'source' }), + node('returns', 'sql/models/shop/returns/returns.sql'), // A node of a declared group whose file sits in the folder. - node('loyalty', 'models/shop/customers/loyalty.sql', { group: 'crm' }), - node('customers', 'models/shop/customers/customers.sql'), - node('codes', 'seeds/lookups/codes.csv', { kind: 'seed' }), - node('score', 'python/ml/score.py', { kind: 'asset' }) + node('loyalty', 'sql/models/shop/customers/loyalty.sql', { group: 'crm' }), + node('customers', 'sql/models/shop/customers/customers.sql'), + node('codes', 'sql/seeds/lookups/codes.csv', { kind: 'seed' }), + node('score', 'python/nodes/ml/score.py', { kind: 'asset' }) ]); const selection = (path: string) => { const find = (fs: ReturnType): ReturnType[number] | undefined => fs.flatMap((f) => (f.path === path ? [f] : [find(f.children)].filter((x) => !!x)))[0]; return find(tree)?.selection; }; - expect(selection('shop/orders')).toBe('path:models/shop/orders'); + expect(selection('shop/orders')).toBe('path:sql/models/shop/orders'); expect(selection('shop/returns')).toBe('returns'); expect(selection('shop/customers')).toBe('customers'); expect(selection('shop')).toBe('orders returns customers'); // `path:seeds/…` is rejected: path selectors start at models/ or python/. expect([selection('seeds'), selection('seeds/lookups')]).toEqual(['codes', 'codes']); - expect(selection('python/ml')).toBe('path:python/ml'); + expect(selection('python/ml')).toBe('path:python/nodes/ml'); }); it('counts each folder with its subfolders, and selects exactly its nodes', () => { const [payments, orders] = folderTree(nodes); expect([payments.path, payments.total, payments.current, payments.behind, payments.failed]).toEqual(['payments', 5, 3, 1, 1]); - expect(payments.selection).toBe('path:models/payments'); + expect(payments.selection).toBe('path:sql/models/payments'); expect(payments.children.map((c) => [c.path, c.total, c.selection])).toEqual([ - ['payments/providers', 3, 'path:models/payments/providers'], - ['payments/settlement', 1, 'path:models/payments/settlement'] + ['payments/providers', 3, 'path:sql/models/payments/providers'], + ['payments/settlement', 1, 'path:sql/models/payments/settlement'] ]); expect(payments.members.map((n) => n.key)).toEqual(['payments_summary']); expect(orders.total).toBe(1); diff --git a/ui/src/lib/build-area/folder-tree.ts b/ui/src/lib/build-area/folder-tree.ts index 1e562ee5b9..393441131b 100644 --- a/ui/src/lib/build-area/folder-tree.ts +++ b/ui/src/lib/build-area/folder-tree.ts @@ -4,7 +4,9 @@ import type { CatalogNode, GroupStatus } from '$lib/api'; import { shortName } from '$lib/build-area/labels'; import { folderOf } from '$lib/lineage/catalog-graph'; -import { canSelectByPath, inexactDirs } from '$lib/selection/folders'; +import { canSelectByPath, dirOfFolder } from '$lib/project-layout'; +import { inexactDirs } from '$lib/selection/folders'; +import { countStatus } from './node-status'; import { needsAttention } from './overview-panels'; import { sortFolders } from './overview-panels'; @@ -34,35 +36,26 @@ export function sortFolderRows(rows: readonly T[], by: Fo /** The top-level folders, each holding its subfolders, unsorted. Sources are left out, as on the Overview. */ export function folderTree(nodes: readonly CatalogNode[]): FolderNode[] { - const byPath = new Map(); + const byPath = new Map(); const top: FolderNode[] = []; for (const n of nodes) { if (n.kind === 'source') continue; const folder = folderOf(n); const dir = dirOf(n.path); - // The file-system folder the catalog folder starts at, such as `models/`; null when the folder is a declared group. - const root = dir === folder || dir.endsWith(`/${folder}`) ? dir.slice(0, dir.length - folder.length) : null; + // Whether the folder is the node's directory, as the layout places it; not for a declared group. + const onDisk = dirOfFolder(folder) === dir; const parts = folder.split('/'); - const stale = n.stale ?? []; - const isChanged = stale.some((s) => s.reason !== 'behind'); - const isBehind = stale.some((s) => s.reason === 'behind'); - const isFailed = n.lastOutcome === 'failed'; - const isCurrent = !stale.length && !isFailed && !!n.lastBuild; let parent: FolderNode | null = null; for (let i = 0; i < parts.length; i++) { const path = parts.slice(0, i + 1).join('/'); let f = byPath.get(path); if (!f) { - f = { group: parts[i], path, depth: i, total: 0, current: 0, changed: 0, behind: 0, failed: 0, children: [], members: [], selection: '', root, keys: [] }; + f = { group: parts[i], path, depth: i, total: 0, current: 0, changed: 0, behind: 0, failed: 0, children: [], members: [], selection: '', onDisk, keys: [] }; byPath.set(path, f); (parent ? parent.children : top).push(f); } - if (f.root !== root) f.root = null; - f.total += 1; - f.current += Number(isCurrent); - f.changed += Number(isChanged); - f.behind += Number(isBehind); - f.failed += Number(isFailed); + f.onDisk &&= onDisk; + countStatus(f, n); f.keys.push(shortName(n.key)); if (i === parts.length - 1) f.members.push(n); parent = f; @@ -71,14 +64,14 @@ export function folderTree(nodes: readonly CatalogNode[]): FolderNode[] { // `path:` selects every node under the folder's directory, so it stands for the folder only when that is // exactly what the folder counts: under a root a path selector accepts, and with no source, and no node // of another folder, in it. Otherwise the folder's nodes are selected by name. - const dirOfFolder = new Map(); - for (const f of byPath.values()) if (f.root !== null && canSelectByPath(`${f.root}${f.path}`)) dirOfFolder.set(`${f.root}${f.path}`, f.path); + const folderAt = new Map(); + for (const f of byPath.values()) if (f.onDisk && canSelectByPath(dirOfFolder(f.path))) folderAt.set(dirOfFolder(f.path), f.path); const inside = (n: CatalogNode, path: string) => n.kind !== 'source' && (folderOf(n) === path || folderOf(n).startsWith(`${path}/`)); - const inexact = inexactDirs(nodes, new Set(dirOfFolder.keys()), (n, dir) => inside(n, dirOfFolder.get(dir)!)); + const inexact = inexactDirs(nodes, new Set(folderAt.keys()), (n, dir) => inside(n, folderAt.get(dir)!)); for (const f of byPath.values()) { - const dir = f.root !== null ? `${f.root}${f.path}` : null; - f.selection = dir && dirOfFolder.has(dir) && !inexact.has(dir) ? `path:${dir}` : [...new Set(f.keys)].join(' '); - delete (f as { root?: unknown }).root; + const dir = dirOfFolder(f.path); + f.selection = folderAt.has(dir) && !inexact.has(dir) ? `path:${dir}` : [...new Set(f.keys)].join(' '); + delete (f as { onDisk?: unknown }).onDisk; delete (f as { keys?: unknown }).keys; } return top; @@ -94,7 +87,7 @@ export type TreeRow = | { kind: 'node'; node: CatalogNode; depth: number } | { kind: 'more'; folder: FolderNode; hidden: number }; -const nodeNeedsAttention = (n: CatalogNode) => n.lastOutcome === 'failed' || !!n.stale?.length; +const nodeNeedsAttention = (n: CatalogNode) => n.status === 'failed' || n.status === 'changed' || n.status === 'behind'; /** * The rows on screen: folders sorted within each level, an expanded folder's subfolders under it and, diff --git a/ui/src/lib/build-area/node-status.test.ts b/ui/src/lib/build-area/node-status.test.ts new file mode 100644 index 0000000000..57fa88f0a1 --- /dev/null +++ b/ui/src/lib/build-area/node-status.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from 'vitest'; +import type { CatalogNode, NodeBuildStatus } from '$lib/api'; +import { groupStatusOf } from '$lib/api/http-overview'; +import { folderTree } from '$lib/build-area/folder-tree'; +import { NODE_STATUS, statusLabel } from '$lib/build-area/node-status'; +import { cardData } from '$lib/lineage/catalog-graph'; +import { viewSummary } from '$lib/lineage/view-summary'; + +const KINDS: { kind: CatalogNode['kind']; path: string }[] = [ + { kind: 'table', path: 'sql/models/marts/orders.sql' }, + { kind: 'view', path: 'sql/models/marts/orders_view.sql' }, + { kind: 'incremental', path: 'sql/models/marts/events.sql' }, + { kind: 'seed', path: 'sql/seeds/regions.csv' }, + { kind: 'udf', path: 'sql/functions/clean.sql' }, + { kind: 'asset', path: 'python/nodes/exports/export_csv.py' }, + { kind: 'loader', path: 'python/nodes/loaders/raw_orders.py' } +]; +const BUILT_STATUSES: NodeBuildStatus[] = ['current', 'changed', 'behind', 'failed', 'not_built']; + +/** + * A node whose raw fields say the opposite of its status (no build, a successful run, no stale + * reasons), so a page that worked the status out again from them would disagree with the server. + */ +function node(kind: CatalogNode['kind'], path: string, status: NodeBuildStatus): CatalogNode { + return { + key: `${kind}:n`, + kind, + materialization: null, + group: null, + tags: [], + description: '', + path, + upstream: [], + relation: null, + columnCount: 0, + lastBuild: null, + lastOutcome: status === 'not_built' ? 'success' : null, + stale: [], + sourceFreshness: null, + checks: null, + status, + statusAt: status === 'not_built' ? null : '2026-11-24T06:00:00Z' + }; +} + +/** What each page shows for one node, as each page's own helper works it out. */ +function pages(n: CatalogNode) { + const [folder] = folderTree([n]); + const [group] = groupStatusOf([n]); + const summary = viewSummary([n]); + const card = cardData(n); + const counted = (counts: { current: number; changed: number; behind: number; failed: number }) => { + const shown = (['current', 'changed', 'behind', 'failed'] as const).filter((s) => counts[s] > 0); + return shown.length ? shown : ['not_built']; + }; + const lineage = card.status === 'fail' ? 'failed' : card.status === 'none' ? 'not_built' : card.stale === 'behind' ? 'behind' : card.stale === 'changed' || card.stale === 'compiled' ? 'changed' : 'current'; + const needs = summary.failed ? 'failed' : summary.changed ? 'changed' : summary.behind ? 'behind' : null; + return { + folderTreeCounts: counted(folder), + folderTreeRow: statusLabel(n)?.label, + catalogList: statusLabel(n)?.label, + nodePage: statusLabel(n)?.label, + lineageCard: lineage, + lineageSummary: needs ?? (lineage === 'not_built' ? 'not_built' : 'current'), + overviewCounts: counted(group) + }; +} + +describe('every page shows the server’s status', () => { + for (const { kind, path } of KINDS) { + it.each(BUILT_STATUSES)(`${kind} that is %s`, (status) => { + const shown = pages(node(kind, path, status)); + expect(shown).toEqual({ + folderTreeCounts: [status], + folderTreeRow: NODE_STATUS[status].label, + catalogList: NODE_STATUS[status].label, + nodePage: NODE_STATUS[status].label, + lineageCard: status, + lineageSummary: status, + overviewCounts: [status] + }); + }); + } + + it('shows a source as a source and leaves it out of the folder counts', () => { + const source = node('source', 'sql/sources/raw.yml', 'source'); + expect([statusLabel(source)?.label, cardData(source).status, folderTree([source]), groupStatusOf([source])]).toEqual(['Source', 'src', [], []]); + }); + + it('shows nothing it would have to guess when the server has not reported a status', () => { + const unknown = { ...node('table', 'sql/models/marts/orders.sql', 'current'), status: null }; + expect([statusLabel(unknown), cardData(unknown).status]).toEqual([null, 'none']); + }); +}); diff --git a/ui/src/lib/build-area/node-status.ts b/ui/src/lib/build-area/node-status.ts new file mode 100644 index 0000000000..0ee3338da8 --- /dev/null +++ b/ui/src/lib/build-area/node-status.ts @@ -0,0 +1,30 @@ +// A node's build status as every page shows it: the server works it out once (`NodeState.status`), +// and pages only name and colour it here, never deriving it again. Pure. + +import type { CatalogNode, GroupStatus, NodeBuildStatus } from '$lib/api'; + +/** Each status's name and colour. */ +export const NODE_STATUS: Record = { + current: { label: 'Current', tone: 'var(--sb-success)' }, + changed: { label: 'Changed', tone: 'var(--sb-stale)' }, + behind: { label: 'Behind', tone: 'var(--sb-behind)' }, + failed: { label: 'Failed', tone: 'var(--sb-error)' }, + not_built: { label: 'Not built', tone: 'var(--muted-foreground)' }, + source: { label: 'Source', tone: 'var(--sb-text-faint)' } +}; + +/** A node's status, or null when the server has not reported it (an older server, or before its state is read). */ +export const statusOf = (node: Pick): NodeBuildStatus | null => node.status ?? null; + +/** A node's status label and colour; null when it is not known. */ +export function statusLabel(node: Pick): { label: string; tone: string } | null { + const status = statusOf(node); + return status ? NODE_STATUS[status] : null; +} + +/** Adds a node to a folder's counts: one of current, changed, behind or failed, or none when not built. */ +export function countStatus(counts: Omit, node: Pick): void { + const status = statusOf(node); + counts.total += 1; + if (status === 'current' || status === 'changed' || status === 'behind' || status === 'failed') counts[status] += 1; +} diff --git a/ui/src/lib/build-area/status-fixtures.ts b/ui/src/lib/build-area/status-fixtures.ts new file mode 100644 index 0000000000..7242a38f77 --- /dev/null +++ b/ui/src/lib/build-area/status-fixtures.ts @@ -0,0 +1,23 @@ +// Test fixtures: a hand-built node with the status the server would give its fields, unless it +// already has one. Only tests import this; pages never work a status out. + +import type { CatalogNode, NodeBuildStatus } from '$lib/api'; + +/** `node` with the server's status for its outcome, stale reasons and build. */ +export function withServerStatus(node: CatalogNode): CatalogNode { + if (node.status) return node; + const stale = node.stale ?? []; + const status: NodeBuildStatus = + node.kind === 'source' + ? 'source' + : node.lastOutcome === 'failed' + ? 'failed' + : stale.some((r) => r.reason === 'changed') + ? 'changed' + : stale.some((r) => r.reason === 'behind') + ? 'behind' + : node.lastBuild || node.lastOutcome + ? 'current' + : 'not_built'; + return { ...node, status, statusAt: node.lastBuild?.builtAt ?? null }; +} diff --git a/ui/src/lib/components/build-area/folder-tree.svelte b/ui/src/lib/components/build-area/folder-tree.svelte index 72d2854038..6ba9805311 100644 --- a/ui/src/lib/components/build-area/folder-tree.svelte +++ b/ui/src/lib/components/build-area/folder-tree.svelte @@ -6,6 +6,7 @@ import type { CatalogNode } from '$lib/api'; import { folderPaths, folderTree, visibleTreeRows, type FolderNode, type FolderSort, type TreeRow } from '$lib/build-area/folder-tree'; import { needsAttention } from '$lib/build-area/overview-panels'; + import { statusLabel } from '$lib/build-area/node-status'; import { nodeIcon, nodeIconKey, shortName } from '$lib/build-area/labels'; import DataTable from '$lib/components/list/data-table.svelte'; import type { TableColumn } from '$lib/components/list/table-columns'; @@ -80,16 +81,7 @@ } /** A folder's own nodes as a selection: the folder itself when it has no subfolders. */ const ownSelection = (f: FolderNode) => (f.children.length ? [...new Set(f.members.map((n) => shortName(n.key)))].join(' ') : f.selection); - const nodeState = (n: CatalogNode): { label: string; tone: string } => - n.lastOutcome === 'failed' - ? { label: 'Failed', tone: 'var(--sb-error)' } - : n.stale?.some((s) => s.reason !== 'behind') - ? { label: 'Changed', tone: 'var(--sb-stale)' } - : n.stale?.length - ? { label: 'Behind', tone: 'var(--sb-behind)' } - : n.lastBuild - ? { label: 'Current', tone: 'var(--sb-success)' } - : { label: 'Not built', tone: 'var(--muted-foreground)' }; + const nodeState = (n: CatalogNode): { label: string; tone: string } => statusLabel(n) ?? { label: '—', tone: 'var(--muted-foreground)' }; const rowKey = (r: TreeRow) => (r.kind === 'folder' ? `f:${r.folder.path}` : r.kind === 'node' ? `n:${r.node.key}` : `m:${r.folder.path}`); diff --git a/ui/src/lib/lineage/catalog-graph.test.ts b/ui/src/lib/lineage/catalog-graph.test.ts index ed9fb0b97e..31ae97a045 100644 --- a/ui/src/lib/lineage/catalog-graph.test.ts +++ b/ui/src/lib/lineage/catalog-graph.test.ts @@ -1,21 +1,27 @@ +import { withServerStatus } from '$lib/build-area/status-fixtures'; import { describe, expect, it } from 'vitest'; import type { CatalogNode } from '$lib/api'; import { cardData, folderOf } from './catalog-graph'; function node(key: string, path: string, upstream: string[] = [], extra: Partial = {}): CatalogNode { const kind = key.startsWith('source:') ? 'source' : key.startsWith('seed:') ? 'seed' : 'table'; - return { key, kind, path, upstream, group: null, stale: [], lastOutcome: null, lastBuild: { builtAt: '2026-11-07T06:00:00Z' }, ...extra } as CatalogNode; + return withServerStatus({ key, kind, path, upstream, group: null, stale: [], lastOutcome: null, lastBuild: { builtAt: '2026-11-07T06:00:00Z' }, ...extra } as CatalogNode); } describe('lineage folders', () => { - it('groups models by folder, sources by file, and lets a declared group win', () => { + it('groups models below sql/models, other SQL below sql, Python below python/nodes, and lets a declared group win', () => { expect([ - folderOf(node('model:dim_orders', 'models/marts/core/dim_orders.sql')), - folderOf(node('source:shop__orders', 'sources/shop.yml')), - folderOf(node('seed:countries', 'seeds/countries.csv')), - folderOf(node('model:orders', 'orders.sql')), - folderOf(node('model:stg_orders', 'models/staging/stg_orders.sql', [], { group: 'shop' })) - ]).toEqual(['marts/core', 'sources/shop', 'seeds', 'models', 'shop']); + folderOf(node('model:dim_orders', 'sql/models/marts/core/dim_orders.sql')), + folderOf(node('model:orders', 'sql/models/orders.sql')), + folderOf(node('source:shop__orders', 'sql/sources/shop.yml')), + folderOf(node('seed:countries', 'sql/seeds/countries.csv')), + folderOf(node('seed:regions', 'sql/seeds/geo/regions.csv')), + folderOf(node('udf:clean', 'sql/functions/clean.sql', [], { kind: 'udf' })), + folderOf(node('udf:to_cents', 'sql/models/staging/_sqlbuild/functions/to_cents.sql', [], { kind: 'udf' })), + folderOf(node('asset:export_csv', 'python/nodes/exports/export_csv.py', [], { kind: 'asset' })), + folderOf(node('asset:score', 'python/nodes/score.py', [], { kind: 'asset' })), + folderOf(node('model:stg_orders', 'sql/models/staging/stg_orders.sql', [], { group: 'shop' })) + ]).toEqual(['marts/core', 'models', 'sources/shop', 'seeds', 'seeds/geo', 'functions', 'staging/_sqlbuild/functions', 'python/exports', 'python', 'shop']); }); }); diff --git a/ui/src/lib/lineage/catalog-graph.ts b/ui/src/lib/lineage/catalog-graph.ts index bab759eae4..a6c9c01be4 100644 --- a/ui/src/lib/lineage/catalog-graph.ts +++ b/ui/src/lib/lineage/catalog-graph.ts @@ -4,16 +4,24 @@ import type { Edge, Node } from '@xyflow/svelte'; import { cardLabel } from './discovered-labels'; import type { CatalogNode, StaleReason } from '$lib/api'; import { FUNCTION_KINDS, PYTHON_KINDS, kindLine, nodeIconKey } from '$lib/build-area/labels'; +import { PYTHON_FOLDER, folderOfDir } from '$lib/project-layout'; export type CardStatus = 'ok' | 'fail' | 'warn' | 'src' | 'none'; export type CardStale = 'changed' | 'compiled' | 'upstream' | 'behind'; export function cardStatus(node: CatalogNode): CardStatus { if (node.kind === 'source') return 'src'; - if (node.lastOutcome === 'failed') return 'fail'; - if (node.lastOutcome === 'warn') return 'warn'; - if (node.lastOutcome === 'success' || node.lastOutcome === 'skipped') return node.lastBuild ? 'ok' : 'none'; - return node.lastBuild ? 'ok' : 'none'; + // The server's status: changed and behind are built, and show as a stale badge. + switch (node.status) { + case 'failed': + return 'fail'; + case 'current': + case 'changed': + case 'behind': + return 'ok'; + default: + return 'none'; + } } /** The stale reason to show on a card: own changes first, then upstream changes, then behind. */ @@ -25,6 +33,18 @@ export function cardStale(reasons: StaleReason[]): CardStale | undefined { return undefined; } +/** A card's stale badge, which follows the server's status; the reasons only say which kind of change. */ +function staleBadge(node: CatalogNode): CardStale | undefined { + const reasons = node.stale ?? []; + if (node.status === 'changed') { + const shown = cardStale(reasons); + return shown === 'compiled' ? 'compiled' : 'changed'; + } + if (node.status === 'behind') return 'behind'; + // A current node can still have an upstream whose definition changed: shown, but not as its status. + return node.status === 'current' && cardStale(reasons) === 'upstream' ? 'upstream' : undefined; +} + export function checksBadge(node: CatalogNode): { checks?: string; checksColor?: string } { const c = node.checks; if (!c?.total) return {}; @@ -42,10 +62,10 @@ export function cardData(node: CatalogNode): Record { nodeKind: node.kind, status: node.liveStatus ?? cardStatus(node), // A node the active run is building, or has just built, shows that, not whether it was stale. - stale: node.liveStatus ? undefined : cardStale(node.stale ?? []), + stale: node.liveStatus ? undefined : staleBadge(node), live: !!node.liveStatus, icon: nodeIconKey(node), - lastBuiltAt: node.kind === 'source' ? (node.sourceFreshness?.loadedAt ?? undefined) : node.lastBuild?.builtAt, + lastBuiltAt: node.kind === 'source' ? (node.sourceFreshness?.loadedAt ?? undefined) : (node.statusAt ?? undefined), description: node.description || undefined, tags: node.tags, columnCount: node.columnCount || undefined, @@ -64,16 +84,17 @@ export function catalogGraph(nodes: CatalogNode[]): { nodes: Node[]; edges: Edge export const GROUPED_ABOVE = 150; /** - * The folder a node lives in, such as `marts/core`, or its source file, such as `sources/orders`; - * a declared group wins. + * The folder a node lives in, as the project layout groups it (`folderOfDir`): a model's folder + * below `sql/models/`, such as `marts/core`, a source's file below `sql/`, such as `sources/orders`, + * or `python/exports` for a Python node; a declared group wins. */ export function folderOf(node: CatalogNode): string { if (node.group) return node.group; - const path = node.path.replace(/^models\//, ''); - if (node.kind === 'source') return path.replace(/\.[^./]+$/, '') || 'sources'; - const slash = path.lastIndexOf('/'); - if (slash > 0) return path.slice(0, slash); - return node.kind === 'seed' ? 'seeds' : PYTHON_KINDS.includes(node.kind) ? 'python' : FUNCTION_KINDS.includes(node.kind) ? 'functions' : 'models'; + if (node.kind === 'source') return folderOfDir(node.path.replace(/\.[^./]+$/, '')) || 'sources'; + const slash = node.path.lastIndexOf('/'); + const folder = slash > 0 ? folderOfDir(node.path.slice(0, slash)) : ''; + if (folder) return folder; + return node.kind === 'seed' ? 'seeds' : PYTHON_KINDS.includes(node.kind) ? PYTHON_FOLDER : FUNCTION_KINDS.includes(node.kind) ? 'functions' : 'models'; } /** The outermost folder around a node, such as `marts`, which the catalog filters and Overview counts by. */ @@ -89,8 +110,8 @@ export function groupCard(group: string, members: CatalogNode[]): GroupCard { return { group, count: members.length, - ok: built.filter((n) => cardStatus(n) === 'ok' && !n.stale?.length).length, - stale: built.filter((n) => !!n.stale?.length).length, - failed: built.filter((n) => n.lastOutcome === 'failed').length + ok: built.filter((n) => n.status === 'current').length, + stale: built.filter((n) => n.status === 'changed' || n.status === 'behind').length, + failed: built.filter((n) => n.status === 'failed').length }; } diff --git a/ui/src/lib/lineage/folder-graph.test.ts b/ui/src/lib/lineage/folder-graph.test.ts index b005672394..29b9ae4bbc 100644 --- a/ui/src/lib/lineage/folder-graph.test.ts +++ b/ui/src/lib/lineage/folder-graph.test.ts @@ -1,3 +1,4 @@ +import { withServerStatus } from '$lib/build-area/status-fixtures'; import { describe, expect, it } from 'vitest'; import type { Node } from '@xyflow/svelte'; import type { CatalogNode } from '$lib/api'; @@ -5,17 +6,17 @@ import { MAX_DRAWN, folderGraph, folderTree, layoutFolderGraph, tooManyToDraw, w function node(key: string, path: string, upstream: string[] = [], extra: Partial = {}): CatalogNode { const kind = key.startsWith('source:') ? 'source' : key.startsWith('seed:') ? 'seed' : 'table'; - return { key, kind, path, upstream, group: null, tags: [], stale: [], lastOutcome: null, lastBuild: { builtAt: '2026-11-07T06:00:00Z' }, ...extra } as CatalogNode; + return withServerStatus({ key, kind, path, upstream, group: null, tags: [], stale: [], lastOutcome: null, lastBuild: { builtAt: '2026-11-07T06:00:00Z' }, ...extra } as CatalogNode); } const nodes = [ - node('source:shop__orders', 'sources/shop.yml'), - node('source:shop__customers', 'sources/shop.yml'), - node('model:stg_orders', 'models/staging/shop/stg_orders.sql', ['source:shop__orders']), - node('model:stg_customers', 'models/staging/crm/stg_customers.sql', ['source:shop__customers'], { stale: [{ reason: 'behind', upstream: [], detail: '', since: '' }] }), - node('model:orders', 'models/marts/orders.sql', ['model:stg_orders', 'model:stg_customers'], { lastOutcome: 'failed' }), - node('model:order_totals', 'models/marts/order_totals.sql', ['model:orders']), - node('model:pick_lists', 'models/orders/fulfilment/staging/pick_lists.sql', ['model:orders']) + node('source:shop__orders', 'sql/sources/shop.yml'), + node('source:shop__customers', 'sql/sources/shop.yml'), + node('model:stg_orders', 'sql/models/staging/shop/stg_orders.sql', ['source:shop__orders']), + node('model:stg_customers', 'sql/models/staging/crm/stg_customers.sql', ['source:shop__customers'], { stale: [{ reason: 'behind', upstream: [], detail: '', since: '' }] }), + node('model:orders', 'sql/models/marts/orders.sql', ['model:stg_orders', 'model:stg_customers'], { lastOutcome: 'failed' }), + node('model:order_totals', 'sql/models/marts/order_totals.sql', ['model:orders']), + node('model:pick_lists', 'sql/models/orders/fulfilment/staging/pick_lists.sql', ['model:orders']) ]; const ids = (graph: { nodes: Node[] }) => graph.nodes.map((n) => [n.id, n.parentId ?? null]); @@ -80,7 +81,7 @@ describe('folder graph', () => { }); it('refuses to lay out more cards than the cap', () => { - const many = Array.from({ length: MAX_DRAWN + 1 }, (_, i) => node(`model:orders_${i}`, `models/orders/orders_${i}.sql`)); + const many = Array.from({ length: MAX_DRAWN + 1 }, (_, i) => node(`model:orders_${i}`, `sql/models/orders/orders_${i}.sql`)); expect(tooManyToDraw(folderGraph(many, new Set()))).toBe(false); expect(tooManyToDraw(folderGraph(many, new Set(['orders'])))).toBe(true); }); @@ -111,7 +112,7 @@ describe('opening a folder', () => { it('moves its siblings out of the way: no boxes or cards overlap at any level', () => { const many: CatalogNode[] = []; for (let f = 0; f < 14; f++) - for (let i = 0; i < 5; i++) many.push(node(`model:f${f}_${i}`, `models/marts/f${f}/sub${i % 2}/m${i}.sql`, i ? [`model:f${f}_0`] : f ? ['model:f0_0'] : [])); + for (let i = 0; i < 5; i++) many.push(node(`model:f${f}_${i}`, `sql/models/marts/f${f}/sub${i % 2}/m${i}.sql`, i ? [`model:f${f}_0`] : f ? ['model:f0_0'] : [])); const t = folderTree(many); const size = (n: Node) => ({ w: n.width ?? 236, h: n.height ?? 61 }); for (const open of [['marts/f0'], ['marts/f3'], ['marts/f3', 'marts/f3/sub0'], ['marts/f13'], ['marts/f3', 'marts/f3/sub0', 'marts/f3/sub1']]) { diff --git a/ui/src/lib/lineage/folder-selection.test.ts b/ui/src/lib/lineage/folder-selection.test.ts index 5c215d8e8e..4390ffde6f 100644 --- a/ui/src/lib/lineage/folder-selection.test.ts +++ b/ui/src/lib/lineage/folder-selection.test.ts @@ -22,14 +22,14 @@ function node(key: string, path: string, upstream: string[] = [], extra: Partial } const nodes = [ - node('source:shop__orders', 'sources/shop.yml'), - node('source:shop__customers', 'sources/shop.yml'), - node('model:stg_orders', 'models/staging/shop/stg_orders.sql', ['source:shop__orders']), - node('model:stg_customers', 'models/staging/crm/stg_customers.sql', ['source:shop__customers']), - node('model:orders', 'models/marts/orders.sql', ['model:stg_orders', 'model:stg_customers'], { stale: [{ reason: 'behind', upstream: [], detail: '', since: '' }] as CatalogNode['stale'] }), - node('model:order_totals', 'models/marts/order_totals.sql', ['model:orders']), - node('model:inventory', 'models/inventory/inventory.sql', ['model:orders']), - node('model:inventory_daily', 'models/inventory/inventory_daily.sql', ['model:inventory']) + node('source:shop__orders', 'sql/sources/shop.yml'), + node('source:shop__customers', 'sql/sources/shop.yml'), + node('model:stg_orders', 'sql/models/staging/shop/stg_orders.sql', ['source:shop__orders']), + node('model:stg_customers', 'sql/models/staging/crm/stg_customers.sql', ['source:shop__customers']), + node('model:orders', 'sql/models/marts/orders.sql', ['model:stg_orders', 'model:stg_customers'], { stale: [{ reason: 'behind', upstream: [], detail: '', since: '' }] as CatalogNode['stale'] }), + node('model:order_totals', 'sql/models/marts/order_totals.sql', ['model:orders']), + node('model:inventory', 'sql/models/inventory/inventory.sql', ['model:orders']), + node('model:inventory_daily', 'sql/models/inventory/inventory_daily.sql', ['model:inventory']) ]; const tree = folderTree(nodes); @@ -127,10 +127,10 @@ describe('picked nodes', () => { }); describe('one rule at every scope', () => { - const flat = (n: number, folder: string) => Array.from({ length: n }, (_, i) => node(`model:${folder.replace(/\//g, '_')}_${i}`, `models/${folder}/m${i}.sql`)); + const flat = (n: number, folder: string) => Array.from({ length: n }, (_, i) => node(`model:${folder.replace(/\//g, '_')}_${i}`, `sql/models/${folder}/m${i}.sql`)); // The same shape twice: once as a whole project, once inside a `marts` folder of a larger project. const shape = (prefix: string) => [...flat(90, `${prefix}core`), ...flat(70, `${prefix}finance`)]; - const project = [...shape('marts/'), node('model:marts_top', 'models/marts/top.sql'), ...flat(40, 'staging')]; + const project = [...shape('marts/'), node('model:marts_top', 'sql/models/marts/top.sql'), ...flat(40, 'staging')]; const ids = (g: { nodes: { id: string; type?: string; parentId?: string }[] }) => g.nodes.filter((n) => n.type !== 'stub').map((n) => `${n.type}:${n.id.replace('marts/', '').replace('model:marts_', 'model:').replace('model:martstop', 'model:top')}`).sort(); diff --git a/ui/src/lib/lineage/member-graph.test.ts b/ui/src/lib/lineage/member-graph.test.ts index d485a43cb6..120020eccd 100644 --- a/ui/src/lib/lineage/member-graph.test.ts +++ b/ui/src/lib/lineage/member-graph.test.ts @@ -1,3 +1,4 @@ +import { withServerStatus } from '$lib/build-area/status-fixtures'; import { describe, expect, it } from 'vitest'; import type { CatalogNode, JobGroupMember, StaleReason } from '$lib/api'; import { layoutFolderGraph } from './folder-graph'; @@ -35,7 +36,7 @@ const member = (jobKey: string, stage: number, waitsFor: string[] = []): JobGrou function node(key: string, upstream: string[] = [], stale: StaleReason['reason'][] = []): CatalogNode { const reasons = stale.map((reason) => ({ reason, upstream: [], detail: '', since: '', change: 'definition' }) as unknown as StaleReason); - return { key, kind: 'table', path: `models/${key.split(':')[1]}.sql`, upstream, group: null, tags: [], stale: reasons, lastOutcome: null, lastBuild: null } as unknown as CatalogNode; + return withServerStatus({ key, kind: 'table', path: `sql/models/${key.split(':')[1]}.sql`, upstream, group: null, tags: [], stale: reasons, lastOutcome: null, lastBuild: null } as unknown as CatalogNode); } // customers builds two staging models; orders reads both, through a source no member selects for one; diff --git a/ui/src/lib/lineage/view-summary.test.ts b/ui/src/lib/lineage/view-summary.test.ts index 6552481051..32b0341aea 100644 --- a/ui/src/lib/lineage/view-summary.test.ts +++ b/ui/src/lib/lineage/view-summary.test.ts @@ -1,3 +1,4 @@ +import { withServerStatus } from '$lib/build-area/status-fixtures'; import { describe, expect, it } from 'vitest'; import type { CatalogNode, StaleReason } from '$lib/api'; import { shownNodes } from './folder-selection'; @@ -5,15 +6,15 @@ import { viewSummary } from './view-summary'; function node(key: string, kind: CatalogNode['kind'], path: string, stale: StaleReason['reason'][] = [], lastOutcome: CatalogNode['lastOutcome'] = null): CatalogNode { const reasons = stale.map((reason) => ({ reason, upstream: [], detail: '', since: '' }) as unknown as StaleReason); - return { key, kind, path, upstream: [], group: null, tags: [], stale: reasons, lastOutcome, lastBuild: null } as unknown as CatalogNode; + return withServerStatus({ key, kind, path, upstream: [], group: null, tags: [], stale: reasons, lastOutcome, lastBuild: null } as unknown as CatalogNode); } const nodes = [ node('source:raw_orders', 'source', 'sources/shop.yml'), - node('model:orders', 'table', 'models/marts/orders.sql', ['changed', 'behind']), - node('model:customers', 'table', 'models/marts/customers.sql', ['behind']), - node('model:order_view', 'view', 'models/marts/order_view.sql', ['changed_upstream']), - node('model:inventory', 'incremental', 'models/stock/inventory.sql', [], 'failed') + node('model:orders', 'table', 'sql/models/marts/orders.sql', ['changed', 'behind']), + node('model:customers', 'table', 'sql/models/marts/customers.sql', ['behind']), + node('model:order_view', 'view', 'sql/models/marts/order_view.sql', ['changed_upstream']), + node('model:inventory', 'incremental', 'sql/models/stock/inventory.sql', [], 'failed') ]; describe('view summary', () => { @@ -26,8 +27,9 @@ describe('view summary', () => { { kind: 'table', count: 2 }, { kind: 'incremental', count: 1 } ], + // One status each: an upstream definition change leaves the view current. changed: 1, - behind: 2, + behind: 1, failed: 1 }); }); diff --git a/ui/src/lib/lineage/view-summary.ts b/ui/src/lib/lineage/view-summary.ts index 139f10b4ba..7fe036d3d8 100644 --- a/ui/src/lib/lineage/view-summary.ts +++ b/ui/src/lib/lineage/view-summary.ts @@ -11,9 +11,9 @@ export function needsBuilding(keys: Iterable, byKey: ReadonlyMap r.reason === 'changed')) changed++; - else if (reasons.length) behind++; + const status = byKey.get(key)?.status; + if (status === 'changed') changed++; + else if (status === 'behind') behind++; } return { changed, behind }; } @@ -28,6 +28,6 @@ export function viewSummary(nodes: readonly CatalogNode[]): ViewSummary { total: nodes.length, byKind, ...needsBuilding(nodes.map((n) => n.key), new Map(nodes.map((n) => [n.key, n]))), - failed: nodes.filter((n) => n.lastOutcome === 'failed').length + failed: nodes.filter((n) => n.status === 'failed').length }; } diff --git a/ui/src/lib/lineage/visible-edges.test.ts b/ui/src/lib/lineage/visible-edges.test.ts index b8b9743ebb..f96387670a 100644 --- a/ui/src/lib/lineage/visible-edges.test.ts +++ b/ui/src/lib/lineage/visible-edges.test.ts @@ -9,13 +9,13 @@ function node(key: string, path: string, upstream: string[] = []): CatalogNode { // Three staging models feed four marts models; inventory reads one mart. const nodes = [ - node('model:stg_orders', 'models/staging/stg_orders.sql'), - node('model:stg_customers', 'models/staging/stg_customers.sql'), - node('model:stg_items', 'models/staging/stg_items.sql'), - node('model:orders', 'models/marts/orders.sql', ['model:stg_orders', 'model:stg_items']), - node('model:customers', 'models/marts/customers.sql', ['model:stg_customers']), - node('model:order_totals', 'models/marts/order_totals.sql', ['model:orders', 'model:stg_orders']), - node('model:inventory', 'models/inventory/inventory.sql', ['model:orders']) + node('model:stg_orders', 'sql/models/staging/stg_orders.sql'), + node('model:stg_customers', 'sql/models/staging/stg_customers.sql'), + node('model:stg_items', 'sql/models/staging/stg_items.sql'), + node('model:orders', 'sql/models/marts/orders.sql', ['model:stg_orders', 'model:stg_items']), + node('model:customers', 'sql/models/marts/customers.sql', ['model:stg_customers']), + node('model:order_totals', 'sql/models/marts/order_totals.sql', ['model:orders', 'model:stg_orders']), + node('model:inventory', 'sql/models/inventory/inventory.sql', ['model:orders']) ]; const tree = folderTree(nodes); diff --git a/ui/src/lib/platform/labels.ts b/ui/src/lib/platform/labels.ts index d248dfaf51..f0e956175c 100644 --- a/ui/src/lib/platform/labels.ts +++ b/ui/src/lib/platform/labels.ts @@ -18,18 +18,22 @@ import type { } from '$lib/api'; export const healthTone: Record = { + starting: 'var(--sb-running)', healthy: 'var(--sb-success)', - degraded: 'var(--sb-warning)', + degraded: 'var(--sb-error)', missing_secrets: 'var(--sb-error)', - discovery_failed: 'var(--sb-warning)', - falling_back: 'var(--sb-warning)', + change_plan_failed: 'var(--sb-error)', + discovery_failed: 'var(--sb-error)', + falling_back: 'var(--sb-error)', broken: 'var(--sb-error)' }; export const healthLabel: Record = { + starting: 'Starting', healthy: 'Healthy', degraded: 'Needs attention', missing_secrets: 'Missing provider secrets', + change_plan_failed: 'Change plan failed', discovery_failed: 'Discovery failed', falling_back: 'Running previous version', broken: 'Broken' @@ -37,9 +41,11 @@ export const healthLabel: Record = { /** What each health means, for tooltips. */ export const healthHelp: Record = { + starting: 'The newest instance is loading the project; earlier instances keep serving', healthy: 'Loaded and starting scheduled runs', degraded: 'Running, with open problems', missing_secrets: 'A provider setting is missing from the location environment', + change_plan_failed: 'Planning what changed failed on the current snapshot, so what needs building is unknown', discovery_failed: 'A discover function failed at the last publish; its nodes keep their last good items', falling_back: 'The last deploy failed to load; the previous version keeps running', broken: 'Not starting scheduled runs' @@ -67,6 +73,7 @@ export const eventKindLabel: Record = { calendar_times_dropped: 'Calendar times dropped', scheduler_no_leader: 'Scheduler stopped', location_broken: 'Location not checking in', + location_failing: 'Location failing', location_missing_secrets: 'Provider secrets missing', launch_failed: 'Couldn’t start runs', connection_test_failed: 'Connection test failed', diff --git a/ui/src/lib/project-layout.test.ts b/ui/src/lib/project-layout.test.ts new file mode 100644 index 0000000000..342832f1bf --- /dev/null +++ b/ui/src/lib/project-layout.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import { canSelectByPath, dirOfFolder, folderOfDir } from './project-layout'; + +describe('the folders a project directory groups under', () => { + it.each([ + ['a model folder below sql/models', 'sql/models/marts/core', 'marts/core'], + ['the top of sql/models', 'sql/models', ''], + ['a seed folder below sql', 'sql/seeds/geo', 'seeds/geo'], + ['the seeds folder', 'sql/seeds', 'seeds'], + ['the functions folder', 'sql/functions', 'functions'], + ['a sources folder', 'sql/sources/raw', 'sources/raw'], + ['a scoped declaration folder, in its owner', 'sql/models/staging/_sqlbuild/functions', 'staging/_sqlbuild/functions'], + ['a Python node folder below python/nodes', 'python/nodes/exports/csv', 'python/exports/csv'], + ['the top of python/nodes', 'python/nodes', 'python'], + ['a trailing slash', 'sql/models/staging/', 'staging'], + ['a directory outside the roots', 'legacy/models', 'legacy/models'] + ])('%s', (_, dir, folder) => { + expect(folderOfDir(dir)).toBe(folder); + }); + + it.each([ + ['a model folder', 'marts/core', 'sql/models/marts/core'], + ['the top of sql/models', '', 'sql/models'], + ['a seed folder', 'seeds/geo', 'sql/seeds/geo'], + ['a source file', 'sources/raw', 'sql/sources/raw'], + ['a Python folder', 'python/exports', 'python/nodes/exports'], + ['the Python folder', 'python', 'python/nodes'], + ['a scoped declaration folder', 'staging/_sqlbuild/functions', 'sql/models/staging/_sqlbuild/functions'] + ])('maps %s back to its directory', (_, folder, dir) => { + expect(dirOfFolder(folder)).toBe(dir); + expect(folderOfDir(dir)).toBe(folder); + }); + + it('lets a path selector name folders below sql/models and python/nodes only', () => { + expect(['sql/models/marts', 'python/nodes/exports', 'sql/models', 'sql/seeds/geo', 'models/marts', 'python/exports'].map(canSelectByPath)).toEqual([true, true, false, false, false, false]); + }); +}); diff --git a/ui/src/lib/project-layout.ts b/ui/src/lib/project-layout.ts new file mode 100644 index 0000000000..4de72368c1 --- /dev/null +++ b/ui/src/lib/project-layout.ts @@ -0,0 +1,47 @@ +// Where a project's files live, and the folders the UI groups nodes by: SQL models by their folder +// below `sql/models/`, other SQL resources by their path below `sql/` (`seeds/…`, `sources/raw`), and +// Python nodes as `python/`. The one place that knows the layout's roots. Pure. + +/** The project folder of everything the warehouse runs. */ +export const SQL_ROOT = 'sql'; +/** The project folder of SQL models; a `path:` selector may start here. */ +export const MODELS_ROOT = 'sql/models'; +/** The project folder of Python nodes; a `path:` selector may start here. */ +export const PYTHON_NODES_ROOT = 'python/nodes'; +/** The folder Python nodes group under. */ +export const PYTHON_FOLDER = 'python'; +/** The folders `sql/` holds besides `models/`, which group by their own name. */ +export const SQL_KIND_FOLDERS = ['seeds', 'sources', 'macros', 'functions', 'enums', 'constants', 'audits', 'hooks', 'schemas'] as const; +/** The roots a `path:` selector accepts; anything else is refused (S012). */ +export const PATH_SELECTOR_ROOTS = [MODELS_ROOT, PYTHON_NODES_ROOT] as const; + +const below = (dir: string, root: string): string | null => (dir === root ? '' : dir.startsWith(`${root}/`) ? dir.slice(root.length + 1) : null); + +/** + * A project directory as the folder the UI groups by: `sql/models/marts/core` is `marts/core` (and + * `sql/models` itself is empty), `sql/seeds/geo` is `seeds/geo`, `python/nodes/exports` is + * `python/exports`. A directory outside the roots stays as it is. + */ +export function folderOfDir(dir: string): string { + const trimmed = dir.replace(/\/+$/, ''); + const model = below(trimmed, MODELS_ROOT); + if (model !== null) return model; + const python = below(trimmed, PYTHON_NODES_ROOT); + if (python !== null) return python ? `${PYTHON_FOLDER}/${python}` : PYTHON_FOLDER; + const sql = below(trimmed, SQL_ROOT); + if (sql) return sql; + return trimmed; +} + +/** The project directory of a folder `folderOfDir` gives: `marts` is `sql/models/marts`, `seeds/geo` is `sql/seeds/geo`, `python/exports` is `python/nodes/exports`. */ +export function dirOfFolder(folder: string): string { + const trimmed = folder.replace(/\/+$/, ''); + const python = below(trimmed, PYTHON_FOLDER); + if (python !== null) return python ? `${PYTHON_NODES_ROOT}/${python}` : PYTHON_NODES_ROOT; + const top = trimmed.split('/')[0]; + if ((SQL_KIND_FOLDERS as readonly string[]).includes(top)) return `${SQL_ROOT}/${trimmed}`; + return trimmed ? `${MODELS_ROOT}/${trimmed}` : MODELS_ROOT; +} + +/** Whether a `path:` selector can name the directory: a folder below one of its roots. */ +export const canSelectByPath = (dir: string) => PATH_SELECTOR_ROOTS.some((root) => dir.startsWith(`${root}/`)); diff --git a/ui/src/lib/run/command.test.ts b/ui/src/lib/run/command.test.ts index fed83b9496..64ea287e8d 100644 --- a/ui/src/lib/run/command.test.ts +++ b/ui/src/lib/run/command.test.ts @@ -5,8 +5,8 @@ import { changedBuildCounts, changedBuildLabel, commandTokens, jobBuildTokens, j const node = (key: string, kind: SnapshotNode['kind'], path: string, tags: string[] = []): SnapshotNode => ({ key, kind, group: '', tags, path, cursor: null, upstream: [] }); const NODES: SnapshotNode[] = [ - node('model:customers', 'table', 'models/marts/customers.sql', ['finance']), - node('seed:countries', 'seed', 'seeds/countries.csv'), + node('model:customers', 'table', 'sql/models/marts/customers.sql', ['finance']), + node('seed:countries', 'seed', 'sql/seeds/countries.csv'), node('source:shop.orders', 'source', 'sources.yml') ]; @@ -21,7 +21,7 @@ describe('the plan page command line', () => { expect(values('sqb build --select countr')).toEqual(['seed:countries']); expect(values('sqb build --select shop.ord')).toEqual(['source:shop.orders']); expect(values('sqb build --select fin')).toEqual(['tag:finance']); - expect(values('sqb build --select marts')).toEqual(['path:models/marts']); + expect(values('sqb build --select marts')).toEqual(['path:sql/models/marts']); }); it('reads --changed as the CLI does: its counts only after =, never the next token', () => { @@ -116,6 +116,12 @@ describe('changed build counts', () => { expect(changedBuildCounts(4, null)).toEqual({ changed: 4, downstream: null, failing: null }); }); + it('keeps the planned count of a plan with models it couldn\'t plan, with them as the tooltip', () => { + const counts = changedBuildCounts(4, { generation: 3, changed: ['model:totals'], downstream: [], failing: "Can't plan 1 model: orders: full_refresh false" }); + expect(counts).toEqual({ changed: 1, downstream: 0, failing: "Can't plan 1 model: orders: full_refresh false" }); + expect(changedBuildLabel(counts.changed, counts.downstream, 'bar', counts.failing).tooltip).toBe("Plan failing: Can't plan 1 model: orders: full_refresh false"); + }); + it('shows no planned count while the location\'s plan is failing, and gives the reason as the tooltip', () => { const counts = changedBuildCounts(4, { generation: 3, changed: [], downstream: [], failing: 'Model orders cannot plan a full rebuild' }); expect(counts).toEqual({ changed: 4, downstream: null, failing: 'Model orders cannot plan a full rebuild' }); diff --git a/ui/src/lib/run/command.ts b/ui/src/lib/run/command.ts index 0c5a36b7c2..326bfcc58f 100644 --- a/ui/src/lib/run/command.ts +++ b/ui/src/lib/run/command.ts @@ -3,6 +3,7 @@ // nodes. The server resolves selectors and refuses flags; nothing here decides // whether a command may run. Pure: no side effects. +import { canSelectByPath } from '$lib/project-layout'; import type { ChangedBuild, CursorWindow, LaunchVerb, RerunMode, SnapshotNode } from '$lib/api'; import { flagSpec, VERBS, type FlagSpec } from './command-table'; import { plural } from '$lib/format/plural'; @@ -108,12 +109,12 @@ export const CHANGED_PLAN_HREF = planHref([], 'build', { flags: { '--changed': t /** * The counts the "Build N changed" button shows: the location's plan of `CHANGED_PLAN_HREF` when it - * names a change, else the nodes whose definitions changed, with the downstream count unknown, and - * why that plan is failing, if it is. + * names a change (a plan with models it couldn't plan still names the rest), else the nodes whose + * definitions changed, with the downstream count unknown, and why that plan is failing, if it is. */ export function changedBuildCounts(definitionChanged: number, build: ChangedBuild | null): { changed: number; downstream: number | null; failing: string | null } { const failing = build?.failing ?? null; - return build?.changed.length && !failing ? { changed: build.changed.length, downstream: build.downstream.length, failing } : { changed: definitionChanged, downstream: null, failing }; + return build?.changed.length ? { changed: build.changed.length, downstream: build.downstream.length, failing } : { changed: definitionChanged, downstream: null, failing }; } /** The "Build N changed" button's main label, its lighter bracketed part (null without one), and its tooltip. */ @@ -232,7 +233,8 @@ function selectorPool(nodes: SnapshotNode[]): { value: string; hint: string }[] const unique = (values: string[]) => [...new Set(values)].sort(); return [ ...unique(nodes.flatMap((n) => n.tags)).map((t) => ({ value: `tag:${t}`, hint: 'tag' })), - ...unique(nodes.filter((n) => n.path.includes('/')).map((n) => n.path.replace(/\/[^/]+$/, ''))).map((p) => ({ value: `path:${p}`, hint: 'folder' })), + // Only folders a `path:` selector accepts, below `sql/models/` or `python/nodes/`. + ...unique(nodes.map((n) => n.path.replace(/\/?[^/]*$/, '')).filter(canSelectByPath)).map((p) => ({ value: `path:${p}`, hint: 'folder' })), ...nodes.map((n) => ({ value: selectorOf(n.key), hint: n.kind })) ]; } diff --git a/ui/src/lib/run/plan-browser.svelte b/ui/src/lib/run/plan-browser.svelte index eea4aabdbf..b1553d584d 100644 --- a/ui/src/lib/run/plan-browser.svelte +++ b/ui/src/lib/run/plan-browser.svelte @@ -255,7 +255,7 @@ // The index under Will run and Won't run, each entry counting nodes once (plan-totals.ts), warnings apart. const counts = $derived(planSectionCounts(plan)); const totals = $derived(planTotals(counts, migrationSteps(plan))); - const WONT_GROUPS = new Set(['held_back', 'skipped']); + const WONT_GROUPS = new Set(['errors', 'window', 'held_back', 'skipped']); const FUNCTION_SECTIONS = new Set(['functions', 'changed_functions']); const runGroups = $derived(groups.filter((g) => !WONT_GROUPS.has(g.key) && g.key !== 'warnings')); const wontGroups = $derived(groups.filter((g) => WONT_GROUPS.has(g.key))); diff --git a/ui/src/lib/run/plan-index.test.ts b/ui/src/lib/run/plan-index.test.ts index 190303c92a..b60bc4237f 100644 --- a/ui/src/lib/run/plan-index.test.ts +++ b/ui/src/lib/run/plan-index.test.ts @@ -130,6 +130,43 @@ describe('the plan index', () => { }); }); +describe('a model that can\'t be planned', () => { + const plan: PlanDocument = { + ...empty, + has_errors: true, + models: [ + model('orders', 'planning_error', { action: 'error', error: { code: 'S203', message: "model 'orders' sets full_refresh false", help: 'allow the rebuild' } }), + model('totals', 'query_changed', { query_diff: [...head, '-select 1', '+select 2'] }) + ] + }; + const groups = planGroups(plan); + + it('is its own group first, with its error, and the rest still plans', () => { + expect(groups.map((g) => [g.key, g.count])).toEqual([ + ['errors', 1], + ['changed', 1] + ]); + expect(groups[0].title).toBe('Planning failed'); + expect(groups[0].rows.map((r) => [r.name, r.action, r.detail, r.notes])).toEqual([['orders', 'error', "error[S203]: model 'orders' sets full_refresh false", ['help: allow the rebuild']]]); + }); +}); + +describe('a model an explicit cursor window skips', () => { + const plan: PlanDocument = { + ...empty, + models: [model('late_feed', 'window_before_cursor_start', { action: 'skip', skip_reason: 'window ends before cursor_start 2021-01-01' }), model('early_feed', 'query_changed', { query_diff: [...head, '-select 1', '+select 2'] })] + }; + + it('is listed with its reason, apart from the models that build', () => { + const groups = planGroups(plan); + expect(groups.map((g) => [g.key, g.count])).toEqual([ + ['window', 1], + ['changed', 1] + ]); + expect(groups[0].rows.map((r) => [r.name, r.action])).toEqual([['late_feed', 'window ends before cursor_start 2021-01-01']]); + }); +}); + describe('an opened diff', () => { it('shows the first changed lines, then says the rest is cut off', () => { const diff = [{ text: '@@', cls: 'hunk' as const }, ...Array.from({ length: 20 }, (_, i) => ({ text: `+${i}`, cls: 'add' as const }))]; diff --git a/ui/src/lib/run/plan-index.ts b/ui/src/lib/run/plan-index.ts index ce24325f0a..80e53ef175 100644 --- a/ui/src/lib/run/plan-index.ts +++ b/ui/src/lib/run/plan-index.ts @@ -6,9 +6,11 @@ import { plural } from '$lib/format/plural'; import { changedSections, loadedRows, looseWarnings, planSections, sectionSize, type PlanEntry, type PlanSection } from './plan-text'; /** The plan's groups in plan order; the index sorts them under Will run and Won't run. */ -export type PlanGroupKey = 'full_refresh' | 'changed' | 'renames' | 'first_run' | 'loads' | 'python' | 'held_back' | 'warnings' | 'unchanged' | 'skipped'; -const ORDER: PlanGroupKey[] = ['full_refresh', 'changed', 'renames', 'first_run', 'loads', 'python', 'held_back', 'warnings', 'unchanged', 'skipped']; +export type PlanGroupKey = 'errors' | 'window' | 'full_refresh' | 'changed' | 'renames' | 'first_run' | 'loads' | 'python' | 'held_back' | 'warnings' | 'unchanged' | 'skipped'; +const ORDER: PlanGroupKey[] = ['errors', 'window', 'full_refresh', 'changed', 'renames', 'first_run', 'loads', 'python', 'held_back', 'warnings', 'unchanged', 'skipped']; const TITLES: Record = { + errors: 'Planning failed', + window: 'Window before cursor_start', full_refresh: 'Full refresh', changed: 'Changed', renames: 'Renames and migrations', @@ -22,6 +24,8 @@ const TITLES: Record = { }; /** Each server section's group in the index. */ const GROUP_OF: Record = { + planning_error: 'errors', + window_before_cursor_start: 'window', full_refresh: 'full_refresh', query_changed: 'changed', function_changed: 'changed', diff --git a/ui/src/lib/run/plan-text.ts b/ui/src/lib/run/plan-text.ts index a89be83222..038dc897e1 100644 --- a/ui/src/lib/run/plan-text.ts +++ b/ui/src/lib/run/plan-text.ts @@ -51,7 +51,7 @@ const keyName = (key: string) => key.slice(key.indexOf(':') + 1); /** The models the run builds: none the planner skips, and under `--changed` only those it runs. */ export function builtModels(plan: PlanDocument): PlanModel[] { - return plan.models.filter((m) => m.action !== 'skip' && runsUnderChanged(plan, `model:${m.name}`)); + return plan.models.filter((m) => !m.error && m.action !== 'skip' && runsUnderChanged(plan, `model:${m.name}`)); } /** Rows of a paged section the plan holds so far, which is the offset of its next page. */ @@ -131,6 +131,7 @@ const SCHEMA_SIGNS: Record = { }; function changedEntry(m: PlanModel, reason: string, windowStart?: string): PlanEntry { + if (m.error) return { name: m.name, value: 'error', detail: [m.error.code ? `error[${m.error.code}]: ${m.error.message}` : m.error.message, ...(m.error.help ? [`help: ${m.error.help}`] : [])] }; if (reason === 'first_run') return { name: m.name, value: materializationLabel(m), detail: cursorLines(m, true, windowStart) }; return { name: m.name, @@ -179,6 +180,8 @@ export function planSections(plan: PlanDocument): PlanSection[] { } const functionEntry = (f: PlanDocument['functions'][number]) => ({ name: f.name, value: f.language, detail: [] }); add('Changed functions', plan.functions.filter((f) => f.reason && f.reason !== 'no_change').map(functionEntry), true, 'changed_functions'); + add('Planning failed', plan.models.filter((m) => m.error).map((m) => changedEntry(m, 'planning_error')), true, 'planning_error'); + add('Window before cursor_start', plan.models.filter((m) => m.skip_reason).map((m) => ({ name: m.name, value: m.skip_reason ?? '', detail: [] })), false, 'window_before_cursor_start'); if (isFullRefresh(plan)) { const counts = new Map(); for (const m of active) counts.set(m.materialization_type, (counts.get(m.materialization_type) ?? 0) + 1); diff --git a/ui/src/lib/run/plan-totals.ts b/ui/src/lib/run/plan-totals.ts index 952d6bb317..a83ced202f 100644 --- a/ui/src/lib/run/plan-totals.ts +++ b/ui/src/lib/run/plan-totals.ts @@ -35,7 +35,7 @@ const RUNS = new Set([ 'python_nodes' ]); /** Sections whose rows are selected nodes the build leaves alone. */ -const WONT = new Set(['held_back', 'unchanged']); +const WONT = new Set(['planning_error', 'window_before_cursor_start', 'held_back', 'unchanged']); /** One part of a total: a label, its nodes, and the plan index group it opens. */ export type TotalPart = { key: string; group: string; label: string; count: number }; @@ -43,7 +43,7 @@ export type TotalPart = { key: string; group: string; label: string; count: numb export type PlanTotals = { /** Nodes the build runs. */ run: number; - /** Selected nodes it doesn't: held back and skipped by `--changed`. */ + /** Selected nodes it doesn't: models it can't plan, held back and skipped by `--changed`. */ wont: number; runParts: TotalPart[]; wontParts: TotalPart[]; @@ -60,6 +60,8 @@ const PARTS: { key: string; group: string; label: string; sections: PlanPageSect { key: 'loads', group: 'loads', label: 'loads', sections: ['loader_reloads', 'loader_loads', 'source_reloads', 'source_loads'] }, { key: 'python', group: 'python', label: 'Python', sections: ['python_nodes'] }, { key: 'unchanged', group: 'unchanged', label: 'unchanged', sections: ['routine_models', 'unchanged_seeds'] }, + { key: 'errors', group: 'errors', label: 'planning failed', sections: ['planning_error'] }, + { key: 'window', group: 'window', label: 'before cursor_start', sections: ['window_before_cursor_start'] }, { key: 'held_back', group: 'held_back', label: 'held back', sections: ['held_back'] }, { key: 'skipped', group: 'skipped', label: 'skipped by --changed', sections: ['unchanged'] } ]; @@ -75,7 +77,7 @@ export function planTotals(counts: PlanSectionCount[], steps: number): PlanTotal const of = (sections: PlanPageSection[]) => counts.filter((c) => sections.includes(c.section)).reduce((n, c) => n + c.total, 0); const sum = (keep: Set) => counts.filter((c) => keep.has(c.section)).reduce((n, c) => n + c.total, 0); const parts = PARTS.map((p) => ({ key: p.key, group: p.group, label: p.label, count: of(p.sections) })).filter((p) => p.count > 0); - const wontKeys = new Set(['held_back', 'skipped']); + const wontKeys = new Set(['errors', 'window', 'held_back', 'skipped']); return { run: sum(RUNS), wont: sum(WONT), diff --git a/ui/src/lib/selection/folders.test.ts b/ui/src/lib/selection/folders.test.ts index 6a08c9aebc..f18e9e7eef 100644 --- a/ui/src/lib/selection/folders.test.ts +++ b/ui/src/lib/selection/folders.test.ts @@ -7,34 +7,34 @@ const node = (key: string, path: string, kind = 'table', group: string | null = describe('folder selections', () => { it('selects a folder by path when it holds exactly the group', () => { const out = folderSelections([ - node('model:orders', 'models/marts/orders.sql'), - node('source:shop', 'models/marts/sources.yml', 'source'), - node('model:stg_a', 'models/staging/shop/stg_a.sql'), - node('model:stg_b', 'models/staging/crm/stg_b.sql') + node('model:orders', 'sql/models/marts/orders.sql'), + node('source:shop', 'sql/models/marts/sources.yml', 'source'), + node('model:stg_a', 'sql/models/staging/shop/stg_a.sql'), + node('model:stg_b', 'sql/models/staging/crm/stg_b.sql') ]); // A source in the folder isn't counted, so its path would select more: the nodes are named instead. expect(out.get('marts')).toBe('orders'); - expect(out.get('staging')).toBe('path:models/staging'); + expect(out.get('staging')).toBe('path:sql/models/staging'); }); it('names the nodes of a group no folder stands for', () => { - const out = folderSelections([node('seed:codes', 'seeds/codes.csv', 'seed'), node('model:top', 'models/top.sql'), node('model:orders', 'models/marts/orders.sql')]); + const out = folderSelections([node('seed:codes', 'sql/seeds/codes.csv', 'seed'), node('model:top', 'sql/models/top.sql'), node('model:orders', 'sql/models/marts/orders.sql')]); expect(out.get('seeds')).toBe('codes'); expect(out.get('models')).toBe('top'); }); it('names the nodes of a folder outside models/ and python/, which a path selector rejects', () => { - const out = folderSelections([node('seed:codes', 'seeds/lookups/codes.csv', 'seed'), node('seed:regions', 'seeds/lookups/regions.csv', 'seed')]); + const out = folderSelections([node('seed:codes', 'sql/seeds/lookups/codes.csv', 'seed'), node('seed:regions', 'sql/seeds/lookups/regions.csv', 'seed')]); expect(out.get('seeds')).toBe('codes regions'); }); it('names the nodes when another group shares the folder', () => { - const out = folderSelections([node('model:orders', 'models/marts/orders.sql'), node('model:legacy', 'models/marts/legacy.sql', 'table', 'archive')]); + const out = folderSelections([node('model:orders', 'sql/models/marts/orders.sql'), node('model:legacy', 'sql/models/marts/legacy.sql', 'table', 'archive')]); expect(out.get('marts')).toBe('orders'); expect(out.get('archive')).toBe('legacy'); }); it('links to the catalog with the selection', () => { - expect(folderCatalogHref('path:models/marts')).toBe('/catalog?select=path%3Amodels%2Fmarts'); + expect(folderCatalogHref('path:sql/models/marts')).toBe('/catalog?select=path%3Asql%2Fmodels%2Fmarts'); }); }); diff --git a/ui/src/lib/selection/folders.ts b/ui/src/lib/selection/folders.ts index ac3306f1d6..e4ca551086 100644 --- a/ui/src/lib/selection/folders.ts +++ b/ui/src/lib/selection/folders.ts @@ -4,13 +4,10 @@ import type { CatalogNode } from '$lib/api'; import { shortName } from '$lib/build-area/labels'; import { topFolder } from '$lib/lineage/catalog-graph'; +import { canSelectByPath } from '$lib/project-layout'; const dirOf = (path: string) => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''); -/** The project folders a `path:` selector can start at; any other, such as `seeds/`, is an error (S012). */ -const PATH_ROOTS = ['models', 'python']; -export const canSelectByPath = (dir: string) => PATH_ROOTS.some((root) => dir.startsWith(`${root}/`)); - /** * Of `dirs`, those a `path:` selector would over-select: a node sits somewhere under one but doesn't * `belong` to it, such as another group's node, or a source declared in a .yml file there. One pass @@ -57,7 +54,7 @@ export function folderSelections(nodes: readonly CatalogNode[]): Map(); for (const [g, list] of groups) { const dir = commonDir(list.map((n) => dirOf(n.path))); - // A bare root such as `models` holds every model; it never stands for one group. Nor can a folder + // A bare root such as `sql/models` holds every model; it never stands for one group. Nor can a folder // outside the roots a path selector accepts. if (!canSelectByPath(dir) || groupAt.has(dir)) continue; folderOf.set(g, dir); diff --git a/ui/src/lib/state/catalog-feed.test.ts b/ui/src/lib/state/catalog-feed.test.ts index b56dd2354d..69165eb856 100644 --- a/ui/src/lib/state/catalog-feed.test.ts +++ b/ui/src/lib/state/catalog-feed.test.ts @@ -21,13 +21,17 @@ function node(key: string, upstream: string[] = []): CatalogNode { lastOutcome: 'success', stale: [], sourceFreshness: null, - checks: null + checks: null, + status: 'current', + statusAt: '2026-01-01T00:00:00.000Z' }; } const failed = (runId: string): NodeState => ({ lastBuild: { fingerprintRunId: runId, runId: null, jobKey: null, builtAt: '2026-01-02T00:00:00.000Z', fingerprint: 'g' }, lastOutcome: 'failed', + status: 'failed', + statusAt: '2026-01-02T00:00:00.000Z', definitionChanged: false, checks: null }); diff --git a/ui/src/lib/state/selection.svelte.ts b/ui/src/lib/state/selection.svelte.ts index 06576028f9..f9d6b7619d 100644 --- a/ui/src/lib/state/selection.svelte.ts +++ b/ui/src/lib/state/selection.svelte.ts @@ -80,6 +80,9 @@ export function createSelection(options: { url?: boolean; follow?: boolean; init let vocabulary = $state.raw(null); let recent = $state.raw(readRecent()); let asked = 0; + /** The query of a link `navigate` is taking: the URL effect leaves it to that one navigation. */ + let following: string | null = null; + let followed = 0; const active = $derived(!!(select.trim() || exclude.trim())); /** The selected nodes' names, without their `kind:`, for lists that name nodes only by name. */ @@ -164,7 +167,7 @@ export function createSelection(options: { url?: boolean; follow?: boolean; init $effect(() => { const params = writeSelectionParams(page.url.searchParams, { select, exclude }); for (const old of options.replaces ?? []) params.delete(old); - if (params.toString() === page.url.searchParams.toString()) return; + if (params.toString() === page.url.searchParams.toString() || params.toString() === following) return; const url = new URL(page.url); url.search = params.toString(); void goto(url, { replaceState: true, noScroll: true, keepFocus: true }); @@ -184,6 +187,20 @@ export function createSelection(options: { url?: boolean; follow?: boolean; init set exclude(v: string) { exclude = v; }, + /** + * Takes a link in place: the selection changes now, and the URL follows as one new history + * entry, so Back goes up again. Nothing replaces that entry while it is being made. + */ + navigate(url: URL) { + const linked = readSelectionParams(url.searchParams); + const ticket = ++followed; + following = url.searchParams.toString(); + select = linked.select; + exclude = linked.exclude; + void goto(url, { noScroll: true, keepFocus: true }).finally(() => { + if (ticket === followed) following = null; + }); + }, /** Whether anything is selected or excepted; otherwise every node is in. */ get active() { return active; diff --git a/ui/src/routes/catalog/+page.svelte b/ui/src/routes/catalog/+page.svelte index dcf94d62ee..9adaa664ef 100644 --- a/ui/src/routes/catalog/+page.svelte +++ b/ui/src/routes/catalog/+page.svelte @@ -29,7 +29,7 @@ import DataTable from '$lib/components/list/data-table.svelte'; import type { TableColumn } from '$lib/components/list/table-columns'; import { formatAgo, formatStamp } from '$lib/format/time'; - import { nodeOutcomeLabel, nodeOutcomeTone } from '$lib/status'; + import { statusLabel } from '$lib/build-area/node-status'; import { KIND_TABS, kindLine, kindTabLabel, kindTabOf, nodeIcon, nodeIconKey, parseKindTab, shortName, shortRunId, type KindTab } from '$lib/build-area/labels'; type StatusFilter = 'stale' | 'changed' | 'behind' | 'failed' | 'warn'; @@ -81,10 +81,10 @@ } const matchesStatus = (n: CatalogNode, f: StatusFilter) => - (f === 'stale' && !!n.stale?.length) || - (f === 'changed' && !!n.stale?.some((s) => s.reason !== 'behind')) || - (f === 'behind' && !!n.stale?.some((s) => s.reason === 'behind')) || - (f === 'failed' && n.lastOutcome === 'failed') || + (f === 'stale' && (n.status === 'changed' || n.status === 'behind')) || + (f === 'changed' && n.status === 'changed') || + (f === 'behind' && n.status === 'behind') || + (f === 'failed' && n.status === 'failed') || (f === 'warn' && n.lastOutcome === 'warn'); const kinds = $derived(KIND_TABS.filter((k) => all.some((n) => kindTabOf(n.kind) === k))); @@ -107,7 +107,7 @@ ); const counts = $derived({ - failed: all.filter((n) => n.lastOutcome === 'failed').length, + failed: all.filter((n) => n.status === 'failed').length, warn: all.filter((n) => n.lastOutcome === 'warn').length, changed: all.filter((n) => matchesStatus(n, 'changed')).length, behind: all.filter((n) => matchesStatus(n, 'behind')).length @@ -190,9 +190,10 @@ {#if n.kind === 'source'} {#if n.sourceFreshness} {:else}External{/if} - {:else if n.lastOutcome} - - {:else}Not built{/if} + {:else if statusLabel(n)} + {@const s = statusLabel(n)!} + + {:else}—{/if} {/if} @@ -206,6 +207,9 @@ {:else if n.lastBuild} + {:else if n.statusAt} + + {:else}Never{/if} diff --git a/ui/src/routes/catalog/[name]/node-view.svelte b/ui/src/routes/catalog/[name]/node-view.svelte index 5ff98d9394..b8e4a9f0aa 100644 --- a/ui/src/routes/catalog/[name]/node-view.svelte +++ b/ui/src/routes/catalog/[name]/node-view.svelte @@ -22,7 +22,7 @@ import { useChecks } from '$lib/state/checks.svelte'; import { untrack } from 'svelte'; import { formatAgo } from '$lib/format/time'; - import { nodeOutcomeLabel, nodeOutcomeTone } from '$lib/status'; + import { statusLabel } from '$lib/build-area/node-status'; import { kindLine, kindTabLabel, kindTabOf, nodeIcon, nodeIconKey, shortName, sqlVersions } from '$lib/build-area/labels'; import { cardData } from '$lib/lineage/catalog-graph'; import OverviewTab from './overview-tab.svelte'; @@ -127,10 +127,9 @@ {#if n} {#if n.kind === 'source'} - {:else if n.lastOutcome} - - {:else if !n.lastBuild} - + {:else if statusLabel(n)} + {@const s = statusLabel(n)!} + {/if} {/if} @@ -142,7 +141,7 @@
{kindLine(n)}{#if n.group}{n.group}{/if} {#if n.kind === 'source'}{n.sourceFreshness?.loadedAt ? `Loaded ${formatAgo(n.sourceFreshness.loadedAt, app.now)}` : 'No freshness data'} - {:else}{n.lastBuild ? `Last built ${formatAgo(n.lastBuild.builtAt, app.now)}` : 'Never built'}{/if} + {:else}{n.statusAt ? `Last built ${formatAgo(n.statusAt, app.now)}` : 'Never built'}{/if}
{/if}
({ value, label }))} onselect={setTab} />
diff --git a/ui/src/routes/catalog/[name]/overview-tab.svelte b/ui/src/routes/catalog/[name]/overview-tab.svelte index f73020d12d..e49107da67 100644 --- a/ui/src/routes/catalog/[name]/overview-tab.svelte +++ b/ui/src/routes/catalog/[name]/overview-tab.svelte @@ -11,6 +11,7 @@ import { app } from '$lib/state/app.svelte'; import { formatAgo, formatStamp } from '$lib/format/time'; import { checkOutcomeLabel, checkOutcomeTone, nodeOutcomeTone, staleReasonDetail, staleReasonLabel } from '$lib/status'; + import { statusLabel } from '$lib/build-area/node-status'; import { formatCredits, formatMs, formatNumber, kindLine, relationName, runScopePhaseHelp, runScopePhaseLabel, shortName } from '$lib/build-area/labels'; import { driftLabel, driftOf, type Tab } from './utils'; @@ -46,7 +47,7 @@ {:else}
- {#if node.lastOutcome}{:else if !node.lastBuild}{/if} + {#if statusLabel(node)}{@const s = statusLabel(node)!}{/if} Last built:
diff --git a/ui/src/routes/cost/cost-view.svelte b/ui/src/routes/cost/cost-view.svelte index 9b02e4da62..412fb6a73b 100644 --- a/ui/src/routes/cost/cost-view.svelte +++ b/ui/src/routes/cost/cost-view.svelte @@ -1,5 +1,5 @@