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