From 8aff17899a57610acbc151472d4a443a667f7ba0 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:28:08 +0000 Subject: [PATCH] fix(server): a read stopped at the statement limit fails alone, not as a control database outage A statement PostgreSQL cancels at its statement limit inside a read transaction is that read's own error: it answers 504 and is logged by request, and is no longer kept as a cut-off session that marks the whole control database failing. Writes, idle cut-offs and the health probe's own read are reported as before. The run page's Statements tab shows the error in place and keeps the last list it loaded. --- .../src/api/_helpers/resources/request_ids.rs | 9 +++++-- .../sqlbuild-orchestration/src/api/errors.rs | 9 +++++++ .../src/health/_helpers/session_cut_offs.rs | 12 ++++----- .../src/health/main/control_cause.rs | 4 ++- .../src/health/main/log_read_timeout.rs | 8 ++++++ .../src/health/main/mod.rs | 1 + .../src/health/main/probe_control_database.rs | 10 +++++-- .../src/store/errors.rs | 14 ++++++++++ .../src/store/main/query.rs | 20 ++++++++++---- .../tests/health/helpers.rs | 8 ++++++ .../tests/health/test_responses.rs | 10 ++++++- .../tests/store/session_limits/helpers.rs | 6 ++--- .../session_limits/test_session_limits.rs | 27 +++++++++++++++++-- .../tests/store/session_limits/test_types.rs | 4 +-- fensu.toml | 6 +++++ ui/e2e/group-run.spec.ts | 19 +++++++++++++ ui/src/routes/runs/[id]/run-tabs.svelte | 4 +++ 17 files changed, 147 insertions(+), 24 deletions(-) create mode 100644 crates/sqlbuild-orchestration/src/health/main/log_read_timeout.rs diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_ids.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_ids.rs index ad2de09da1..e113cbc290 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_ids.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_ids.rs @@ -2,7 +2,7 @@ use axum::body::Body; use axum::extract::{Request, State}; -use axum::http::{HeaderValue, header}; +use axum::http::{HeaderValue, StatusCode, header}; use axum::middleware::Next; use axum::response::Response; use chrono::Utc; @@ -11,9 +11,10 @@ use uuid::Uuid; use crate::api::constants::REQUEST_ID_HEADER; use crate::api::models::{ErrorCause, ErrorReply, RequestId}; use crate::health::main::log_cause::log_cause; +use crate::health::main::log_read_timeout::log_read_timeout; use crate::health::models::ServerHealth; -/// Name every request in `x-request-id`; an error the control database's unavailability caused also names it, its cause and since when in the body, and is recorded and logged. +/// Name every request in `x-request-id`; an error the control database's unavailability caused also names it, its cause and since when in the body, and is recorded and logged. A read stopped at the statement limit is logged by what it read. pub(crate) async fn identify_request( State(health): State, mut request: Request, @@ -21,10 +22,14 @@ pub(crate) async fn identify_request( ) -> Response { let request_id: Uuid = Uuid::now_v7(); request.extensions_mut().insert(RequestId(request_id)); + let read = format!("{} {}", request.method(), request.uri().path()); let mut response = next.run(request).await; if let Ok(value) = HeaderValue::from_str(&request_id.to_string()) { response.headers_mut().insert(REQUEST_ID_HEADER, value); } + if response.status() == StatusCode::GATEWAY_TIMEOUT { + log_read_timeout(request_id, &read); + } let Some(ErrorReply { mut body, cause: Some(cause), diff --git a/crates/sqlbuild-orchestration/src/api/errors.rs b/crates/sqlbuild-orchestration/src/api/errors.rs index 7ac9f66785..4d045877d8 100644 --- a/crates/sqlbuild-orchestration/src/api/errors.rs +++ b/crates/sqlbuild-orchestration/src/api/errors.rs @@ -8,6 +8,7 @@ use uuid::Uuid; use crate::api::models::{ApiErrorBody, ErrorReply}; use crate::health::main::control_cause::control_cause; use crate::health::models::{ControlCause, ControlTarget}; +use crate::store::constants::STATEMENT_TIMEOUT; use crate::store::errors::ControlError; #[derive(Debug, thiserror::Error)] @@ -57,6 +58,14 @@ impl From for ApiError { }; match error { ControlError::Invalid(message) => plain(StatusCode::BAD_REQUEST, message, None), + ControlError::ReadTimedOut(_) => plain( + StatusCode::GATEWAY_TIMEOUT, + format!( + "This read ran past the control database's {}-minute limit and was stopped", + STATEMENT_TIMEOUT.as_secs() / 60 + ), + None, + ), ControlError::NotCheckingIn(message) => plain(StatusCode::CONFLICT, message, None), ControlError::Denied { reason, diff --git a/crates/sqlbuild-orchestration/src/health/_helpers/session_cut_offs.rs b/crates/sqlbuild-orchestration/src/health/_helpers/session_cut_offs.rs index 1737b28432..16234abc2b 100644 --- a/crates/sqlbuild-orchestration/src/health/_helpers/session_cut_offs.rs +++ b/crates/sqlbuild-orchestration/src/health/_helpers/session_cut_offs.rs @@ -5,7 +5,8 @@ use std::sync::PoisonError; use chrono::Utc; use crate::health::models::{SessionCutOff, SessionCutOffs}; -use crate::store::constants::{IDLE_IN_TRANSACTION_CODE, PENDING_CUT_OFFS, QUERY_CANCELED_CODE}; +use crate::store::constants::{IDLE_IN_TRANSACTION_CODE, PENDING_CUT_OFFS}; +use crate::store::errors::ControlError; use crate::store::models::ControlStore; /// This process's cut-off sessions, for every store it opens, told apart by database. @@ -67,14 +68,13 @@ pub(crate) fn restore( /// Whether PostgreSQL cut the session off: `Some(true)` for a transaction left idle, `Some(false)` for a statement past its timeout. fn cut_off(error: &sqlx_core::Error) -> Option { + if ControlError::statement_timed_out(error) { + return Some(false); + } let sqlx_core::Error::Database(error) = error else { return None; }; - match error.code()?.as_ref() { - IDLE_IN_TRANSACTION_CODE => Some(true), - QUERY_CANCELED_CODE if error.message().contains("statement timeout") => Some(false), - _ => None, - } + (error.code()?.as_ref() == IDLE_IN_TRANSACTION_CODE).then_some(true) } /// Which database a store is: its PostgreSQL host, port and database, or its SQLite file. diff --git a/crates/sqlbuild-orchestration/src/health/main/control_cause.rs b/crates/sqlbuild-orchestration/src/health/main/control_cause.rs index 652065ab77..42b90f4361 100644 --- a/crates/sqlbuild-orchestration/src/health/main/control_cause.rs +++ b/crates/sqlbuild-orchestration/src/health/main/control_cause.rs @@ -12,7 +12,9 @@ pub fn control_cause( (target, pool_full): (&ControlTarget, bool), ) -> Option { let (case, chain): (ControlCauseCase, Vec) = match error { - ControlError::Database(error) => (database_case(error, pool_full), database_chain(error)), + ControlError::Database(error) | ControlError::ReadTimedOut(error) => { + (database_case(error, pool_full), database_chain(error)) + } ControlError::Sqlite(error) => (sqlite_case(error), chain(error)), ControlError::Worker(error) => (ControlCauseCase::Other, chain(error)), ControlError::Io(error) => (ControlCauseCase::Other, chain(error)), diff --git a/crates/sqlbuild-orchestration/src/health/main/log_read_timeout.rs b/crates/sqlbuild-orchestration/src/health/main/log_read_timeout.rs new file mode 100644 index 0000000000..dec50ef920 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/main/log_read_timeout.rs @@ -0,0 +1,8 @@ +//! Write a read the control database stopped at its statement limit to the server log, by the request and what it read. + +/// One log line for a read the control database stopped at its statement limit, naming the request and what it read. +pub(crate) fn log_read_timeout(request_id: uuid::Uuid, read: &str) { + eprintln!( + "A read ran past the control database's statement limit and was stopped (request {request_id}): {read}" + ); +} diff --git a/crates/sqlbuild-orchestration/src/health/main/mod.rs b/crates/sqlbuild-orchestration/src/health/main/mod.rs index 7cb55016ff..8801b47c48 100644 --- a/crates/sqlbuild-orchestration/src/health/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/health/main/mod.rs @@ -3,6 +3,7 @@ pub mod control_target; pub mod failing_forwarding; pub mod health_report; pub mod log_cause; +pub(crate) mod log_read_timeout; pub(crate) mod note_session_cut_off; pub mod probe_control_database; pub mod read_health_details; diff --git a/crates/sqlbuild-orchestration/src/health/main/probe_control_database.rs b/crates/sqlbuild-orchestration/src/health/main/probe_control_database.rs index 73870c9e0a..eb468e9abb 100644 --- a/crates/sqlbuild-orchestration/src/health/main/probe_control_database.rs +++ b/crates/sqlbuild-orchestration/src/health/main/probe_control_database.rs @@ -7,6 +7,7 @@ use tokio::sync::watch; use crate::health::constants::HEALTH_PROBE_INTERVAL; use crate::health::main::control_cause::control_cause; use crate::health::main::log_cause::log_cause; +use crate::health::main::note_session_cut_off::note_session_cut_off; use crate::health::models::{ServerHealth, StoredLocationReport}; use crate::store::errors::ControlError; use crate::store::main::query_records::query_records; @@ -59,7 +60,7 @@ pub async fn probe_control_database( } } -/// Every active location with its instances' newest report. +/// Every active location with its instances' newest report. Unlike a page's read, the probe's own small read stopped at the statement limit says the database is struggling, so it is kept as a cut-off session for the next round to report. async fn active_locations(store: &ControlStore) -> Result, ControlError> { let transaction = begin(store, TransactionMode::Read).await?; let (transaction, locations) = query_records( @@ -69,7 +70,12 @@ async fn active_locations(store: &ControlStore) -> Result bool { + let sqlx_core::Error::Database(error) = error else { + return false; + }; + error.code().as_deref() == Some(QUERY_CANCELED_CODE) + && error.message().contains("statement timeout") + } + pub(crate) fn transient_database(error: &sqlx_core::Error) -> bool { match error { sqlx_core::Error::Io(_) diff --git a/crates/sqlbuild-orchestration/src/store/main/query.rs b/crates/sqlbuild-orchestration/src/store/main/query.rs index 52234db6ae..293185cbee 100644 --- a/crates/sqlbuild-orchestration/src/store/main/query.rs +++ b/crates/sqlbuild-orchestration/src/store/main/query.rs @@ -3,9 +3,10 @@ use crate::health::main::note_session_cut_off::note_session_cut_off; use crate::store::_helpers::database::{postgres_query, sqlite_query}; use crate::store::errors::ControlError; -use crate::store::models::{Connection, ControlTransaction, Parameter}; +use crate::store::models::{Connection, ControlTransaction, Parameter, TransactionMode}; use crate::store::types::Row; +/// Runs `sql` in `transaction`. A read PostgreSQL stopped at its statement limit is that read's own failure, `ReadTimedOut`: the database answered, so its health stands. Any other cut-off session is kept for the health probe. pub(crate) async fn query( mut transaction: ControlTransaction, sql: &str, @@ -29,10 +30,19 @@ pub(crate) async fn query( result? } Connection::Postgres(mut connection) => { - let result = postgres_query(&mut connection, sql, parameters).await; - if let Err(ControlError::Database(error)) = &result { - note_session_cut_off(&transaction.store, error); - } + let result = match postgres_query(&mut connection, sql, parameters).await { + Err(ControlError::Database(error)) + if transaction.mode == TransactionMode::Read + && ControlError::statement_timed_out(&error) => + { + Err(ControlError::ReadTimedOut(error)) + } + Err(ControlError::Database(error)) => { + note_session_cut_off(&transaction.store, &error); + Err(ControlError::Database(error)) + } + other => other, + }; transaction.connection = Some(Connection::Postgres(connection)); result? } diff --git a/crates/sqlbuild-orchestration/tests/health/helpers.rs b/crates/sqlbuild-orchestration/tests/health/helpers.rs index 96506327c4..1575624b81 100644 --- a/crates/sqlbuild-orchestration/tests/health/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/health/helpers.rs @@ -20,6 +20,14 @@ pub(crate) fn coded(code: &'static str, message: &'static str) -> ControlError { }))) } +/// A read PostgreSQL stopped at its statement limit, as `query` returns it. +pub(crate) fn read_timed_out() -> ControlError { + ControlError::ReadTimedOut(sqlx_core::Error::Database(Box::new(CodedError { + code: "57014", + message: "canceling statement due to statement timeout", + }))) +} + pub(crate) fn io(kind: std::io::ErrorKind, message: &'static str) -> ControlError { ControlError::Database(sqlx_core::Error::Io(std::io::Error::new(kind, message))) } diff --git a/crates/sqlbuild-orchestration/tests/health/test_responses.rs b/crates/sqlbuild-orchestration/tests/health/test_responses.rs index eeffa92a87..3be9da83a0 100644 --- a/crates/sqlbuild-orchestration/tests/health/test_responses.rs +++ b/crates/sqlbuild-orchestration/tests/health/test_responses.rs @@ -8,7 +8,7 @@ use crate::api::_helpers::resources::request_ids::identify_request; use crate::api::errors::ApiError; use crate::health::_helpers::details::health_details; use crate::health::models::{ControlCauseCase, ServerHealth}; -use crate::health::tests::helpers::{coded, io, sqlite_busy, target}; +use crate::health::tests::helpers::{coded, io, read_timed_out, sqlite_busy, target}; use crate::health::tests::test_types::CauseResponseTestCase; use crate::store::errors::ControlError; use crate::store::tests::store_helpers::run; @@ -116,6 +116,14 @@ fn given_each_control_database_failure_when_a_request_meets_it_then_the_response expected_case: None, expected_unavailable: false, }, + CauseResponseTestCase { + description: "a read stopped at the statement limit fails alone, leaving health untouched", + error: read_timed_out, + expected_status: 504, + expected_message: "This read ran past the control database's 5-minute limit and was stopped", + expected_case: None, + expected_unavailable: false, + }, CauseResponseTestCase { description: "an unknown transient error keeps its own message", error: || ControlError::Database(sqlx_core::Error::WorkerCrashed), diff --git a/crates/sqlbuild-orchestration/tests/store/session_limits/helpers.rs b/crates/sqlbuild-orchestration/tests/store/session_limits/helpers.rs index 22ce7aeb0f..107c277f38 100644 --- a/crates/sqlbuild-orchestration/tests/store/session_limits/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/store/session_limits/helpers.rs @@ -37,16 +37,16 @@ pub(super) async fn session_limits(mode: TransactionMode) -> Option<(String, Str )) } -/// Run `session`'s statements, lowering a limit, pausing, then running one PostgreSQL cuts off, and report the cut-off as the health probe does. +/// Run `session`'s statements in a transaction of its mode, lowering a limit, pausing, then running one PostgreSQL cuts off, and report the cut-off as the health probe does. pub(super) async fn cut_off_session( - (limit, pause_ms, statement): (&str, u64, &str), + (mode, limit, pause_ms, statement): (TransactionMode, &str, u64, &str), ) -> Option { let test_store = open_test_store(Backend::Postgres).await?; let store = &test_store.store; migrate_store(store).await.expect("migrate"); let health = ServerHealth::new("test", false); health.attach_store(store); - let transaction = begin(store, TransactionMode::Read).await.expect("begin"); + let transaction = begin(store, mode).await.expect("begin"); let (transaction, _) = query(transaction, limit, Vec::new()) .await .expect("lower the limit"); diff --git a/crates/sqlbuild-orchestration/tests/store/session_limits/test_session_limits.rs b/crates/sqlbuild-orchestration/tests/store/session_limits/test_session_limits.rs index 1ddd91c4fa..f829104878 100644 --- a/crates/sqlbuild-orchestration/tests/store/session_limits/test_session_limits.rs +++ b/crates/sqlbuild-orchestration/tests/store/session_limits/test_session_limits.rs @@ -50,6 +50,7 @@ fn given_a_session_past_its_limit_when_postgres_cuts_it_off_then_health_and_a_pl CutOffTestCase { description: "a transaction left idle past its limit", session: ( + TransactionMode::Read, "SET LOCAL idle_in_transaction_session_timeout = 300", 1500, "SELECT 1 AS one", @@ -62,8 +63,13 @@ fn given_a_session_past_its_limit_when_postgres_cuts_it_off_then_health_and_a_pl }, }, CutOffTestCase { - description: "a statement that ran past its limit", - session: ("SET LOCAL statement_timeout = 300", 0, "SELECT pg_sleep(3)"), + description: "a write statement that ran past its limit", + session: ( + TransactionMode::Write, + "SET LOCAL statement_timeout = 300", + 0, + "SELECT pg_sleep(3)", + ), expected_report: CutOffReport { cause: Some(ControlCauseCase::SessionCutOff), reported: true, @@ -71,6 +77,23 @@ fn given_a_session_past_its_limit_when_postgres_cuts_it_off_then_health_and_a_pl events: vec![false], }, }, + // A slow read, such as a page's list of a large run's statements, fails on its own: the + // database answered, so the control database stays healthy and no outage is recorded. + CutOffTestCase { + description: "a read statement that ran past its limit", + session: ( + TransactionMode::Read, + "SET LOCAL statement_timeout = 300", + 0, + "SELECT pg_sleep(3)", + ), + expected_report: CutOffReport { + cause: Some(ControlCauseCase::SessionCutOff), + reported: false, + health: None, + events: vec![], + }, + }, ]; for test_case in test_cases { let Some(observed) = run(cut_off_session(test_case.session)) else { diff --git a/crates/sqlbuild-orchestration/tests/store/session_limits/test_types.rs b/crates/sqlbuild-orchestration/tests/store/session_limits/test_types.rs index 7caee6cfdb..175cb18da7 100644 --- a/crates/sqlbuild-orchestration/tests/store/session_limits/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/store/session_limits/test_types.rs @@ -14,8 +14,8 @@ pub(super) struct SessionLimitTestCase { #[derive(Debug)] pub(super) struct CutOffTestCase { pub(super) description: &'static str, - /// The statement that lowers one limit for the transaction, the pause after it, and the statement PostgreSQL cuts off. - pub(super) session: (&'static str, u64, &'static str), + /// The transaction's mode, the statement that lowers one limit for it, the pause after it, and the statement PostgreSQL cuts off. + pub(super) session: (TransactionMode, &'static str, u64, &'static str), pub(super) expected_report: CutOffReport, } diff --git a/fensu.toml b/fensu.toml index b6f8250cda..9e56fe6eb7 100644 --- a/fensu.toml +++ b/fensu.toml @@ -2083,6 +2083,12 @@ path = "crates/sqlbuild-orchestration/src/health/main/log_cause.rs" symbols = ["log_cause"] reason = "The server log is where operators find a control database failure: the request it failed, the sentence the API returned, and each cause's own message, never a password or stack trace. Requests and the health probe that meet the failure have no caller to return it to beyond the response." +[[targets.rust.rule_exceptions]] +rule = "FPRSH011" +path = "crates/sqlbuild-orchestration/src/health/main/log_read_timeout.rs" +symbols = ["log_read_timeout"] +reason = "A read the control database stopped at its statement limit fails only that request, so health stays healthy; the server log is where operators still see which request and what it read. The request has no caller to return it to beyond its 504 response." + [[targets.rust.rule_exceptions]] rule = "FPRSS130" path = "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/audit_repeats.rs" diff --git a/ui/e2e/group-run.spec.ts b/ui/e2e/group-run.spec.ts index f222a75b8d..3fb909cfde 100644 --- a/ui/e2e/group-run.spec.ts +++ b/ui/e2e/group-run.spec.ts @@ -457,6 +457,25 @@ test('a 3,000-node group run draws only the rows in view, collapsed or with ever expect(Math.max(0, ...(await longTasks(page)))).toBeLessThan(500); }); +test("a statement list read the control database stopped at its limit fails in the Statements tab alone, and the Runs page still loads", async ({ page }) => { + const { fake, run } = server(['load_orders', 'orders_mart']); + await fake.install(page); + // As the server answers a read PostgreSQL cancelled at its statement limit: that read's failure, not an outage. + const stopped = "This read ran past the control database's 5-minute limit and was stopped"; + await page.route('**/statements**', (route) => route.fulfill({ status: 504, contentType: 'application/json', body: JSON.stringify({ error: stopped }) })); + await page.goto(`/runs/${run.id}`); + await page.getByRole('tab', { name: /^Statements/ }).click({ timeout: 20_000 }); + await expect(page.getByTestId('statements-error')).toContainText(stopped); + await expect(page.getByTestId('outage')).toHaveCount(0); + await expect(page.getByTestId('run-tree')).toBeVisible(); + + // Within the same page load, as a person carries on after the failed read. + await page.getByRole('link', { name: /^Runs/ }).first().click(); + await expect(page).toHaveURL(/\/runs$/); + await expect(page.getByText(GROUP).first()).toBeVisible(); + await expect(page.getByTestId('outage')).toHaveCount(0); +}); + test("a group run's page reads only the event types it shows, for the group and every member", async ({ page }) => { const { fake, run } = server(['load_orders', 'stage_orders', 'orders_mart']); await fake.install(page); diff --git a/ui/src/routes/runs/[id]/run-tabs.svelte b/ui/src/routes/runs/[id]/run-tabs.svelte index ef2f5820ef..dd2d2f564e 100644 --- a/ui/src/routes/runs/[id]/run-tabs.svelte +++ b/ui/src/routes/runs/[id]/run-tabs.svelte @@ -195,6 +195,10 @@
{#if view.tab === 'statements'} + {#if view.statementsRes.error} + +

Couldn't load the statement list{view.statements.length ? '; showing the last one loaded' : ''}: {view.statementsRes.error}

+ {/if} {:else if view.tab === 'cost'} {#if view.cost}