Skip to main content

servers/postgres/copy_in/
mod.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! PostgreSQL `COPY ... FROM STDIN` (copy-in) support.
16//!
17//! The wire handshake is driven by pgwire: returning [`Response::CopyIn`]
18//! from a query handler makes the server send a `CopyInResponse` and enter
19//! the copy-in sub-protocol; subsequent `CopyData` messages from the client
20//! are dispatched to [`CopyHandler`], whose implementation below parses
21//! the data stream incrementally and flushes it into the query handler as
22//! [`RowInsertRequests`] batches.
23//!
24//! # Formats
25//!
26//! The supported formats are the explicit [`codec::CopyFormat`] enum —
27//! `csv` (table-bound, incremental row parsing) and `influxdb`
28//! (table-less, one bounded whole-payload request). Each format states
29//! its own target rule and ingestion shape in the match arms of the
30//! copy lifecycle below; adding a format is a new variant plus its
31//! arms. Builders resolve a `FORMAT` name (and its aliases) through
32//! [`REGISTERED_FORMATS`]. See the `codec` module docs.
33
34mod arrow;
35mod codec;
36mod csv;
37mod influxdb;
38mod jsonl;
39mod options;
40mod otlp;
41mod parse;
42mod prom_write;
43
44use std::fmt::Debug;
45use std::sync::Arc;
46use std::sync::atomic::AtomicU64;
47
48use crate::influxdb::InfluxdbRequest;
49use crate::query_handler::{CopyInHandler, PipelineHandlerRef};
50use api::helper::ColumnDataTypeWrapper;
51use api::v1::column_def::options_from_column_schema;
52use api::v1::{
53    Row as GrpcRow, RowInsertRequest, RowInsertRequests, Rows as GrpcRows, SemanticType,
54};
55use async_trait::async_trait;
56use codec::{CopyFormat, RecordParser, TableBoundCodec};
57use common_base::readable_size::ReadableSize;
58use common_catalog::consts::{TRACE_TABLE_NAME, TRACE_TABLE_NAME_SESSION_KEY};
59use common_grpc::precision::Precision;
60use common_query::OutputData;
61use common_telemetry::{info, warn};
62use datafusion::sql::sqlparser::ast::{CopyTarget, Statement as SqlParserStatement};
63use datatypes::data_type::DataType;
64use datatypes::schema::{ColumnSchema, SchemaRef};
65use futures::{Sink, SinkExt, stream};
66use influxdb::InfluxdbOptions;
67use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
68use otlp::{OtlpOptions, OtlpSignal};
69use pgwire::api::copy::CopyHandler;
70use pgwire::api::results::{CopyResponse, Response, Tag};
71use pgwire::api::{ClientInfo, PgWireConnectionState};
72use pgwire::error::{ErrorInfo, PgWireError, PgWireResult};
73use pgwire::messages::PgWireBackendMessage;
74use pgwire::messages::copy::{CopyData, CopyDone, CopyFail};
75use prom_write::{PromWriteOptions, PromWriteVersion};
76use prost::Message;
77use session::context::QueryContextRef;
78use snafu::ResultExt;
79use table::metadata::TableInfo;
80
81use crate::metrics::METRIC_POSTGRES_COPY_IN_ROWS;
82use crate::postgres::PostgresServerHandlerInner;
83use crate::postgres::types::PgErrorCode;
84use crate::postgres::utils::convert_err;
85use crate::request_memory_limiter::ServerMemoryLimiter;
86
87/// Number of parsed rows buffered before flushing a batch to the handler.
88///
89/// Each flush runs the full insert pipeline (catalog lookup, on-demand
90/// schema check, partition split, region write) and, without the
91/// pending-rows batcher, waits for it — so larger batches mean fewer
92/// round trips at the cost of linearly more memory per connection
93/// (decoder batch + rows buffer). The constant doubles as the arrow
94/// decoder's batch size. High-rate COPY users should enable the
95/// pending-rows batcher (`global-table-batch` / `BatcherOptions.protocols`
96/// containing `Postgres`), which turns flushes into enqueues and makes
97/// the per-batch fixed costs negligible.
98pub(crate) const COPY_IN_FLUSH_ROWS: usize = 32768;
99
100/// Default upper bound of a table-less COPY FROM STDIN payload (influxdb
101/// line protocol, OTLP, Prometheus Remote Write). One COPY statement is one
102/// bounded ingestion request (the whole payload is buffered like one HTTP
103/// request body); a larger import is multiple COPY statements. Deployments
104/// override it with `postgres.max_copy_in_payload` (0 disables the bound).
105pub const COPY_IN_MAX_PAYLOAD_BYTES: u64 = 64 * 1024 * 1024;
106
107/// Builds a format from the format-neutral option set.
108type FormatBuilder = fn(options::CopyOptionSet) -> PgWireResult<CopyFormat>;
109
110/// The registered COPY FROM STDIN formats: accepted `FORMAT` name to
111/// builder. Unimplemented PostgreSQL text/binary formats are registered
112/// to report a clear "not supported yet" instead of an unknown-format error.
113const REGISTERED_FORMATS: &[(&str, FormatBuilder)] = &[
114    ("csv", csv::build_csv_codec),
115    ("jsonl", jsonl::build_jsonl_codec),
116    // Alias matching the file-based format's name; it still means
117    // newline-delimited objects, not a top-level JSON array.
118    ("json", jsonl::build_jsonl_codec),
119    ("arrow", arrow::build_arrow_codec),
120    ("influxdb", influxdb::build_influxdb_codec),
121    ("influxdb_line", influxdb::build_influxdb_codec),
122    ("otlp", otlp::build_otlp_codec),
123    ("otlp_metrics", otlp::build_otlp_codec),
124    ("promwrite", prom_write::build_prom_write_codec),
125    ("text", build_unimplemented_text_codec),
126    ("txt", build_unimplemented_text_codec),
127    ("binary", build_unimplemented_binary_codec),
128];
129
130fn build_unimplemented_text_codec(_options: options::CopyOptionSet) -> PgWireResult<CopyFormat> {
131    Err(unsupported(
132        "the text format is not supported yet; use WITH (FORMAT csv)",
133    ))
134}
135
136fn build_unimplemented_binary_codec(_options: options::CopyOptionSet) -> PgWireResult<CopyFormat> {
137    Err(unsupported(
138        "COPY FROM STDIN WITH (FORMAT binary) is not supported yet",
139    ))
140}
141
142/// Resolves the format from the parsed options.
143fn resolve_format(options: &mut options::CopyOptionSet) -> PgWireResult<CopyFormat> {
144    let name = options.take_format()?.ok_or_else(|| {
145        unsupported(
146            "COPY FROM STDIN requires an explicit format in this version; use WITH (FORMAT csv)",
147        )
148    })?;
149    let builder = REGISTERED_FORMATS
150        .iter()
151        .find(|(registered, _)| *registered == name)
152        .map(|(_, builder)| *builder)
153        .ok_or_else(|| bad_copy_data(format!("unknown COPY format \"{}\"", name)))?;
154    builder(std::mem::take(options))
155}
156
157/// The parsed `COPY tbl [(columns)] FROM STDIN [(options)]` statement.
158#[derive(Debug, Clone)]
159pub(crate) struct CopyFromStdin {
160    /// Table name parts as written (`t`, `schema.t`, `catalog.schema.t`);
161    /// quoted names keep their case.
162    table: Vec<String>,
163    /// Requested column list; empty means all columns in table order.
164    columns: Vec<String>,
165    /// The resolved format with its validated options.
166    format: CopyFormat,
167}
168
169fn copy_in_error(code: PgErrorCode, message: impl Into<String>) -> PgWireError {
170    PgWireError::UserError(Box::new(code.to_err_info(message.into())))
171}
172
173pub(super) fn unsupported(message: impl Into<String>) -> PgWireError {
174    copy_in_error(PgErrorCode::Ec0A000, message)
175}
176
177fn bad_copy_data(message: impl Into<String>) -> PgWireError {
178    copy_in_error(PgErrorCode::Ec22P04, message)
179}
180
181fn invalid_text_repr(message: impl Into<String>) -> PgWireError {
182    copy_in_error(PgErrorCode::Ec22P02, message)
183}
184
185pub(crate) fn copy_in_must_run_alone_error() -> PgWireError {
186    PgWireError::UserError(Box::new(ErrorInfo::new(
187        "ERROR".to_string(),
188        PgErrorCode::Ec0A000.code(),
189        "COPY FROM STDIN must be executed alone".to_string(),
190    )))
191}
192
193/// Parses a leading `COPY ... FROM STDIN` statement from SQL text.
194///
195/// The statement is parsed textually — not through sqlparser — because the
196/// `WITH (...)` option list is open: formats may accept options beyond
197/// sqlparser's COPY grammar, and unknown options must reach the format
198/// codec instead of failing statement parsing. Returns `Ok(None)` when
199/// the string does not lead with a copy-in statement.
200pub(crate) fn copy_from_stdin_from_sql(sql: &str) -> PgWireResult<Option<CopyFromStdin>> {
201    let raw = match parse::scan_copy_from_stdin(sql)? {
202        parse::CopyInScan::NotCopyIn => return Ok(None),
203        parse::CopyInScan::CopyIn(raw) => raw,
204    };
205    let mut option_set = raw.options;
206    let format = resolve_format(&mut option_set)?;
207    Ok(Some(CopyFromStdin {
208        table: raw.table,
209        columns: raw.columns,
210        format,
211    }))
212}
213
214/// Whether an already-parsed statement is a `COPY ... FROM STDIN`; used to
215/// reject copy-in statements trailing other statements, where the textual
216/// scanner (which only sees statement-leading COPYs) does not see them.
217pub(crate) fn is_copy_from_stdin(statement: &SqlParserStatement) -> bool {
218    matches!(
219        statement,
220        SqlParserStatement::Copy {
221            to: false,
222            target: CopyTarget::Stdin,
223            ..
224        }
225    )
226}
227
228/// Resolves table name parts against the query context defaults.
229fn resolve_table_name(
230    query_ctx: &QueryContextRef,
231    parts: &[String],
232) -> PgWireResult<(String, String, String)> {
233    match parts {
234        [table] => Ok((
235            query_ctx.current_catalog().to_string(),
236            query_ctx.current_schema(),
237            table.clone(),
238        )),
239        [schema, table] => Ok((
240            query_ctx.current_catalog().to_string(),
241            schema.clone(),
242            table.clone(),
243        )),
244        [catalog, schema, table] => Ok((catalog.clone(), schema.clone(), table.clone())),
245        _ => Err(unsupported(format!(
246            "invalid table name for COPY: {}",
247            parts.join(".")
248        ))),
249    }
250}
251
252/// Per-connection state of an in-progress COPY FROM STDIN.
253///
254/// The payload shape follows the codec: table-bound formats (csv) parse
255/// records into rows against the targeted table's columns; table-less
256/// formats (influxdb line protocol) split the stream into complete
257/// lines that each route to their own measurement, and flush through
258/// the handler's line-protocol pipeline — the same one the HTTP write
259/// endpoint uses.
260pub(crate) struct CopyInState {
261    query_ctx: QueryContextRef,
262    payload: Payload,
263    /// Reservations against the shared request-memory limiter for the
264    /// bytes buffered by a table-less payload, acquired per CopyData
265    /// chunk as it arrives and held until the buffer is flushed or the
266    /// copy ends — the receive-stage counterpart of HTTP's
267    /// body-accounting middleware, so concurrent unfinished COPY
268    /// requests cannot retain unaccounted memory.
269    memory_guards: Vec<
270        common_memory_manager::MemoryGuard<crate::request_memory_metrics::RequestMemoryMetrics>,
271    >,
272    /// Payload bytes already covered by limiter grants, in the
273    /// limiter's KiB grant granularity. Chunks acquire only the
274    /// uncovered delta (`buffered_total - granted`), so rounding adds at
275    /// most one KiB for the whole stream instead of one per chunk.
276    granted_bytes: u64,
277    /// The resolved codec's name, for logging.
278    codec_name: &'static str,
279    /// The wire format code of the resolved codec.
280    codec_format_code: i8,
281    rows_written: u64,
282}
283
284/// The receive-stage reservation for one buffered payload, handed to
285/// the flush that consumes the payload: the guards must outlive the
286/// payload's bytes (they may coexist with the decode buffer or wait on
287/// decode quota), and `charged_bytes` is the payload's pre-charged
288/// reservation to hand to decode-side fits checks.
289pub(crate) struct BufferedReservation {
290    /// Held only for its Drop (the reservation release); never read.
291    #[allow(dead_code)]
292    guards: Vec<
293        common_memory_manager::MemoryGuard<crate::request_memory_metrics::RequestMemoryMetrics>,
294    >,
295    granted_bytes: u64,
296}
297
298impl BufferedReservation {
299    /// The payload bytes already charged at the receive stage; decode
300    /// paths take this as their pre-held reservation.
301    pub(crate) fn charged_bytes(&self) -> u64 {
302        self.granted_bytes
303    }
304}
305
306enum Payload {
307    /// Table-bound Arrow IPC batches, written without protobuf row conversion.
308    Arrow(Box<arrow::ArrowCopyState>),
309    /// Table-bound rows: parsed against `grpc_schema` and flushed to
310    /// `table_name` via `copy_in_insert`. The schema is cloned into each
311    /// flushed batch: `Rows.schema` is an owned `Vec` in the proto
312    /// request, so one copy per request is inherent.
313    Table {
314        grpc_schema: Vec<api::v1::ColumnSchema>,
315        table_name: String,
316        parser: Box<dyn RecordParser + Send>,
317        /// Parsed rows not yet flushed to the handler.
318        rows: Vec<GrpcRow>,
319        memory: TableCopyMemory,
320    },
321    /// The whole buffered influxdb line-protocol payload with its
322    /// request precision. One COPY statement is one bounded ingestion
323    /// request, buffered until `CopyDone` — exactly like one HTTP write
324    /// body — and record boundaries belong to the line-protocol parser,
325    /// never to the COPY layer.
326    Influxdb {
327        data: Vec<u8>,
328        precision: Option<Precision>,
329    },
330    /// The whole buffered OTLP payload with its validated options,
331    /// decoded and completed as one request at `CopyDone` through the
332    /// matching OTLP pipeline.
333    Otlp { data: Vec<u8>, options: OtlpOptions },
334    /// The whole buffered Prometheus Remote Write body with its
335    /// validated options, completed as one request at `CopyDone`
336    /// through the shared remote-write ingestion core.
337    PromWrite {
338        data: Vec<u8>,
339        options: PromWriteOptions,
340    },
341}
342
343/// Estimated working-set reservation for a row-based COPY stream.
344///
345/// Arrow retains decoder capacity across flushes, so the reservation follows the
346/// largest batch seen, not the cumulative import size. It stays held through
347/// inserts and until the decoder is dropped (including errors and disconnects).
348/// This is admission accounting, not an exact bound on allocator/RSS usage.
349struct TableCopyMemory {
350    limiter: ServerMemoryLimiter,
351    guard: common_memory_manager::MemoryGuard<crate::request_memory_metrics::RequestMemoryMetrics>,
352    fixed_bytes: u64,
353    batch_bytes: u64,
354}
355
356impl TableCopyMemory {
357    // Covers variable-sized decoder/tape buffers, capacity growth, Arrow arrays
358    // and protobuf strings coexisting during conversion. Fixed per-cell storage
359    // is charged separately so sparse JSON and empty CSV fields are not free.
360    const INPUT_EXPANSION: u64 = 16;
361    // Bound speculative admission and CPU work before checking for a full batch.
362    const DECODE_BYTES: usize = 8 * 1024;
363
364    async fn new(limiter: ServerMemoryLimiter, columns: usize) -> PgWireResult<Self> {
365        // Two copies of fixed cell/row storage plus Arrow validity/offset buffers
366        // and CSV's field offsets/initial data allocation. Reserve before creating
367        // the decoder, including for streams that never send a complete record.
368        let cell_bytes = std::mem::size_of::<api::v1::Value>() + 32;
369        let fixed_bytes = columns
370            .checked_mul(cell_bytes)
371            .and_then(|bytes| bytes.checked_add(std::mem::size_of::<GrpcRow>()))
372            .and_then(|bytes| bytes.checked_mul(COPY_IN_FLUSH_ROWS * 2))
373            .and_then(|bytes| bytes.checked_add(1024))
374            .ok_or_else(|| bad_copy_data("COPY decode memory estimate overflow"))?
375            as u64;
376        let guard = limiter.admit_stream(fixed_bytes).await.map_err(|error| {
377            convert_err(crate::prom_remote_write::map_memory_acquire_timeout(error))
378        })?;
379        Ok(Self {
380            limiter,
381            guard,
382            fixed_bytes,
383            batch_bytes: 0,
384        })
385    }
386
387    /// Prefer a prefix that fits immediately, including previously reserved
388    /// capacity. At zero headroom, try one byte so the normal fits check and
389    /// wait policy distinguish a self-limit from temporary contention.
390    fn input_budget(&self) -> usize {
391        let peak = self
392            .guard
393            .granted_bytes()
394            .saturating_add(self.limiter.available_bytes());
395        let capacity = peak.saturating_sub(self.fixed_bytes) / Self::INPUT_EXPANSION;
396        capacity
397            .saturating_sub(self.batch_bytes)
398            .clamp(1, Self::DECODE_BYTES as u64) as usize
399    }
400
401    /// Release only the speculative growth from this decode. Arrow may retain
402    /// all capacity covered by earlier grants, even across a batch flush.
403    fn discard_unused_grant(&mut self, previous_grant: u64) {
404        // reserve_input already checked this estimate for the entire preview.
405        let required = self.fixed_bytes + self.batch_bytes * Self::INPUT_EXPANSION;
406        let mut excess = self.guard.granted_bytes() - previous_grant.max(required);
407        if self.limiter.limit_bytes() != 0 {
408            // release_partial rounds *up* to permits. Release whole KiB only
409            // so that the consumed prefix is still covered during the insert.
410            let unit = common_memory_manager::PermitGranularity::Kilobyte.bytes();
411            excess -= excess % unit;
412        }
413        let released = self.guard.release_partial(excess);
414        debug_assert!(released);
415    }
416
417    async fn reserve_input(&mut self, bytes: usize, wire_bytes: u64) -> PgWireResult<()> {
418        let required = self
419            .batch_bytes
420            .checked_add(bytes as u64)
421            .and_then(|bytes| bytes.checked_mul(Self::INPUT_EXPANSION))
422            .and_then(|bytes| bytes.checked_add(self.fixed_bytes))
423            .ok_or_else(|| bad_copy_data("COPY decode memory estimate overflow"))?;
424        let uncovered = required.saturating_sub(self.guard.granted_bytes());
425        if uncovered != 0 {
426            // Amortize growth for tiny fragments, including with an unlimited pool.
427            let uncovered = uncovered.max(1024);
428            let held = self
429                .guard
430                .granted_bytes()
431                .checked_add(wire_bytes)
432                .ok_or_else(|| bad_copy_data("COPY decode memory estimate overflow"))?;
433            self.limiter
434                .check_request_fits(uncovered, held)
435                .map_err(convert_err)?;
436            self.guard
437                .acquire_additional_with_policy(uncovered, self.limiter.policy())
438                .await
439                .context(crate::error::MemoryLimitExceededSnafu)
440                .map_err(|error| {
441                    convert_err(crate::prom_remote_write::map_memory_acquire_timeout(error))
442                })?;
443        }
444        Ok(())
445    }
446}
447
448impl CopyInState {
449    async fn new(
450        codec: &dyn TableBoundCodec,
451        columns: Vec<String>,
452        table_info: Arc<TableInfo>,
453        query_ctx: QueryContextRef,
454        table_name: String,
455        memory_limiter: ServerMemoryLimiter,
456    ) -> PgWireResult<Self> {
457        let schema = table_info.meta.schema.clone();
458        let timestamp_index = schema.timestamp_index();
459
460        let columns = resolve_columns(codec, columns, &schema, &table_info)?;
461        if let Some(ts_index) = timestamp_index {
462            let ts_column = &schema.column_schemas()[ts_index];
463            if !columns.iter().any(|column| column.name == ts_column.name) {
464                return Err(unsupported(format!(
465                    "COPY FROM STDIN requires the time index column \"{}\" in the column list",
466                    ts_column.name
467                )));
468            }
469        }
470        let memory = TableCopyMemory::new(memory_limiter, columns.len()).await?;
471        let parser = codec.create_parser(&columns, query_ctx.timezone().to_string().as_str())?;
472
473        let grpc_schema = columns
474            .iter()
475            .map(|column| build_grpc_column_schema(column, &table_info))
476            .collect::<PgWireResult<Vec<_>>>()?;
477
478        Ok(Self {
479            query_ctx,
480            payload: Payload::Table {
481                grpc_schema,
482                table_name,
483                parser,
484                rows: Vec::new(),
485                memory,
486            },
487            memory_guards: Vec::new(),
488            granted_bytes: 0,
489            codec_name: codec.name(),
490            codec_format_code: 0,
491            rows_written: 0,
492        })
493    }
494
495    /// State for the influxdb format: the whole payload is buffered and
496    /// completed once at `CopyDone` through the line-protocol pipeline.
497    fn new_influxdb(options: &InfluxdbOptions, query_ctx: QueryContextRef) -> Self {
498        Self {
499            query_ctx,
500            payload: Payload::Influxdb {
501                data: Vec::new(),
502                precision: options.precision,
503            },
504            memory_guards: Vec::new(),
505            granted_bytes: 0,
506            codec_name: "influxdb",
507            codec_format_code: 0,
508            rows_written: 0,
509        }
510    }
511
512    /// State for the OTLP format: the whole binary payload is buffered
513    /// and completed once at `CopyDone` through the matching OTLP
514    /// pipeline. Binary: the advertised wire format code is 1.
515    fn new_otlp(options: OtlpOptions, query_ctx: QueryContextRef) -> Self {
516        Self {
517            query_ctx,
518            payload: Payload::Otlp {
519                data: Vec::new(),
520                options,
521            },
522            memory_guards: Vec::new(),
523            granted_bytes: 0,
524            codec_name: "otlp",
525            codec_format_code: 1,
526            rows_written: 0,
527        }
528    }
529
530    /// State for the promwrite format: the whole request body is
531    /// buffered and completed once at `CopyDone` through the shared
532    /// remote-write ingestion core. Binary: the advertised wire format
533    /// code is 1.
534    fn new_prom_write(options: &PromWriteOptions, query_ctx: QueryContextRef) -> Self {
535        Self {
536            query_ctx,
537            payload: Payload::PromWrite {
538                data: Vec::new(),
539                options: options.clone(),
540            },
541            memory_guards: Vec::new(),
542            granted_bytes: 0,
543            codec_name: "promwrite",
544            codec_format_code: 1,
545            rows_written: 0,
546        }
547    }
548
549    /// The wire format code advertised to the client.
550    pub(crate) fn format_code(&self) -> i8 {
551        self.codec_format_code
552    }
553
554    /// Whether the payload buffers raw CopyData bytes until `CopyDone`
555    /// (the table-less formats); such bytes are charged against the
556    /// shared request-memory limiter as they arrive.
557    fn buffers_payload(&self) -> bool {
558        matches!(
559            self.payload,
560            Payload::Influxdb { .. } | Payload::Otlp { .. } | Payload::PromWrite { .. }
561        )
562    }
563
564    /// The payload bytes currently buffered (charged or not).
565    fn buffered_bytes(&self) -> u64 {
566        match &self.payload {
567            Payload::Influxdb { data, .. }
568            | Payload::Otlp { data, .. }
569            | Payload::PromWrite { data, .. } => data.len() as u64,
570            Payload::Table { .. } | Payload::Arrow(_) => 0,
571        }
572    }
573
574    /// The payload bytes already covered by grants (KiB-aligned).
575    fn granted_bytes(&self) -> u64 {
576        self.granted_bytes
577    }
578
579    /// Retains a new reservation and records the granted coverage: the
580    /// limiter grants in KiB granularity, so coverage rounds the
581    /// buffered total up to the next KiB — subsequent chunks inside
582    /// that headroom need no acquisition.
583    fn charge_chunk(
584        &mut self,
585        guard: common_memory_manager::MemoryGuard<
586            crate::request_memory_metrics::RequestMemoryMetrics,
587        >,
588        buffered_total: u64,
589    ) {
590        self.memory_guards.push(guard);
591        self.granted_bytes = buffered_total.div_ceil(1024) * 1024;
592    }
593
594    /// Detaches the buffered-payload reservation so a flush can hold it
595    /// alongside the payload until the payload's memory is actually
596    /// consumed; see [`Self::memory_guards`].
597    fn take_reservation(&mut self) -> BufferedReservation {
598        BufferedReservation {
599            guards: std::mem::take(&mut self.memory_guards),
600            granted_bytes: std::mem::take(&mut self.granted_bytes),
601        }
602    }
603
604    /// Returns the new payload size, rejecting chunks that would grow it past
605    /// `max_bytes` (0: unbounded). The caller checks it BEFORE charging the
606    /// chunk against the shared limiter: a chunk the bound rejects must
607    /// neither wait for permits nor take memory that other requests need.
608    fn check_payload_bound(&self, chunk_bytes: u64, max_bytes: u64) -> PgWireResult<u64> {
609        let total = self
610            .buffered_bytes()
611            .checked_add(chunk_bytes)
612            .ok_or_else(|| bad_copy_data("COPY FROM STDIN payload size overflow"))?;
613        if max_bytes != 0 && total > max_bytes {
614            return Err(bad_copy_data(format!(
615                "COPY FROM STDIN payload exceeds the {} limit; split the import into multiple COPY statements",
616                ReadableSize(max_bytes)
617            )));
618        }
619        Ok(total)
620    }
621
622    /// Buffers a `CopyData` chunk of a table-less payload. The payload bound
623    /// is the caller's job ([`Self::check_payload_bound`]).
624    fn feed(&mut self, data: &[u8]) -> PgWireResult<()> {
625        match &mut self.payload {
626            Payload::Table { .. } => return Err(bad_copy_data("Table requires accounted decode")),
627            // Arrow's asynchronous feed writes each complete batch immediately.
628            Payload::Arrow(_) => return Err(bad_copy_data("Arrow requires asynchronous feed")),
629            Payload::Influxdb { data: buffered, .. }
630            | Payload::Otlp { data: buffered, .. }
631            | Payload::PromWrite { data: buffered, .. } => {
632                buffered.extend_from_slice(data);
633            }
634        }
635        Ok(())
636    }
637
638    /// Parses the buffered tail at `CopyDone`; a final record without a
639    /// trailing newline is accepted.
640    fn finish(&mut self) -> PgWireResult<()> {
641        match &mut self.payload {
642            Payload::Table { parser, rows, .. } => rows.extend(parser.finish()?),
643            // Finalized asynchronously by on_copy_done.
644            Payload::Arrow(_) => {}
645            // The whole payload is one request body; nothing to finalize.
646            Payload::Influxdb { .. } | Payload::Otlp { .. } | Payload::PromWrite { .. } => {}
647        }
648        Ok(())
649    }
650
651    async fn feed_table(
652        &mut self,
653        mut data: &[u8],
654        handler: &dyn CopyInHandler,
655    ) -> PgWireResult<()> {
656        let Payload::Table { memory, .. } = &self.payload else {
657            return Err(bad_copy_data("expected table COPY payload"));
658        };
659        // The entire incoming frame stays live while decoding or awaiting an insert.
660        memory
661            .limiter
662            .check_request_fits(data.len() as u64, memory.guard.granted_bytes())
663            .map_err(convert_err)?;
664        let wire = memory
665            .limiter
666            .acquire(data.len() as u64)
667            .await
668            .map_err(|error| {
669                convert_err(crate::prom_remote_write::map_memory_acquire_timeout(error))
670            })?;
671        while !data.is_empty() {
672            let Payload::Table {
673                parser,
674                rows,
675                memory,
676                ..
677            } = &mut self.payload
678            else {
679                return Err(bad_copy_data("expected table COPY payload"));
680            };
681            let slice = &data[..data.len().min(TableCopyMemory::DECODE_BYTES)];
682            let (len, charge) = parser.plan_input(slice, memory.input_budget());
683            let previous_grant = memory.guard.granted_bytes();
684            memory.reserve_input(charge, wire.granted_bytes()).await?;
685            let (consumed, actual_charge) = parser.decode(&slice[..len])?;
686            memory.batch_bytes += actual_charge as u64;
687            if actual_charge < charge {
688                memory.discard_unused_grant(previous_grant);
689            }
690            data = &data[consumed..];
691            if parser.is_full() {
692                *rows = parser.flush()?;
693                // Arrow retains its capacity; reset the batch estimate, not the guard.
694                memory.batch_bytes = 0;
695                let written = self.flush_table(handler, wire.granted_bytes()).await?;
696                self.rows_written += written;
697                METRIC_POSTGRES_COPY_IN_ROWS.inc_by(written);
698            } else if consumed == 0 {
699                return Err(bad_copy_data("COPY decoder made no progress"));
700            }
701        }
702        Ok(())
703    }
704
705    async fn flush_table(
706        &mut self,
707        handler: &dyn CopyInHandler,
708        wire_bytes: u64,
709    ) -> PgWireResult<u64> {
710        let Payload::Table {
711            grpc_schema,
712            table_name,
713            rows,
714            memory,
715            ..
716        } = &mut self.payload
717        else {
718            return Ok(0);
719        };
720        if rows.is_empty() {
721            return Ok(0);
722        }
723        let rows = GrpcRows {
724            schema: grpc_schema.clone(),
725            rows: std::mem::take(rows),
726        };
727        let requests = RowInsertRequests {
728            inserts: vec![RowInsertRequest {
729                table_name: table_name.clone(),
730                rows: Some(rows),
731            }],
732        };
733        // Publish only for the lifetime of this insert; cloned contexts must
734        // not retain a stale count after the transport releases its permits.
735        let held = Arc::new(AtomicU64::new(memory.guard.granted_bytes() + wire_bytes));
736        let mut ctx = (*self.query_ctx).clone();
737        ctx.set_body_memory_bytes(Arc::downgrade(&held));
738        let output = handler
739            .copy_in_insert(requests, Arc::new(ctx))
740            .await
741            .map_err(convert_err)?;
742        match output.data {
743            OutputData::AffectedRows(rows) => Ok(rows as u64),
744            OutputData::RecordBatches(_) | OutputData::Stream(_) => {
745                warn!("unexpected output from COPY FROM STDIN insert");
746                Ok(0)
747            }
748        }
749    }
750
751    /// Takes the buffered OTLP payload and its options, if any.
752    fn take_otlp(&mut self) -> Option<(OtlpOptions, Vec<u8>, BufferedReservation)> {
753        let Payload::Otlp { options, data } = &mut self.payload else {
754            return None;
755        };
756        if data.is_empty() {
757            return None;
758        }
759        Some((
760            options.clone(),
761            std::mem::take(data),
762            self.take_reservation(),
763        ))
764    }
765
766    /// Takes the buffered remote-write body and its options, if any.
767    fn take_prom_write(&mut self) -> Option<(PromWriteOptions, Vec<u8>, BufferedReservation)> {
768        let Payload::PromWrite { options, data } = &mut self.payload else {
769            return None;
770        };
771        if data.is_empty() {
772            return None;
773        }
774        Some((
775            options.clone(),
776            std::mem::take(data),
777            self.take_reservation(),
778        ))
779    }
780
781    /// Takes the buffered payload as one line-protocol request body, if
782    /// any — the same bytes an HTTP write of the same records would
783    /// carry.
784    fn take_lines(&mut self) -> PgWireResult<Option<(InfluxdbRequest, BufferedReservation)>> {
785        let Payload::Influxdb { data, precision } = &mut self.payload else {
786            return Ok(None);
787        };
788        if data.is_empty() {
789            return Ok(None);
790        }
791        let request = InfluxdbRequest {
792            precision: *precision,
793            lines: String::from_utf8(std::mem::take(data)).map_err(|e| {
794                bad_copy_data(format!("COPY FROM STDIN data is not valid UTF-8: {e}"))
795            })?,
796        };
797        Ok(Some((request, self.take_reservation())))
798    }
799}
800
801fn resolve_columns(
802    codec: &dyn TableBoundCodec,
803    columns: Vec<String>,
804    schema: &SchemaRef,
805    table_info: &Arc<TableInfo>,
806) -> PgWireResult<Vec<ColumnSchema>> {
807    let table_name = &table_info.name;
808    let selected: Vec<ColumnSchema> = if columns.is_empty() {
809        schema.column_schemas().to_vec()
810    } else {
811        let mut selected = Vec::with_capacity(columns.len());
812        for name in &columns {
813            let column = schema
814                .column_schema_by_name(name)
815                .ok_or_else(|| {
816                    copy_in_error(
817                        PgErrorCode::Ec42703,
818                        format!(
819                            "column \"{}\" of relation \"{}\" does not exist",
820                            name, table_name
821                        ),
822                    )
823                })?
824                .clone();
825            if selected.iter().any(|c: &ColumnSchema| &c.name == name) {
826                return Err(bad_copy_data(format!(
827                    "column \"{}\" specified more than once",
828                    name
829                )));
830            }
831            selected.push(column);
832        }
833        selected
834    };
835
836    for column in &selected {
837        codec.check_column_type(&column.data_type)?;
838    }
839
840    Ok(selected)
841}
842
843/// Derives a column's semantic type the same way the flow adapter does
844/// (`flow::adapter::util::column_schemas_to_proto`): the time-index flag
845/// for timestamps, primary-key membership for tags.
846fn semantic_type_of(table_info: &TableInfo, column: &ColumnSchema) -> PgWireResult<SemanticType> {
847    let meta = &table_info.meta;
848    if column.is_time_index() {
849        Ok(SemanticType::Timestamp)
850    } else if meta
851        .primary_key_indices
852        .iter()
853        .any(|&index| meta.schema.column_schemas()[index].name == column.name)
854    {
855        Ok(SemanticType::Tag)
856    } else {
857        Ok(SemanticType::Field)
858    }
859}
860
861fn build_grpc_column_schema(
862    column: &ColumnSchema,
863    table_info: &Arc<TableInfo>,
864) -> PgWireResult<api::v1::ColumnSchema> {
865    let (datatype, datatype_extension) = ColumnDataTypeWrapper::try_from(column.data_type.clone())
866        .map_err(|_| {
867            unsupported(format!(
868                "column type \"{}\" is not supported for COPY FROM STDIN yet",
869                column.data_type.name()
870            ))
871        })?
872        .to_parts();
873    Ok(api::v1::ColumnSchema {
874        column_name: column.name.clone(),
875        datatype: datatype as i32,
876        semantic_type: semantic_type_of(table_info, column)? as i32,
877        datatype_extension,
878        options: options_from_column_schema(column),
879    })
880}
881
882// ---------------------------------------------------------------------------
883// pgwire handlers
884// ---------------------------------------------------------------------------
885
886impl PostgresServerHandlerInner {
887    /// Prepares a COPY FROM STDIN: resolves the target table, validates
888    /// columns and stashes the per-connection copy state.
889    pub(crate) async fn begin_copy_in(&self, stmt: CopyFromStdin) -> PgWireResult<Response> {
890        // The batching-aware context routes copy-in flushes through the
891        // pending-rows batcher like SQL INSERT when it is enabled for
892        // this connection.
893        let query_ctx = self.new_query_context();
894
895        // Each format states its own target rule and ingestion shape
896        // explicitly.
897        let state = match &stmt.format {
898            // Row-based table-bound formats parse records against the
899            // target columns and insert them in batches.
900            CopyFormat::Csv(codec) => {
901                self.table_bound_state(&stmt, codec, query_ctx.clone())
902                    .await?
903            }
904            CopyFormat::Jsonl(codec) => {
905                self.table_bound_state(&stmt, codec, query_ctx.clone())
906                    .await?
907            }
908            CopyFormat::Arrow(options) => {
909                if stmt.table.is_empty() {
910                    return Err(unsupported("format arrow requires a target table"));
911                }
912                if !stmt.columns.is_empty() {
913                    return Err(unsupported(
914                        "format arrow uses IPC field names; omit the COPY column list",
915                    ));
916                }
917                let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?;
918                // Validate against the original context, including COPY's
919                // cross-catalog policy, before changing the target scope.
920                if self
921                    .copy_in_handler
922                    .copy_in_table(&catalog, &schema, &table, query_ctx.clone())
923                    .await
924                    .map_err(convert_err)?
925                    .is_none()
926                {
927                    return Err(copy_in_error(
928                        PgErrorCode::Ec42P01,
929                        format!("relation \"{}\" does not exist", stmt.table.join(".")),
930                    ));
931                }
932                let query_ctx =
933                    options.query_context(&adjust_query_context(query_ctx, &catalog, &schema));
934                let arrow = arrow::ArrowCopyState::new(
935                    table,
936                    &self.copy_in_handler,
937                    query_ctx.clone(),
938                    self.memory_limiter.clone(),
939                )
940                .await?;
941                CopyInState {
942                    query_ctx,
943                    payload: Payload::Arrow(Box::new(arrow)),
944                    memory_guards: Vec::new(),
945                    granted_bytes: 0,
946                    codec_name: "arrow",
947                    codec_format_code: 1,
948                    rows_written: 0,
949                }
950            }
951            // influxdb forbids a target table — each line names its own
952            // measurement — and completes through the line-protocol
953            // pipeline the HTTP write endpoints use; the server must be
954            // wired for it.
955            CopyFormat::Influxdb(options) => {
956                if !stmt.table.is_empty() {
957                    return Err(unsupported(format!(
958                        "format influxdb routes each record to its own table; \"COPY {} FROM STDIN\" must not name one",
959                        stmt.table.join(".")
960                    )));
961                }
962                if self.influxdb_handler.is_none() {
963                    return Err(unsupported(
964                        "this server is not wired for the influxdb line protocol format",
965                    ));
966                }
967                CopyInState::new_influxdb(options, query_ctx)
968            }
969            // OTLP metrics route to their own tables. Logs and traces
970            // accept a destination without requiring it to exist yet.
971            CopyFormat::Otlp(options) => {
972                if !stmt.columns.is_empty() {
973                    return Err(unsupported("format otlp does not support a column list"));
974                }
975                if self.otlp_handler.is_none() {
976                    return Err(unsupported("this server is not wired for the otlp format"));
977                }
978                let (options, target_ctx) =
979                    resolve_otlp_target(options, &stmt.table, query_ctx.clone())?;
980                if target_ctx.current_catalog() != query_ctx.current_catalog()
981                    || target_ctx.current_schema() != query_ctx.current_schema()
982                {
983                    // The same cross-catalog restriction SQL INSERT and
984                    // the csv format enforce — must run against the
985                    // ORIGINAL session context, before the user-provider
986                    // scope check and before any data is transferred.
987                    self.copy_in_handler
988                        .copy_in_validate_scope(
989                            target_ctx.current_catalog(),
990                            &target_ctx.current_schema(),
991                            query_ctx.clone(),
992                        )
993                        .await
994                        .map_err(convert_err)?;
995                    if let Some(source) = &self.auth_source {
996                        source
997                            .authorize_database(
998                                target_ctx.current_catalog(),
999                                &target_ctx.current_schema(),
1000                                &query_ctx.current_user(),
1001                            )
1002                            .await?;
1003                    }
1004                }
1005                CopyInState::new_otlp(options, target_ctx)
1006            }
1007            // promwrite forbids a target table too — the body's series
1008            // carry their own metric names — and completes through the
1009            // shared remote-write ingestion core; the server must be
1010            // wired.
1011            CopyFormat::PromWrite(options) => {
1012                if !stmt.table.is_empty() {
1013                    return Err(unsupported(format!(
1014                        "format promwrite routes each series to its own metric table; \"COPY {} FROM STDIN\" must not name one",
1015                        stmt.table.join(".")
1016                    )));
1017                }
1018                if self.prom_write_state.is_none() {
1019                    return Err(unsupported(
1020                        "this server is not wired for the promwrite format",
1021                    ));
1022                }
1023                CopyInState::new_prom_write(options, query_ctx)
1024            }
1025        };
1026        let num_columns = match &state.payload {
1027            Payload::Table { grpc_schema, .. } => grpc_schema.len(),
1028            // The IPC schema arrives after the COPY handshake.
1029            Payload::Arrow(_) => 0,
1030            // No fixed column set: the format routes per record.
1031            Payload::Influxdb { .. } | Payload::Otlp { .. } | Payload::PromWrite { .. } => 0,
1032        };
1033        let format_code = state.format_code();
1034
1035        *self.copy_in_state.lock().await = Some(state);
1036
1037        Ok(Response::CopyIn(CopyResponse::new(
1038            format_code,
1039            num_columns,
1040            stream::empty(),
1041        )))
1042    }
1043
1044    /// Resolves the target table and builds the table-bound copy state
1045    /// shared by csv and jsonl. `query_ctx` is the connection's context
1046    /// `begin_copy_in` created, so every format arm works from the same
1047    /// snapshot of the session.
1048    async fn table_bound_state(
1049        &self,
1050        stmt: &CopyFromStdin,
1051        codec: &dyn TableBoundCodec,
1052        query_ctx: QueryContextRef,
1053    ) -> PgWireResult<CopyInState> {
1054        if stmt.table.is_empty() {
1055            return Err(unsupported(format!(
1056                "format {} requires a table: COPY tbl [(cols)] FROM STDIN WITH (FORMAT {})",
1057                stmt.format.name(),
1058                stmt.format.name()
1059            )));
1060        }
1061        let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?;
1062
1063        let Some(table_info) = self
1064            .copy_in_handler
1065            .copy_in_table(&catalog, &schema, &table, query_ctx.clone())
1066            .await
1067            .map_err(convert_err)?
1068        else {
1069            return Err(copy_in_error(
1070                PgErrorCode::Ec42P01,
1071                format!("relation \"{}\" does not exist", stmt.table.join(".")),
1072            ));
1073        };
1074
1075        // The insert path resolves the bare table name against the query
1076        // context, so point the context at the resolved catalog and schema
1077        // when the COPY target is qualified.
1078        let query_ctx = adjust_query_context(query_ctx, &catalog, &schema);
1079
1080        CopyInState::new(
1081            codec,
1082            stmt.columns.clone(),
1083            table_info,
1084            query_ctx,
1085            table,
1086            self.memory_limiter.clone(),
1087        )
1088        .await
1089    }
1090
1091    /// Flushes the buffered payload of an in-progress copy. Returns the
1092    /// number of rows written by the flushed batch.
1093    async fn flush_copy_in(&self, state: &mut CopyInState) -> PgWireResult<u64> {
1094        let query_ctx = state.query_ctx.clone();
1095        // The buffered influxdb payload is completed through the
1096        // line-protocol pipeline — the same handler the HTTP write
1097        // endpoints use, so conversion, permissions, interceptors,
1098        // timestamp alignment and inserts are identical to an HTTP
1099        // write of the same bytes. The context stays this connection's
1100        // postgres context.
1101        if let Some((options, bytes, reservation)) = state.take_otlp() {
1102            let Some(otlp_handler) = &self.otlp_handler else {
1103                return Err(unsupported("this server is not wired for the otlp format"));
1104            };
1105            // The reservation outlives the payload: it is dropped when
1106            // the payload's bytes are consumed below.
1107            let rows = self
1108                .flush_otlp(
1109                    otlp_handler,
1110                    options,
1111                    bytes,
1112                    reservation.charged_bytes(),
1113                    query_ctx,
1114                )
1115                .await?;
1116            drop(reservation);
1117            return Ok(rows);
1118        }
1119        if let Some((options, bytes, reservation)) = state.take_prom_write() {
1120            let Some(prom_write_state) = &self.prom_write_state else {
1121                return Err(unsupported(
1122                    "this server is not wired for the promwrite format",
1123                ));
1124            };
1125            return self
1126                .flush_prom_write(prom_write_state, options, bytes, reservation, query_ctx)
1127                .await;
1128        }
1129        if let Some((request, reservation)) = state.take_lines()? {
1130            let Some(influxdb_handler) = &self.influxdb_handler else {
1131                return Err(unsupported(
1132                    "this server is not wired for the influxdb line protocol format",
1133                ));
1134            };
1135            let output = influxdb_handler
1136                .exec(request, query_ctx)
1137                .await
1138                .map_err(convert_err)?;
1139            drop(reservation);
1140            return match output.data {
1141                OutputData::AffectedRows(rows) => Ok(rows as u64),
1142                OutputData::RecordBatches(_) | OutputData::Stream(_) => Ok(0),
1143            };
1144        }
1145        state.flush_table(self.copy_in_handler.as_ref(), 0).await
1146    }
1147
1148    /// Completes an OTLP copy through the pipeline the matching
1149    /// OTLP/HTTP endpoint uses — the payload is decoded with the same
1150    /// protobuf types and handed to the same handler methods with the
1151    /// same context preparation, so both ingestion routes are
1152    /// identical. The context stays this connection's postgres context
1153    /// apart from the signal-specific preparation below.
1154    async fn flush_otlp(
1155        &self,
1156        otlp_handler: &crate::query_handler::OpenTelemetryProtocolHandlerRef,
1157        options: OtlpOptions,
1158        bytes: Vec<u8>,
1159        body_reserved_bytes: u64,
1160        query_ctx: QueryContextRef,
1161    ) -> PgWireResult<u64> {
1162        use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
1163        use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
1164        use pipeline::{GreptimePipelineParams, PipelineWay, SelectInfo};
1165        use session::protocol_ctx::{MetricType, OtlpMetricCtx, ProtocolCtx};
1166
1167        // The HTTP routes derive the pipeline handler from the same
1168        // protocol handler via trait upcasting; so does the copy.
1169        let pipeline_handler: PipelineHandlerRef = otlp_handler.clone();
1170        match options.signal {
1171            OtlpSignal::Metrics {
1172                promote_all_resource_attrs,
1173                resource_attrs,
1174                promote_scope_attrs,
1175                translation_strategy,
1176            } => {
1177                // Same context preparation as the HTTP metrics route.
1178                let mut ctx = (*query_ctx).clone();
1179                ctx.set_protocol_ctx(ProtocolCtx::OtlpMetric(OtlpMetricCtx {
1180                    promote_all_resource_attrs,
1181                    resource_attrs,
1182                    promote_scope_attrs,
1183                    with_metric_engine: self.otlp_with_metric_engine,
1184                    // Set by the frontend from its config.
1185                    resource_info: false,
1186                    metric_type: MetricType::Init,
1187                    metric_translation_strategy: translation_strategy,
1188                }));
1189                let request = ExportMetricsServiceRequest::decode(bytes.as_slice())
1190                    .map_err(|e| bad_copy_data(format!("invalid OTLP payload: {e}")))?;
1191                let outcome = otlp_handler
1192                    .metrics(
1193                        request,
1194                        Arc::new(ctx),
1195                        Some((self.memory_limiter.clone(), body_reserved_bytes)),
1196                    )
1197                    .await
1198                    .map_err(convert_err)?;
1199                // Same failure semantics as the HTTP route: a payload
1200                // whose points were all rejected is an error, not a
1201                // successful `COPY 0`.
1202                if outcome.accepted_data_points == 0 && outcome.rejected_data_points > 0 {
1203                    return Err(all_rejected_error(
1204                        "data points",
1205                        outcome.rejected_data_points,
1206                        outcome.error_message.as_deref(),
1207                    ));
1208                }
1209                // Rows are the accepted data points.
1210                Ok(outcome.accepted_data_points.max(0) as u64)
1211            }
1212            OtlpSignal::Traces {
1213                table_name,
1214                pipeline_name,
1215                pipeline_version,
1216                pipeline_params,
1217            } => {
1218                let table_name = table_name.unwrap_or_else(|| TRACE_TABLE_NAME.to_string());
1219                // Same context preparation as the HTTP traces route.
1220                let mut ctx = (*query_ctx).clone();
1221                ctx.set_extension(TRACE_TABLE_NAME_SESSION_KEY, &table_name);
1222                let pipeline = PipelineWay::from_name_and_default(
1223                    pipeline_name.as_deref(),
1224                    pipeline_version.as_deref(),
1225                    None,
1226                )
1227                .map_err(convert_err)?;
1228                let request = ExportTraceServiceRequest::decode(bytes.as_slice())
1229                    .map_err(|e| bad_copy_data(format!("invalid OTLP payload: {e}")))?;
1230                let outcome = otlp_handler
1231                    .traces(
1232                        pipeline_handler,
1233                        request,
1234                        pipeline,
1235                        GreptimePipelineParams::from_params(pipeline_params.as_deref()),
1236                        table_name,
1237                        Arc::new(ctx),
1238                    )
1239                    .await
1240                    .map_err(convert_err)?;
1241                // Same failure semantics as the HTTP route.
1242                if outcome.accepted_spans == 0 && outcome.rejected_spans > 0 {
1243                    return Err(all_rejected_error(
1244                        "spans",
1245                        outcome.rejected_spans as i64,
1246                        outcome.error_message.as_deref(),
1247                    ));
1248                }
1249                // Rows are the accepted spans.
1250                Ok(outcome.accepted_spans as u64)
1251            }
1252            OtlpSignal::Logs {
1253                table_name,
1254                pipeline_name,
1255                pipeline_version,
1256                pipeline_params,
1257                extract_keys,
1258            } => {
1259                let table_name = table_name.unwrap_or_else(|| "opentelemetry_logs".to_string());
1260                // Same select semantics as the HTTP extract-keys header.
1261                let select_info = match extract_keys.as_deref() {
1262                    Some(keys) if !keys.is_empty() => SelectInfo::from(keys.to_string()),
1263                    _ => Default::default(),
1264                };
1265                let pipeline = PipelineWay::from_name_and_default(
1266                    pipeline_name.as_deref(),
1267                    pipeline_version.as_deref(),
1268                    Some(PipelineWay::OtlpLogDirect(Box::new(select_info))),
1269                )
1270                .map_err(convert_err)?;
1271                let request = ExportLogsServiceRequest::decode(bytes.as_slice())
1272                    .map_err(|e| bad_copy_data(format!("invalid OTLP payload: {e}")))?;
1273                let outputs = otlp_handler
1274                    .logs(
1275                        pipeline_handler,
1276                        request,
1277                        pipeline,
1278                        GreptimePipelineParams::from_params(pipeline_params.as_deref()),
1279                        table_name,
1280                        query_ctx,
1281                    )
1282                    .await
1283                    .map_err(convert_err)?;
1284                // Rows are the affected rows across the outputs.
1285                Ok(outputs
1286                    .iter()
1287                    .map(|o| match &o.data {
1288                        OutputData::AffectedRows(rows) => *rows as u64,
1289                        _ => 0,
1290                    })
1291                    .sum())
1292            }
1293        }
1294    }
1295
1296    /// Completes a promwrite copy through the shared remote-write
1297    /// ingestion core: the same decode, validation, conversion and
1298    /// write paths the `/v1/prometheus/write` endpoint runs, with the
1299    /// same context extensions, under the connection's regular postgres
1300    /// query context. No parsing or conversion lives at the copy layer.
1301    async fn flush_prom_write(
1302        &self,
1303        prom_write_state: &crate::http::prom_store::PromStoreState,
1304        options: PromWriteOptions,
1305        bytes: Vec<u8>,
1306        reservation: BufferedReservation,
1307        query_ctx: QueryContextRef,
1308    ) -> PgWireResult<u64> {
1309        use crate::http::prom_store::{
1310            ingest_remote_write_v1, ingest_remote_write_v2, stamp_remote_write_extensions,
1311        };
1312        use crate::prom_remote_write::{REMOTE_WRITE_V1_VERSION, REMOTE_WRITE_V2_VERSION};
1313
1314        let version_str = match options.version {
1315            PromWriteVersion::V1 => REMOTE_WRITE_V1_VERSION,
1316            PromWriteVersion::V2 => REMOTE_WRITE_V2_VERSION,
1317        };
1318        // Same context extensions the HTTP endpoint stamps (physical
1319        // table, semantic identity); the channel stays this
1320        // connection's postgres channel.
1321        // Capture pipeline presence BEFORE the options are moved: the
1322        // v2 core rejects pipelines combined with exemplars, exactly
1323        // like the HTTP route, so the same payload+options cannot be
1324        // silently ingested without the pipeline over COPY.
1325        let has_pipeline = options.pipeline_name.is_some();
1326        let mut ctx = (*query_ctx).clone();
1327        stamp_remote_write_extensions(&mut ctx, options.physical_table.as_deref(), version_str);
1328        let pipeline_info = crate::http::extractor::PipelineInfo {
1329            pipeline_name: options.pipeline_name,
1330            pipeline_version: options.pipeline_version,
1331            pipeline_params: Default::default(),
1332        };
1333        let body = axum::body::Bytes::from(bytes);
1334        // The db labels the write-progress counters. The body's receive
1335        // reservation stays held for the whole ingestion (the guards in
1336        // `reservation` drop when it does), and its charged bytes ride
1337        // along as the decode-side pre-held reservation — the same
1338        // contract HTTP's body accounting passes downstream.
1339        let body_reserved_bytes = reservation.charged_bytes();
1340        let db = query_ctx.get_db_string();
1341        match options.version {
1342            PromWriteVersion::V1 => {
1343                let result = ingest_remote_write_v1(
1344                    prom_write_state,
1345                    &db,
1346                    pipeline_info,
1347                    options.zstd,
1348                    Arc::new(ctx),
1349                    body,
1350                    body_reserved_bytes,
1351                )
1352                .await
1353                .map_err(|error| convert_err(error.error))?;
1354                Ok(result.written.iter().sum())
1355            }
1356            PromWriteVersion::V2 => {
1357                let result = ingest_remote_write_v2(
1358                    prom_write_state,
1359                    &db,
1360                    has_pipeline,
1361                    options.zstd,
1362                    ctx,
1363                    body,
1364                    body_reserved_bytes,
1365                )
1366                .await
1367                .map_err(|error| convert_err(error.error))?;
1368                Ok(result.written.iter().sum())
1369            }
1370        }
1371    }
1372}
1373
1374/// The error for an OTLP payload whose points/spans were all rejected,
1375/// carrying the pipeline's reason when it provided one.
1376fn all_rejected_error(kind: &str, rejected: i64, reason: Option<&str>) -> PgWireError {
1377    bad_copy_data(match reason {
1378        Some(reason) => format!("OTLP ingestion rejected all {rejected} {kind}: {reason}"),
1379        None => format!("OTLP ingestion rejected all {rejected} {kind}"),
1380    })
1381}
1382
1383/// Resolves the SQL target's scope and supplies a fallback destination
1384/// for logs/traces. The explicit WITH table_name option takes precedence
1385/// over the SQL target's name, but does not override its catalog/schema.
1386fn resolve_otlp_target(
1387    options: &OtlpOptions,
1388    parts: &[String],
1389    query_ctx: QueryContextRef,
1390) -> PgWireResult<(OtlpOptions, QueryContextRef)> {
1391    let mut options = options.clone();
1392    if parts.is_empty() {
1393        return Ok((options, query_ctx));
1394    }
1395    let table_name = match &mut options.signal {
1396        OtlpSignal::Metrics { .. } => {
1397            return Err(unsupported(format!(
1398                "format otlp routes each metric to its own table; \"COPY {} FROM STDIN\" must not name one",
1399                parts.join(".")
1400            )));
1401        }
1402        OtlpSignal::Traces { table_name, .. } | OtlpSignal::Logs { table_name, .. } => table_name,
1403    };
1404    let (catalog, schema, table) = resolve_table_name(&query_ctx, parts)?;
1405    table_name.get_or_insert(table);
1406    Ok((options, adjust_query_context(query_ctx, &catalog, &schema)))
1407}
1408
1409fn adjust_query_context(
1410    query_ctx: QueryContextRef,
1411    catalog: &str,
1412    schema: &str,
1413) -> QueryContextRef {
1414    if query_ctx.current_catalog() == catalog && query_ctx.current_schema() == schema {
1415        return query_ctx;
1416    }
1417    let mut forked = query_ctx.fork();
1418    forked.set_current_catalog(catalog);
1419    forked.set_current_schema(schema);
1420    Arc::new(forked)
1421}
1422
1423#[async_trait]
1424impl CopyHandler for PostgresServerHandlerInner {
1425    async fn on_copy_data<C>(&self, _client: &mut C, copy_data: CopyData) -> PgWireResult<()>
1426    where
1427        C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send + Sync,
1428        C::Error: Debug,
1429        PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
1430    {
1431        let mut guard = self.copy_in_state.lock().await;
1432        let Some(mut state) = guard.take() else {
1433            return Err(copy_in_error(
1434                PgErrorCode::Ec08P01,
1435                "CopyData message received outside COPY FROM STDIN",
1436            ));
1437        };
1438        // The state is owned here: any parse, conversion or insert error
1439        // below aborts the whole copy and drops the buffered data —
1440        // otherwise a pooled connection would retain failed-import
1441        // buffers until its next COPY. On success it is put back.
1442        //
1443        // Buffered table-less payloads charge their bytes against the
1444        // shared request-memory limiter as they arrive (the
1445        // receive-stage counterpart of HTTP's body accounting); the
1446        // reservation is held until the buffer is flushed or the state
1447        // is dropped.
1448        if let Payload::Arrow(arrow) = &mut state.payload {
1449            let rows = arrow.feed(&copy_data.data).await?;
1450            state.rows_written += rows;
1451            METRIC_POSTGRES_COPY_IN_ROWS.inc_by(rows);
1452        } else if state.buffers_payload() {
1453            let chunk_bytes = u64::try_from(copy_data.data.len())
1454                .map_err(|_| bad_copy_data("chunk too large"))?;
1455            // The payload bound comes first: a chunk it rejects must not
1456            // wait on the limiter's Wait policy (up to its timeout) nor
1457            // take permits that other requests could use, and the client
1458            // should see the bound's error, not a memory-quota one.
1459            let buffered_after =
1460                state.check_payload_bound(chunk_bytes, self.max_copy_in_payload)?;
1461            // Charge only this chunk's uncovered delta against the
1462            // shared budget: the limiter rounds each acquisition up to a
1463            // KiB, so per-chunk full charges would accumulate rounding
1464            // overhead (64 x 16-byte chunks would retain 64 KiB of
1465            // permits for 1 KiB of payload). The fits check covers only
1466            // THIS request's own holdings — cross-request contention is
1467            // left to `acquire`, which applies the configured
1468            // Wait/Reject policy instead of failing fast.
1469            // Granted coverage is KiB-aligned, so it can exceed the
1470            // buffered bytes: chunks inside the rounding headroom are
1471            // already covered.
1472            let uncovered = buffered_after.saturating_sub(state.granted_bytes());
1473            if uncovered > 0 {
1474                self.memory_limiter
1475                    .check_request_fits(uncovered, state.granted_bytes())
1476                    .map_err(convert_err)?;
1477                let memory_guard = self.memory_limiter.acquire(uncovered).await.map_err(|e| {
1478                    convert_err(crate::prom_remote_write::map_memory_acquire_timeout(e))
1479                })?;
1480                state.feed(&copy_data.data)?;
1481                state.charge_chunk(memory_guard, buffered_after);
1482            } else {
1483                // Fully covered by the previous acquisitions' rounding
1484                // headroom.
1485                state.feed(&copy_data.data)?;
1486            }
1487        } else {
1488            state
1489                .feed_table(&copy_data.data, self.copy_in_handler.as_ref())
1490                .await?;
1491        }
1492        *guard = Some(state);
1493        Ok(())
1494    }
1495
1496    async fn on_copy_done<C>(&self, client: &mut C, _done: CopyDone) -> PgWireResult<()>
1497    where
1498        C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send + Sync,
1499        C::Error: Debug,
1500        PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
1501    {
1502        let mut guard = self.copy_in_state.lock().await;
1503        // Take ownership up front: even finalization failures (parse
1504        // errors in the trailing record, insert errors) drop the state
1505        // instead of retaining it on a long-lived connection.
1506        let Some(mut state) = guard.take() else {
1507            return Err(copy_in_error(
1508                PgErrorCode::Ec08P01,
1509                "CopyDone message received outside COPY FROM STDIN",
1510            ));
1511        };
1512        let rows = if let Payload::Arrow(arrow) = &mut state.payload {
1513            arrow.finish().await?
1514        } else {
1515            state.finish()?;
1516            self.flush_copy_in(&mut state).await?
1517        };
1518        state.rows_written += rows;
1519        METRIC_POSTGRES_COPY_IN_ROWS.inc_by(rows);
1520
1521        let rows_written = state.rows_written;
1522        let codec_name = state.codec_name;
1523        // Release decoder capacity and its reservation before acknowledging COPY.
1524        // A slow client reading the response must not keep ingestion memory live.
1525        drop(state);
1526        info!(
1527            "PostgreSQL COPY FROM STDIN (format {}) finished: {} rows written",
1528            codec_name, rows_written
1529        );
1530        client
1531            .send(PgWireBackendMessage::CommandComplete(
1532                Tag::new("COPY").with_rows(rows_written as usize).into(),
1533            ))
1534            .await?;
1535
1536        // After a successful extended-protocol copy-in, pgwire leaves the
1537        // connection in `CopyInProgress(true)` and swallows the client's
1538        // terminating `Sync` message, so `ReadyForQuery` would never be
1539        // sent and the connection would deadlock. Route the state to
1540        // `AwaitingSync` so the `Sync` is dispatched to `on_sync`, which
1541        // completes the round trip.
1542        if let PgWireConnectionState::CopyInProgress(true) = client.state() {
1543            client.set_state(PgWireConnectionState::AwaitingSync);
1544        }
1545        Ok(())
1546    }
1547
1548    async fn on_copy_fail<C>(&self, _client: &mut C, fail: CopyFail) -> PgWireError
1549    where
1550        C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send + Sync,
1551        C::Error: Debug,
1552        PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
1553    {
1554        // Discard unflushed rows. Batches already inserted are not rolled back.
1555        self.copy_in_state.lock().await.take();
1556        copy_in_error(
1557            PgErrorCode::Ec57014,
1558            format!("COPY FROM STDIN mode terminated by user: {}", fail.message),
1559        )
1560    }
1561}
1562
1563#[cfg(test)]
1564mod tests {
1565    use super::*;
1566
1567    #[tokio::test]
1568    async fn test_table_copy_memory_tracks_peak_not_total() {
1569        let limiter = ServerMemoryLimiter::new(
1570            64 * 1024 * 1024,
1571            common_memory_manager::OnExhaustedPolicy::Fail,
1572        );
1573        let mut memory = TableCopyMemory::new(limiter.clone(), 2).await.unwrap();
1574        let fixed = limiter.used_bytes();
1575        assert!(fixed > 0);
1576        for _ in 0..100 {
1577            // Tiny chunks share the rounding headroom; resetting the current
1578            // batch reuses the high-water reservation, including after a flush.
1579            for _ in 0..1024 {
1580                memory.reserve_input(1, 0).await.unwrap();
1581                memory.batch_bytes += 1;
1582            }
1583            memory.batch_bytes = 0;
1584            assert_eq!(
1585                limiter.used_bytes(),
1586                fixed + 1024 * TableCopyMemory::INPUT_EXPANSION
1587            );
1588        }
1589        drop(memory);
1590        assert_eq!(limiter.used_bytes(), 0);
1591    }
1592
1593    #[tokio::test]
1594    async fn test_table_copy_memory_unlimited_tiny_chunks() {
1595        let limiter = ServerMemoryLimiter::default();
1596        let mut memory = TableCopyMemory::new(limiter.clone(), 2).await.unwrap();
1597        for _ in 0..1024 {
1598            memory.reserve_input(1, 0).await.unwrap();
1599            memory.batch_bytes += 1;
1600        }
1601        assert_eq!(memory.guard.granted_bytes(), memory.fixed_bytes + 16 * 1024);
1602        drop(memory);
1603        assert_eq!(limiter.used_bytes(), 0);
1604    }
1605
1606    #[tokio::test]
1607    async fn test_table_copy_memory_includes_held_wire_bytes() {
1608        let limiter = ServerMemoryLimiter::new(
1609            32 * 1024 * 1024,
1610            common_memory_manager::OnExhaustedPolicy::default(),
1611        );
1612        let mut memory = TableCopyMemory::new(limiter.clone(), 2).await.unwrap();
1613        let wire = limiter
1614            .acquire(limiter.limit_bytes() - memory.guard.granted_bytes() - 1024)
1615            .await
1616            .unwrap();
1617        // It cannot fit alongside its OWN frame. Fail immediately, not after
1618        // waiting for permits that only this request can release.
1619        let result = tokio::time::timeout(
1620            std::time::Duration::from_secs(1),
1621            memory.reserve_input(8192, wire.granted_bytes()),
1622        )
1623        .await
1624        .unwrap();
1625        assert!(result.is_err());
1626        drop(memory);
1627        drop(wire);
1628        assert_eq!(limiter.used_bytes(), 0);
1629    }
1630
1631    #[tokio::test]
1632    async fn test_table_copy_memory_waits_for_other_request() {
1633        let probe = TableCopyMemory::new(ServerMemoryLimiter::default(), 2)
1634            .await
1635            .unwrap();
1636        let limiter = ServerMemoryLimiter::new(
1637            probe.guard.granted_bytes() + 2048,
1638            common_memory_manager::OnExhaustedPolicy::default(),
1639        );
1640        let mut first = TableCopyMemory::new(limiter.clone(), 2).await.unwrap();
1641        let second = TableCopyMemory::new(limiter.clone(), 2);
1642        tokio::pin!(second);
1643        assert!(
1644            tokio::time::timeout(std::time::Duration::from_millis(50), &mut second)
1645                .await
1646                .is_err()
1647        );
1648        // B is waiting, but A can still receive a frame and grow its batch.
1649        let wire = limiter.acquire(1).await.unwrap();
1650        first.reserve_input(1, wire.granted_bytes()).await.unwrap();
1651        drop(wire);
1652        drop(first);
1653        let second = tokio::time::timeout(std::time::Duration::from_secs(1), second)
1654            .await
1655            .unwrap()
1656            .unwrap();
1657        drop(second);
1658        assert_eq!(limiter.used_bytes(), 0);
1659    }
1660
1661    #[tokio::test]
1662    async fn test_table_copy_memory_admission_timeout_sqlstate() {
1663        let limiter = ServerMemoryLimiter::new(
1664            32 << 20,
1665            common_memory_manager::OnExhaustedPolicy::Wait {
1666                timeout: std::time::Duration::from_millis(5),
1667            },
1668        );
1669        let _other = limiter.acquire(limiter.limit_bytes()).await.unwrap();
1670        let error = TableCopyMemory::new(limiter, 1).await.err().unwrap();
1671        assert_eq!(error.code().to_string(), "53000");
1672    }
1673
1674    // Each insert exposes its context, then waits for the test to supply a
1675    // downstream reservation size. Use the same fits check as pending rows.
1676    struct TestInsert {
1677        limiter: ServerMemoryLimiter,
1678        inserts: tokio::sync::mpsc::UnboundedSender<(
1679            usize,
1680            QueryContextRef,
1681            tokio::sync::oneshot::Sender<u64>,
1682        )>,
1683    }
1684
1685    #[async_trait]
1686    impl CopyInHandler for TestInsert {
1687        async fn copy_in_validate_scope(
1688            &self,
1689            _: &str,
1690            _: &str,
1691            _: QueryContextRef,
1692        ) -> crate::error::Result<()> {
1693            unreachable!()
1694        }
1695        async fn copy_in_table(
1696            &self,
1697            _: &str,
1698            _: &str,
1699            _: &str,
1700            _: QueryContextRef,
1701        ) -> crate::error::Result<Option<Arc<TableInfo>>> {
1702            unreachable!()
1703        }
1704        async fn copy_in_insert(
1705            &self,
1706            requests: RowInsertRequests,
1707            ctx: QueryContextRef,
1708        ) -> crate::error::Result<common_query::Output> {
1709            let rows = requests.inserts[0].rows.as_ref().unwrap().rows.len();
1710            let (tx, rx) = tokio::sync::oneshot::channel();
1711            self.inserts.send((rows, ctx.clone(), tx)).unwrap();
1712            self.limiter
1713                .check_request_fits(rx.await.unwrap(), ctx.held_memory_bytes())?;
1714            Ok(common_query::Output::new_with_affected_rows(rows))
1715        }
1716    }
1717
1718    async fn jsonl_state(limiter: ServerMemoryLimiter) -> CopyInState {
1719        let columns = [ColumnSchema::new(
1720            "v",
1721            datatypes::prelude::ConcreteDataType::string_datatype(),
1722            true,
1723        )];
1724        CopyInState {
1725            query_ctx: session::context::QueryContext::arc(),
1726            payload: Payload::Table {
1727                grpc_schema: vec![],
1728                table_name: "test".to_string(),
1729                parser: jsonl::JsonlCodec.create_parser(&columns, "UTC").unwrap(),
1730                rows: vec![],
1731                memory: TableCopyMemory::new(limiter, columns.len()).await.unwrap(),
1732            },
1733            memory_guards: vec![],
1734            granted_bytes: 0,
1735            codec_name: "jsonl",
1736            codec_format_code: 0,
1737            rows_written: 0,
1738        }
1739    }
1740
1741    #[tokio::test]
1742    async fn test_waiting_http_body_leaves_headroom_for_copy() {
1743        waiting_body_leaves_headroom_for_copy(true).await;
1744    }
1745
1746    #[tokio::test]
1747    async fn test_waiting_chunked_body_leaves_headroom_for_copy() {
1748        waiting_body_leaves_headroom_for_copy(false).await;
1749    }
1750
1751    async fn waiting_body_leaves_headroom_for_copy(with_content_length: bool) {
1752        use axum::{
1753            Router,
1754            body::{Body, Bytes},
1755            http::Request,
1756            middleware,
1757            routing::post,
1758        };
1759        use tower::ServiceExt;
1760
1761        let limiter = ServerMemoryLimiter::new(32 << 20, Default::default());
1762        let mut state = jsonl_state(limiter.clone()).await;
1763        let other = limiter
1764            .acquire(limiter.available_bytes() - 2048)
1765            .await
1766            .unwrap();
1767        let app = Router::new()
1768            .route(
1769                "/",
1770                post(|body: Bytes| async move { assert_eq!(body.len(), 3072) }),
1771            )
1772            .layer(middleware::from_fn_with_state(
1773                limiter.clone(),
1774                crate::http::memory_limit_middleware,
1775            ));
1776        let mut req = Request::post("/");
1777        if with_content_length {
1778            req = req.header("content-length", 3072);
1779        }
1780        let frames = [Bytes::new(), Bytes::from(vec![0; 3072])];
1781        let req = req
1782            .body(Body::from_stream(futures::stream::iter(
1783                frames.map(Ok::<_, std::convert::Infallible>),
1784            )))
1785            .unwrap();
1786        let mut http = Box::pin(app.oneshot(req));
1787        assert!(futures::poll!(&mut http).is_pending());
1788        assert_eq!(
1789            limiter.available_bytes(),
1790            2048,
1791            "waiting HTTP admission must leave the COPY headroom available"
1792        );
1793        let (inserts, mut rx) = tokio::sync::mpsc::unbounded_channel();
1794        let handler = TestInsert {
1795            limiter: limiter.clone(),
1796            inserts,
1797        };
1798        state.feed_table(b"{}", &handler).await.unwrap();
1799        state.finish().unwrap();
1800        let mut insert = Box::pin(state.flush_table(&handler, 0));
1801        assert!(futures::poll!(&mut insert).is_pending());
1802        rx.try_recv().unwrap().2.send(0).unwrap();
1803        assert_eq!(insert.await.unwrap(), 1);
1804        drop(state);
1805        assert!(http.await.unwrap().status().is_success());
1806        drop(other);
1807        assert_eq!(limiter.used_bytes(), 0);
1808    }
1809
1810    #[tokio::test]
1811    async fn test_table_copy_memory_insert_lifetime() {
1812        for full in [false, true] {
1813            for cancel in [false, true] {
1814                let limiter = ServerMemoryLimiter::new(32 << 20, Default::default());
1815                let mut state = jsonl_state(limiter.clone()).await;
1816                let (inserts, mut rx) = tokio::sync::mpsc::unbounded_channel();
1817                let handler = TestInsert {
1818                    limiter: limiter.clone(),
1819                    inserts,
1820                };
1821                let count = if full { COPY_IN_FLUSH_ROWS } else { 1 };
1822                let mut copy = Box::pin(async move {
1823                    state.feed_table(&b"{}".repeat(count), &handler).await?;
1824                    state.finish()?;
1825                    state.flush_table(&handler, 0).await
1826                });
1827                assert!(futures::poll!(&mut copy).is_pending());
1828                let (rows, ctx, resume) = rx.try_recv().unwrap();
1829                assert_eq!(rows, count);
1830                let held = ctx.held_memory_bytes();
1831                assert!(held > 0);
1832                assert_eq!(
1833                    held,
1834                    limiter.used_bytes(),
1835                    "include frame only during CopyData"
1836                );
1837                if cancel {
1838                    drop(copy);
1839                } else {
1840                    resume.send(limiter.limit_bytes() - held + 1).unwrap();
1841                    assert_eq!(copy.await.unwrap_err().code().to_string(), "54000");
1842                }
1843                assert_eq!(limiter.used_bytes(), 0);
1844                assert_eq!(ctx.held_memory_bytes(), 0);
1845            }
1846        }
1847    }
1848
1849    #[tokio::test]
1850    async fn test_table_copy_memory_batch_boundary() {
1851        // A has one row left; the last frame also contains an oversized row.
1852        // Only a full A may be inserted, never its buffered prefix.
1853        let fixed = TableCopyMemory::new(ServerMemoryLimiter::default(), 1)
1854            .await
1855            .unwrap()
1856            .fixed_bytes;
1857        for complete in [false, true] {
1858            let mut tail = if complete { b"{}".to_vec() } else { vec![] };
1859            tail.extend_from_slice(b"{\"v\":\"");
1860            tail.resize(72 * 1024, b'x');
1861            let limit = fixed
1862                + (2 * COPY_IN_FLUSH_ROWS) as u64 * TableCopyMemory::INPUT_EXPANSION
1863                + tail.len() as u64;
1864            let limiter = ServerMemoryLimiter::new(limit, Default::default());
1865            let mut state = jsonl_state(limiter.clone()).await;
1866            let (inserts, mut rx) = tokio::sync::mpsc::unbounded_channel();
1867            let handler = TestInsert { limiter, inserts };
1868            state
1869                .feed_table(&b"{}".repeat(COPY_IN_FLUSH_ROWS - 1), &handler)
1870                .await
1871                .unwrap();
1872            let mut copy = Box::pin(state.feed_table(&tail, &handler));
1873            if complete {
1874                assert!(futures::poll!(&mut copy).is_pending());
1875                let (rows, _, resume) = rx.try_recv().unwrap();
1876                assert_eq!(rows, COPY_IN_FLUSH_ROWS);
1877                resume.send(0).unwrap();
1878            }
1879            assert!(matches!(
1880                futures::poll!(&mut copy),
1881                std::task::Poll::Ready(Err(_))
1882            ));
1883            assert!(rx.try_recv().is_err());
1884        }
1885    }
1886
1887    #[tokio::test]
1888    async fn test_table_copy_releases_only_speculative_suffix() {
1889        for first_extra in [0, 1024] {
1890            let limiter = ServerMemoryLimiter::new(16 << 20, Default::default());
1891            let mut state = jsonl_state(limiter.clone()).await;
1892            let fixed = limiter.used_bytes();
1893            let (inserts, mut rx) = tokio::sync::mpsc::unbounded_channel();
1894            let handler = TestInsert {
1895                limiter: limiter.clone(),
1896                inserts,
1897            };
1898            let almost_full = b"{}".repeat(COPY_IN_FLUSH_ROWS - 1);
1899            // Establish a real previous peak, then fill the second batch up to
1900            // its final row. Exercise previous peaks both above and below it.
1901            for (i, extra) in [first_extra, 128].into_iter().enumerate() {
1902                state.feed_table(&almost_full, &handler).await.unwrap();
1903                let mut frame = format!("\n{{\"v\":\"{}\"}}", "x".repeat(extra)).into_bytes();
1904                if i == 1 {
1905                    frame.extend(b"{}".repeat(4096));
1906                }
1907                let mut feed = Box::pin(state.feed_table(&frame, &handler));
1908                assert!(futures::poll!(&mut feed).is_pending());
1909                let (rows, ctx, resume) = rx.try_recv().unwrap();
1910                assert_eq!(rows, COPY_IN_FLUSH_ROWS);
1911                let actual = almost_full.len() + 8 + extra.max(first_extra);
1912                let peak = fixed
1913                    + (actual as u64 * TableCopyMemory::INPUT_EXPANSION).next_multiple_of(1024);
1914                assert_eq!(
1915                    ctx.held_memory_bytes(),
1916                    peak + (frame.len() as u64).next_multiple_of(1024)
1917                );
1918                resume.send(0).unwrap();
1919                feed.await.unwrap();
1920                assert_eq!(limiter.used_bytes(), peak);
1921            }
1922            // This frame fits exactly beside the true retained peak, not the
1923            // 8 KiB preview. Its whitespace needs no decoder grant.
1924            let frame = vec![b'\n'; limiter.available_bytes() as usize];
1925            state.feed_table(&frame, &handler).await.unwrap();
1926        }
1927    }
1928
1929    #[test]
1930    fn test_resolve_otlp_target() {
1931        for signal in ["logs", "traces"] {
1932            for (target, catalog, schema, expected_table) in [
1933                ("", "greptime", "public", None),
1934                ("my_table", "greptime", "public", Some("my_table")),
1935                ("other.my_table", "greptime", "other", Some("my_table")),
1936                ("cat.other.my_table", "cat", "other", Some("my_table")),
1937                (
1938                    "\"Other\".\"MyTable\"",
1939                    "greptime",
1940                    "Other",
1941                    Some("MyTable"),
1942                ),
1943            ] {
1944                for override_name in [None, Some("overridden")] {
1945                    let override_option = override_name
1946                        .map(|name| format!(", table_name '{name}'"))
1947                        .unwrap_or_default();
1948                    let stmt = copy_from_stdin_from_sql(&format!(
1949                        "COPY {target} FROM STDIN WITH (FORMAT otlp, signal '{signal}'{override_option})"
1950                    ))
1951                    .unwrap()
1952                    .unwrap();
1953                    let CopyFormat::Otlp(options) = stmt.format else {
1954                        panic!("expected OTLP");
1955                    };
1956                    let original_ctx = session::context::QueryContext::arc();
1957                    let (resolved, ctx) =
1958                        resolve_otlp_target(&options, &stmt.table, original_ctx.clone()).unwrap();
1959                    let table_name = match resolved.signal {
1960                        OtlpSignal::Logs { table_name, .. }
1961                        | OtlpSignal::Traces { table_name, .. } => table_name,
1962                        _ => panic!("expected logs or traces"),
1963                    };
1964                    assert_eq!(table_name.as_deref(), override_name.or(expected_table));
1965                    assert_eq!(ctx.current_catalog(), catalog);
1966                    assert_eq!(ctx.current_schema(), schema);
1967                    // A qualified target must not change the session context.
1968                    assert_eq!(original_ctx.current_catalog(), "greptime");
1969                    assert_eq!(original_ctx.current_schema(), "public");
1970                }
1971            }
1972        }
1973    }
1974
1975    #[test]
1976    fn test_resolve_otlp_metrics_target_rejected() {
1977        for signal in ["", ", signal 'metrics'"] {
1978            let stmt = copy_from_stdin_from_sql(&format!(
1979                "COPY my_metrics FROM STDIN WITH (FORMAT otlp{signal})"
1980            ))
1981            .unwrap()
1982            .unwrap();
1983            let CopyFormat::Otlp(options) = stmt.format else {
1984                panic!("expected OTLP");
1985            };
1986            let ctx = session::context::QueryContext::arc();
1987            let err = resolve_otlp_target(&options, &stmt.table, ctx).unwrap_err();
1988            assert!(err.to_string().contains("must not name one"), "{err}");
1989        }
1990    }
1991
1992    #[test]
1993    fn test_parse_copy_from_stdin_requires_format() {
1994        let err = copy_from_stdin_from_sql("COPY t FROM STDIN").unwrap_err();
1995        assert!(
1996            err.to_string()
1997                .contains("requires an explicit format in this version"),
1998            "{err}"
1999        );
2000
2001        let copy = copy_from_stdin_from_sql("COPY t FROM STDIN WITH (FORMAT csv)")
2002            .unwrap()
2003            .unwrap();
2004        assert_eq!(copy.table, vec!["t"]);
2005        assert!(copy.columns.is_empty());
2006        assert!(matches!(copy.format, CopyFormat::Csv(_)));
2007        // Both formats are textual: format code 0.
2008    }
2009
2010    #[test]
2011    fn test_parse_copy_from_stdin_csv() {
2012        let copy = copy_from_stdin_from_sql(
2013            "COPY t (a, b) FROM STDIN WITH (FORMAT csv, HEADER, DELIMITER ';')",
2014        )
2015        .unwrap()
2016        .unwrap();
2017        assert_eq!(copy.columns, vec!["a", "b"]);
2018        assert!(matches!(copy.format, CopyFormat::Csv(_)));
2019    }
2020
2021    #[test]
2022    fn test_parse_copy_from_stdin_jsonl_and_json_alias() {
2023        for sql in [
2024            "COPY t FROM STDIN WITH (FORMAT jsonl)",
2025            "COPY t FROM STDIN WITH (FORMAT json)",
2026        ] {
2027            let copy = copy_from_stdin_from_sql(sql).unwrap().unwrap();
2028            assert!(matches!(copy.format, CopyFormat::Jsonl(_)), "{sql}");
2029            assert_eq!(copy.format.name(), "jsonl", "{sql}");
2030        }
2031    }
2032
2033    #[test]
2034    fn test_table_bound_codec_names() {
2035        // The codec names `CopyInState` logs come from the codecs
2036        // themselves, not a literal per match arm.
2037        let csv = match csv::build_csv_codec(options::CopyOptionSet::default()).unwrap() {
2038            CopyFormat::Csv(codec) => codec,
2039            other => panic!("expected csv, got {other:?}"),
2040        };
2041        let jsonl = match jsonl::build_jsonl_codec(options::CopyOptionSet::default()).unwrap() {
2042            CopyFormat::Jsonl(codec) => codec,
2043            other => panic!("expected jsonl, got {other:?}"),
2044        };
2045        assert_eq!(csv.name(), "csv");
2046        assert_eq!(jsonl.name(), "jsonl");
2047    }
2048
2049    #[test]
2050    fn test_parse_copy_from_stdin_text_unsupported() {
2051        for sql in [
2052            "COPY t FROM STDIN WITH (FORMAT text)",
2053            "COPY t FROM STDIN WITH (FORMAT txt)",
2054        ] {
2055            let err = copy_from_stdin_from_sql(sql).unwrap_err();
2056            assert!(
2057                err.to_string().contains("text format is not supported yet"),
2058                "{err}"
2059            );
2060        }
2061    }
2062
2063    #[test]
2064    fn test_parse_copy_from_stdin_binary_unsupported() {
2065        let err = copy_from_stdin_from_sql("COPY t FROM STDIN WITH (FORMAT binary)").unwrap_err();
2066        assert!(err.to_string().contains("not supported"));
2067    }
2068
2069    #[test]
2070    fn test_parse_copy_from_stdin_unknown_format() {
2071        let err = copy_from_stdin_from_sql("COPY t FROM STDIN WITH (FORMAT parquet)").unwrap_err();
2072        assert!(err.to_string().contains("unknown COPY format"));
2073    }
2074
2075    #[test]
2076    fn test_parse_copy_from_stdin_not_copy_in() {
2077        assert!(
2078            copy_from_stdin_from_sql("COPY (SELECT 1) TO STDOUT")
2079                .unwrap()
2080                .is_none()
2081        );
2082        assert!(
2083            copy_from_stdin_from_sql("COPY t TO '/tmp/x.csv'")
2084                .unwrap()
2085                .is_none()
2086        );
2087        // GreptimeDB's own file-based COPY FROM.
2088        assert!(
2089            copy_from_stdin_from_sql("COPY t FROM '/tmp/x.csv' WITH (FORMAT csv)")
2090                .unwrap()
2091                .is_none()
2092        );
2093    }
2094
2095    #[test]
2096    fn test_redundant_options() {
2097        let err = copy_from_stdin_from_sql("COPY t FROM STDIN WITH (FORMAT csv, FORMAT text)")
2098            .unwrap_err();
2099        assert!(err.to_string().contains("redundant FORMAT"));
2100
2101        let err = copy_from_stdin_from_sql("COPY t FROM STDIN WITH (DELIMITER ',', DELIMITER ';')")
2102            .unwrap_err();
2103        assert!(err.to_string().contains("redundant DELIMITER"));
2104    }
2105
2106    #[test]
2107    fn test_format_specific_options_rejected() {
2108        // The open WITH section parses anything, but the format rejects
2109        // the options it does not understand.
2110        let err =
2111            copy_from_stdin_from_sql("COPY t FROM STDIN WITH (FORMAT csv, PRECISION 'ns', FREEZE)")
2112                .unwrap_err();
2113        assert!(
2114            err.to_string().contains("not supported by format csv"),
2115            "{err}"
2116        );
2117    }
2118
2119    #[test]
2120    fn test_multi_statement_rejected() {
2121        let err = copy_from_stdin_from_sql("COPY t FROM STDIN; SELECT 1").unwrap_err();
2122        assert!(err.to_string().contains("alone"));
2123        // Trailing separators and quoted semicolons are fine.
2124        assert!(
2125            copy_from_stdin_from_sql("COPY t FROM STDIN WITH (FORMAT csv);")
2126                .unwrap()
2127                .is_some()
2128        );
2129        assert!(
2130            copy_from_stdin_from_sql("COPY t FROM STDIN WITH (FORMAT csv, DELIMITER ';')")
2131                .unwrap()
2132                .is_some()
2133        );
2134    }
2135
2136    /// A table-less (influxdb) copy state already holding `buffered` bytes.
2137    fn influxdb_state_with(buffered: usize) -> CopyInState {
2138        let mut state = CopyInState::new_influxdb(
2139            &InfluxdbOptions { precision: None },
2140            session::context::QueryContext::arc(),
2141        );
2142        if buffered > 0 {
2143            state.feed(&vec![b'x'; buffered]).unwrap();
2144        }
2145        state
2146    }
2147
2148    #[test]
2149    fn test_payload_bound_boundary() {
2150        let state = influxdb_state_with(1023);
2151        // Filling the bound exactly is accepted ...
2152        assert_eq!(state.check_payload_bound(1, 1024).unwrap(), 1024);
2153        // ... one byte more is not, as bad copy data (22P04) naming a
2154        // human-readable size rather than a raw byte count.
2155        let err = state.check_payload_bound(2, 1024).unwrap_err();
2156        assert_eq!(err.code(), PgErrorCode::Ec22P04.code());
2157        assert_eq!(
2158            err.to_string(),
2159            "User provided error: ErrorInfo: ERROR, 22P04, COPY FROM STDIN payload exceeds the \
2160             1.0KiB limit; split the import into multiple COPY statements"
2161        );
2162    }
2163
2164    #[test]
2165    fn test_payload_bound_default() {
2166        // The shipped default renders as 64 MiB, not 67108864.
2167        let state = influxdb_state_with(0);
2168        state
2169            .check_payload_bound(COPY_IN_MAX_PAYLOAD_BYTES, COPY_IN_MAX_PAYLOAD_BYTES)
2170            .unwrap();
2171        let err = state
2172            .check_payload_bound(COPY_IN_MAX_PAYLOAD_BYTES + 1, COPY_IN_MAX_PAYLOAD_BYTES)
2173            .unwrap_err();
2174        assert!(
2175            err.to_string()
2176                .contains("exceeds the 64.0MiB limit; split the import"),
2177            "{err}"
2178        );
2179    }
2180
2181    #[test]
2182    fn test_payload_bound_zero_is_unbounded() {
2183        assert_eq!(
2184            influxdb_state_with(8)
2185                .check_payload_bound(u64::MAX - 8, 0)
2186                .unwrap(),
2187            u64::MAX
2188        );
2189    }
2190
2191    #[test]
2192    fn test_payload_bound_size_overflow_rejected() {
2193        // Defensive: a size that cannot even be represented is rejected
2194        // rather than wrapping around into the bound.
2195        let state = influxdb_state_with(8);
2196        for cap in [0, u64::MAX] {
2197            assert_eq!(
2198                state.check_payload_bound(u64::MAX, cap).unwrap_err().code(),
2199                PgErrorCode::Ec22P04.code()
2200            );
2201        }
2202    }
2203}