Skip to main content

rivet/source/mysql/
mod.rs

1//! MySQL `Source` implementation.
2//!
3//! Module layout (mirrors `postgres/`):
4//!
5//! - `mod.rs` (this file) — `MysqlSource` struct + connect/TLS path, the
6//!   extraction-pressure sampler, the `lean_pool_opts` / `connect_pool` /
7//!   `build_mysql_ssl_opts` helpers, `introspect_mysql_table_for_chunking`
8//!   together with the InnoDB `AVG_ROW_LENGTH` correction, the cursor-bound
9//!   `exec_iter` export loop (`mysql_run_export`), and the `Source` trait impl.
10//! - [`arrow_convert`] — the entire row → Arrow `RecordBatch` pipeline:
11//!   `mysql_type_to_rivet` + `mysql_native_type_name`,
12//!   `mysql_schema_and_arrow_types`, BIT / TIME / DECIMAL decoders, and the
13//!   array builders. Kept in a sibling because it is the largest
14//!   single-purpose cluster in this driver (~510 LoC) and has zero reverse
15//!   dependency back into the connection / pool / cursor layer.
16//! - [`proxy`] — `MysqlProxyKind` enum, the pure `classify_mysql_proxy`
17//!   classifier, the I/O wrapper `detect_mysql_proxy_kind`, and
18//!   `warn_proxy_kind`. Detection runs once at connect time; the classifier
19//!   is exhaustively unit-tested in isolation (no live MySQL needed).
20
21mod arrow_convert;
22mod proxy;
23
24use std::sync::Arc;
25
26use arrow::datatypes::Schema;
27use mysql::prelude::*;
28use mysql::{Opts, OptsBuilder, Pool, PoolConstraints, PoolOpts, SslOpts};
29
30use crate::config::{SourceType, TlsConfig, TlsMode};
31use crate::error::Result;
32use crate::source::batch_controller::{
33    AdaptiveBatchController, DEFAULT_BATCH_TARGET_MB, PROBE_BATCH_SIZE,
34};
35use crate::source::query::build_export_query;
36use crate::tuning::SourceTuning;
37use crate::types::ColumnOverrides;
38
39use arrow_convert::{
40    mysql_native_type_name, mysql_schema_and_arrow_types, mysql_type_to_rivet,
41    rows_to_record_batch_typed,
42};
43// `bit_bytes_to_u64` is only referenced by the `tests` module below — gate the
44// re-import on `cfg(test)` so non-test builds don't see an unused-import warning.
45#[cfg(test)]
46use arrow_convert::bit_bytes_to_u64;
47use proxy::{detect_mysql_proxy_kind, warn_proxy_kind};
48
49// Re-exported so external code (`tests/live_pool_safety.rs`) can still write
50// `use rivet::source::mysql::MysqlProxyKind` after the proxy block moved to
51// the `proxy` submodule.
52pub use proxy::MysqlProxyKind;
53
54pub struct MysqlSource {
55    pool: Pool,
56    proxy_kind: MysqlProxyKind,
57}
58
59/// Pool options that prevent eager pre-connection. The default mysql::Pool
60/// opens `min=10` connections immediately, which overflows MySQL's
61/// max_connections when many parallel exports run simultaneously.
62fn lean_pool_opts() -> PoolOpts {
63    PoolOpts::default()
64        .with_constraints(PoolConstraints::new(1, 100).expect("valid pool constraints"))
65}
66
67/// Sample an **extraction-pressure** proxy (Epic 18 C1) — the MySQL analogue of
68/// PG's `temp_bytes`. Sums two monotonic global counters:
69///
70/// - `Created_tmp_disk_tables` — a query spilled an internal temp table to disk
71///   (a `GROUP BY` / `DISTINCT` / `ORDER BY` that exceeded `tmp_table_size`).
72/// - `Innodb_buffer_pool_wait_free` — InnoDB had to wait for a free buffer-pool
73///   page, i.e. the read is evicting pages under memory pressure.
74///
75/// Either moving means "my extraction is stressing the source"; their sum is
76/// monotonic, so the governor's `cur > prev` comparison works unchanged. The
77/// sum is robust to MySQL 8.0's `TempTable` engine, where a spill may not bump
78/// `Created_tmp_disk_tables` — `Innodb_buffer_pool_wait_free` carries the signal
79/// then (and `Created_tmp_disk_tables` adds it on 5.7 / MariaDB). This replaces
80/// the old `Innodb_log_waits`, which is redo-**write** pressure and barely moves
81/// during a read-only export.
82fn mysql_sample_extraction_pressure(pool: &Pool) -> Option<u64> {
83    let mut conn = pool.get_conn().ok()?;
84    let rows: Vec<(String, u64)> = conn
85        .query(
86            "SHOW GLOBAL STATUS WHERE Variable_name IN \
87             ('Created_tmp_disk_tables', 'Innodb_buffer_pool_wait_free')",
88        )
89        .ok()?;
90    if rows.is_empty() {
91        return None;
92    }
93    Some(rows.iter().map(|(_, v)| *v).sum())
94}
95
96impl MysqlSource {
97    /// Build a source from an existing pool: the single place that detects the
98    /// proxy kind, warns once, and wraps the pool. The `connect*` entry points
99    /// all funnel through here (also handy in tests that share the pool for
100    /// post-export state inspection).
101    pub fn from_pool(pool: Pool) -> Self {
102        let proxy_kind = detect_mysql_proxy_kind(&pool);
103        warn_proxy_kind(proxy_kind);
104        Self { pool, proxy_kind }
105    }
106
107    /// Connect with no transport security (legacy path).
108    pub fn connect(url: &str) -> Result<Self> {
109        let opts =
110            Opts::from(OptsBuilder::from_opts(Opts::from_url(url)?).pool_opts(lean_pool_opts()));
111        Ok(Self::from_pool(Pool::new(opts)?))
112    }
113
114    /// Connect honoring the user's [`TlsConfig`].
115    pub fn connect_with_tls(url: &str, tls: Option<&TlsConfig>) -> Result<Self> {
116        // Refuse remote plaintext (no `tls:` block) before any dial (CWE-319).
117        crate::source::require_tls_or_loopback(url, tls)?;
118        match tls {
119            Some(cfg) if cfg.mode.is_enforced() => {
120                let base = Opts::from_url(url)?;
121                let ssl = build_mysql_ssl_opts(cfg);
122                let opts = Opts::from(
123                    OptsBuilder::from_opts(base)
124                        .ssl_opts(Some(ssl))
125                        .pool_opts(lean_pool_opts()),
126                );
127                Ok(Self::from_pool(Pool::new(opts)?))
128            }
129            _ => Self::connect(url),
130        }
131    }
132
133    /// Expose the proxy classification for diagnostic tools (preflight,
134    /// integration tests). Not part of the public Source trait — same
135    /// internal-may-change contract as the rest of `rivet::source::mysql::*`.
136    ///
137    /// `#[allow(dead_code)]` covers the binary compilation unit; the lib +
138    /// integration tests reference this through the `rivet::source::mysql`
139    /// public surface.
140    #[allow(dead_code)]
141    pub fn proxy_kind(&self) -> MysqlProxyKind {
142        self.proxy_kind
143    }
144}
145
146/// Build a MySQL connection pool honoring the configured TLS policy.
147///
148/// Shared by preflight, doctor, init, and anywhere else we need a pool outside
149/// the `Source` trait. `tls = None` falls back to plaintext (legacy behavior).
150pub(crate) fn connect_pool(url: &str, tls: Option<&TlsConfig>) -> Result<Pool> {
151    // Refuse remote plaintext (no `tls:` block) before any dial (CWE-319).
152    crate::source::require_tls_or_loopback(url, tls)?;
153    match tls {
154        Some(cfg) if cfg.mode.is_enforced() => {
155            let base = Opts::from_url(url)?;
156            let ssl = build_mysql_ssl_opts(cfg);
157            let opts = Opts::from(
158                OptsBuilder::from_opts(base)
159                    .ssl_opts(Some(ssl))
160                    .pool_opts(lean_pool_opts()),
161            );
162            Ok(Pool::new(opts)?)
163        }
164        _ => {
165            let opts = Opts::from(
166                OptsBuilder::from_opts(Opts::from_url(url)?).pool_opts(lean_pool_opts()),
167            );
168            Ok(Pool::new(opts)?)
169        }
170    }
171}
172
173/// Threshold above which `AVG_ROW_LENGTH` is treated as inflated by InnoDB BLOB
174/// overflow pages and divided down. Rows under 8 KB fit inline (no overflow),
175/// so the raw figure is accurate; above it the divisor compensates.
176const INNODB_BLOB_OVERFLOW_THRESHOLD_BYTES: i64 = 8 * 1024;
177
178/// Empirical divisor for InnoDB BLOB-page inflation. A wide-text row that
179/// allocates eight 16 KB overflow pages reports ~128 KB in `AVG_ROW_LENGTH`
180/// while the actual wire content is ~40 KB → factor of ~3.
181const INNODB_BLOB_OVERFLOW_DIVISOR: i64 = 3;
182
183/// Apply the InnoDB BLOB-overflow correction to a raw `AVG_ROW_LENGTH` value.
184/// Pure function for unit testability — the live introspection helper calls
185/// this on the figure returned by `information_schema.TABLES`.
186///
187/// - Below the 8 KB threshold: raw value is accurate (no overflow).
188/// - Above: divide by 3, floored at threshold/2 so we never undershoot too far.
189fn correct_innodb_avg_row_length(raw_bytes: i64) -> i64 {
190    if raw_bytes > INNODB_BLOB_OVERFLOW_THRESHOLD_BYTES {
191        (raw_bytes / INNODB_BLOB_OVERFLOW_DIVISOR).max(INNODB_BLOB_OVERFLOW_THRESHOLD_BYTES / 2)
192    } else {
193        raw_bytes
194    }
195}
196
197/// Probe `information_schema` for stats chunked-mode planning needs.
198///
199/// MySQL analogue of [`crate::source::postgres::introspect_pg_table_for_chunking`]:
200/// returns the same source-neutral [`crate::source::TableIntrospection`] so
201/// `plan/build.rs` can dispatch on `source_type` and reuse the same downstream
202/// logic for chunk-column / chunk_size derivation.
203///
204/// Two queries per call, both against `information_schema` (no extra grants
205/// required for a normal app user):
206/// - `TABLES.AVG_ROW_LENGTH` + `TABLE_ROWS` for the row-size and row-count estimate.
207///   These come from `mysql.innodb_table_stats` and are only as fresh as the
208///   last `ANALYZE TABLE` / autostat run. Empty / unanalysed → zero.
209/// - `STATISTICS` filtered to `INDEX_NAME='PRIMARY'` with `SEQ_IN_INDEX=1` and a
210///   second probe ensuring no `SEQ_IN_INDEX=2` row exists — single-column PK only.
211///
212/// `qualified_table` is `<schema>.<table>` or bare `<table>` (resolved under the
213/// current database for the connection). Same strict ident rules as the YAML
214/// `table:` shortcut so the SQL stays trivially safe.
215pub(crate) fn introspect_mysql_table_for_chunking(
216    url: &str,
217    tls: Option<&TlsConfig>,
218    qualified_table: &str,
219) -> Result<crate::source::TableIntrospection> {
220    let pool = connect_pool(url, tls)?;
221    let mut conn = pool.get_conn()?;
222    let default_db: Option<String> = conn.query_first("SELECT DATABASE()")?;
223    let default_db = default_db.unwrap_or_default();
224
225    let (schema, table) = match qualified_table.split_once('.') {
226        Some((s, t)) => (s.to_string(), t.to_string()),
227        None => (default_db, qualified_table.to_string()),
228    };
229
230    // (1) Row count + avg row bytes. AVG_ROW_LENGTH already accounts for
231    // overflow pages on InnoDB, so we use it directly rather than dividing
232    // DATA_LENGTH by TABLE_ROWS (which under-counts for tables with TOAST-like
233    // overflow). Fall back to division when AVG_ROW_LENGTH is 0.
234    let row_stats: Option<(i64, i64, i64)> = conn.exec_first(
235        "SELECT CAST(IFNULL(TABLE_ROWS, 0) AS SIGNED), \
236                CAST(IFNULL(AVG_ROW_LENGTH, 0) AS SIGNED), \
237                CAST(IFNULL(DATA_LENGTH, 0) AS SIGNED) \
238         FROM information_schema.TABLES \
239         WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?",
240        (&schema, &table),
241    )?;
242    let (row_estimate, avg_row_bytes) = match row_stats {
243        Some((rows, avg, data_len)) => {
244            let row_count = rows.max(0);
245            let raw_per_row = if avg > 0 {
246                Some(avg)
247            } else if row_count > 0 {
248                Some(data_len / row_count)
249            } else {
250                None
251            };
252            // InnoDB stores TEXT/BLOB > ~768 B off-page in 16 KB BLOB pages,
253            // and `AVG_ROW_LENGTH` counts the allocated page bytes — not the
254            // actual content. On wide-text workloads (CMS bodies, JSON logs,
255            // audit trails) this inflates the per-row estimate 3-5× compared
256            // to what the client driver actually buffers over the wire.
257            //
258            // We empirically divide by 3 above an 8 KB threshold. Below 8 KB
259            // a row fits inline with no overflow, so the raw figure is
260            // accurate. Above it, dividing by 3 brings content_items' 41 KB
261            // estimate down to ~14 KB — still conservative vs the ~10 KB the
262            // PG side reports for the same payload via `pg_total_relation_size`.
263            //
264            // Pilots who want exact control can set `chunk_size:` explicitly
265            // (it always wins over the budget-derived size).
266            let per_row = raw_per_row.map(correct_innodb_avg_row_length);
267            (row_count, per_row.filter(|b| *b > 0))
268        }
269        None => (0, None),
270    };
271
272    // (2) Single-column int PK probe. STATISTICS has one row per (column,
273    // index) so we filter to PRIMARY + SEQ_IN_INDEX=1 and then check that
274    // the PRIMARY index has no SEQ_IN_INDEX=2 row (composite).
275    let pk_first: Option<(String,)> = conn.exec_first(
276        "SELECT COLUMN_NAME \
277         FROM information_schema.STATISTICS \
278         WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND INDEX_NAME = 'PRIMARY' AND SEQ_IN_INDEX = 1",
279        (&schema, &table),
280    )?;
281    let single_int_pk = if let Some((col,)) = pk_first {
282        let composite: Option<(String,)> = conn.exec_first(
283            "SELECT COLUMN_NAME FROM information_schema.STATISTICS \
284             WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND INDEX_NAME = 'PRIMARY' AND SEQ_IN_INDEX = 2 \
285             LIMIT 1",
286            (&schema, &table),
287        )?;
288        if composite.is_some() {
289            log::debug!(
290                "introspect_mysql_table: composite PK on {schema}.{table} — skipping auto-resolve"
291            );
292            None
293        } else {
294            // Column type must be integer-family for safe range chunking.
295            let type_row: Option<(String,)> = conn.exec_first(
296                "SELECT DATA_TYPE FROM information_schema.COLUMNS \
297                 WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?",
298                (&schema, &table, &col),
299            )?;
300            match type_row.map(|(t,)| t.to_ascii_lowercase()) {
301                Some(t)
302                    if matches!(
303                        t.as_str(),
304                        "tinyint" | "smallint" | "mediumint" | "int" | "bigint"
305                    ) =>
306                {
307                    Some(col)
308                }
309                Some(t) => {
310                    log::debug!(
311                        "introspect_mysql_table: PK '{col}' on {schema}.{table} has non-int type '{t}' — skipping auto-resolve"
312                    );
313                    None
314                }
315                None => None,
316            }
317        }
318    } else {
319        None
320    };
321
322    // (3) Keyset keys (OPT-4): single-column, NOT NULL, UNIQUE index columns —
323    // usable as a seek-pagination key. NON_UNIQUE=0 filters to unique indexes
324    // (PRIMARY included); SEQ_IN_INDEX=1 with no SEQ_IN_INDEX=2 row keeps only
325    // single-column indexes; IS_NULLABLE='NO' guarantees `> last` never has to
326    // reason about NULL ordering. Index-backed by definition, so keyset's
327    // `ORDER BY key LIMIT n` is a range scan, not a filesort.
328    let keyset_rows: Vec<(String, String, String)> = conn.exec(
329        "SELECT s.COLUMN_NAME, s.INDEX_NAME, c.IS_NULLABLE \
330         FROM information_schema.STATISTICS s \
331         JOIN information_schema.COLUMNS c \
332           ON c.TABLE_SCHEMA = s.TABLE_SCHEMA AND c.TABLE_NAME = s.TABLE_NAME \
333              AND c.COLUMN_NAME = s.COLUMN_NAME \
334         WHERE s.TABLE_SCHEMA = ? AND s.TABLE_NAME = ? AND s.NON_UNIQUE = 0 \
335           AND s.SEQ_IN_INDEX = 1 \
336           AND NOT EXISTS ( \
337             SELECT 1 FROM information_schema.STATISTICS s2 \
338             WHERE s2.TABLE_SCHEMA = s.TABLE_SCHEMA AND s2.TABLE_NAME = s.TABLE_NAME \
339               AND s2.INDEX_NAME = s.INDEX_NAME AND s2.SEQ_IN_INDEX = 2)",
340        (&schema, &table),
341    )?;
342    let mut keyset_keys: Vec<String> = Vec::new();
343    // PRIMARY first (most efficient — clustered), then other unique indexes.
344    for primary in [true, false] {
345        for (col, index_name, is_nullable) in &keyset_rows {
346            let is_primary = index_name == "PRIMARY";
347            if is_primary == primary
348                && is_nullable.eq_ignore_ascii_case("NO")
349                && !keyset_keys.contains(col)
350            {
351                keyset_keys.push(col.clone());
352            }
353        }
354    }
355
356    Ok(crate::source::TableIntrospection {
357        single_int_pk,
358        keyset_keys,
359        row_estimate,
360        avg_row_bytes,
361    })
362}
363
364fn build_mysql_ssl_opts(cfg: &TlsConfig) -> SslOpts {
365    let mut ssl = SslOpts::default();
366    if let Some(path) = &cfg.ca_file {
367        ssl = ssl.with_root_cert_path(Some(std::path::PathBuf::from(path)));
368    }
369    match cfg.mode {
370        TlsMode::Require => {
371            ssl = ssl
372                .with_danger_accept_invalid_certs(true)
373                .with_danger_skip_domain_validation(true);
374        }
375        TlsMode::VerifyCa => {
376            ssl = ssl.with_danger_skip_domain_validation(true);
377        }
378        TlsMode::VerifyFull => {
379            // Strict: verify chain + hostname.
380        }
381        TlsMode::Disable => {
382            // Never invoked: gated in connect_with_tls.
383        }
384    }
385    if cfg.accept_invalid_certs {
386        ssl = ssl.with_danger_accept_invalid_certs(true);
387    }
388    if cfg.accept_invalid_hostnames {
389        ssl = ssl.with_danger_skip_domain_validation(true);
390    }
391    ssl
392}
393
394/// RAII reset of the per-connection session state the export mutates
395/// (`time_zone`, optionally `max_execution_time`) — the MySQL analogue of
396/// `postgres::PgTxnGuard` (Epic 18 B1).
397///
398/// MySQL hands connections back to the `mysql` crate's pool on drop, and may sit
399/// behind ProxySQL / MaxScale that reuse a physical backend across logical
400/// connections. The previous end-of-`export()` reset covered success and the
401/// `Err` return (no `?`), but **not** a panic mid-export, nor an early `?` on
402/// the `SET max_execution_time` itself (MariaDB spells it `max_statement_time`,
403/// so that SET errors — and `time_zone`, already set, would leak). Arming the
404/// reset on `Drop` closes both: whatever exit path the export takes, the
405/// connection is clean before it returns to the pool.
406struct MysqlSessionGuard<'a> {
407    conn: &'a mut mysql::PooledConn,
408    reset_max_exec: bool,
409}
410
411impl<'a> MysqlSessionGuard<'a> {
412    /// Apply the session SETs and arm the reset. `time_zone` is always set (UTC
413    /// normalisation so Parquet writes `isAdjustedToUTC=true`); the guard is
414    /// constructed *immediately* after it, so if the later `max_execution_time`
415    /// SET fails (or anything panics), `Drop` still resets `time_zone`.
416    fn apply(conn: &'a mut mysql::PooledConn, max_exec_ms: Option<u64>) -> Result<Self> {
417        conn.query_drop("SET time_zone = '+00:00'")?;
418        let mut guard = Self {
419            conn,
420            reset_max_exec: false,
421        };
422        if let Some(ms) = max_exec_ms {
423            guard
424                .conn
425                .query_drop(format!("SET SESSION max_execution_time = {ms}"))?;
426            guard.reset_max_exec = true;
427        }
428        Ok(guard)
429    }
430
431    fn conn(&mut self) -> &mut mysql::PooledConn {
432        self.conn
433    }
434}
435
436impl Drop for MysqlSessionGuard<'_> {
437    fn drop(&mut self) {
438        // Best-effort; the connection is about to return to the pool either way.
439        let _ = self.conn.query_drop("SET time_zone = @@global.time_zone");
440        if self.reset_max_exec {
441            let _ = self.conn.query_drop("SET SESSION max_execution_time = 0");
442        }
443    }
444}
445
446/// Execute the MySQL query and stream results to sink.
447///
448/// Session-state cleanup (`time_zone`, `max_execution_time`) is handled by the
449/// caller's [`MysqlSessionGuard`], which resets it on `Drop` regardless of how
450/// this function exits (success, `Err`, or panic).
451///
452/// `sample_pool`: when `tuning.adaptive` is true, a clone of the source pool used
453/// to obtain a second connection for extraction-pressure sampling without interfering
454/// with the streaming result set on `conn`.
455fn mysql_run_export(
456    conn: &mut mysql::PooledConn,
457    sample_pool: Option<Pool>,
458    sql: &str,
459    cursor_param: Option<&str>,
460    tuning: &SourceTuning,
461    column_overrides: &ColumnOverrides,
462    sink: &mut dyn super::BatchSink,
463) -> Result<usize> {
464    // SecOps: cursor value is bound via exec_iter rather than string-interpolated.
465    // Using exec_iter uniformly (even with empty params) keeps match arms
466    // type-compatible — query_iter returns a Text-protocol result, exec_iter Binary.
467    let mut result = match cursor_param {
468        Some(val) => conn.exec_iter(sql, (val,))?,
469        None => conn.exec_iter(sql, ())?,
470    };
471    let columns = result.columns().as_ref().to_vec();
472
473    // Compute TypeMappings once; derive both the Arrow schema and the
474    // per-column DataType vec from the same source so they can never diverge.
475    let (schema, arrow_types) = mysql_schema_and_arrow_types(&columns, column_overrides)?;
476    let schema = Arc::new(schema);
477
478    sink.on_schema(schema.clone())?;
479
480    // PG path uses `work_mem × 0.7 / row_bytes` for FETCH N — the analogous
481    // bottleneck on MySQL is *our* `row_buf` accumulator. The mysql crate
482    // streams rows from the wire one-at-a-time, but we pile up `effective_bs`
483    // of them in a `Vec<Row>` before flushing to Arrow → for `batch_size: 50000`
484    // (fast profile) on content_items that's ~650 MB just for the row_buf,
485    // plus another ~650 MB for the Arrow batch it feeds — RSS scales with
486    // `batch_size`, not chunk size.
487    //
488    // Fix: start with a small probe (`PROBE_BATCH_SIZE`), measure the actual
489    // Arrow bytes per row after the first batch, then cap `effective_bs` so
490    // each flush fits in roughly `MYSQL_BATCH_TARGET_MB` of Arrow memory.
491    // Caller's `batch_size_memory_mb` wins when set; the default is 64 MB —
492    // chosen to keep peak RSS well under 200 MB on wide-row tables while
493    // keeping batches large enough to be efficient for the parquet writer.
494    let configured_batch_size = tuning.effective_batch_size(Some(&schema));
495    // Shared batch-size state machine (probe → memory-cap → adaptive → throttle);
496    // MySQL provides only the row source + the target-MB cap formula below.
497    let mut ctl = AdaptiveBatchController::new(tuning, configured_batch_size);
498    ctl.seed_pressure(if tuning.adaptive {
499        sample_pool
500            .as_ref()
501            .and_then(mysql_sample_extraction_pressure)
502    } else {
503        None
504    });
505    let row_set = result
506        .iter()
507        .ok_or_else(|| anyhow::anyhow!("no result set"))?;
508    let mut row_buf: Vec<mysql::Row> = Vec::with_capacity(ctl.target());
509    let mut total_rows: usize = 0;
510    let mut memory_cap_applied = false;
511    // Per-value ceiling (MB→bytes; `0`/None disables), enforced pre-allocation
512    // inside the batch builder so an oversized cell bails before Arrow reserves
513    // the buffer. Same source of truth as the sink's backstop guard.
514    let max_value_bytes = tuning.max_value_bytes();
515
516    for row_result in row_set {
517        let row = row_result?;
518        row_buf.push(row);
519
520        if row_buf.len() >= ctl.target() {
521            total_rows += row_buf.len();
522            let batch =
523                rows_to_record_batch_typed(&schema, &arrow_types, &row_buf, max_value_bytes)?;
524            let batch_rows = row_buf.len();
525            row_buf.clear();
526
527            // After the first (probe-sized) batch we know how many bytes per
528            // row Arrow actually uses. Cap subsequent flushes to a memory
529            // target. The controller clamps it to the configured `batch_size`.
530            if !memory_cap_applied && batch_rows > 0 {
531                let arrow_bytes = crate::tuning::SourceTuning::batch_memory_bytes(&batch);
532                let arrow_per_row = (arrow_bytes / batch_rows).max(64);
533                let target_mb = tuning
534                    .batch_size_memory_mb
535                    .unwrap_or(DEFAULT_BATCH_TARGET_MB);
536                let safe = ((target_mb * 1024 * 1024) / arrow_per_row).max(PROBE_BATCH_SIZE);
537                if let Some(new) = ctl.apply_memory_cap(safe) {
538                    log::info!(
539                        "MySQL row_buf cap: arrow≈{} B/row, target={} MB → batch_size → {} (configured={})",
540                        arrow_per_row,
541                        target_mb,
542                        new,
543                        configured_batch_size
544                    );
545                    row_buf.reserve(new.saturating_sub(row_buf.capacity()));
546                }
547                memory_cap_applied = true;
548            }
549
550            sink.on_batch(&batch)?;
551
552            if let Some((new, under_pressure)) = ctl.after_batch(|| {
553                sample_pool
554                    .as_ref()
555                    .and_then(mysql_sample_extraction_pressure)
556            }) {
557                log::info!(
558                    "adaptive batch size → {} ({})",
559                    new,
560                    if under_pressure {
561                        "pressure"
562                    } else {
563                        "recovery"
564                    }
565                );
566            }
567
568            log::info!("fetched {} rows so far...", total_rows);
569            ctl.throttle();
570        }
571    }
572
573    if !row_buf.is_empty() {
574        total_rows += row_buf.len();
575        let batch = rows_to_record_batch_typed(&schema, &arrow_types, &row_buf, max_value_bytes)?;
576        sink.on_batch(&batch)?;
577    }
578
579    drop(result);
580    Ok(total_rows)
581}
582
583impl super::Source for MysqlSource {
584    fn export(
585        &mut self,
586        request: &super::ExportRequest<'_>,
587        sink: &mut dyn super::BatchSink,
588    ) -> Result<()> {
589        let built = build_export_query(request, SourceType::Mysql);
590        log::debug!(
591            "executing query (connection={}): {}",
592            self.proxy_kind.log_label(),
593            built.sql
594        );
595
596        let mut conn = self.pool.get_conn()?;
597
598        // Per-connection session state, reset on `Drop` (Epic 18 B1) so a pooled
599        // connection — returned to the mysql-crate pool or reused behind
600        // ProxySQL/MaxScale — never carries our settings into the next checkout,
601        // even on a panic or an early return. `time_zone` normalises TIMESTAMP to
602        // UTC (Parquet `isAdjustedToUTC=true`); `max_execution_time` bounds the
603        // statement when a timeout is configured.
604        let max_exec_ms = (request.tuning.statement_timeout_s > 0)
605            .then(|| request.tuning.statement_timeout_s * 1000);
606        let mut guard = MysqlSessionGuard::apply(&mut conn, max_exec_ms)?;
607
608        let sample_pool = if request.tuning.adaptive {
609            Some(self.pool.clone())
610        } else {
611            None
612        };
613        let result = mysql_run_export(
614            guard.conn(),
615            sample_pool,
616            &built.sql,
617            built.cursor_param.as_deref(),
618            request.tuning,
619            request.column_overrides,
620            sink,
621        );
622        // Reset now (success or `Err`); the `Drop` impl is the backstop for a
623        // panic or early return inside `mysql_run_export`.
624        drop(guard);
625
626        // The empty-result fallback to `Schema::empty()` lives here for
627        // parity with the PG implementation, even though `exec_iter` always
628        // returns the column metadata before yielding any rows so
629        // mysql_run_export's `on_schema` already fired.
630        let total_rows = result?;
631        if total_rows == 0 {
632            sink.on_schema(Arc::new(Schema::empty()))?;
633        }
634        log::info!("total: {} rows", total_rows);
635        Ok(())
636    }
637
638    fn query_scalar(&mut self, sql: &str) -> Result<Option<String>> {
639        let mut conn = self.pool.get_conn()?;
640        let row: Option<mysql::Row> = conn.query_first(sql)?;
641        match row {
642            Some(r) => {
643                let val: Option<mysql::Value> = r.get(0);
644                match val {
645                    Some(mysql::Value::Bytes(b)) => {
646                        Ok(Some(String::from_utf8_lossy(&b).into_owned()))
647                    }
648                    Some(mysql::Value::Int(v)) => Ok(Some(v.to_string())),
649                    Some(mysql::Value::UInt(v)) => Ok(Some(v.to_string())),
650                    Some(mysql::Value::Float(v)) => Ok(Some(v.to_string())),
651                    Some(mysql::Value::Double(v)) => Ok(Some(v.to_string())),
652                    _ => Ok(None),
653                }
654            }
655            None => Ok(None),
656        }
657    }
658
659    fn type_mappings(
660        &mut self,
661        query: &str,
662        column_overrides: &ColumnOverrides,
663    ) -> Result<Vec<crate::types::TypeMapping>> {
664        let wrapped = format!("SELECT * FROM ({}) AS _rivet_type_probe LIMIT 0", query);
665        let mut conn = self.pool.get_conn()?;
666        let result = conn.exec_iter(&wrapped, ())?;
667        let columns = result.columns().as_ref().to_vec();
668        drop(result);
669        let mappings = columns
670            .iter()
671            .map(|col| {
672                let rivet =
673                    crate::types::resolve_or(column_overrides, col.name_str().as_ref(), || {
674                        mysql_type_to_rivet(col)
675                    });
676                let source = crate::types::SourceColumn::simple(
677                    col.name_str().as_ref(),
678                    mysql_native_type_name(col),
679                    true,
680                );
681                crate::types::TypeMapping::from_source(&source, rivet)
682            })
683            .collect();
684        Ok(mappings)
685    }
686
687    /// Governor pressure proxy (Epic 18 C1): the same monotonic
688    /// extraction-pressure sum the adaptive batch loop samples
689    /// (`Created_tmp_disk_tables` + `Innodb_buffer_pool_wait_free`). Rising
690    /// between samples means the extraction is spilling a temp table to disk or
691    /// stalling on buffer-pool memory — the MySQL analogue of PG `temp_bytes`.
692    fn sample_pressure(&mut self) -> Option<u64> {
693        mysql_sample_extraction_pressure(&self.pool)
694    }
695}
696
697#[cfg(test)]
698mod tests {
699    use super::{bit_bytes_to_u64, correct_innodb_avg_row_length};
700
701    // Proxy classifier tests live in `proxy.rs` alongside the classifier.
702
703    // ── bit_bytes_to_u64 (lives in arrow_convert.rs, exported pub(super)) ──
704
705    #[test]
706    fn bit_bytes_single_byte() {
707        assert_eq!(bit_bytes_to_u64(&[0x00]), 0);
708        assert_eq!(bit_bytes_to_u64(&[0x01]), 1);
709        assert_eq!(bit_bytes_to_u64(&[0xFF]), 255);
710    }
711
712    #[test]
713    fn bit_bytes_multi_byte() {
714        assert_eq!(bit_bytes_to_u64(&[0x01, 0x02]), 258);
715        assert_eq!(bit_bytes_to_u64(&[0xFF; 8]), u64::MAX);
716    }
717
718    #[test]
719    fn bit_bytes_empty() {
720        assert_eq!(bit_bytes_to_u64(&[]), 0);
721    }
722
723    #[test]
724    fn bit_bytes_ascii_digit_bytes_are_bits_not_text() {
725        // Regression (mysql-bit): BIT bytes that happen to be ASCII digits are
726        // still big-endian bits — never decimal text.
727        assert_eq!(bit_bytes_to_u64(&[0x39]), 57); // "9" as text, BIT(8) 57
728        assert_eq!(bit_bytes_to_u64(&[0x31, 0x32]), 0x3132); // b"12" → 12594
729        assert_eq!(bit_bytes_to_u64(&[0x31, 0xFF]), 12799); // digit head, non-digit tail
730    }
731
732    // ── InnoDB AVG_ROW_LENGTH correction ────────────────────────────────
733
734    #[test]
735    fn innodb_correction_below_threshold_is_identity() {
736        assert_eq!(correct_innodb_avg_row_length(82), 82);
737        assert_eq!(correct_innodb_avg_row_length(314), 314);
738        assert_eq!(correct_innodb_avg_row_length(2_048), 2_048);
739        assert_eq!(correct_innodb_avg_row_length(8 * 1024), 8 * 1024);
740    }
741
742    #[test]
743    fn innodb_correction_above_threshold_divides_by_three() {
744        assert_eq!(correct_innodb_avg_row_length(40_978), 40_978 / 3);
745        assert_eq!(correct_innodb_avg_row_length(120_000), 40_000);
746    }
747
748    #[test]
749    fn innodb_correction_does_not_undershoot_floor() {
750        let just_above = 8 * 1024 + 1;
751        let divided = correct_innodb_avg_row_length(just_above);
752        assert!(divided >= 4 * 1024, "got {divided}");
753    }
754}