From 1c688bc5d104c8b72bc6bf97c81110e40164aaa5 Mon Sep 17 00:00:00 2001 From: Ning Sun Date: Wed, 25 Nov 2026 16:49:44 +0800 Subject: [PATCH] fix(postgres): check the COPY FROM STDIN payload bound first and make it configurable The 64 MiB bound on a table-less COPY FROM STDIN payload (influxdb line protocol, OTLP, Prometheus Remote Write) was checked only after the chunk had been charged against the shared request-memory limiter, so a chunk the bound rejects could first stall on the limiter's Wait policy until its timeout and then surface a misleading "Timeout waiting for memory quota" (53000) instead of the bound's own error. The bound is now checked before the charge: a rejected chunk neither waits for nor takes permits. The bound also becomes `postgres.max_copy_in_payload` (default 64MB, 0 disables it), mirroring `http.body_limit`, and the error names it as a human-readable size (`64.0MiB`) instead of a raw byte count. Tests: unit tests for the bound; servers-crate tests driving it end to end against the OTLP double (default, configured, unbounded, and bound before quota); tests-integration coverage through the real line-protocol pipeline; config-loading assertions and the regenerated config docs. Signed-off-by: Ning Sun --- config/config.md | 2 + config/frontend.example.toml | 5 + config/standalone.example.toml | 5 + src/cmd/src/frontend.rs | 5 + src/cmd/src/standalone.rs | 5 + src/frontend/src/server.rs | 1 + src/frontend/src/service_config/postgres.rs | 16 ++ src/servers/src/postgres.rs | 7 + src/servers/src/postgres/copy_in/mod.rs | 109 ++++++-- src/servers/src/postgres/server.rs | 17 +- src/servers/tests/postgres/mod.rs | 235 ++++++++++++++++++ tests-integration/src/test_util.rs | 27 +- .../src/tests/postgres_copy_in_test.rs | 152 ++++++++--- 13 files changed, 540 insertions(+), 46 deletions(-) diff --git a/config/config.md b/config/config.md index 50081ebcd85..c7bfe75e7ce 100644 --- a/config/config.md +++ b/config/config.md @@ -68,6 +68,7 @@ | `postgres.addr` | String | `127.0.0.1:4003` | The addr to bind the PostgresSQL server. | | `postgres.runtime_size` | Integer | `2` | The number of server worker threads. | | `postgres.keep_alive` | String | `0s` | Server-side keep-alive time.
Set to 0 (default) to disable. | +| `postgres.max_copy_in_payload` | String | `64MB` | Maximum size of a table-less `COPY ... FROM STDIN` payload: the influxdb line protocol, OTLP and Prometheus Remote Write formats, which buffer the whole payload until the copy completes, like an HTTP request body.
Table-bound formats (csv, jsonl, arrow) stream and are not bound by it.
The following units are supported: `B`, `KB`, `KiB`, `MB`, `MiB`, `GB`, `GiB`, `TB`, `TiB`, `PB`, `PiB`.
Set to 0 to disable limit. | | `postgres.tls` | -- | -- | PostgresSQL server TLS options, see `mysql.tls` section. | | `postgres.tls.mode` | String | `disable` | TLS mode. | | `postgres.tls.cert_path` | String | Unset | Certificate file path. | @@ -352,6 +353,7 @@ | `postgres.addr` | String | `127.0.0.1:4003` | The addr to bind the PostgresSQL server. | | `postgres.runtime_size` | Integer | `2` | The number of server worker threads. | | `postgres.keep_alive` | String | `0s` | Server-side keep-alive time.
Set to 0 (default) to disable. | +| `postgres.max_copy_in_payload` | String | `64MB` | Maximum size of a table-less `COPY ... FROM STDIN` payload: the influxdb line protocol, OTLP and Prometheus Remote Write formats, which buffer the whole payload until the copy completes, like an HTTP request body.
Table-bound formats (csv, jsonl, arrow) stream and are not bound by it.
The following units are supported: `B`, `KB`, `KiB`, `MB`, `MiB`, `GB`, `GiB`, `TB`, `TiB`, `PB`, `PiB`.
Set to 0 to disable limit. | | `postgres.tls` | -- | -- | PostgresSQL server TLS options, see `mysql.tls` section. | | `postgres.tls.mode` | String | `disable` | TLS mode. | | `postgres.tls.cert_path` | String | Unset | Certificate file path. | diff --git a/config/frontend.example.toml b/config/frontend.example.toml index fa1a99d185a..2fd1b7a20ef 100644 --- a/config/frontend.example.toml +++ b/config/frontend.example.toml @@ -221,6 +221,11 @@ runtime_size = 2 ## Server-side keep-alive time. ## Set to 0 (default) to disable. keep_alive = "0s" +## Maximum size of a table-less `COPY ... FROM STDIN` payload: the influxdb line protocol, OTLP and Prometheus Remote Write formats, which buffer the whole payload until the copy completes, like an HTTP request body. +## Table-bound formats (csv, jsonl, arrow) stream and are not bound by it. +## The following units are supported: `B`, `KB`, `KiB`, `MB`, `MiB`, `GB`, `GiB`, `TB`, `TiB`, `PB`, `PiB`. +## Set to 0 to disable limit. +max_copy_in_payload = "64MB" ## PostgresSQL server TLS options, see `mysql.tls` section. [postgres.tls] diff --git a/config/standalone.example.toml b/config/standalone.example.toml index e41b423466f..25cb0c14aec 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -201,6 +201,11 @@ runtime_size = 2 ## Server-side keep-alive time. ## Set to 0 (default) to disable. keep_alive = "0s" +## Maximum size of a table-less `COPY ... FROM STDIN` payload: the influxdb line protocol, OTLP and Prometheus Remote Write formats, which buffer the whole payload until the copy completes, like an HTTP request body. +## Table-bound formats (csv, jsonl, arrow) stream and are not bound by it. +## The following units are supported: `B`, `KB`, `KiB`, `MB`, `MiB`, `GB`, `GiB`, `TB`, `TiB`, `PB`, `PiB`. +## Set to 0 to disable limit. +max_copy_in_payload = "64MB" ## PostgresSQL server TLS options, see `mysql.tls` section. [postgres.tls] diff --git a/src/cmd/src/frontend.rs b/src/cmd/src/frontend.rs index 7a430d7619d..4220f243297 100644 --- a/src/cmd/src/frontend.rs +++ b/src/cmd/src/frontend.rs @@ -777,6 +777,7 @@ mod tests { assert_eq!(ReadableSize::mb(64), opts.http.body_limit); assert_eq!(opts.mysql.addr, "127.0.0.1:5678"); assert_eq!(opts.postgres.addr, "127.0.0.1:5432"); + assert_eq!(ReadableSize::mb(64), opts.postgres.max_copy_in_payload); let internal_grpc = opts.internal_grpc.as_ref().unwrap(); assert_eq!(internal_grpc.bind_addr, "127.0.0.1:4010"); @@ -806,6 +807,9 @@ mod tests { timeout = "0s" body_limit = "2GB" + [postgres] + max_copy_in_payload = "128MB" + [opentsdb] enable = false @@ -827,6 +831,7 @@ mod tests { assert_eq!(Duration::from_secs(0), fe_opts.http.timeout); assert_eq!(ReadableSize::gb(2), fe_opts.http.body_limit); + assert_eq!(ReadableSize::mb(128), fe_opts.postgres.max_copy_in_payload); assert_eq!("debug", fe_opts.logging.level.as_ref().unwrap()); assert_eq!( diff --git a/src/cmd/src/standalone.rs b/src/cmd/src/standalone.rs index 934429517f4..c66b27d46e5 100644 --- a/src/cmd/src/standalone.rs +++ b/src/cmd/src/standalone.rs @@ -1404,6 +1404,9 @@ mod tests { timeout = "33s" body_limit = "128MB" + [postgres] + max_copy_in_payload = "0B" + [opentsdb] enable = true @@ -1433,6 +1436,8 @@ mod tests { assert_eq!("127.0.0.1:4000".to_string(), fe_opts.http.addr); assert_eq!(Duration::from_secs(33), fe_opts.http.timeout); assert_eq!(ReadableSize::mb(128), fe_opts.http.body_limit); + // The standalone mirrors the frontend's `[postgres]` options. + assert_eq!(ReadableSize(0), fe_opts.postgres.max_copy_in_payload); assert_eq!("127.0.0.1:4001".to_string(), fe_opts.grpc.bind_addr); assert!(fe_opts.mysql.enable); assert_eq!("127.0.0.1:4002", fe_opts.mysql.addr); diff --git a/src/frontend/src/server.rs b/src/frontend/src/server.rs index bc16a4cfa10..56219164f9c 100644 --- a/src/frontend/src/server.rs +++ b/src/frontend/src/server.rs @@ -435,6 +435,7 @@ where .with_influxdb_handler(instance.clone()) .with_otlp_handler(instance.clone(), prom_store.with_metric_engine) .with_memory_limiter(self.server_memory_limiter.clone()) + .with_max_copy_in_payload(opts.max_copy_in_payload) .with_prom_remote_write( instance.clone(), Some(instance.clone()), diff --git a/src/frontend/src/service_config/postgres.rs b/src/frontend/src/service_config/postgres.rs index 015c968386c..c337db457bb 100644 --- a/src/frontend/src/service_config/postgres.rs +++ b/src/frontend/src/service_config/postgres.rs @@ -12,9 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +use common_base::readable_size::ReadableSize; use serde::{Deserialize, Serialize}; +use servers::postgres::COPY_IN_MAX_PAYLOAD_BYTES; use servers::tls::TlsOption; +fn default_max_copy_in_payload() -> ReadableSize { + ReadableSize(COPY_IN_MAX_PAYLOAD_BYTES) +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct PostgresOptions { pub enable: bool, @@ -28,6 +34,15 @@ pub struct PostgresOptions { #[serde(default = "Default::default")] #[serde(with = "humantime_serde")] pub keep_alive: std::time::Duration, + /// Maximum size of a table-less `COPY ... FROM STDIN` payload: the + /// influxdb line protocol, OTLP and Prometheus Remote Write formats, + /// which buffer the whole payload until the copy completes, like an + /// HTTP request body. Table-bound formats (csv, jsonl, arrow) stream + /// and are not bound by it. + /// The following units are supported: `B`, `KB`, `KiB`, `MB`, `MiB`, `GB`, `GiB`, `TB`, `TiB`, `PB`, `PiB`. + /// Set to 0 to disable limit. + #[serde(default = "default_max_copy_in_payload")] + pub max_copy_in_payload: ReadableSize, } impl Default for PostgresOptions { @@ -38,6 +53,7 @@ impl Default for PostgresOptions { runtime_size: 2, tls: Default::default(), keep_alive: std::time::Duration::from_secs(0), + max_copy_in_payload: default_max_copy_in_payload(), } } } diff --git a/src/servers/src/postgres.rs b/src/servers/src/postgres.rs index d3bccb88d4e..7f00d7e8867 100644 --- a/src/servers/src/postgres.rs +++ b/src/servers/src/postgres.rs @@ -33,6 +33,7 @@ use std::sync::Arc; use std::sync::atomic::AtomicBool; use ::auth::{UserInfoRef, UserProviderRef}; +pub use copy_in::COPY_IN_MAX_PAYLOAD_BYTES; use derive_builder::Builder; use pgwire::api::auth::{AuthDriver, ServerParameterProvider, StartupHandler}; use pgwire::api::query::{ExtendedQueryHandler, SimpleQueryHandler}; @@ -96,6 +97,9 @@ pub struct PostgresServerHandlerInner { otlp_handler: Option, otlp_with_metric_engine: bool, memory_limiter: ServerMemoryLimiter, + /// Upper bound of a table-less COPY FROM STDIN payload, in bytes; 0 is + /// unbounded. Checked before the chunk is charged against the limiter. + max_copy_in_payload: u64, /// Completes `COPY FROM STDIN WITH (FORMAT promwrite)` payloads /// through the shared remote-write ingestion core — the same state /// the `/v1/prometheus/write` endpoint runs. @@ -126,6 +130,8 @@ pub(crate) struct MakePostgresServerHandler { otlp_with_metric_engine: bool, #[builder(default)] memory_limiter: ServerMemoryLimiter, + #[builder(default = "COPY_IN_MAX_PAYLOAD_BYTES")] + max_copy_in_payload: u64, #[builder(default)] prom_write_state: Option, user_provider: Option, @@ -182,6 +188,7 @@ impl MakePostgresServerHandler { otlp_handler: self.otlp_handler.clone(), otlp_with_metric_engine: self.otlp_with_metric_engine, memory_limiter: self.memory_limiter.clone(), + max_copy_in_payload: self.max_copy_in_payload, prom_write_state: self.prom_write_state.clone(), force_tls: self.force_tls, auth_driver: AuthDriver::new(self.param_provider.clone()) diff --git a/src/servers/src/postgres/copy_in/mod.rs b/src/servers/src/postgres/copy_in/mod.rs index 5dfda180267..db4fb3b1715 100644 --- a/src/servers/src/postgres/copy_in/mod.rs +++ b/src/servers/src/postgres/copy_in/mod.rs @@ -53,6 +53,7 @@ use api::v1::{ }; use async_trait::async_trait; use codec::{CopyFormat, RecordParser, TableBoundCodec}; +use common_base::readable_size::ReadableSize; use common_catalog::consts::{TRACE_TABLE_NAME, TRACE_TABLE_NAME_SESSION_KEY}; use common_grpc::precision::Precision; use common_query::OutputData; @@ -94,11 +95,12 @@ use crate::request_memory_limiter::ServerMemoryLimiter; /// the per-batch fixed costs negligible. pub(crate) const COPY_IN_FLUSH_ROWS: usize = 32768; -/// Upper bound of a table-less COPY FROM STDIN payload (influxdb line -/// protocol, OTLP). One COPY statement is one bounded ingestion request -/// (the whole payload is buffered like one HTTP request body); a larger -/// import is multiple COPY statements. -pub(crate) const COPY_IN_MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024; +/// Default upper bound of a table-less COPY FROM STDIN payload (influxdb +/// line protocol, OTLP, Prometheus Remote Write). One COPY statement is one +/// bounded ingestion request (the whole payload is buffered like one HTTP +/// request body); a larger import is multiple COPY statements. Deployments +/// override it with `postgres.max_copy_in_payload` (0 disables the bound). +pub const COPY_IN_MAX_PAYLOAD_BYTES: u64 = 64 * 1024 * 1024; /// Builds a format from the format-neutral option set. type FormatBuilder = fn(options::CopyOptionSet) -> PgWireResult; @@ -568,8 +570,25 @@ impl CopyInState { } } - /// Feeds a `CopyData` chunk into the parser and buffers parsed rows - /// (csv) or payload bytes (influxdb). + /// Rejects a chunk that would grow the buffered payload past + /// `max_bytes` (0: unbounded). The caller checks it BEFORE charging the + /// chunk against the shared limiter: a chunk the bound rejects must + /// neither wait for permits nor take memory that other requests need. + fn check_payload_bound(&self, chunk_bytes: u64, max_bytes: u64) -> PgWireResult<()> { + if max_bytes == 0 { + return Ok(()); + } + match self.buffered_bytes().checked_add(chunk_bytes) { + Some(total) if total <= max_bytes => Ok(()), + _ => Err(bad_copy_data(format!( + "COPY FROM STDIN payload exceeds the {} limit; split the import into multiple COPY statements", + ReadableSize(max_bytes) + ))), + } + } + + /// Buffers a `CopyData` chunk of a table-less payload. The payload bound + /// is the caller's job ([`Self::check_payload_bound`]). fn feed(&mut self, data: &[u8]) -> PgWireResult<()> { match &mut self.payload { Payload::Table { .. } => return Err(bad_copy_data("Table requires accounted decode")), @@ -578,12 +597,6 @@ impl CopyInState { Payload::Influxdb { data: buffered, .. } | Payload::Otlp { data: buffered, .. } | Payload::PromWrite { data: buffered, .. } => { - if buffered.len() + data.len() > COPY_IN_MAX_PAYLOAD_BYTES { - return Err(bad_copy_data(format!( - "COPY FROM STDIN payload exceeds the {} limit; split the import into multiple COPY statements", - COPY_IN_MAX_PAYLOAD_BYTES - ))); - } buffered.extend_from_slice(data); } } @@ -1356,6 +1369,12 @@ impl CopyHandler for PostgresServerHandlerInner { } else if state.buffers_payload() { let chunk_bytes = u64::try_from(copy_data.data.len()) .map_err(|_| bad_copy_data("chunk too large"))?; + let buffered_after = state.buffered_bytes() + chunk_bytes; + // The payload bound comes first: a chunk it rejects must not + // wait on the limiter's Wait policy (up to its timeout) nor + // take permits that other requests could use, and the client + // should see the bound's error, not a memory-quota one. + state.check_payload_bound(chunk_bytes, self.max_copy_in_payload)?; // Charge only this chunk's uncovered delta against the // shared budget: the limiter rounds each acquisition up to a // KiB, so per-chunk full charges would accumulate rounding @@ -1364,7 +1383,6 @@ impl CopyHandler for PostgresServerHandlerInner { // THIS request's own holdings — cross-request contention is // left to `acquire`, which applies the configured // Wait/Reject policy instead of failing fast. - let buffered_after = state.buffered_bytes() + chunk_bytes; // Granted coverage is KiB-aligned, so it can exceed the // buffered bytes: chunks inside the rounding headroom are // already covered. @@ -1808,4 +1826,67 @@ mod tests { .is_some() ); } + + /// A table-less (influxdb) copy state already holding `buffered` bytes. + fn influxdb_state_with(buffered: usize) -> CopyInState { + let mut state = CopyInState::new_influxdb( + &InfluxdbOptions { precision: None }, + session::context::QueryContext::arc(), + ); + if buffered > 0 { + state.feed(&vec![b'x'; buffered]).unwrap(); + } + state + } + + #[test] + fn test_payload_bound_boundary() { + let state = influxdb_state_with(1023); + // Filling the bound exactly is accepted ... + state.check_payload_bound(1, 1024).unwrap(); + // ... one byte more is not, as bad copy data (22P04) naming a + // human-readable size rather than a raw byte count. + let err = state.check_payload_bound(2, 1024).unwrap_err(); + assert_eq!(err.code(), PgErrorCode::Ec22P04.code()); + assert_eq!( + err.to_string(), + "User provided error: ErrorInfo: ERROR, 22P04, COPY FROM STDIN payload exceeds the \ + 1.0KiB limit; split the import into multiple COPY statements" + ); + } + + #[test] + fn test_payload_bound_default() { + // The shipped default renders as 64 MiB, not 67108864. + let state = influxdb_state_with(0); + state + .check_payload_bound(COPY_IN_MAX_PAYLOAD_BYTES, COPY_IN_MAX_PAYLOAD_BYTES) + .unwrap(); + let err = state + .check_payload_bound(COPY_IN_MAX_PAYLOAD_BYTES + 1, COPY_IN_MAX_PAYLOAD_BYTES) + .unwrap_err(); + assert!( + err.to_string() + .contains("exceeds the 64.0MiB limit; split the import"), + "{err}" + ); + } + + #[test] + fn test_payload_bound_zero_is_unbounded() { + influxdb_state_with(8) + .check_payload_bound(u64::MAX - 8, 0) + .unwrap(); + } + + #[test] + fn test_payload_bound_size_overflow_rejected() { + // Defensive: a size that cannot even be represented is rejected + // rather than wrapping around into the bound. + assert!( + influxdb_state_with(8) + .check_payload_bound(u64::MAX, u64::MAX) + .is_err() + ); + } } diff --git a/src/servers/src/postgres/server.rs b/src/servers/src/postgres/server.rs index 39a50ed047a..88b1d9a5878 100644 --- a/src/servers/src/postgres/server.rs +++ b/src/servers/src/postgres/server.rs @@ -20,6 +20,7 @@ use std::sync::Arc; use ::auth::UserProviderRef; use async_trait::async_trait; use catalog::process_manager::ProcessManagerRef; +use common_base::readable_size::ReadableSize; use common_runtime::Runtime; use common_runtime::runtime::RuntimeTrait; use common_telemetry::{debug, warn}; @@ -29,7 +30,9 @@ use tokio_rustls::TlsAcceptor; use crate::batcher::logical_table::LogicalTablePendingRowsBatcher; use crate::error::Result; -use crate::postgres::{MakePostgresServerHandler, MakePostgresServerHandlerBuilder}; +use crate::postgres::{ + COPY_IN_MAX_PAYLOAD_BYTES, MakePostgresServerHandler, MakePostgresServerHandlerBuilder, +}; use crate::prom_remote_write::validation::PromValidationMode; use crate::query_handler::CopyInHandlerRef; use crate::query_handler::InfluxdbLineProtocolHandlerRef; @@ -51,6 +54,7 @@ pub struct PostgresServer { otlp_handler: Option, otlp_with_metric_engine: bool, memory_limiter: ServerMemoryLimiter, + max_copy_in_payload: u64, prom_write_state: Option, bind_addr: Option, process_manager: Option, @@ -93,6 +97,7 @@ impl PostgresServer { otlp_handler: None, otlp_with_metric_engine: false, memory_limiter: ServerMemoryLimiter::default(), + max_copy_in_payload: COPY_IN_MAX_PAYLOAD_BYTES, prom_write_state: None, bind_addr: None, process_manager, @@ -111,6 +116,15 @@ impl PostgresServer { self } + /// Sets the upper bound of a table-less `COPY ... FROM STDIN` payload + /// (`postgres.max_copy_in_payload`); `0` leaves the payload unbounded. + /// The bound is checked before a chunk is charged against the shared + /// memory limiter. + pub fn with_max_copy_in_payload(mut self, limit: ReadableSize) -> Self { + self.max_copy_in_payload = limit.as_bytes(); + self + } + /// Wires the influxdb line-protocol handler used by table-less /// `COPY FROM STDIN WITH (FORMAT influxdb)` flushes — the same /// handler the HTTP influxdb write endpoints use, so a flushed batch @@ -187,6 +201,7 @@ impl PostgresServer { otlp_handler: self.otlp_handler.clone(), otlp_with_metric_engine: self.otlp_with_metric_engine, memory_limiter: self.memory_limiter.clone(), + max_copy_in_payload: self.max_copy_in_payload, prom_write_state, user_provider: make_handler.user_provider.clone(), param_provider: make_handler.param_provider.clone(), diff --git a/src/servers/tests/postgres/mod.rs b/src/servers/tests/postgres/mod.rs index a9f2305c8ba..193d9c02515 100644 --- a/src/servers/tests/postgres/mod.rs +++ b/src/servers/tests/postgres/mod.rs @@ -27,8 +27,10 @@ use auth::{ UserProvider, UserProviderRef, format_pg_scram_sha256_password_verifier, user_provider_from_option, }; +use common_base::readable_size::ReadableSize; use common_base::secrets::ExposeSecret; use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME}; +use common_memory_manager::OnExhaustedPolicy; use common_runtime::Builder as RuntimeBuilder; use common_runtime::runtime::BuilderBuild; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; @@ -42,8 +44,10 @@ use rustls::{Error, SignatureScheme}; use rustls_pki_types::{CertificateDer, ServerName}; use servers::error::Result; use servers::install_default_crypto_provider; +use servers::postgres::COPY_IN_MAX_PAYLOAD_BYTES; use servers::postgres::PostgresServer; use servers::query_handler::OpenTelemetryProtocolHandlerRef; +use servers::request_memory_limiter::ServerMemoryLimiter; use servers::server::Server; use servers::tls::{ReloadableTlsServerConfig, TlsOption}; use table::TableRef; @@ -1606,3 +1610,234 @@ async fn test_copy_in_multi_statement_rejected() -> Result<()> { server.shutdown().await.unwrap(); Ok(()) } + +const MIB: usize = 1024 * 1024; +const OTLP_LOGS_COPY: &str = "COPY FROM STDIN WITH (FORMAT otlp, signal 'logs')"; + +/// A server wired with the OTLP double, a memory limiter and a table-less +/// COPY payload bound, so table-less copies can be driven end to end and +/// checked for whether ingestion was reached. +async fn start_table_less_copy_server( + limiter: ServerMemoryLimiter, + max_copy_in_payload: ReadableSize, +) -> Result<(Box, u16, Arc)> { + common_telemetry::init_default_ut_logging(); + let _ = install_default_crypto_provider(); + let otlp_handler = Arc::new(crate::CountingOtlpHandler::new()); + let instance = Arc::new(create_testing_instance(MemTable::default_numbers_table())); + let copy_in_handler = Arc::new(crate::RecordingCopyInHandler::new( + instance.catalog_manager(), + )); + let io_runtime = RuntimeBuilder::default() + .worker_threads(2) + .thread_name("postgres-io-handlers") + .build() + .unwrap(); + let mut server = PostgresServer::new( + instance, + copy_in_handler, + false, + Arc::new(ReloadableTlsServerConfig::try_new(Default::default()).unwrap()), + 0, + io_runtime, + None, + None, + ) + .with_otlp_handler(otlp_handler.clone(), false) + .with_memory_limiter(limiter) + .with_max_copy_in_payload(max_copy_in_payload); + let listening = "127.0.0.1:0".parse::().unwrap(); + server.start(listening).await.unwrap(); + let port = server.bind_addr().unwrap().port(); + Ok((Box::new(server), port, otlp_handler)) +} + +/// A valid OTLP logs payload of exactly `bytes` bytes: one log record +/// whose string body is padded to size, so a payload that passes the bound +/// decodes instead of failing for another reason. +fn otlp_logs_payload_of_size(bytes: usize) -> bytes::Bytes { + use opentelemetry_proto::tonic::common::v1::AnyValue; + use opentelemetry_proto::tonic::common::v1::any_value::Value as AnyValueValue; + use opentelemetry_proto::tonic::logs::v1::{LogRecord, ScopeLogs}; + use std::cmp::Ordering; + + let build = |body_len: usize| ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord { + body: Some(AnyValue { + value: Some(AnyValueValue::StringValue("x".repeat(body_len))), + }), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + }; + let overhead = build(0).encode_to_vec().len(); + let mut body_len = bytes - overhead; + loop { + let encoded = build(body_len).encode_to_vec(); + match encoded.len().cmp(&bytes) { + Ordering::Equal => return bytes::Bytes::from(encoded), + // The body's varint length prefix grows with the body. + Ordering::Greater => body_len -= encoded.len() - bytes, + Ordering::Less => body_len += bytes - encoded.len(), + } + } +} + +/// Splits `payload` into `chunk`-sized CopyData messages. +fn chunks_of(payload: bytes::Bytes, chunk: usize) -> Vec { + (0..payload.len()) + .step_by(chunk) + .map(|start| payload.slice(start..(start + chunk).min(payload.len()))) + .collect() +} + +/// Asserts the error is the payload bound's (22P04) and returns its message. +fn copy_in_bound_message(error: PgError) -> String { + let message = error + .as_db_error() + .filter(|db_error| *db_error.code() == SqlState::BAD_COPY_FILE_FORMAT) + .map(|db_error| db_error.message().to_string()) + .unwrap_or_else(|| panic!("expected the payload bound's 22P04 error, got {error}")); + assert!(message.contains("exceeds the"), "{message}"); + message +} + +/// The default bound accepts a payload of exactly 64 MiB and rejects one +/// byte more — as bad copy data naming a human-readable size — whether the +/// excess arrives as many chunks or as one message; nothing is flushed and +/// the connection stays usable. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_copy_in_payload_bound_default() -> Result<()> { + let (server, port, otlp_handler) = start_table_less_copy_server( + ServerMemoryLimiter::default(), + ReadableSize(COPY_IN_MAX_PAYLOAD_BYTES), + ) + .await?; + let client = create_plain_connection(port, false).await.unwrap(); + + feed_copy_in( + &client, + OTLP_LOGS_COPY, + chunks_of(otlp_logs_payload_of_size(64 * MIB), MIB), + ) + .await + .unwrap(); + assert_eq!(otlp_handler.calls(), 1); + + for chunks in [ + chunks_of(otlp_logs_payload_of_size(64 * MIB + 1), MIB), + vec![otlp_logs_payload_of_size(64 * MIB + 1)], + ] { + let message = copy_in_bound_message( + feed_copy_in(&client, OTLP_LOGS_COPY, chunks) + .await + .expect_err("one byte over the bound must fail"), + ); + assert!( + message.contains( + "exceeds the 64.0MiB limit; split the import into multiple COPY statements" + ), + "{message}" + ); + // Rejected before ingestion. + assert_eq!(otlp_handler.calls(), 1); + // The connection stays usable. + client.simple_query("SELECT 1").await.unwrap(); + } + + server.shutdown().await.unwrap(); + Ok(()) +} + +/// `postgres.max_copy_in_payload` is honored, and 0 leaves the payload +/// unbounded. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_copy_in_payload_bound_configurable() -> Result<()> { + let (server, port, otlp_handler) = + start_table_less_copy_server(ServerMemoryLimiter::default(), ReadableSize::mb(8)).await?; + let client = create_plain_connection(port, false).await.unwrap(); + + feed_copy_in( + &client, + OTLP_LOGS_COPY, + chunks_of(otlp_logs_payload_of_size(8 * MIB), MIB), + ) + .await + .unwrap(); + let message = copy_in_bound_message( + feed_copy_in( + &client, + OTLP_LOGS_COPY, + vec![otlp_logs_payload_of_size(8 * MIB + 1)], + ) + .await + .expect_err("the configured bound must apply"), + ); + assert!(message.contains("exceeds the 8.0MiB limit"), "{message}"); + assert_eq!(otlp_handler.calls(), 1); + server.shutdown().await.unwrap(); + + let (server, port, otlp_handler) = + start_table_less_copy_server(ServerMemoryLimiter::default(), ReadableSize(0)).await?; + let client = create_plain_connection(port, false).await.unwrap(); + feed_copy_in( + &client, + OTLP_LOGS_COPY, + chunks_of(otlp_logs_payload_of_size(64 * MIB + 1), MIB), + ) + .await + .unwrap(); + assert_eq!(otlp_handler.calls(), 1); + server.shutdown().await.unwrap(); + Ok(()) +} + +/// The bound is checked before a chunk is charged against the memory +/// limiter: a chunk it rejects fails at once with the bound's error even +/// when the limiter's Wait policy would otherwise stall it, and the permits +/// held so far are released. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_copy_in_payload_bound_precedes_memory_quota() -> Result<()> { + // The test holds 15 MiB of the 80 MiB budget, so a copy that already + // buffers 60 MiB cannot get the next 10 MiB chunk from the limiter + // without waiting. That chunk also pushes the payload over the default + // bound. + let limiter = ServerMemoryLimiter::new( + 80 * MIB as u64, + OnExhaustedPolicy::Wait { + timeout: Duration::from_secs(60), + }, + ); + let held = limiter.acquire(15 * MIB as u64).await.unwrap(); + let (server, port, otlp_handler) = + start_table_less_copy_server(limiter.clone(), ReadableSize(COPY_IN_MAX_PAYLOAD_BYTES)) + .await?; + let client = create_plain_connection(port, false).await.unwrap(); + + let payload = otlp_logs_payload_of_size(70 * MIB); + let mut chunks = chunks_of(payload.slice(..60 * MIB), MIB); + chunks.push(payload.slice(60 * MIB..)); + // Under the old ordering the chunk would wait out the policy's timeout. + let error = tokio::time::timeout( + Duration::from_secs(20), + feed_copy_in(&client, OTLP_LOGS_COPY, chunks), + ) + .await + .expect("the bound must reject the chunk without waiting on the limiter") + .expect_err("the chunk exceeds the bound"); + copy_in_bound_message(error); + assert_eq!(otlp_handler.calls(), 0); + // Only the test's own reservation is left held. + assert_eq!(limiter.used_bytes(), 15 * MIB as u64); + client.simple_query("SELECT 1").await.unwrap(); + + drop(held); + assert_eq!(limiter.used_bytes(), 0); + server.shutdown().await.unwrap(); + Ok(()) +} diff --git a/tests-integration/src/test_util.rs b/tests-integration/src/test_util.rs index 9742fb5bb61..1f427c2689a 100644 --- a/tests-integration/src/test_util.rs +++ b/tests-integration/src/test_util.rs @@ -1277,6 +1277,30 @@ pub async fn setup_pg_server_with_user_provider( pub async fn setup_pg_server_for_frontend_instance( fe_instance_ref: Arc, user_provider: Option, +) -> Box { + start_pg_server(fe_instance_ref, user_provider, PostgresOptions::default()).await +} + +/// Sets up a standalone instance with a Postgres server configured by the +/// given `[postgres]` options; the options' `addr` is replaced with a free +/// port. +pub async fn setup_pg_server_with_postgres_options( + store_type: StorageType, + name: &str, + opts: PostgresOptions, +) -> (TestGuard, Arc>) { + let instance = setup_standalone_instance(name, store_type).await; + let pg_server = start_pg_server(instance.fe_instance().clone(), None, opts).await; + + (instance.guard, Arc::new(pg_server)) +} + +/// Builds and starts a Postgres server on an existing frontend instance +/// with the given `[postgres]` options, wired like `FrontendServer` does. +async fn start_pg_server( + fe_instance_ref: Arc, + user_provider: Option, + opts: PostgresOptions, ) -> Box { let runtime = RuntimeBuilder::default() .worker_threads(2) @@ -1288,7 +1312,7 @@ pub async fn setup_pg_server_for_frontend_instance( let opts = PostgresOptions { addr: fe_pg_addr.clone(), - ..Default::default() + ..opts }; let tls_server_config = Arc::new( ReloadableTlsServerConfig::try_new(opts.tls.clone()) @@ -1308,6 +1332,7 @@ pub async fn setup_pg_server_for_frontend_instance( ) .with_influxdb_handler(fe_instance_ref.clone()) .with_otlp_handler(fe_instance_ref.clone(), true) + .with_max_copy_in_payload(opts.max_copy_in_payload) .with_prom_remote_write( fe_instance_ref.clone(), Some(fe_instance_ref.clone()), diff --git a/tests-integration/src/tests/postgres_copy_in_test.rs b/tests-integration/src/tests/postgres_copy_in_test.rs index 4ed6df48ea3..d91b89a85d9 100644 --- a/tests-integration/src/tests/postgres_copy_in_test.rs +++ b/tests-integration/src/tests/postgres_copy_in_test.rs @@ -16,12 +16,15 @@ //! covering the full ingestion path (parser -> insert -> storage). use bytes::Bytes; +use common_base::readable_size::ReadableSize; use common_telemetry::init_default_ut_logging; use datatypes::arrow; +use frontend::service_config::PostgresOptions; use futures::SinkExt; use tokio_postgres::NoTls; +use tokio_postgres::error::SqlState; -use crate::test_util::{StorageType, setup_pg_server}; +use crate::test_util::{StorageType, setup_pg_server, setup_pg_server_with_postgres_options}; async fn connect(port: u16) -> tokio_postgres::Client { let url = format!("host=127.0.0.1 port={port} dbname=public connect_timeout=5"); @@ -1069,7 +1072,10 @@ async fn test_postgres_copy_in_influxdb_multiline_quoted_field() { server.shutdown().await.unwrap(); } -/// The payload is bounded by the HTTP write endpoints' own body limit. +/// A table-less payload is bounded by `postgres.max_copy_in_payload`, +/// 64 MiB by default: one byte over fails as bad copy data naming the +/// bound, before the buffered payload is handed to the line-protocol +/// pipeline, and the connection stays usable. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_postgres_copy_in_influxdb_payload_limit() { init_default_ut_logging(); @@ -1077,47 +1083,133 @@ async fn test_postgres_copy_in_influxdb_payload_limit() { let port = server.bind_addr().unwrap().port(); let client = connect(port).await; - // The HTTP write endpoints' default body limit (64 MiB) — kept in - // sync with servers::http::DEFAULT_BODY_LIMIT. + // A seed row, so "nothing of the rejected payload was written" is + // observable on a table that exists. + feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + vec![Bytes::from_static(b"m,host=seed v=0 1\n")], + ) + .await + .unwrap(); + + // Several 1 MiB chunks over the default bound, none containing a + // record boundary. let limit = 64 * 1024 * 1024; - // Several chunks over the limit, none containing a record boundary. - let chunk = vec![b'x'; 1024 * 1024]; - let mut sent = 0usize; - let mut sink = Box::pin( - client - .copy_in("COPY FROM STDIN WITH (FORMAT influxdb)") - .await - .unwrap(), - ); - while sent <= limit { - sink.as_mut() - .send(Bytes::from(chunk.clone())) - .await - .unwrap(); - sent += chunk.len(); + let chunk = Bytes::from(vec![b'x'; 1024 * 1024]); + let mut chunks = Vec::new(); + while chunks.len() * chunk.len() <= limit { + chunks.push(chunk.clone()); } - // The cap fires mid-stream; the error surfaces when the copy + // The bound fires mid-stream; the error surfaces when the copy // completes (the sink buffers sends locally). - let error = sink - .as_mut() - .finish() + let error = feed_copy_in(&client, "COPY FROM STDIN WITH (FORMAT influxdb)", chunks) .await .expect_err("expected the oversized payload to fail"); + let db_error = error.as_db_error().expect("expected a db error"); + assert_eq!(*db_error.code(), SqlState::BAD_COPY_FILE_FORMAT, "{error}"); assert!( - error - .as_db_error() - .map(|d| d.message().contains("exceeds")) - .unwrap_or(false), + db_error + .message() + .contains("exceeds the 64.0MiB limit; split the import into multiple COPY statements"), "unexpected error: {error}" ); - // The connection stays usable. - let messages = client.simple_query("SELECT 1").await.unwrap(); - assert!(!messages.is_empty()); + // Only the seed row exists, and the connection stays usable. + let rows = count_rows(&client, "SELECT count(*) FROM m").await; + assert_eq!(rows, 1); server.shutdown().await.unwrap(); } +/// `postgres.max_copy_in_payload` is honored end to end: a payload one +/// byte over the configured bound is rejected whole, and 0 removes the +/// bound. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_payload_bound_configurable() { + init_default_ut_logging(); + const BOUND: usize = 1024 * 1024; + // Valid line protocol a little over the bound, sent in several chunks. + let mut lines = String::new(); + let mut expected: i64 = 0; + while lines.len() <= BOUND { + lines.push_str(&format!( + "m,host=h{expected} v={expected} {}\n", + 1_000 + expected + )); + expected += 1; + } + let payload = Bytes::from(lines); + let chunks: Vec = (0..payload.len()) + .step_by(64 * 1024) + .map(|start| payload.slice(start..(start + 64 * 1024).min(payload.len()))) + .collect(); + + let (_guard, server) = setup_pg_server_with_postgres_options( + StorageType::File, + "pg_copy_in_influxdb_cap_configured", + PostgresOptions { + max_copy_in_payload: ReadableSize::mb(1), + ..Default::default() + }, + ) + .await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + let error = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + chunks.clone(), + ) + .await + .expect_err("expected the configured bound to reject the payload"); + let db_error = error.as_db_error().expect("expected a db error"); + assert_eq!(*db_error.code(), SqlState::BAD_COPY_FILE_FORMAT, "{error}"); + assert!( + db_error.message().contains("exceeds the 1.0MiB limit"), + "unexpected error: {error}" + ); + // Rejected whole: the table was never created. + assert!(client.simple_query("SELECT count(*) FROM m").await.is_err()); + server.shutdown().await.unwrap(); + + let (_guard, server) = setup_pg_server_with_postgres_options( + StorageType::File, + "pg_copy_in_influxdb_cap_unbounded", + PostgresOptions { + max_copy_in_payload: ReadableSize(0), + ..Default::default() + }, + ) + .await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + let rows = feed_copy_in(&client, "COPY FROM STDIN WITH (FORMAT influxdb)", chunks) + .await + .unwrap(); + assert_eq!(rows, expected as u64); + assert_eq!( + count_rows(&client, "SELECT count(*) FROM m").await, + expected + ); + server.shutdown().await.unwrap(); +} + +/// Runs a `count(*)` query and returns the single resulting value. +async fn count_rows(client: &tokio_postgres::Client, sql: &str) -> i64 { + let messages = client.simple_query(sql).await.unwrap(); + let mut counts = messages.iter().filter_map(|message| match message { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::parse::), + _ => None, + }); + let count = counts + .next() + .expect("one count row") + .expect("a valid count"); + assert!(counts.next().is_none(), "exactly one count row"); + count +} + /// The regression for the retired line-splitter's failure mode: with /// 32,767 ordinary records plus a multiline quoted record whose first /// physical line lands exactly on the old 32,768-line flush threshold —