Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -11,20 +11,25 @@ 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<ServerHealth>,
mut request: Request,
next: Next,
) -> 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),
Expand Down
9 changes: 9 additions & 0 deletions crates/sqlbuild-orchestration/src/api/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -57,6 +58,14 @@ impl From<ControlError> 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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<bool> {
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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ pub fn control_cause(
(target, pool_full): (&ControlTarget, bool),
) -> Option<ControlCause> {
let (case, chain): (ControlCauseCase, Vec<String>) = 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)),
Expand Down
Original file line number Diff line number Diff line change
@@ -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}"
);
}
1 change: 1 addition & 0 deletions crates/sqlbuild-orchestration/src/health/main/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Vec<StoredLocationReport>, ControlError> {
let transaction = begin(store, TransactionMode::Read).await?;
let (transaction, locations) = query_records(
Expand All @@ -69,7 +70,12 @@ async fn active_locations(store: &ControlStore) -> Result<Vec<StoredLocationRepo
FROM sqb_locations l WHERE l.archived_at IS NULL ORDER BY l.name",
Vec::new(),
)
.await?;
.await
.inspect_err(|error| {
if let ControlError::ReadTimedOut(error) = error {
note_session_cut_off(store, error);
}
})?;
commit(transaction).await?;
Ok(locations)
}
14 changes: 14 additions & 0 deletions crates/sqlbuild-orchestration/src/store/errors.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
//! Control-store failures; callers must not publish a successful state after one.

use crate::store::constants::QUERY_CANCELED_CODE;

/// A rejected control-plane operation or failed durable write.
#[derive(Debug, thiserror::Error)]
pub enum ControlError {
#[error("control store: {0}")]
Database(#[from] sqlx_core::Error),
#[error("control store: {0}")]
Sqlite(#[from] rusqlite::Error),
/// A read ran past PostgreSQL's statement limit and was cancelled: that read's own failure, which leaves the control database's health alone.
#[error("control store read ran past its time limit: {0}")]
ReadTimedOut(sqlx_core::Error),
#[error("control-store worker failed: {0}")]
Worker(#[from] tokio::task::JoinError),
#[error("control-store filesystem: {0}")]
Expand Down Expand Up @@ -93,6 +98,15 @@ impl ControlError {
}
}

/// Whether PostgreSQL cancelled the statement for running past its statement limit.
pub(crate) fn statement_timed_out(error: &sqlx_core::Error) -> 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(_)
Expand Down
20 changes: 15 additions & 5 deletions crates/sqlbuild-orchestration/src/store/main/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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?
}
Expand Down
8 changes: 8 additions & 0 deletions crates/sqlbuild-orchestration/tests/health/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
}
Expand Down
10 changes: 9 additions & 1 deletion crates/sqlbuild-orchestration/tests/health/test_responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<CutOffReport> {
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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -62,15 +63,37 @@ 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,
health: Some(ControlCauseCase::SessionCutOff),
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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}

Expand Down
6 changes: 6 additions & 0 deletions fensu.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
19 changes: 19 additions & 0 deletions ui/e2e/group-run.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions ui/src/routes/runs/[id]/run-tabs.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,10 @@
<div class="log-area">
<PageBody padding="0" bind:scroller {onscroll}>
{#if view.tab === 'statements'}
{#if view.statementsRes.error}
<!-- The read's own failure, here only: other pages and the server's health are untouched. -->
<p class="err" data-testid="statements-error">Couldn't load the statement list{view.statements.length ? '; showing the last one loaded' : ''}: {view.statementsRes.error}</p>
{/if}
<StatementsTab {statements} total={view.statements.length} {grouped} focusId={view.statementFocus} capped={view.cappedStatements} />
{:else if view.tab === 'cost'}
{#if view.cost}
Expand Down
Loading