From 6e2026a0395d4e7e04042c6eb2b8b01ffc2a45a7 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:08:26 +0000 Subject: [PATCH 1/2] perf(server): read a run's statements a page at a time from a cursor The run page re-read every statement of every job run on each change, and the server summarised the whole run each time. A run's statement list is now read from a recall_events.storage_id cursor: each read touches only the events stored after it, through two new partial indexes, and identical concurrent reads share one read. The page follows each run's statements like its events, reads on until a page is not full, and waits at least as long as the last read took before asking again. --- clients/typescript/src/schema.d.ts | 11 +- .../api/_helpers/resources/person_reads.rs | 17 +- .../sqlbuild-orchestration/src/api/errors.rs | 25 +- .../sqlbuild-orchestration/src/api/models.rs | 8 + .../src/health/_helpers/session_cut_offs.rs | 22 +- .../sqlbuild-orchestration/src/runs/models.rs | 2 + .../src/store/indexes.sql | 2 + .../src/store/models.rs | 19 + .../store_migrations/_helpers/migration.rs | 6 + .../sql/0014_run_statement_reads.postgres.sql | 6 + .../sql/0014_run_statement_reads.sqlite.sql | 4 + .../warehouse_history/_helpers/run_recall.rs | 372 ++++++++++++++++-- .../main/runs/read_person_run_statements.rs | 20 +- .../tests/api/test_reads.rs | 27 +- .../tests/store/recall/helpers.rs | 132 +++++++ .../tests/store/recall/test_run_statements.rs | 269 +++++++++++++ .../tests/store/recall/test_types.rs | 36 +- .../tests/store/recall/test_views.rs | 98 +++-- .../store/schema/test_store_migrations.rs | 8 + .../tests/store/test_contracts.rs | 2 + .../src/schema/_helpers/relational_views.rs | 15 +- crates/sqlbuild-recall/src/schema/main/mod.rs | 1 - .../src/schema/main/scoped_statements.rs | 9 - fensu.toml | 6 + ui/e2e/group-run.spec.ts | 23 +- ui/e2e/live-reads.spec.ts | 49 +++ ui/e2e/real/group-rerun.spec.ts | 21 + ui/e2e/real/server.ts | 2 + ui/src/lib/api/client.ts | 5 +- ui/src/lib/api/http-client.ts | 8 +- ui/src/lib/api/http-runs.test.ts | 6 +- ui/src/lib/api/http-runs.ts | 2 +- ui/src/lib/api/mock/mock-client.ts | 4 +- ui/src/lib/api/mock/operate-store.ts | 7 +- ui/src/lib/api/types/operate.ts | 14 +- ui/src/lib/state/resource.svelte.ts | 22 +- ui/src/routes/runs/[id]/api/follow.test.ts | 43 +- ui/src/routes/runs/[id]/api/follow.ts | 36 +- ui/src/routes/runs/[id]/run-tabs.svelte | 2 +- ui/src/routes/runs/[id]/state.svelte.ts | 20 +- ui/src/routes/runs/[id]/statements-tab.svelte | 13 +- 41 files changed, 1192 insertions(+), 202 deletions(-) create mode 100644 crates/sqlbuild-orchestration/src/store_migrations/sql/0014_run_statement_reads.postgres.sql create mode 100644 crates/sqlbuild-orchestration/src/store_migrations/sql/0014_run_statement_reads.sqlite.sql create mode 100644 crates/sqlbuild-orchestration/tests/store/recall/test_run_statements.rs delete mode 100644 crates/sqlbuild-recall/src/schema/main/scoped_statements.rs diff --git a/clients/typescript/src/schema.d.ts b/clients/typescript/src/schema.d.ts index 5d61eb0aa3..ac111f5164 100644 --- a/clients/typescript/src/schema.d.ts +++ b/clients/typescript/src/schema.d.ts @@ -5068,6 +5068,11 @@ export interface components { RunStatementRecord: { /** Format: int64 */ affected_rows?: number | null; + /** + * Format: int64 + * @description Where the read that listed it stopped: pass it as `after` to read only the statements that changed since. + */ + cursor: number; /** Format: double */ duration_ms?: number | null; ended_at?: string | null; @@ -9499,7 +9504,9 @@ export interface operations { listPersonRunStatements: { parameters: { query?: { - /** @description Maximum statements; defaults to 1000, capped at 5000 */ + /** @description A `cursor` from an earlier read: only statements with events stored since are listed, each in full; defaults to 0, every statement */ + after?: number; + /** @description Maximum statements; defaults to 1000, capped at 5000. A full page's `cursor` reads on from where it stopped */ limit?: number; }; header?: never; @@ -9512,7 +9519,7 @@ export interface operations { }; requestBody?: never; responses: { - /** @description Statement metadata in start order, without SQL */ + /** @description Statement metadata in start order, without SQL; each carries the cursor to read on from */ 200: { headers: { [name: string]: unknown; 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 9e45ef34d6..1c4590b095 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs @@ -1,5 +1,7 @@ //! Person reads of run nodes and their errors, node run history, catalog nodes, jobs and one job's declaration, triggers, ticks and publications; refusal precedes every lookup, so unknown objects look forbidden. +use std::sync::Arc; + use axum::extract::{Path, Query, State}; use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; use axum::response::{IntoResponse, Response}; @@ -12,8 +14,8 @@ use crate::api::_helpers::resources::runs::no_output_store; use crate::api::errors::ApiError; use crate::api::models::BrowserOrigin; use crate::api::models::{ - CostQuery, PlatformEventsQuery, ReadQuery, RunEventsQuery, RunNodePath, ServerFacts, - StatementSqlQuery, TargetTicksQuery, + CostQuery, PlatformEventsQuery, ReadQuery, RunEventsQuery, RunNodePath, RunStatementsQuery, + ServerFacts, StatementSqlQuery, TargetTicksQuery, }; use crate::credentials::models::{AuditContext, AuthenticatedPerson, DefaultRole}; use crate::declarations::main::list_person_jobs::list_person_jobs; @@ -237,8 +239,9 @@ pub(crate) async fn run_events( #[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/statements", operation_id = "listPersonRunStatements", params(("location_id" = Uuid, Path), ("target" = String, Path), ("run_id" = Uuid, Path), - ("limit" = Option, Query, description = "Maximum statements; defaults to 1000, capped at 5000")), - responses((status = 200, body = Vec, description = "Statement metadata in start order, without SQL"), + ("after" = Option, Query, description = "A `cursor` from an earlier read: only statements with events stored since are listed, each in full; defaults to 0, every statement"), + ("limit" = Option, Query, description = "Maximum statements; defaults to 1000, capped at 5000. A full page's `cursor` reads on from where it stopped")), + responses((status = 200, body = Vec, description = "Statement metadata in start order, without SQL; each carries the cursor to read on from"), (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody), (status = 404, description = "Run not found for a person who may view the whole target")), security(("session" = []), ("cliSession" = [])))] @@ -247,7 +250,7 @@ pub(crate) async fn run_statements( Extension(default_role): Extension, (Path((location_id, target, run_id)), Query(options)): ( Path<(Uuid, String, Uuid)>, - Query, + Query, ), Extension(AuthenticatedPerson(principal, _)): Extension, ) -> Result>, ApiError> { @@ -256,12 +259,12 @@ pub(crate) async fn run_statements( (&context, principal), ( (location_id, &target, run_id), - options.limit.unwrap_or(1000), + (options.after.unwrap_or(0), options.limit.unwrap_or(1000)), ), default_role, ) .await? - .map(Json) + .map(|statements| Json(Arc::unwrap_or_clone(statements))) .ok_or_else(|| not_found("run not found")) } diff --git a/crates/sqlbuild-orchestration/src/api/errors.rs b/crates/sqlbuild-orchestration/src/api/errors.rs index 4d045877d8..7b0b2d5d45 100644 --- a/crates/sqlbuild-orchestration/src/api/errors.rs +++ b/crates/sqlbuild-orchestration/src/api/errors.rs @@ -1,5 +1,7 @@ //! HTTP errors name the cause when the control database is unavailable; any other error never returns database diagnostics, connection strings or credentials. +use std::sync::Arc; + use axum::Json; use axum::http::{HeaderValue, StatusCode, header}; use axum::response::{IntoResponse, Response}; @@ -32,7 +34,20 @@ pub struct ApiError { impl From for ApiError { fn from(error: ControlError) -> Self { - let cause: Option = control_cause(&error, (&ControlTarget::default(), false)) + Self::from(&error) + } +} + +/// A failure shared by every request that waited on one read. +impl From> for ApiError { + fn from(error: Arc) -> Self { + Self::from(&*error) + } +} + +impl From<&ControlError> for ApiError { + fn from(error: &ControlError) -> Self { + let cause: Option = control_cause(error, (&ControlTarget::default(), false)) .filter(ControlCause::unavailable); if let Some(cause) = cause { return Self { @@ -57,7 +72,7 @@ impl From for ApiError { cause: None, }; match error { - ControlError::Invalid(message) => plain(StatusCode::BAD_REQUEST, message, None), + ControlError::Invalid(message) => plain(StatusCode::BAD_REQUEST, message.clone(), None), ControlError::ReadTimedOut(_) => plain( StatusCode::GATEWAY_TIMEOUT, format!( @@ -66,14 +81,16 @@ impl From for ApiError { ), None, ), - ControlError::NotCheckingIn(message) => plain(StatusCode::CONFLICT, message, None), + ControlError::NotCheckingIn(message) => { + plain(StatusCode::CONFLICT, message.clone(), None) + } ControlError::Denied { reason, decision_id, } => plain( StatusCode::FORBIDDEN, format!("{reason}; decision {decision_id}"), - Some(decision_id), + Some(*decision_id), ), ControlError::UnreadableSnapshot { .. } | ControlError::StaleGeneration diff --git a/crates/sqlbuild-orchestration/src/api/models.rs b/crates/sqlbuild-orchestration/src/api/models.rs index b8975fe67e..0fcee30732 100644 --- a/crates/sqlbuild-orchestration/src/api/models.rs +++ b/crates/sqlbuild-orchestration/src/api/models.rs @@ -233,6 +233,14 @@ pub(crate) struct RunEventsQuery { pub(crate) types: String, } +/// A page of a run's statements: those with events after the cursor `after`, at most `limit`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct RunStatementsQuery { + pub(crate) after: Option, + pub(crate) limit: Option, +} + #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub(crate) struct StatementSqlQuery { 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 16234abc2b..affcfae0d6 100644 --- a/crates/sqlbuild-orchestration/src/health/_helpers/session_cut_offs.rs +++ b/crates/sqlbuild-orchestration/src/health/_helpers/session_cut_offs.rs @@ -22,7 +22,7 @@ pub(crate) fn note(cut_offs: &SessionCutOffs, store: &ControlStore, error: &sqlx .lock() .unwrap_or_else(PoisonError::into_inner); pending.push(( - database(store), + store.identity(), SessionCutOff { at: Utc::now(), idle, @@ -35,7 +35,7 @@ pub(crate) fn note(cut_offs: &SessionCutOffs, store: &ControlStore, error: &sqlx /// `store`'s cut-off sessions in `cut_offs`, which the caller now owns. pub(crate) fn take(cut_offs: &SessionCutOffs, store: &ControlStore) -> Vec { - let key = database(store); + let key = store.identity(); let mut pending = cut_offs .pending .lock() @@ -51,7 +51,7 @@ pub(crate) fn restore( store: &ControlStore, unreported: Vec, ) { - let key = database(store); + let key = store.identity(); let mut pending = cut_offs .pending .lock() @@ -76,19 +76,3 @@ fn cut_off(error: &sqlx_core::Error) -> Option { }; (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. -fn database(store: &ControlStore) -> String { - match store { - ControlStore::Postgres(pool) => { - let options = pool.connect_options(); - format!( - "{}:{}/{}", - options.get_host(), - options.get_port(), - options.get_database().unwrap_or_default() - ) - } - ControlStore::Sqlite(sqlite) => sqlite.path.display().to_string(), - } -} diff --git a/crates/sqlbuild-orchestration/src/runs/models.rs b/crates/sqlbuild-orchestration/src/runs/models.rs index 65439529c0..e511ec2c76 100644 --- a/crates/sqlbuild-orchestration/src/runs/models.rs +++ b/crates/sqlbuild-orchestration/src/runs/models.rs @@ -643,6 +643,8 @@ pub struct RunStatementRecord { pub affected_rows: Option, pub sql_available: bool, pub sql_unavailable_reason: Option, + /// Where the read that listed it stopped: pass it as `after` to read only the statements that changed since. + pub cursor: i64, } /// One statement's executed SQL; `sql` is null when capture was off or retention dropped it. diff --git a/crates/sqlbuild-orchestration/src/store/indexes.sql b/crates/sqlbuild-orchestration/src/store/indexes.sql index 9086da0ec7..2d34dd6a5c 100644 --- a/crates/sqlbuild-orchestration/src/store/indexes.sql +++ b/crates/sqlbuild-orchestration/src/store/indexes.sql @@ -13,3 +13,5 @@ CREATE INDEX IF NOT EXISTS sqb_warehouse_fingerprints_received ON sqb_warehouse_ CREATE INDEX IF NOT EXISTS sqb_warehouse_consumption_received ON sqb_warehouse_consumption(location_id, target, received_at); CREATE INDEX IF NOT EXISTS sqb_warehouse_observations_received ON sqb_warehouse_observations(location_id, target, received_at); CREATE INDEX IF NOT EXISTS sqb_security_audit_attention ON sqb_security_audit((scope_json ->> 'location_id'), (scope_json ->> 'target'), (scope_json ->> 'key'), storage_id) WHERE action IN ('attention.acknowledged', 'attention.acknowledgement_withdrawn'); +CREATE INDEX IF NOT EXISTS recall_events_invocation_statements ON recall_events(invocation_id, storage_id, statement_id, event_type) WHERE statement_id IS NOT NULL; +CREATE INDEX IF NOT EXISTS recall_events_invocation_resources ON recall_events(invocation_id, resource_id, resource_name, resource_kind) WHERE resource_name IS NOT NULL; diff --git a/crates/sqlbuild-orchestration/src/store/models.rs b/crates/sqlbuild-orchestration/src/store/models.rs index de0f1d6a28..5a039a44f8 100644 --- a/crates/sqlbuild-orchestration/src/store/models.rs +++ b/crates/sqlbuild-orchestration/src/store/models.rs @@ -97,6 +97,25 @@ pub(crate) enum Connection { Postgres(sqlx_core::transaction::Transaction<'static, sqlx_postgres::Postgres>), } +impl ControlStore { + /// A PostgreSQL store's host, port, database and options (such as its schema), or a SQLite store's file. + pub(crate) fn identity(&self) -> String { + match self { + ControlStore::Postgres(pool) => { + let options = pool.connect_options(); + format!( + "{}:{}/{}?{}", + options.get_host(), + options.get_port(), + options.get_database().unwrap_or_default(), + options.get_options().unwrap_or_default() + ) + } + ControlStore::Sqlite(sqlite) => sqlite.path.display().to_string(), + } + } +} + impl ControlTransaction { /// `column`, a compressed body, selected as hexadecimal text, never as bytes, which the store returns one JSON number per byte. pub(crate) fn hex_column(&self, column: &str) -> String { diff --git a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs index 50318a8769..c3e2eb03bd 100644 --- a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs +++ b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs @@ -89,6 +89,12 @@ pub(crate) const MIGRATIONS: &[StoreMigration] = &[ postgres: include_str!("../sql/0013_write_claim_waits.postgres.sql"), step: None, }, + StoreMigration { + name: "run_statement_reads", + sqlite: include_str!("../sql/0014_run_statement_reads.sqlite.sql"), + postgres: include_str!("../sql/0014_run_statement_reads.postgres.sql"), + step: None, + }, ]; /// The schema version a store created by this build has. diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0014_run_statement_reads.postgres.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0014_run_statement_reads.postgres.sql new file mode 100644 index 0000000000..2ec9a65669 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0014_run_statement_reads.postgres.sql @@ -0,0 +1,6 @@ +-- A run page reads a run's statement events stored after a cursor, and the names of their +-- resources, from these indexes alone instead of passing over every event of the run. +-- IF NOT EXISTS skips an index an operator pre-built. On a large Recall history, pre-build them +-- with CREATE INDEX CONCURRENTLY IF NOT EXISTS to keep runs reporting while the server upgrades. +CREATE INDEX IF NOT EXISTS recall_events_invocation_statements ON recall_events(invocation_id, storage_id, statement_id, event_type) WHERE statement_id IS NOT NULL; +CREATE INDEX IF NOT EXISTS recall_events_invocation_resources ON recall_events(invocation_id, resource_id, resource_name, resource_kind) WHERE resource_name IS NOT NULL; diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0014_run_statement_reads.sqlite.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0014_run_statement_reads.sqlite.sql new file mode 100644 index 0000000000..e2cb6fece7 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0014_run_statement_reads.sqlite.sql @@ -0,0 +1,4 @@ +-- A run page reads a run's statement events stored after a cursor, and the names of their +-- resources, from these indexes alone instead of passing over every event of the run. +CREATE INDEX IF NOT EXISTS recall_events_invocation_statements ON recall_events(invocation_id, storage_id, statement_id, event_type) WHERE statement_id IS NOT NULL; +CREATE INDEX IF NOT EXISTS recall_events_invocation_resources ON recall_events(invocation_id, resource_id, resource_name, resource_kind) WHERE resource_name IS NOT NULL; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs index e06380f2cc..c2a2469c0c 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs @@ -1,8 +1,12 @@ //! A run's Recall rows: the scheduler invocation and its claimed worker's invocations, with fixed column lists. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashMap}; +use std::sync::{Arc, LazyLock, Mutex, PoisonError}; use std::time::Duration; +use futures_util::FutureExt; +use futures_util::future::{BoxFuture, Shared}; + use serde_json::{Value, json}; use sqlbuild_core::event_export::constants::INVOCATION_START_EVENT_TYPE as INVOCATION_STARTED_EVENT; use sqlbuild_core::event_export::constants::{ @@ -13,7 +17,6 @@ use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; use sqlbuild_recall::records::constants::{ ARTIFACT_DIGEST_PREFIX, AUDIT_COMPLETED_EVENT, AUDIT_EVIDENCE_KIND, }; -use sqlbuild_recall::schema::main::scoped_statements::scoped_statements; use uuid::Uuid; use crate::authorization::main::decisions::authorize_listing::authorize_listing; @@ -33,9 +36,7 @@ use crate::store::errors::ControlError; use crate::store::main::decode_row::decode_row; use crate::store::main::query::query; use crate::store::main::{begin::begin, commit::commit}; -use crate::store::models::{ - Connection, ControlStore, ControlTransaction, Parameter, TransactionMode, -}; +use crate::store::models::{ControlStore, ControlTransaction, Parameter, TransactionMode}; use crate::store::types::Row; use crate::warehouse_history::_helpers::audit_repeats::{audit_due, record_audit}; use crate::warehouse_history::_helpers::checks::evidence_table; @@ -43,6 +44,48 @@ use crate::warehouse_history::constants::{BUILTIN_CHECK_ROWS, CHECK_ROWS}; use crate::warehouse_history::models::CheckEvidence; use crate::warehouse_history::types::RunEventPage; +/// A page read every request asking for it at the same time waits on. +type SharedPage = + Shared>, Arc>>>; + +/// A page read's identity. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct PageKey { + store: String, + run_id: Uuid, + after: i64, + limit: u32, +} + +/// A page read's place in the in-flight map, given up when the read ends, even by a panic. +struct InFlightEntry(PageKey); + +impl Drop for InFlightEntry { + fn drop(&mut self) { + IN_FLIGHT + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(&self.0); + } +} + +/// The page reads under way. +static IN_FLIGHT: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +/// The most statements one read lists. +const PAGE_LIMIT: u32 = 5000; + +/// A worker's nested invocations holding statements (`$1` its name and `/`, `$2` its name and `0`), one index probe each. +pub(crate) const NESTED_INVOCATIONS: &str = "WITH RECURSIVE nested(invocation_id) AS ( \ + SELECT MIN(invocation_id) FROM recall_events \ + WHERE invocation_id >= $1 AND invocation_id < $2 AND statement_id IS NOT NULL \ + UNION ALL \ + SELECT (SELECT MIN(e.invocation_id) FROM recall_events AS e \ + WHERE e.invocation_id > nested.invocation_id AND e.invocation_id < $2 AND e.statement_id IS NOT NULL) \ + FROM nested WHERE nested.invocation_id IS NOT NULL) \ + SELECT invocation_id FROM nested WHERE invocation_id IS NOT NULL"; + /// Events whose node may be named only in their payload: older node and check events, and audit results. const NODE_EVENTS: &str = "'run_node_started','run_node_finished','run_check_started','run_check_finished','audit_completed'"; @@ -73,6 +116,11 @@ pub(crate) struct RunRecallScope { } impl RunRecallScope { + /// The run's scheduler and worker invocations; a worker's nested ones share its name as a prefix. + pub(crate) fn namespaces(&self) -> &[String] { + &self.namespaces + } + /// A run's invocations, for reads that authorize nothing by node. pub(crate) const fn of_invocations(namespaces: Vec) -> Self { Self { @@ -598,35 +646,6 @@ fn delay_text(seconds: u64) -> String { } } -pub(crate) async fn run_statements_in( - transaction: ControlTransaction, - scope: &RunRecallScope, - limit: u32, -) -> Result<(ControlTransaction, Vec), ControlError> { - let postgres = matches!(transaction.connection, Some(Connection::Postgres(_))); - recall_records( - transaction, - scope, - ( - |filter: &str, next: usize| { - format!("SELECT invocation_id, statement_id, resource_id, resource_name, resource_kind, intent, statement_kind, \ - purpose, query_id, started_at, ended_at, outcome, error_type, error_code, duration_ms, row_count, affected_rows, \ - sql_available, sql_unavailable_reason FROM ({}) AS statements ORDER BY started_at, statement_id LIMIT ${next}", - scoped_statements(postgres, filter)) - }, - vec![Parameter::Integer(i64::from(limit.min(5000)))], - ), - |row: &mut Row| { - let available = row - .get("sql_available") - .is_some_and(|value| value.as_bool().unwrap_or_else(|| value.as_i64() == Some(1))); - row.insert("sql_available".into(), Value::Bool(available)); - Ok(()) - }, - ) - .await -} - /// One check result's kept rows in this run, from its `audit_completed` event and the evidence artifact the event names; `None` when the run has no such result. pub(crate) async fn check_evidence_in( transaction: ControlTransaction, @@ -700,12 +719,11 @@ pub(crate) async fn statement_sql_in( let (filter, mut parameters) = invocation_filter(scope, 1); let next = parameters.len() + 1; parameters.push(Parameter::Text(statement_id.into())); - let postgres = matches!(transaction.connection, Some(Connection::Postgres(_))); let (transaction, statements) = query( transaction, &format!( - "SELECT sql_digest FROM ({}) AS statements WHERE statement_id=${next}", - scoped_statements(postgres, &filter) + "SELECT sql_digest FROM recall_events WHERE {filter} AND statement_id=${next} \ + AND event_type LIKE 'statement!_%' ESCAPE '!' ORDER BY invocation_sequence, occurred_at, event_id LIMIT 1" ), parameters.clone(), ) @@ -838,3 +856,283 @@ fn truncated_flag(flag: &Value) -> Option { flag => Some((flag.as_i64() == Some(1)).to_string()), } } + +/// The statement events of `invocations` (`$1..$n`), as the run page lists them. +fn statement_events(invocations: &str) -> String { + format!( + "invocation_id IN ({invocations}) AND statement_id IS NOT NULL AND event_type LIKE 'statement!_%' ESCAPE '!'" + ) +} + +/// `$first, $first+1, ...` for `count` parameters. +fn placeholders(first: usize, count: usize) -> String { + (first..first + count) + .map(|n| format!("${n}")) + .collect::>() + .join(", ") +} + +/// A page read for already-authorized requests: one under way is waited out, as its snapshot may predate them, and the next shared. +pub(crate) async fn shared_run_statements( + store: &ControlStore, + run_id: Uuid, + (after, limit): (i64, u32), +) -> Result>, Arc> { + let key = PageKey { + store: store.identity(), + run_id, + after, + limit, + }; + let earlier = IN_FLIGHT + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(&key) + .cloned(); + if let Some(earlier) = earlier { + drop(earlier.await); + } + let read = IN_FLIGHT + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(key.clone()) + .or_insert_with(|| start_page_read(store.clone(), key)) + .clone(); + read.await +} + +/// The page read in a task of its own, which finishes and leaves the in-flight map however its requests end. +fn start_page_read(store: ControlStore, key: PageKey) -> SharedPage { + let (run_id, page) = (key.run_id, (key.after, key.limit)); + let task = tokio::spawn(async move { + let _entry = InFlightEntry(key); + read_page(&store, run_id, page).await + }); + async move { + match task.await { + Ok(read) => read.map(Arc::new).map_err(Arc::new), + Err(failed) => Err(Arc::new(ControlError::Worker(failed))), + } + } + .boxed() + .shared() +} + +/// One page in a read transaction of its own, over the run's invocations as that transaction sees them. +async fn read_page( + store: &ControlStore, + run_id: Uuid, + page: (i64, u32), +) -> Result, ControlError> { + let transaction = begin(store, TransactionMode::Read).await?; + let (transaction, namespaces) = run_invocations(transaction, run_id).await?; + let scope = RunRecallScope::of_invocations(namespaces); + let (transaction, records) = run_statements_in(transaction, &scope, page).await?; + commit(transaction).await?; + Ok(records) +} + +/// The run's statements with events after `after`, at most `limit`, in start order, each with the cursor to read on from. +pub(crate) async fn run_statements_in( + transaction: ControlTransaction, + scope: &RunRecallScope, + (after, limit): (i64, u32), +) -> Result<(ControlTransaction, Vec), ControlError> { + let limit = usize::try_from(limit.clamp(1, PAGE_LIMIT)).unwrap_or(1); + let (transaction, invocations) = invocations(transaction, scope).await?; + if invocations.is_empty() { + return Ok((transaction, Vec::new())); + } + let (transaction, (page, cursor)) = page(transaction, &invocations, (after, limit)).await?; + if page.is_empty() { + return Ok((transaction, Vec::new())); + } + let (transaction, rows) = summaries(transaction, &invocations, &page).await?; + let records = rows + .into_iter() + .map(|mut row| { + let available = row + .get("sql_available") + .is_some_and(|value| value.as_bool().unwrap_or_else(|| value.as_i64() == Some(1))); + row.insert("sql_available".into(), Value::Bool(available)); + row.insert("cursor".into(), Value::from(cursor)); + decode_row(row) + }) + .collect::>()?; + Ok((transaction, records)) +} + +/// The run's invocations by name: the scheduler's and worker's, and each invocation nested in a worker's that holds statements. +async fn invocations( + mut transaction: ControlTransaction, + scope: &RunRecallScope, +) -> Result<(ControlTransaction, Vec), ControlError> { + let mut names: Vec = scope.namespaces().to_vec(); + for namespace in scope + .namespaces() + .iter() + .filter(|n| n.starts_with("worker/")) + { + let (next, rows) = query( + transaction, + NESTED_INVOCATIONS, + vec![ + Parameter::Text(format!("{namespace}/")), + Parameter::Text(format!("{namespace}0")), + ], + ) + .await?; + transaction = next; + names.extend( + rows.iter() + .filter_map(|row| row["invocation_id"].as_str().map(str::to_owned)), + ); + } + Ok((transaction, names)) +} + +/// A page's statements over `invocations` names (`$1..`), then the cursor and the limit plus one. +pub(crate) fn page_sql(invocations: usize) -> String { + let next = invocations + 1; + format!( + "SELECT statement_id, MIN(storage_id) AS first_new, MAX(storage_id) AS last_new FROM recall_events \ + WHERE {} AND storage_id > ${next} GROUP BY statement_id ORDER BY first_new LIMIT ${}", + statement_events(&placeholders(1, invocations)), + next + 1 + ) +} + +/// Up to `limit` statements by first event after `after`, and a cursor before the first left out's first new event, else past the last. +async fn page( + transaction: ControlTransaction, + invocations: &[String], + (after, limit): (i64, usize), +) -> Result<(ControlTransaction, (Vec, i64)), ControlError> { + let mut parameters: Vec = invocations.iter().cloned().map(Parameter::Text).collect(); + parameters.push(Parameter::Integer(after)); + parameters.push(Parameter::Integer( + i64::try_from(limit + 1).unwrap_or(i64::MAX), + )); + let (transaction, rows) = query(transaction, &page_sql(invocations.len()), parameters).await?; + let id = |row: &Row, column: &str| row[column].as_i64().unwrap_or(after); + let cursor = match rows.get(limit) { + Some(left_out) => id(left_out, "first_new") - 1, + None => rows + .iter() + .map(|row| id(row, "last_new")) + .max() + .unwrap_or(after), + }; + let page: Vec = rows + .iter() + .take(limit) + .filter_map(|row| row["statement_id"].as_str().map(str::to_owned)) + .collect(); + Ok((transaction, (page, cursor))) +} + +/// Each of `statements` summarised from its events in start order: first facts, start, last outcome, kept SQL and resource name. +async fn summaries( + transaction: ControlTransaction, + invocations: &[String], + statements: &[String], +) -> Result<(ControlTransaction, Vec), ControlError> { + let mut parameters: Vec = invocations.iter().cloned().map(Parameter::Text).collect(); + parameters.extend(statements.iter().cloned().map(Parameter::Text)); + query( + transaction, + &summaries_sql(invocations.len(), statements.len()), + parameters, + ) + .await +} + +/// The summaries over `invocations` names (`$1..`), then `statements` IDs. +pub(crate) fn summaries_sql(invocations: usize, statements: usize) -> String { + let within = placeholders(1, invocations); + let listed = placeholders(invocations + 1, statements); + format!( + "WITH facts AS ( + SELECT invocation_id, invocation_sequence, occurred_at, event_id, event_type, statement_id, run_id, resource_id, + resource_attempt_id, operation_id, intent, statement_kind, purpose, sql_digest, started_at, query_id, + error_type, error_code, duration_ms, row_count, affected_rows, outcome + FROM recall_events + WHERE {events} AND statement_id IN ({listed}) +), +firsts AS ( + SELECT invocation_id, statement_id, run_id, resource_id, resource_attempt_id, operation_id, intent, + statement_kind, purpose, sql_digest, + ROW_NUMBER() OVER (PARTITION BY statement_id ORDER BY invocation_sequence, occurred_at, event_id) AS position + FROM facts +), +started AS ( + SELECT statement_id, MIN(started_at) AS started_at + FROM ( + SELECT statement_id, occurred_at AS started_at FROM facts WHERE event_type = 'statement_started' + UNION ALL + SELECT statement_id, started_at FROM facts WHERE started_at IS NOT NULL + ) AS starts + GROUP BY statement_id +), +query_ids AS ( + SELECT statement_id, MAX(query_id) AS query_id FROM facts GROUP BY statement_id +), +terminals AS ( + SELECT statement_id, event_type, occurred_at, query_id, error_type, error_code, duration_ms, row_count, + affected_rows, outcome, + ROW_NUMBER() OVER (PARTITION BY statement_id ORDER BY invocation_sequence DESC, occurred_at DESC, event_id DESC) AS position + FROM facts + WHERE event_type IN ('statement_completed', 'statement_failed') +), +captures AS ( + SELECT firsts.statement_id, MAX(CASE WHEN artifact.digest IS NOT NULL THEN 1 ELSE 0 END) AS stored + FROM firsts + JOIN recall_artifact_refs AS ref + ON ref.invocation_id = firsts.invocation_id AND ref.digest = 'sha256:' || firsts.sql_digest + LEFT JOIN recall_artifacts AS artifact ON artifact.digest = ref.digest + WHERE firsts.position = 1 + GROUP BY firsts.statement_id +), +resources AS ( + SELECT invocation_id, resource_id, MIN(resource_name) AS resource_name, MIN(resource_kind) AS resource_kind + FROM recall_events + WHERE resource_name IS NOT NULL + AND (invocation_id, resource_id) IN (SELECT invocation_id, resource_id FROM firsts WHERE position = 1) + GROUP BY invocation_id, resource_id +) +SELECT + firsts.invocation_id, + firsts.statement_id, + firsts.resource_id, + resources.resource_name, + resources.resource_kind, + firsts.intent, + firsts.statement_kind, + firsts.purpose, + COALESCE(terminals.query_id, query_ids.query_id) AS query_id, + started.started_at, + terminals.occurred_at AS ended_at, + CASE terminals.event_type + WHEN 'statement_completed' THEN 'completed' + WHEN 'statement_failed' THEN CASE WHEN terminals.outcome = 'handled' THEN 'handled' ELSE 'failed' END + ELSE 'no_terminal' + END AS outcome, + terminals.error_type, + terminals.error_code, + terminals.duration_ms, + terminals.row_count, + terminals.affected_rows, + COALESCE(captures.stored, 0) AS sql_available, + CASE captures.stored WHEN 1 THEN NULL WHEN 0 THEN 'expired_or_not_captured' ELSE 'not_captured' END + AS sql_unavailable_reason +FROM firsts +LEFT JOIN started ON started.statement_id = firsts.statement_id +LEFT JOIN query_ids ON query_ids.statement_id = firsts.statement_id +LEFT JOIN terminals ON terminals.statement_id = firsts.statement_id AND terminals.position = 1 +LEFT JOIN captures ON captures.statement_id = firsts.statement_id +LEFT JOIN resources ON resources.invocation_id = firsts.invocation_id AND resources.resource_id = firsts.resource_id +WHERE firsts.position = 1 +ORDER BY started.started_at, firsts.statement_id", + events = statement_events(&within), + ) +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_statements.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_statements.rs index 37eeaf565e..e6ce0059b5 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_statements.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_statements.rs @@ -1,25 +1,33 @@ //! A run's statement metadata needs view on every current node; the SQL text has its own read. +use std::sync::Arc; + use uuid::Uuid; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::runs::models::RunStatementRecord; use crate::store::errors::ControlError; use crate::store::models::ControlStore; -use crate::warehouse_history::_helpers::run_recall::{run_read, run_statements_in}; +use crate::warehouse_history::_helpers::run_recall::run_read; +use crate::warehouse_history::_helpers::run_recall::shared_run_statements; -/// `None` when the run is not in this location and target. +/// The person's page of statements after cursor `page.0`, at most `page.1`, shared with concurrent askers; `None` outside the scope. pub async fn read_person_run_statements( store: &ControlStore, credentials: (&AuditContext, Uuid), - (run, limit): ((Uuid, &str, Uuid), u32), + (run, page): ((Uuid, &str, Uuid), (i64, u32)), default_role: DefaultRole, -) -> Result>, ControlError> { - run_read( +) -> Result>>, Arc> { + let Some(()) = run_read( store, credentials, (run, default_role, None), - async |transaction, scope| run_statements_in(transaction, scope, limit).await, + async |transaction, _| Ok((transaction, ())), ) .await + .map_err(Arc::new)? + else { + return Ok(None); + }; + shared_run_statements(store, run.2, page).await.map(Some) } diff --git a/crates/sqlbuild-orchestration/tests/api/test_reads.rs b/crates/sqlbuild-orchestration/tests/api/test_reads.rs index 11e1e1fee7..f27905f151 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_reads.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_reads.rs @@ -541,14 +541,18 @@ fn given_published_locations_and_scheduled_work_when_read_through_http_then_reso typed.len() < run_events.len(), "the filter leaves other types out" ); - let mut statements: Vec<(String, Option)> = - read_person_run_statements(store, (&audit, viewer), (run, 100), DefaultRole::None) - .await - .expect("viewer statements") - .expect("claimed run") - .into_iter() - .map(|statement| (statement.invocation_id, statement.duration_ms)) - .collect(); + let mut statements: Vec<(String, Option)> = read_person_run_statements( + store, + (&audit, viewer), + (run, (0, 100)), + DefaultRole::None, + ) + .await + .expect("viewer statements") + .expect("claimed run") + .iter() + .map(|statement| (statement.invocation_id.clone(), statement.duration_ms)) + .collect(); statements.sort_by(|left, right| left.0.cmp(&right.0)); assert_eq!( statements, @@ -563,16 +567,17 @@ fn given_published_locations_and_scheduled_work_when_read_through_http_then_reso let statement_id = read_person_run_statements( store, (&audit, administrator), - (run, 100), + (run, (0, 100)), DefaultRole::None, ) .await .expect("statements") .expect("claimed run") - .into_iter() + .iter() .find(|statement| statement.invocation_id == execution) .expect("execution statement") - .statement_id; + .statement_id + .clone(); for refused in [ read_person_run_statement_sql( store, diff --git a/crates/sqlbuild-orchestration/tests/store/recall/helpers.rs b/crates/sqlbuild-orchestration/tests/store/recall/helpers.rs index 63731afd03..7f4a101578 100644 --- a/crates/sqlbuild-orchestration/tests/store/recall/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/store/recall/helpers.rs @@ -211,6 +211,19 @@ pub(crate) const RUN_STATEMENTS: &[(&str, &str, &str)] = &[ ), ]; +/// The scheduler's record that `worker/{claim_id}` claimed run `run_id`. +pub(crate) fn claimed_row(run_id: uuid::Uuid, claim_id: &str) -> RecallRow { + let envelope = RowEnvelope { + invocation_id: format!("scheduler/{run_id}"), + invocation_started_at: "2026-01-02T00:00:00Z".into(), + producer_version: "test".into(), + }; + event_object_row(&envelope, json!({"event_id": format!("scheduler/{run_id}-run_claimed"), "event_type": "run_claimed", + "schema_version": 1, "occurred_at": "2026-01-02T00:00:00Z", "producer": "sqlbuild", "invocation_sequence": 1, + "payload": {"claim": {"claim_id": claim_id}}}) + .as_object().expect("event object")).expect("claim fact") +} + /// Each invocation's statements, one finished and one running, on one resource id each names differently. pub(crate) fn scoped_statement_rows() -> Vec { SCOPED_INVOCATIONS @@ -239,3 +252,122 @@ pub(crate) fn scoped_statement_rows() -> Vec { }) .collect() } + +/// The `running` statement of `invocation_id` completing, as its worker reports it later. +pub(crate) fn finished_running_row(invocation_id: &str) -> RecallRow { + let envelope = RowEnvelope { + invocation_id: invocation_id.into(), + invocation_started_at: "2026-01-02T00:00:00Z".into(), + producer_version: "test".into(), + }; + let statement_id = format!("{invocation_id}#running"); + event_object_row(&envelope, json!({"event_id": format!("{statement_id}-statement_completed"), "event_type": "statement_completed", + "schema_version": 1, "occurred_at": "2026-01-02T00:00:04Z", "producer": "sqlbuild", "invocation_sequence": 4, + "statement_id": statement_id, "resource_id": "resource-orders", "payload": {"row_count": 3, "duration_ms": 2.5}}) + .as_object().expect("event object")).expect("statement fact") +} + +/// PostgreSQL rows for `statements` statements of `worker/{run}` over 50 nested invocations, each started and completed. +pub(crate) fn large_run_sql(run: &str, statements: usize, offset: usize) -> String { + format!( + "INSERT INTO recall_events (event_id, invocation_sequence, occurred_at, event_type, event_kind, severity, producer, \ + event_schema_version, statement_id, resource_id, resource_name, resource_kind, intent, statement_kind, sql_digest, \ + duration_ms, payload, invocation_id, invocation_started_at, schema_version, producer_version, ingested_at, content_hash) \ + SELECT '{run}-' || (n + {offset}) || '-' || step.kind, (n + {offset}) * 2 + step.position, \ + TIMESTAMPTZ '2026-01-02 00:00:00Z' + (n + {offset}) * INTERVAL '1 second' + step.position * INTERVAL '1 millisecond', \ + step.kind, 'statement', 'info', 'sqlbuild', 1, 'worker/{run}/part-' || (n % 50) || '#' || (n + {offset}), \ + 'model.shop.orders_' || (n + {offset}), CASE WHEN step.position = 0 THEN 'orders_' || (n + {offset}) END, \ + CASE WHEN step.position = 0 THEN 'model' END, 'execute', 'CREATE', md5(n::text), 1.5, '{{}}'::jsonb, \ + 'worker/{run}/part-' || (n % 50), TIMESTAMPTZ '2026-01-02 00:00:00Z', 1, 'test', now(), md5('{run}' || n || step.kind) \ + FROM generate_series(1, {statements}) AS series(n), \ + (VALUES (0, 'statement_started'), (1, 'statement_completed')) AS step(position, kind) \ + ORDER BY n, step.position" + ) +} + +/// The run `worker/orders`'s statements with events after `after`, at most `limit`, in a read of their own. +pub(crate) async fn read_statements( + store: &ControlStore, + (after, limit): (i64, u32), +) -> Vec { + let scope = + crate::warehouse_history::_helpers::run_recall::RunRecallScope::of_invocations(vec![ + "worker/orders".into(), + ]); + let transaction = begin(store, TransactionMode::Read).await.expect("begin"); + let (transaction, records) = crate::warehouse_history::_helpers::run_recall::run_statements_in( + transaction, + &scope, + (after, limit), + ) + .await + .expect("run statements"); + commit(transaction).await.expect("commit"); + records +} + +/// Runs `sql` in a write transaction of its own, such as seeding rows or `ANALYZE`. +pub(crate) async fn execute(store: &ControlStore, sql: &str) { + let transaction = begin(store, TransactionMode::Write).await.expect("begin"); + let (transaction, _) = query(transaction, sql, Vec::new()).await.expect(sql); + commit(transaction).await.expect("commit"); +} + +/// Waits, inside PostgreSQL, until a session of `pool`'s database is blocked on a table lock, as a read held by the test is. +pub(crate) async fn until_a_read_waits_on_a_lock(pool: &sqlx_postgres::PgPool) { + sqlx_core::query::query( + "DO $$ BEGIN FOR attempt IN 1..1000 LOOP \ + PERFORM pg_stat_clear_snapshot(); \ + EXIT WHEN EXISTS (SELECT 1 FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock'); \ + PERFORM pg_sleep(0.02); END LOOP; END $$", + ) + .execute(pool) + .await + .expect("wait for a read to wait on the lock"); +} + +/// Vacuums and analyzes Recall events as autovacuum would, so plans do not depend on whether it ran yet. +pub(crate) async fn settle_recall_events(store: &ControlStore) { + let ControlStore::Postgres(pool) = store else { + return; + }; + sqlx_core::query::query("VACUUM ANALYZE recall_events") + .execute(pool) + .await + .expect("vacuum recall events"); +} + +/// The Recall table rows PostgreSQL read to answer `sql`: each scan's returned and filtered rows times its loops. +pub(crate) async fn rows_read(store: &ControlStore, sql: &str, parameters: Vec) -> f64 { + let transaction = begin(store, TransactionMode::Read).await.expect("begin"); + let (transaction, rows) = query( + transaction, + &format!("EXPLAIN (ANALYZE, FORMAT JSON) {sql}"), + parameters, + ) + .await + .expect("explain"); + commit(transaction).await.expect("commit"); + let plan = &rows[0]["QUERY PLAN"]; + let plan: serde_json::Value = plan.as_str().map_or_else( + || plan.clone(), + |text| serde_json::from_str(text).expect("plan JSON"), + ); + scanned(&plan[0]["Plan"]) +} + +fn scanned(node: &serde_json::Value) -> f64 { + let number = |key: &str| node[key].as_f64().unwrap_or(0.0); + let own = node["Relation Name"] + .as_str() + .filter(|table| table.starts_with("recall_")) + .map_or(0.0, |_| { + (number("Actual Rows") + + number("Rows Removed by Filter") + + number("Rows Removed by Index Recheck")) + * number("Actual Loops") + }); + own + node["Plans"] + .as_array() + .map_or(0.0, |plans| plans.iter().map(scanned).sum()) +} diff --git a/crates/sqlbuild-orchestration/tests/store/recall/test_run_statements.rs b/crates/sqlbuild-orchestration/tests/store/recall/test_run_statements.rs new file mode 100644 index 0000000000..bcc417fd78 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/store/recall/test_run_statements.rs @@ -0,0 +1,269 @@ +//! A run's statement list read from a cursor lists only statements with new events, with bounded work. + +use std::cell::Cell; +use std::collections::BTreeMap; + +use crate::store::_helpers::statement_count::STATEMENTS; +use crate::store::main::migrate_store::migrate_store; +use crate::store::models::{ControlStore, Parameter}; +use crate::store::tests::helpers::{ + claimed_row, execute, finished_running_row, large_run_sql, publish_recall, read_statements, + rows_read, scoped_statement_rows, settle_recall_events, until_a_read_waits_on_a_lock, +}; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; +use crate::store::tests::test_types::{ + LargeRunReadTestCase, SharedPageTestCase, StatementCursorTestCase, +}; +use crate::warehouse_history::_helpers::run_recall::{ + NESTED_INVOCATIONS, page_sql, shared_run_statements, summaries_sql, +}; + +#[test] +fn given_a_runs_statements_when_reading_on_from_a_cursor_then_only_statements_with_new_events_are_listed_in_full() + { + let test_cases = [ + StatementCursorTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_whole: 4, + expected_unchanged: 0, + expected_changed: &[("worker/orders/session#running", "completed")], + expected_pages: 4, + }, + StatementCursorTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_whole: 4, + expected_unchanged: 0, + expected_changed: &[("worker/orders/session#running", "completed")], + expected_pages: 4, + }, + ]; + 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"); + publish_recall(store, &scoped_statement_rows()) + .await + .expect("publish statements"); + let whole = read_statements(store, (0, 100)).await; + let cursor = whole[0].cursor; + let unchanged = read_statements(store, (cursor, 100)).await; + publish_recall(store, &[finished_running_row("worker/orders/session")]) + .await + .expect("publish a completion"); + let changed: Vec<(String, Option)> = read_statements(store, (cursor, 100)) + .await + .into_iter() + .map(|s| (s.statement_id, s.outcome)) + .collect(); + // One statement a page, each read starting at the last page's cursor, ends where a whole read does. + let mut paged = BTreeMap::new(); + let mut after = 0; + let mut pages = 0; + for _ in 0..=test_case.expected_pages { + let page = read_statements(store, (after, 1)).await; + after = page.last().map_or(after, |s| s.cursor); + pages += page.len(); + paged.extend(page.into_iter().map(|s| (s.statement_id, s.outcome))); + } + let fresh: BTreeMap> = read_statements(store, (0, 100)) + .await + .into_iter() + .map(|s| (s.statement_id, s.outcome)) + .collect(); + close_test_store(fixture).await; + let expected_changed: Vec<(String, Option)> = test_case + .expected_changed + .iter() + .map(|(id, outcome)| ((*id).to_owned(), Some((*outcome).to_owned()))) + .collect(); + assert_eq!( + (whole.len(), unchanged.len(), changed, pages, paged), + ( + test_case.expected_whole, + test_case.expected_unchanged, + expected_changed, + test_case.expected_pages, + fresh + ), + "{}", + test_case.description + ); + }); + } +} + +#[test] +fn given_a_run_of_ten_thousand_statements_when_reading_its_statement_list_then_each_read_stays_within_its_budget() + { + let test_cases = [LargeRunReadTestCase { + description: "PostgreSQL, a run of 10,000 statements beside another of 10,000", + statements: 10_000, + expected_pages: [5_000, 5_000, 0], + max_store_statements: 4, + max_rows_first_page: 36_000.0, + max_rows_new_events: 100.0, + }]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Postgres).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + execute(store, &large_run_sql("orders", test_case.statements, 0)).await; + execute(store, &large_run_sql("returns", test_case.statements, 0)).await; + settle_recall_events(store).await; + let counted = |page: (i64, u32)| { + STATEMENTS.scope(Cell::new(0), async move { + let records = read_statements(store, page).await; + (records, STATEMENTS.with(Cell::get)) + }) + }; + let mut pages = Vec::new(); + let mut costs = Vec::new(); + let mut after = 0; + let mut first_page = Vec::new(); + for _ in 0..3 { + let (records, statements) = counted((after, 5_000)).await; + after = records.last().map_or(after, |r| r.cursor); + pages.push(records.len()); + costs.push(statements); + first_page.extend( + records + .iter() + .take(5_000 - first_page.len().min(5_000)) + .map(|r| r.statement_id.clone()), + ); + } + let invocations: Vec = std::iter::once("worker/orders".to_owned()) + .chain((0..50).map(|part| format!("worker/orders/part-{part}"))) + .collect(); + let named = || { + invocations + .iter() + .cloned() + .map(Parameter::Text) + .collect::>() + }; + let nested = || { + vec![ + Parameter::Text("worker/orders/".into()), + Parameter::Text("worker/orders0".into()), + ] + }; + let mut listed = named(); + listed.extend(first_page.iter().take(5_000).cloned().map(Parameter::Text)); + let mut paged = named(); + paged.extend([Parameter::Integer(0), Parameter::Integer(5_001)]); + let first_rows = rows_read(store, NESTED_INVOCATIONS, nested()).await + + rows_read(store, &page_sql(invocations.len()), paged).await + + rows_read(store, &summaries_sql(invocations.len(), 5_000), listed).await; + // Five statements arrive: the next read sees only them. + execute(store, &large_run_sql("orders", 5, test_case.statements)).await; + let (new, new_cost) = counted((after, 5_000)).await; + let mut since = named(); + since.extend([Parameter::Integer(after), Parameter::Integer(5_001)]); + let mut new_listed = named(); + new_listed.extend(new.iter().map(|r| Parameter::Text(r.statement_id.clone()))); + let new_rows = rows_read(store, NESTED_INVOCATIONS, nested()).await + + rows_read(store, &page_sql(invocations.len()), since).await + + rows_read( + store, + &summaries_sql(invocations.len(), new.len()), + new_listed, + ) + .await; + costs.push(new_cost); + close_test_store(fixture).await; + assert_eq!( + ( + pages, + new.len(), + costs + .iter() + .all(|cost| *cost <= test_case.max_store_statements), + first_rows <= test_case.max_rows_first_page, + new_rows <= test_case.max_rows_new_events, + ), + (test_case.expected_pages.to_vec(), 5, true, true, true), + "{}: statements per read {costs:?}, rows read for the first page {first_rows}, for the new events {new_rows}", + test_case.description + ); + }); + } +} + +#[test] +fn given_a_page_read_under_way_when_the_same_page_is_asked_for_after_a_commit_then_the_later_request_sees_it() + { + let test_cases = [SharedPageTestCase { + description: "PostgreSQL, a read held on a lock after taking its snapshot", + statement_id: "worker/orders/session#running", + expected_held_outcome: "no_terminal", + expected_later_outcome: "completed", + }]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Postgres).await else { + return; + }; + let store = fixture.store.clone(); + let ControlStore::Postgres(pool) = &store else { + return; + }; + migrate_store(&store).await.expect("migrate"); + publish_recall(&store, &scoped_statement_rows()) + .await + .expect("publish statements"); + let run_id = uuid::Uuid::now_v7(); + publish_recall(&store, &[claimed_row(run_id, "orders")]) + .await + .expect("publish the claim"); + let ask = |store: ControlStore| { + tokio::spawn(async move { + shared_run_statements(&store, run_id, (0, 100)) + .await + .expect("statements") + }) + }; + let mut lock = pool.begin().await.expect("begin lock"); + sqlx_core::query::query("LOCK TABLE recall_artifacts IN ACCESS EXCLUSIVE MODE") + .execute(&mut *lock) + .await + .expect("hold artifacts"); + let held = ask(store.clone()); + until_a_read_waits_on_a_lock(pool).await; + publish_recall(&store, &[finished_running_row("worker/orders/session")]) + .await + .expect("publish a completion"); + let later = ask(store.clone()); + tokio::task::yield_now().await; + lock.commit().await.expect("release artifacts"); + let outcome = |records: &[crate::runs::models::RunStatementRecord]| { + records + .iter() + .find(|r| r.statement_id == test_case.statement_id) + .and_then(|r| r.outcome.clone()) + }; + let held = outcome(&held.await.expect("held read")); + let later = outcome(&later.await.expect("later read")); + drop(store); + close_test_store(fixture).await; + assert_eq!( + (held.as_deref(), later.as_deref()), + ( + Some(test_case.expected_held_outcome), + Some(test_case.expected_later_outcome) + ), + "{}", + test_case.description + ); + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/store/recall/test_types.rs b/crates/sqlbuild-orchestration/tests/store/recall/test_types.rs index ced42ea29a..bdb06a5060 100644 --- a/crates/sqlbuild-orchestration/tests/store/recall/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/store/recall/test_types.rs @@ -1,5 +1,6 @@ //! Expected Recall storage outcomes for both supported databases. +use crate::store::models::Parameter; use crate::store::tests::store_test_types::Backend; pub(crate) struct RecallTestCase { @@ -28,5 +29,38 @@ pub(crate) struct ScopedStatementsTestCase { pub(crate) struct StatementPlanTestCase { pub(crate) description: &'static str, - pub(crate) expected_index: &'static str, + /// One query of the run statements read, and its parameters over the fixture. + pub(crate) sql: fn() -> String, + pub(crate) parameters: fn() -> Vec, + /// The tables its plan reads whole: none. + pub(crate) expected_scanned: &'static [&'static str], +} + +/// The statement list read whole, again from its cursor, after a completion, and one statement a page. +pub(crate) struct StatementCursorTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) expected_whole: usize, + pub(crate) expected_unchanged: usize, + /// The statements listed after a completion arrives: id and outcome. + pub(crate) expected_changed: &'static [(&'static str, &'static str)], + pub(crate) expected_pages: usize, +} + +/// A large run's statement list: its pages, and the most statements and table rows each read may cost. +pub(crate) struct LargeRunReadTestCase { + pub(crate) description: &'static str, + pub(crate) statements: usize, + pub(crate) expected_pages: [usize; 3], + pub(crate) max_store_statements: usize, + pub(crate) max_rows_first_page: f64, + pub(crate) max_rows_new_events: f64, +} + +/// A page read held after taking its snapshot while a statement completes, and a request for the same page meanwhile. +pub(crate) struct SharedPageTestCase { + pub(crate) description: &'static str, + pub(crate) statement_id: &'static str, + pub(crate) expected_held_outcome: &'static str, + pub(crate) expected_later_outcome: &'static str, } diff --git a/crates/sqlbuild-orchestration/tests/store/recall/test_views.rs b/crates/sqlbuild-orchestration/tests/store/recall/test_views.rs index 1a0d861fd4..74b24a85f1 100644 --- a/crates/sqlbuild-orchestration/tests/store/recall/test_views.rs +++ b/crates/sqlbuild-orchestration/tests/store/recall/test_views.rs @@ -9,8 +9,9 @@ use crate::store::main::query::query; use crate::store::main::read_recall_view::read_recall_view; use crate::store::models::{Parameter, TransactionMode}; use crate::warehouse_history::_helpers::run_recall::{ - RunRecallScope, invocation_filter, run_statements_in, statement_sql_in, + NESTED_INVOCATIONS, page_sql, run_statements_in, summaries_sql, }; +use crate::warehouse_history::_helpers::run_recall::{RunRecallScope, statement_sql_in}; use serde_json::{Value, json}; use sqlbuild_recall::records::main::artifact_rows::artifact_rows; use sqlbuild_recall::records::main::delivery_row::delivery_row; @@ -21,7 +22,6 @@ use sqlbuild_recall::records::main::output_row::output_row; use sqlbuild_recall::records::models::{ ArtifactInput, DeliveryCounts, InvocationContext, OutputChunk, OutputStream, RowEnvelope, }; -use sqlbuild_recall::schema::main::scoped_statements::scoped_statements; use crate::store::tests::helpers::{ RUN_STATEMENTS, publish_recall, read_recall_events, scoped_statement_rows, @@ -268,9 +268,14 @@ fn given_runs_with_neighbouring_invocation_ids_when_reading_one_runs_statements_ .expect("publish statements"); let scope = RunRecallScope::of_invocations(vec!["worker/orders".into()]); let transaction = begin(store, TransactionMode::Read).await.expect("begin"); - let (transaction, scoped) = run_statements_in(transaction, &scope, 100) + let (transaction, scoped) = run_statements_in(transaction, &scope, (0, 100)) .await .expect("run statements"); + // Every record's cursor is past the run's last statement event, so the next read starts there. + let (transaction, last) = query(transaction, + "SELECT MAX(storage_id) AS last FROM recall_events WHERE (invocation_id=$1 OR invocation_id LIKE $2) AND statement_id IS NOT NULL", + vec![Parameter::Text("worker/orders".into()), Parameter::Text("worker/orders/%".into())]).await.expect("last event"); + let cursor = last[0]["last"].clone(); // The view, filtered after its windows as the read was before, is the reference. let (transaction, viewed) = query(transaction, "SELECT invocation_id, statement_id, resource_id, resource_name, resource_kind, intent, statement_kind, purpose, query_id, \ @@ -284,6 +289,7 @@ fn given_runs_with_neighbouring_invocation_ids_when_reading_one_runs_statements_ let available = row["sql_available"] == json!(true) || row["sql_available"] == json!(1); row.insert("sql_available".into(), Value::Bool(available)); + row.insert("cursor".into(), cursor.clone()); decode_row(row).expect("view row") }) .collect(); @@ -321,12 +327,46 @@ fn given_runs_with_neighbouring_invocation_ids_when_reading_one_runs_statements_ } #[test] -fn given_a_runs_statements_read_when_planning_on_sqlite_then_every_events_read_uses_the_invocation_index() - { - let test_cases = [StatementPlanTestCase { - description: "SQLite run statements plan", - expected_index: "INDEX recall_events_invocation", - }]; +fn given_a_runs_statements_read_when_planning_on_sqlite_then_every_table_read_searches_an_index() { + let test_cases = [ + StatementPlanTestCase { + description: "the invocations nested in a worker's", + sql: || NESTED_INVOCATIONS.to_owned(), + parameters: || { + vec![ + Parameter::Text("worker/orders/".into()), + Parameter::Text("worker/orders0".into()), + ] + }, + expected_scanned: &[], + }, + StatementPlanTestCase { + description: "a page of statements after a cursor", + sql: || page_sql(2), + parameters: || { + vec![ + Parameter::Text("worker/orders".into()), + Parameter::Text("worker/orders/session".into()), + Parameter::Integer(0), + Parameter::Integer(101), + ] + }, + expected_scanned: &[], + }, + StatementPlanTestCase { + description: "the page's statement summaries", + sql: || summaries_sql(2, 2), + parameters: || { + vec![ + Parameter::Text("worker/orders".into()), + Parameter::Text("worker/orders/session".into()), + Parameter::Text("worker/orders#finished".into()), + Parameter::Text("worker/orders#running".into()), + ] + }, + expected_scanned: &[], + }, + ]; for test_case in test_cases { run(async { let fixture = open_test_store(Backend::Sqlite) @@ -339,39 +379,39 @@ fn given_a_runs_statements_read_when_planning_on_sqlite_then_every_events_read_u publish_recall(store, &scoped_statement_rows()) .await .expect("publish statements"); - let (filter, parameters) = invocation_filter( - &RunRecallScope::of_invocations(vec!["worker/orders".into()]), - 1, - ); let transaction = begin(store, TransactionMode::Read).await.expect("begin"); let (transaction, plan) = query( transaction, - &format!( - "EXPLAIN QUERY PLAN SELECT statement_id FROM ({}) AS statements", - scoped_statements(false, &filter) - ), - parameters, + &format!("EXPLAIN QUERY PLAN {}", (test_case.sql)()), + (test_case.parameters)(), ) .await .expect("plan"); commit(transaction).await.expect("commit"); - // Work done, not time: every read of the events searches the invocation index, never scans. - let reads: Vec<&str> = plan + // Work done, not time: each table is searched by an index, never scanned whole. + let details: Vec<&str> = plan .iter() .filter_map(|row| row["detail"].as_str()) - .filter(|detail| detail.contains("recall_events")) + .collect(); + let scanned: Vec<&&str> = details + .iter() + .filter(|detail| { + ["SCAN recall_events", "SCAN e", "SCAN ref", "SCAN artifact"] + .iter() + .any(|table| { + detail.split(' ').take(2).collect::>().join(" ") == *table + }) + }) .collect(); assert!( - !reads.is_empty(), - "{}: the plan reads the events", + details.iter().any(|detail| detail.starts_with("SEARCH")), + "{}: {details:?}", test_case.description ); - assert!( - reads - .iter() - .all(|detail| detail.starts_with("SEARCH recall_events USING") - && detail.contains(test_case.expected_index)), - "{}: {reads:?}", + assert_eq!( + scanned, + test_case.expected_scanned.iter().collect::>(), + "{}: {details:?}", test_case.description ); close_test_store(fixture).await; diff --git a/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs b/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs index 3138a47c8f..6d05b20f31 100644 --- a/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs +++ b/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs @@ -84,6 +84,10 @@ const SQLITE_CHECKSUMS: &[(i64, &str)] = &[ 13, "7247c7db84dac65ffd8ee2742210138bfbef2c0a2c43a9e0b14d43ff35593f28", ), + ( + 14, + "0930ea02a7cd333c7dbbb8fe32990fe08e23f2b8fba9ccc81f815db26dc0ea1b", + ), ]; const POSTGRES_CHECKSUMS: &[(i64, &str)] = &[ ( @@ -139,6 +143,10 @@ const POSTGRES_CHECKSUMS: &[(i64, &str)] = &[ 13, "8c5e583802f105098d808461ef118dc9348555da67f331808dcd6bfff3c8d6f4", ), + ( + 14, + "ae2729ee2edb0e3964214e57b1a4a11f5a38665267936888486d154247c243de", + ), ]; /// A version 1 store mid-run: a child run holding a concurrency slot, a jobs document and an audit result. const VERSION_1_LIVE_WORK: &str = "ALTER TABLE sqb_schema_version ADD COLUMN version BIGINT; \ diff --git a/crates/sqlbuild-orchestration/tests/store/test_contracts.rs b/crates/sqlbuild-orchestration/tests/store/test_contracts.rs index 23441f04f3..3f11bf100e 100644 --- a/crates/sqlbuild-orchestration/tests/store/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/store/test_contracts.rs @@ -24,6 +24,8 @@ pub(crate) mod store_helpers; pub(crate) mod store_test_types; #[path = "recall/test_contract.rs"] mod test_contract; +#[path = "recall/test_run_statements.rs"] +mod test_run_statements; #[path = "recall/test_types.rs"] mod test_types; #[path = "recall/test_views.rs"] diff --git a/crates/sqlbuild-recall/src/schema/_helpers/relational_views.rs b/crates/sqlbuild-recall/src/schema/_helpers/relational_views.rs index bdaf377f88..23919a9c11 100644 --- a/crates/sqlbuild-recall/src/schema/_helpers/relational_views.rs +++ b/crates/sqlbuild-recall/src/schema/_helpers/relational_views.rs @@ -49,16 +49,13 @@ fn events(postgres: bool, control: bool) -> String { format!("SELECT\n {columns}\nFROM recall_events") } -/// The statements view's body, over only the `recall_events` rows `within` selects when it is given. -pub(crate) fn statements(postgres: bool, within: Option<&str>) -> String { +/// The statements view's body. +pub(crate) fn statements(postgres: bool) -> String { let available = relational_cast(postgres, ("artifact.digest IS NOT NULL", "INTEGER")); - let (materialized, scoped) = within.map_or((String::new(), String::new()), |within| { - (" MATERIALIZED".to_owned(), format!("({within}) AND ")) - }); - format!("WITH facts AS{materialized} ( + format!("WITH facts AS ( SELECT * FROM recall_events - WHERE {scoped}statement_id IS NOT NULL AND event_type LIKE 'statement!_%' ESCAPE '!' + WHERE statement_id IS NOT NULL AND event_type LIKE 'statement!_%' ESCAPE '!' ), firsts AS ( SELECT invocation_id, invocation_started_at, statement_id, run_id, resource_id, resource_attempt_id, operation_id, @@ -109,7 +106,7 @@ resources AS ( SELECT invocation_id, resource_id, MIN(resource_name) AS resource_name, MIN(resource_kind) AS resource_kind FROM recall_events - WHERE {scoped}resource_id IS NOT NULL AND resource_name IS NOT NULL + WHERE resource_id IS NOT NULL AND resource_name IS NOT NULL GROUP BY invocation_id, resource_id ) SELECT @@ -567,7 +564,7 @@ WHERE position <= {OUTPUT_TAIL_RECORDS}" pub(crate) fn relational_view_bodies(postgres: bool, control: bool) -> Vec<(&'static str, String)> { vec![ ("invocations", invocations(postgres)), - ("statements", statements(postgres, None)), + ("statements", statements(postgres)), ("audit_results", audit_results(postgres)), ("output_invocations", output_invocations(postgres)), ("output_tail", output_tail(postgres)), diff --git a/crates/sqlbuild-recall/src/schema/main/mod.rs b/crates/sqlbuild-recall/src/schema/main/mod.rs index 27eed3ddce..58d39be9c9 100644 --- a/crates/sqlbuild-recall/src/schema/main/mod.rs +++ b/crates/sqlbuild-recall/src/schema/main/mod.rs @@ -8,7 +8,6 @@ pub mod ddl_statements; pub mod render_script; pub mod retention_fix_statements; pub mod schema_age; -pub mod scoped_statements; pub mod sqlite_retention_sql; pub mod store_version_with_views; pub mod table_columns; diff --git a/crates/sqlbuild-recall/src/schema/main/scoped_statements.rs b/crates/sqlbuild-recall/src/schema/main/scoped_statements.rs deleted file mode 100644 index eeb9650bcb..0000000000 --- a/crates/sqlbuild-recall/src/schema/main/scoped_statements.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! `scoped_statements`: the statements view's rows for some invocations, without reading the rest. - -use crate::schema::_helpers::relational_views::statements; - -/// The `statements` view's query over only the `recall_events` rows `within` selects, such as one run's. -#[must_use] -pub fn scoped_statements(postgres: bool, within: &str) -> String { - statements(postgres, Some(within)) -} diff --git a/fensu.toml b/fensu.toml index 9e56fe6eb7..4639340889 100644 --- a/fensu.toml +++ b/fensu.toml @@ -2095,6 +2095,12 @@ path = "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/audit_repea symbols = ["audit_due", "record_audit"] reason = "A page following a run repeats its output reads every few seconds; this process-wide record of when each person last had each kind of read of each run audited lets the server audit those reads once per window rather than writing an audit row per poll. Authorization still runs on every read." +[[targets.rust.rule_exceptions]] +rule = "FPRSS130" +path = "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs" +symbols = ["shared_run_statements", "InFlightEntry::drop"] +reason = "Everyone following a large run polls the same page of its statements; this process-wide map of the page reads under way lets requests share one read instead of each running it against the control store; a request waits out a read already under way, whose snapshot may predate it, and shares the next. An entry lives only while its read runs, in a task of its own that removes it however the read ends, so an abandoned request never holds a connection. Authorization still runs on every request." + [[targets.rust.rule_exceptions]] rule = "FPRSH011" path = "crates/sqlbuild-orchestration/src/run_output/_helpers/store/prune.rs" diff --git a/ui/e2e/group-run.spec.ts b/ui/e2e/group-run.spec.ts index 8c9e4cf65f..98af62c48d 100644 --- a/ui/e2e/group-run.spec.ts +++ b/ui/e2e/group-run.spec.ts @@ -719,19 +719,24 @@ test('a tab shows no count until its read has answered for every job run, never await expect(tab).toHaveText('Statements0'); }); -test("a member whose statements reach the read's limit says only its first are listed, and the page asks for the limit", async ({ page }) => { +test('a member with more statements than one read returns lists them all, reading on from where the first page stopped', async ({ page }) => { const { fake, run } = server(['load_orders', 'stage_orders']); await fake.install(page); const big = run.members[1]; - // One member with as many statements as one read returns: the server's cap. - const records = Array.from({ length: 5000 }, (_, i) => ({ statement_id: `s${i}`, invocation_id: `worker/${big.id}/execution`, started_at: new Date(Date.now() - 60_000 + i).toISOString(), ended_at: new Date(Date.now() - 59_000 + i).toISOString(), outcome: 'completed', statement_kind: 'INSERT', resource_kind: 'table', resource_name: 'payments', sql_available: false })); - await page.route(new RegExp(`/runs/${big.id}/statements`), (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(records) })); + // A full first page, then the rest past its cursor; a read past the end lists nothing. + const record = (i: number, cursor: number) => ({ statement_id: `s${i}`, invocation_id: `worker/${big.id}/execution`, started_at: new Date(Date.now() - 60_000 + i).toISOString(), ended_at: new Date(Date.now() - 59_000 + i).toISOString(), outcome: 'completed', statement_kind: 'INSERT', resource_kind: 'table', resource_name: 'payments', sql_available: false, cursor }); + const pages: Record = { '': Array.from({ length: 5000 }, (_, i) => record(i, 5000)), '5000': Array.from({ length: 1200 }, (_, i) => record(5000 + i, 6200)) }; + const asked: string[] = []; + await page.route(new RegExp(`/runs/${big.id}/statements`), (route) => { + const after = new URL(route.request().url()).searchParams.get('after') ?? ''; + asked.push(after); + return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(pages[after] ?? []) }); + }); await page.goto(`/runs/${run.id}`); - await page.getByRole('tab', { name: /^Statements/ }).click({ timeout: 20_000 }); - await expect(page.getByTestId('statements-capped')).toContainText('Only the first 5,000 queries of stage_orders are listed'); - const reads = fake.requested.filter((r) => /^runs\/[^/]+\/statements/.test(r)); - expect(reads.length).toBeGreaterThan(0); - expect(reads.every((r) => r.endsWith('?limit=5000')), reads.join(' ')).toBe(true); + const tab = page.getByRole('tab', { name: /^Statements/ }); + await tab.click({ timeout: 20_000 }); + await expect(tab).toHaveText(/^Statements6,?200$/); + expect(asked.slice(0, 2)).toEqual(['', '5000']); }); test("a job group's History opens a member to its nodes, and says when its runs couldn't be read", async ({ page }) => { diff --git a/ui/e2e/live-reads.spec.ts b/ui/e2e/live-reads.spec.ts index bb8b20d17e..b181124af0 100644 --- a/ui/e2e/live-reads.spec.ts +++ b/ui/e2e/live-reads.spec.ts @@ -107,6 +107,55 @@ test('a group run page under a steady stream of progress reads its run at most o for (const member of run.members) expect(statementsRead.get(member.jobKey), member.jobKey).toBeGreaterThanOrEqual(TICKS - 1); }); +// The page's clock stands still between steps, so how long a read took is what the test says, not the machine's speed. +test('a read that answered slowly is not asked again until as long again has passed, though the run moved meanwhile', async ({ page }) => { + const { fake, run } = server(); + const moving = run.members[2]; + let release = () => {}; + let held: Promise | null = null; + let asked = 0; + await page.clock.install(); + await fake.install(page); + // Registered after the fake, so it answers first: counts the moving job run's statements reads as they are made, + // and holds one while the test says. + await page.route(new RegExp(`/runs/${moving.id}/statements`), async (route) => { + asked += 1; + if (held) await held; + await route.fallback(); + }); + await page.goto(`/runs/${run.id}`); + await expect(page.getByText(run.members[0].jobKey).first()).toBeVisible({ timeout: 20_000 }); + await page.clock.pauseAt(Date.now() + 1000); + await page.clock.runFor(4000); + await page.waitForTimeout(500); + + // The job run moves; its statements read starts and takes 5 s of the page's time, while it moves again. + held = new Promise((r) => (release = r)); + const before = asked; + fake.advance(moving); + await page.waitForTimeout(600); + await page.clock.runFor(1000); + await expect.poll(() => asked).toBe(before + 1); + fake.advance(moving); + await page.waitForTimeout(600); + await page.clock.runFor(5000); + // One more move while the read is still held: its wait is replaced by the back-off once the read answers, not kept. + fake.advance(moving); + await page.waitForTimeout(600); + held = null; + release(); + // It answered, and the moves it missed are still to read: not in the next second. + await page.waitForTimeout(1500); + await page.clock.runFor(1000); + await page.waitForTimeout(1500); + expect(asked).toBe(before + 1); + // Once as long again has passed, they are, in one read. + await page.clock.runFor(6000); + await expect.poll(() => asked).toBe(before + 2); + await page.waitForTimeout(1500); + expect(asked).toBe(before + 2); +}); + test('a group page with its run under way reads only that run as a job run moves, not the jobs or runs listings', async ({ page }) => { const { fake, run } = server(); await fake.install(page); diff --git a/ui/e2e/real/group-rerun.spec.ts b/ui/e2e/real/group-rerun.spec.ts index 17c22b2fe2..2e5d524569 100644 --- a/ui/e2e/real/group-rerun.spec.ts +++ b/ui/e2e/real/group-rerun.spec.ts @@ -89,6 +89,27 @@ test('the nodes a failed job held back in later jobs build once its retry succee expect(nodes.filter((n) => n.node_key.endsWith('stg_payments') || n.node_key.endsWith('order_payments')).map((n) => n.status)).toEqual(['success', 'success']); }); +test('a run\'s statements read one at a time from the cursor are the same as one read, and the page lists them all', async ({ page }) => { + const members = await server.members(groupRunId); + let total = 0; + for (const member of members) { + const whole = await server.statements(member.run_id); + const paged = new Map(); + for (let after = 0, page = await server.statements(member.run_id, after, 1); page.length; page = await server.statements(member.run_id, after, 1)) { + for (const s of page) paged.set(s.statement_id, s.outcome); + after = page[0].cursor; + } + expect(paged, member.job_key).toEqual(new Map(whole.map((s) => [s.statement_id, s.outcome]))); + total += whole.length; + } + expect(total).toBeGreaterThan(0); + await page.goto(`${server.uiUrl}/runs/${groupRunId}`); + const tab = page.getByRole('tab', { name: /^Statements/ }); + await tab.click({ timeout: 30_000 }); + await expect(tab).toHaveText(`Statements${total.toLocaleString('en-GB')}`, { timeout: 30_000 }); + await expect(page.getByRole('alert')).toHaveCount(0); +}); + test('the timeline shows the group run and reads every schedule\'s ticks in one request', async ({ page }) => { const perSchedule: string[] = []; page.on('request', (request) => { diff --git a/ui/e2e/real/server.ts b/ui/e2e/real/server.ts index 458578263d..88da85fc87 100644 --- a/ui/e2e/real/server.ts +++ b/ui/e2e/real/server.ts @@ -154,6 +154,8 @@ export class RealServer { runs = () => this.api('/runs?limit=100'); nodes = (runId: string) => this.api(`/runs/${runId}/nodes`); + /** A page of a run's statements with events after the cursor `after`. */ + statements = (runId: string, after = 0, limit = 5000) => this.api<{ statement_id: string; outcome: string | null; cursor: number }[]>(`/runs/${runId}/statements?after=${after}&limit=${limit}`); /** A group run's job runs, every attempt, oldest first. */ async members(groupRunId: string): Promise { diff --git a/ui/src/lib/api/client.ts b/ui/src/lib/api/client.ts index 6707915fbb..9475531cdd 100644 --- a/ui/src/lib/api/client.ts +++ b/ui/src/lib/api/client.ts @@ -37,7 +37,7 @@ import type { NodeOutputSearch, RunRowPage, RunRowQuery, - RunStatement, + RunStatementPage, IgnoredAuditFailure, RunCostRow, CostSummary, @@ -132,7 +132,8 @@ export interface ApiClient extends PlatformApi { getRunDetail(scope: Scope, runId: string, options?: { lineage?: boolean }): Promise; /** Recall events and scheduler facts in storage order, paged by `after`. */ listRunEvents(scope: Scope, runId: string, query?: RunEventQuery): Promise; - listRunStatements(scope: Scope, runId: string): Promise; + /** The run's statements with events after `after`, a page at a time; from the start without it. */ + listRunStatements(scope: Scope, runId: string, after?: number | null): Promise; /** The audit failures a run and its group's current member runs let through, run by run. */ listRunIgnoredAudits(scope: Scope, runId: string): Promise; /** The latest estimated query cost observations of one run; empty until a collection synced. */ diff --git a/ui/src/lib/api/http-client.ts b/ui/src/lib/api/http-client.ts index 42bf135dfb..e519001a81 100644 --- a/ui/src/lib/api/http-client.ts +++ b/ui/src/lib/api/http-client.ts @@ -28,7 +28,7 @@ import type { ChangeSubscription, ChangedChannel, ChangedSignal, ConnectionState import type { AuthMode, Bootstrap, BuiltInRole, Capability, DiscoveredSet, Location, MemberRetryScope, NavCounts, PlatformEvent, RepublishResult, Scope, Snapshot, WarehouseSync } from './types'; import type { Account, AuditEntry, AuditQuery, ConnectionTest, IssuedToken, KeyRotation, LocationDetail, NewPasswordAccount, NewServiceAccount, ServiceAccount, ServerSettings, WarehouseConnection, LocationSummary, PlatformEventQuery, PlatformEventRecord, PlatformHealth, ServerHealth, HealthComponentDetails, MaintenanceHistory, ProviderConnection, RoleAssignment, RoleAssignmentRequest, RoleDefinition, RoleDetail } from './types/platform'; import type { Acknowledgement, CatalogNode, CatalogNodeDetail, Check, CheckDetail, CheckEvidence, CheckSql, NodeStates, NodeStatusDelta, Overview, Publication, SnapshotChange, ColumnLineage, AttentionAcknowledgement, ConditionShape, AutomaticWithdrawal } from './types/build'; -import type { NodeOutputIndex, NodeOutputMatches, NodeOutputPage, NodeOutputSearch, RunNode, RunEdge, RunOutputFollow, AdhocRunCheck, AdhocRunRequest, BulkRunResult, SelectionEvaluation, SelectionRequest, SelectionVocabulary, PlanDiff, PlanPage, PlanPageSection, PlanResult, QueueEntry, Timeline, Job, JobDetail, JobLaunchOptions, SnapshotNode, Run, RunDetail, RunListQuery, RunRowPage, RunRowQuery, RunTabCounts, Trigger, TriggerDetail, TriggerState, RunEventPage, RunEventQuery, RunNodeError, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostSummary, CostSelection, CostSelectionQuery, CostSeriesGroup, NodeBuildCost, StatementSql } from './types/operate'; +import type { NodeOutputIndex, NodeOutputMatches, NodeOutputPage, NodeOutputSearch, RunNode, RunEdge, RunOutputFollow, AdhocRunCheck, AdhocRunRequest, BulkRunResult, SelectionEvaluation, SelectionRequest, SelectionVocabulary, PlanDiff, PlanPage, PlanPageSection, PlanResult, QueueEntry, Timeline, Job, JobDetail, JobLaunchOptions, SnapshotNode, Run, RunDetail, RunListQuery, RunRowPage, RunRowQuery, RunTabCounts, Trigger, TriggerDetail, TriggerState, RunEventPage, RunEventQuery, RunNodeError, RunOutputLine, RunStatementPage, IgnoredAuditFailure, RunCostRow, CostSummary, CostSelection, CostSelectionQuery, CostSeriesGroup, NodeBuildCost, StatementSql } from './types/operate'; import { newRequestId } from '$lib/browser/request-id'; type Wire = components['schemas']; @@ -457,11 +457,11 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, if (!data) throw new ApiError(errorText(error, response), response.status); return { events: data.flatMap((e) => toRunEvent(e, runId) ?? []), nextCursor: data.length === limit ? (data.at(-1)?.storage_id ?? null) : null }; }, - async listRunStatements(scope: Scope, runId: string): Promise { - const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/statements', { params: { path: runPath(scope, runId), query: { limit: STATEMENT_LIMIT } } }); + async listRunStatements(scope: Scope, runId: string, after?: number | null): Promise { + const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/statements', { params: { path: runPath(scope, runId), query: { after: after ?? undefined, limit: STATEMENT_LIMIT } } }); if (response.status === 401) onUnauthorized(); if (!data) throw new ApiError(errorText(error, response), response.status); - return toRunStatements(data, runId); + return { statements: toRunStatements(data, runId), cursor: data[0]?.cursor ?? null, more: data.length === STATEMENT_LIMIT }; }, async listRunIgnoredAudits(scope: Scope, runId: string): Promise { const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/ignored-audits', { params: { path: runPath(scope, runId) } }); diff --git a/ui/src/lib/api/http-runs.test.ts b/ui/src/lib/api/http-runs.test.ts index e83fcad3be..465860ed24 100644 --- a/ui/src/lib/api/http-runs.test.ts +++ b/ui/src/lib/api/http-runs.test.ts @@ -304,12 +304,12 @@ describe('run Recall reads', () => { const seed = { resource_id: '3b7370f99e385665996e8f73523b4fd5', resource_kind: 'seed', resource_name: 'seed__order_type__alpha' }; const mapped = [event('resource_attempt_started', seed), event('resource_attempt_completed', { ...seed, outcome: 'success' }), event('statement_completed', { ...seed, statement_id: 's9' })].flatMap((e) => toRunEvent(e, 'r1') ?? []); expect(mapped.map((e) => e.nodeKey)).toEqual(['seed:seed__order_type__alpha', 'seed:seed__order_type__alpha', 'seed:seed__order_type__alpha']); - const [statement] = toRunStatements([{ invocation_id: inv, statement_id: 's9', sql_available: true, ...seed }], 'r1'); + const [statement] = toRunStatements([{ invocation_id: inv, statement_id: 's9', sql_available: true, cursor: 0, ...seed }], 'r1'); expect(statement.nodeKey).toBe('seed:seed__order_type__alpha'); // A model's rows carry its materialization, which the run keys as `model:`. const table = { resource_id: '9c1e', resource_kind: 'table', resource_name: 'orders' }; const view = { resource_id: '9c1f', resource_kind: 'view', resource_name: 'customers' }; - expect([toRunEvent(event('resource_attempt_failed', table), 'r1')?.nodeKey, toRunStatements([{ invocation_id: inv, statement_id: 's10', sql_available: true, ...view }], 'r1')[0].nodeKey]).toEqual(['model:orders', 'model:customers']); + expect([toRunEvent(event('resource_attempt_failed', table), 'r1')?.nodeKey, toRunStatements([{ invocation_id: inv, statement_id: 's10', sql_available: true, cursor: 0, ...view }], 'r1')[0].nodeKey]).toEqual(['model:orders', 'model:customers']); // A hash alone names no node; the scheduler's node events carry none yet. expect(toRunEvent(event('resource_attempt_started', { resource_id: '3b7370f99e385665996e8f73523b4fd5' }), 'r1')?.nodeKey).toBeNull(); }); @@ -332,7 +332,7 @@ describe('run Recall reads', () => { }); it('orders statements as sent and tells running from finished by the end time', () => { - const statement = (id: string, extra: Partial): W['RunStatementRecord'] => ({ invocation_id: inv, statement_id: id, sql_available: true, ...extra }); + const statement = (id: string, extra: Partial): W['RunStatementRecord'] => ({ invocation_id: inv, statement_id: id, sql_available: true, cursor: 0, ...extra }); const statements = toRunStatements( [ statement('s1', { resource_id: `["${inv}","seed:countries"]`, statement_kind: 'CREATE', ended_at: '2026-11-08T06:00:01Z', affected_rows: 3 }), diff --git a/ui/src/lib/api/http-runs.ts b/ui/src/lib/api/http-runs.ts index 7fd09285e9..d264a5734c 100644 --- a/ui/src/lib/api/http-runs.ts +++ b/ui/src/lib/api/http-runs.ts @@ -1,7 +1,7 @@ import type { components } from '$control/schema.d.ts'; import { isActiveRun, isUnfinishedNode, UNFINISHED_NODE_STATUSES } from '$lib/status'; import type { Capability, Principal } from './types'; -import type { AdhocRunCheck, LaunchVerb, NodeCounts, NodeKind, PlanChanged, PlanDocument, PlanPage, PlanPageSection, PlanResult, PlanWarning, QueueEntry, QueueWait, Run, RunDetail, RunListQuery, RunNode, RunNodeStatus, RunRow, RunRowPage, RunRowQuery, RunTabCounts, RunEvent, RunEventCheck, RunEventLevel, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostGroup, CostSummary, PriceSource, NodeBuildCost } from './types/operate'; +import type { AdhocRunCheck, LaunchVerb, NodeCounts, NodeKind, PlanChanged, PlanDocument, PlanPage, PlanPageSection, PlanResult, PlanWarning, QueueEntry, QueueWait, Run, RunDetail, RunListQuery, RunNode, RunNodeStatus, RunRow, RunRowPage, RunRowQuery, RunTabCounts, RunEvent, RunEventCheck, RunEventLevel, RunOutputLine, RunStatement, RunStatementPage, IgnoredAuditFailure, RunCostRow, CostGroup, CostSummary, PriceSource, NodeBuildCost } from './types/operate'; import { RECALL_EVENT_TYPES, SCHEDULER_FACTS } from './types/operate'; type Wire = components['schemas']; diff --git a/ui/src/lib/api/mock/mock-client.ts b/ui/src/lib/api/mock/mock-client.ts index 0ca93a9a43..f9fbcf60ca 100644 --- a/ui/src/lib/api/mock/mock-client.ts +++ b/ui/src/lib/api/mock/mock-client.ts @@ -40,7 +40,7 @@ import type { NodeOutputPage, NodeOutputSearch, CheckEvidence, - RunStatement, + RunStatementPage, RunCostRow, IgnoredAuditFailure, CostSummary, @@ -297,7 +297,7 @@ export class MockApiClient implements ApiClient { return this.#operate.listRunEvents(scope, runId, query); } - async listRunStatements(scope: Scope, runId: string): Promise { + async listRunStatements(scope: Scope, runId: string): Promise { this.#location(scope); return this.#operate.listRunStatements(scope, runId); } diff --git a/ui/src/lib/api/mock/operate-store.ts b/ui/src/lib/api/mock/operate-store.ts index 1a23f84ae0..52004a1815 100644 --- a/ui/src/lib/api/mock/operate-store.ts +++ b/ui/src/lib/api/mock/operate-store.ts @@ -51,7 +51,7 @@ import type { RunRow, RunRowPage, RunRowQuery, - RunStatement, + RunStatementPage, RunCostRow, CostSummary, NodeBuildCost, @@ -394,10 +394,11 @@ export class MockOperate { return this.#ctx.reply({ events: page, nextCursor: page.length ? (more || isActive(rec.run.status) ? page[page.length - 1].storageId : null) : after || null }); } - listRunStatements(scope: Scope, runId: string): Promise { + /** Every statement each time, with no cursor: a whole page each reader merges by ID. */ + listRunStatements(scope: Scope, runId: string): Promise { const rec = this.#require(runId); const now = Date.now(); - return this.#ctx.reply(execution(rec, this.#nodesOf(rec, now), now).statements); + return this.#ctx.reply({ statements: execution(rec, this.#nodesOf(rec, now), now).statements, cursor: null, more: false }); } listRunCost(scope: Scope, runId: string): Promise { diff --git a/ui/src/lib/api/types/operate.ts b/ui/src/lib/api/types/operate.ts index 4425af816d..0130fce6ee 100644 --- a/ui/src/lib/api/types/operate.ts +++ b/ui/src/lib/api/types/operate.ts @@ -517,9 +517,21 @@ export type NodeBuildCost = { queryCount: number; }; -/** The most statements one read of a run returns, the server's cap; a run with more lists its first this many. */ +/** The most statements one read of a run returns, the server's cap; a run with more is read on in pages. */ export const STATEMENT_LIMIT = 5000; +/** + * The statements with events after a cursor: new ones, and earlier ones that moved on, which replace their + * earlier record by `id`. `sequence` is left for the reader to number once the pages are merged. + */ +export type RunStatementPage = { + statements: RunStatement[]; + /** Pass back as `after` to read only what changed since; null when the page listed nothing. */ + cursor: number | null; + /** Whether the page was full, so more statements wait past `cursor` now. */ + more: boolean; +}; + export type RunStatement = { id: string; runId: string; diff --git a/ui/src/lib/state/resource.svelte.ts b/ui/src/lib/state/resource.svelte.ts index 7c166f8272..9342aedf0e 100644 --- a/ui/src/lib/state/resource.svelte.ts +++ b/ui/src/lib/state/resource.svelte.ts @@ -33,7 +33,8 @@ export type Resource = { * * Change signals arrive in bursts while a run progresses, so they are coalesced: * one reload starts after a short pause, and signals during a reload queue at - * most one more. + * most one more. A reload waits at least as long as the last read took, so a + * busy server is asked at most half the time, not again the moment it answers. * * Must be called during component initialisation. Reactive values read * synchronously inside `load` (such as route params) are also dependencies. @@ -65,6 +66,9 @@ export function createResource( let reloadAgain = false; let pause: ReturnType | null = null; let started = -Infinity; + /** When the last read answered, and how long it took. */ + let answered = -Infinity; + let took = 0; function run(scope: Scope) { const request = ++latest; @@ -76,9 +80,11 @@ export function createResource( loading = true; const done = () => { settled = request; + answered = Date.now(); + took = answered - started; if (reloadAgain && request === latest) { reloadAgain = false; - refresh(); + later(0); } }; load(app.client, scope).then( @@ -104,9 +110,11 @@ export function createResource( ); } - function signalled() { - if (pause) return; - const wait = Math.max(SIGNAL_PAUSE_MS, started + (options.every ?? 0) - Date.now()); + /** Reloads once `least` has passed, the throttle has, and as long again as the last read took. */ + function later(least: number) { + if (pause) clearTimeout(pause); + const now = Date.now(); + const wait = Math.max(least, started + (options.every ?? 0) - now, answered + took - now); pause = setTimeout(() => { pause = null; if (settled === latest) refresh(); @@ -114,6 +122,10 @@ export function createResource( }, wait); } + function signalled() { + if (!pause) later(SIGNAL_PAUSE_MS); + } + function refresh() { if (app.scope) run(app.scope); } diff --git a/ui/src/routes/runs/[id]/api/follow.test.ts b/ui/src/routes/runs/[id]/api/follow.test.ts index d32bbeae27..abe33e4ac4 100644 --- a/ui/src/routes/runs/[id]/api/follow.test.ts +++ b/ui/src/routes/runs/[id]/api/follow.test.ts @@ -1,13 +1,14 @@ import { describe, expect, it } from 'vitest'; -import type { ApiClient, RunEvent, RunOutputFollow, RunOutputLine, Scope } from '$lib/api'; -import { followEvents, followOutput, newFollow, type RunFollow } from './follow'; +import type { ApiClient, RunEvent, RunOutputFollow, RunOutputLine, RunStatement, RunStatementPage, Scope } from '$lib/api'; +import { followEvents, followOutput, followStatements, newFollow, type RunFollow } from './follow'; const scope = { locationId: 'loc', target: 'dev' } as unknown as Scope; const event = (storageId: number) => ({ id: `e${storageId}`, storageId, occurredAt: `2026-11-21T09:00:0${storageId}Z` }) as RunEvent; const line = (text: string) => ({ invocationId: '', stream: 'stdout', at: '2026-11-21T09:00:00Z', text, error: false }) as RunOutputLine; +const statement = (n: number, status: RunStatement['status'] = 'completed') => ({ id: `s${n}`, startedAt: `2026-11-21T09:00:${String(n).padStart(2, '0')}Z`, status, sequence: 0 }) as RunStatement; /** A client that answers each read from a queue and records what it was asked. */ -function client(answers: { events?: { events: RunEvent[]; nextCursor: number | null }[]; output?: (RunOutputFollow | null)[] }) { +function client(answers: { events?: { events: RunEvent[]; nextCursor: number | null }[]; output?: (RunOutputFollow | null)[]; statements?: RunStatementPage[] }) { const asked: string[] = []; const fake = { listRunEvents: async (_: Scope, id: string, query: { after?: number }) => { @@ -21,6 +22,10 @@ function client(answers: { events?: { events: RunEvent[]; nextCursor: number | n listRunOutput: async (_: Scope, id: string) => { asked.push(`recall output ${id}`); return [line('from recall')]; + }, + listRunStatements: async (_: Scope, id: string, after: number | null) => { + asked.push(`statements ${id} after ${after ?? '-'}`); + return answers.statements!.shift()!; } }; return { fake: fake as unknown as ApiClient, asked }; @@ -59,6 +64,29 @@ describe('following a run', () => { const lines = await followOutput(fake, scope, newFollow(), { id: 'r1', ended: false }); expect([lines.map((l) => [l.text, l.runId]), asked]).toEqual([[['from recall', 'r1']], ['output r1 after -', 'recall output r1']]); }); + + it('reads statements on while pages are full, keeps the latest record of each, and numbers them by start', async () => { + const { fake, asked } = client({ + statements: [ + // Listed by first new event, not by start: the second page starts before part of the first. + { statements: [statement(5, 'running'), statement(3)], cursor: 10, more: true }, + { statements: [statement(1)], cursor: 12, more: false }, + // Later the running one finishes: listed again, it replaces its earlier record. + { statements: [statement(5)], cursor: 15, more: false } + ] + }); + const follow = newFollow(); + const shown = (rows: RunStatement[]) => rows.map((s) => [s.sequence, s.id, s.status]); + const first = shown(await followStatements(fake, scope, follow, { id: 'r1', ended: false })); + const second = shown(await followStatements(fake, scope, follow, { id: 'r1', ended: true })); + const third = shown(await followStatements(fake, scope, follow, { id: 'r1', ended: true })); + expect([first, second, third, asked]).toEqual([ + [[1, 's1', 'completed'], [2, 's3', 'completed'], [3, 's5', 'running']], + [[1, 's1', 'completed'], [2, 's3', 'completed'], [3, 's5', 'completed']], + [[1, 's1', 'completed'], [2, 's3', 'completed'], [3, 's5', 'completed']], + ['statements r1 after -', 'statements r1 after 10', 'statements r1 after 12'] + ]); + }); }); /** A client whose reads wait until the test answers or fails them. */ @@ -67,7 +95,8 @@ function waitingClient() { const held = (after: number | null) => new Promise((answer, fail) => reads.push({ after, answer, fail })); const fake = { listRunEvents: (_: Scope, __: string, query: { after?: number }) => held(query.after ?? null), - followRunOutput: (_: Scope, __: string, after: number | null) => held(after) + followRunOutput: (_: Scope, __: string, after: number | null) => held(after), + listRunStatements: (_: Scope, __: string, after: number | null) => held(after) }; return { fake: fake as unknown as ApiClient, reads }; } @@ -84,6 +113,12 @@ const followers = [ read: async (fake: ApiClient, follow: RunFollow, ended: boolean) => (await followOutput(fake, scope, follow, { id: 'r1', ended })).map((l) => Number(l.text)), answer: (numbers: number[]) => ({ lines: numbers.map((n) => line(String(n))), logs: [], last: Math.max(...numbers), replaced: false }) + }, + { + name: 'followStatements', + read: async (fake: ApiClient, follow: RunFollow, ended: boolean) => + (await followStatements(fake, scope, follow, { id: 'r1', ended })).map((s) => Number(s.id.slice(1))), + answer: (numbers: number[]): RunStatementPage => ({ statements: numbers.map((n) => statement(n)), cursor: Math.max(...numbers), more: false }) } ]; /** Lets settled promises run their continuations. */ diff --git a/ui/src/routes/runs/[id]/api/follow.ts b/ui/src/routes/runs/[id]/api/follow.ts index b7fed76a2b..d8ef5df753 100644 --- a/ui/src/routes/runs/[id]/api/follow.ts +++ b/ui/src/routes/runs/[id]/api/follow.ts @@ -1,6 +1,6 @@ -// Reading a run's events and output on from where the last read stopped. Side effects: the client. +// Reading a run's events, output and statements on from where the last read stopped. Side effects: the client. -import { RECALL_EVENT_TYPES, SCHEDULER_FACTS, type ApiClient, type RunEvent, type RunOutputLine, type Scope } from '$lib/api'; +import { RECALL_EVENT_TYPES, SCHEDULER_FACTS, type ApiClient, type RunEvent, type RunOutputLine, type RunStatement, type Scope } from '$lib/api'; /** A read under way, and whether the run had ended when it started. */ type Reading = { ended: boolean; done: Promise }; @@ -16,8 +16,13 @@ export type RunFollow = { lastLine: number | null; logs: RunEvent[]; outputDone: boolean; - /** The reads under way: one at most of the events and one of the output, as each appends from the cursor it started at. */ - reading: { events?: Reading; output?: Reading }; + /** The statements read so far by ID: a later page's record of one replaces the earlier. */ + statements: Map; + /** Where the last statements page stopped, to read on after. */ + statementCursor: number | null; + statementsDone: boolean; + /** The reads under way: one at most of each kind, as each carries on from the cursor it started at. */ + reading: { events?: Reading; output?: Reading; statements?: Reading }; }; /** @@ -31,14 +36,14 @@ const EVENT_PAGES = 5; const EVENT_PAGE = 5000; export function newFollow(): RunFollow { - return { events: [], cursor: null, eventsDone: false, lines: [], lastLine: null, logs: [], outputDone: false, reading: {} }; + return { events: [], cursor: null, eventsDone: false, lines: [], lastLine: null, logs: [], outputDone: false, statements: new Map(), statementCursor: null, statementsDone: false, reading: {} }; } /** * Runs `read` unless one is under way, which the caller then shares. A caller that saw the run ended waits out * a read started before that, whether it works or fails, and then reads once more for the run's last part. */ -async function readAlone(follow: RunFollow, what: 'events' | 'output', ended: boolean, read: () => Promise): Promise { +async function readAlone(follow: RunFollow, what: 'events' | 'output' | 'statements', ended: boolean, read: () => Promise): Promise { while (!follow[`${what}Done`]) { const under = follow.reading[what]; if (!under) { @@ -83,3 +88,22 @@ export async function followOutput(client: ApiClient, scope: Scope, follow: RunF }); return follow.lines; } + +/** + * The run's statements in start order, numbered from 1: those read and any that started or moved on since. A read + * goes on until a page is not full: a page costs the server only the statements it lists, and a run that has + * ended is not signalled again to read the rest later. + */ +export async function followStatements(client: ApiClient, scope: Scope, follow: RunFollow, { id, ended }: { id: string; ended: boolean }): Promise { + await readAlone(follow, 'statements', ended, async () => { + for (let more = true; more; ) { + const read = await client.listRunStatements(scope, id, follow.statementCursor); + for (const s of read.statements) follow.statements.set(s.id, s); + follow.statementCursor = read.cursor ?? follow.statementCursor; + more = read.more; + } + follow.statementsDone = ended; + }); + const at = (s: RunStatement) => s.startedAt || '\uffff'; + return [...follow.statements.values()].sort((a, b) => (at(a) < at(b) ? -1 : at(a) > at(b) ? 1 : 0)).map((s, i) => ({ ...s, sequence: i + 1 })); +} diff --git a/ui/src/routes/runs/[id]/run-tabs.svelte b/ui/src/routes/runs/[id]/run-tabs.svelte index dd2d2f564e..09b492200c 100644 --- a/ui/src/routes/runs/[id]/run-tabs.svelte +++ b/ui/src/routes/runs/[id]/run-tabs.svelte @@ -199,7 +199,7 @@

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} view.focusNode(key, 'cost')} /> diff --git a/ui/src/routes/runs/[id]/state.svelte.ts b/ui/src/routes/runs/[id]/state.svelte.ts index a2ec640a5f..4e541353e5 100644 --- a/ui/src/routes/runs/[id]/state.svelte.ts +++ b/ui/src/routes/runs/[id]/state.svelte.ts @@ -1,12 +1,12 @@ import { to } from '$lib/paths'; -import { STATEMENT_LIMIT, type MemberRetryScope, type RunEvent, type RunNode, type RunNodeError } from '$lib/api'; +import { type MemberRetryScope, type RunEvent, type RunNode, type RunNodeError } from '$lib/api'; import { untrack } from 'svelte'; -import { followEvents, followOutput, newFollow, type RunFollow } from './api/follow'; +import { followEvents, followOutput, followStatements, newFollow, type RunFollow } from './api/follow'; import { errorMessage } from '$lib/platform/labels'; import { app } from '$lib/state/app.svelte'; import { createResource } from '$lib/state/resource.svelte'; import { createSelection } from '$lib/state/selection.svelte'; -import { nodeLabel, shortRunId } from '$lib/operate/labels'; +import { nodeLabel } from '$lib/operate/labels'; import { planHref } from '$lib/run/command'; import { pageMemory } from './utils/page-memory'; import { runFailures, summaryOf, withNameToggled, type RunFailure } from './utils'; @@ -89,7 +89,7 @@ export function createRunDetailState(runId: string) { } }; } - // Each run's events and output carry on from where the last read stopped, and a run read once + // Each run's events, output and statements carry on from where the last read stopped, and a run read once // after it ended is not read again: its record cannot change. const follows = new Map(); const followOf = (id: string) => follows.get(id) ?? follows.set(id, newFollow()).get(id)!; @@ -119,7 +119,7 @@ export function createRunDetailState(runId: string) { ); /** The runs' events with the lines their nodes logged with `ctx.log`, in time order. */ const events = $derived(nodeLogs.length ? [...(eventsRes.data ?? []), ...nodeLogs].sort((a, b) => a.occurredAt.localeCompare(b.occurredAt)) : (eventsRes.data ?? [])); - const statementsOf = perRun((id) => app.client.listRunStatements(app.scope!, id)); + const statementsOf = perRun((id) => followStatements(app.client, app.scope!, followOf(id), { id, ended: endedRuns().has(id) })); const statementsRes = createResource((client) => (client.supports('listRunStatements') ? statementsOf.read() : Promise.resolve([])), runTopics, BULKY); // A run's cost arrives only with a warehouse sync, not as the run moves. const costOf = perRun((id) => app.client.listRunCost(app.scope!, id), () => ['warehouse_sync']); @@ -193,13 +193,6 @@ export function createRunDetailState(runId: string) { : [] ); const statements = $derived(statementsRes.data ?? []); - /** The page's runs, by job, whose statements reached the read's limit: only their first ones are listed. */ - const cappedStatements = $derived.by(() => { - const counts = new Map(); - for (const s of statements) counts.set(s.runId, (counts.get(s.runId) ?? 0) + 1); - const runs = [detailRes.data?.run, ...(detailRes.data?.children ?? [])]; - return [...counts].filter(([, n]) => n >= STATEMENT_LIMIT).map(([id]) => runs.find((r) => r?.id === id)?.jobKey ?? shortRunId(id)); - }); const cost = $derived(costRes.data ? runCostOf(costRes.data) : null); let showDetails = $state(false); @@ -522,9 +515,6 @@ export function createRunDetailState(runId: string) { get statements() { return statements; }, - get cappedStatements() { - return cappedStatements; - }, get selected() { return selected; }, diff --git a/ui/src/routes/runs/[id]/statements-tab.svelte b/ui/src/routes/runs/[id]/statements-tab.svelte index eb785745f9..9ad35c446c 100644 --- a/ui/src/routes/runs/[id]/statements-tab.svelte +++ b/ui/src/routes/runs/[id]/statements-tab.svelte @@ -8,7 +8,7 @@ import CircleXIcon from '@lucide/svelte/icons/circle-x'; import CircleSlashIcon from '@lucide/svelte/icons/circle-slash'; import LoaderIcon from '@lucide/svelte/icons/loader-circle'; - import { STATEMENT_LIMIT, type RunStatement } from '$lib/api'; + import type { RunStatement } from '$lib/api'; import SqlBlock from '$lib/components/code/sql-block.svelte'; import CopyButton from '$lib/components/copy-button.svelte'; import { formatStamp } from '$lib/format/time'; @@ -17,8 +17,7 @@ import { formatSpan } from './utils'; /** `focusId`: a statement to open and scroll to, as when a check's "In Statements" was clicked. */ - /** `capped`: the runs, by job, whose statements reached the read's limit, so only their first ones are listed. */ - let { statements, total, grouped, focusId = null, capped = [] }: { statements: RunStatement[]; total: number; grouped: boolean; focusId?: string | null; capped?: string[] } = $props(); + let { statements, total, grouped, focusId = null }: { statements: RunStatement[]; total: number; grouped: boolean; focusId?: string | null } = $props(); type SqlState = { state: 'loading' } | { state: 'ok'; sql: string | null } | { state: 'error'; message: string }; let open = $state>(new Set()); @@ -88,9 +87,6 @@ ]); -{#if capped.length} -

Only the first {STATEMENT_LIMIT.toLocaleString('en-GB')} queries of {capped.join(', ')} are listed; the rest are in the warehouse's query history.

-{/if} st.id} empty={total ? 'No queries match the filter.' : 'No queries yet.'}> {#snippet row(st)} toggle(st)}> @@ -147,11 +143,6 @@