Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
456cae2
refactor: extract Source trait and engine dispatch for multi-source s…
mazzitano May 3, 2026
54b5dec
feat: add MySQL CDC source with binlog streaming and Offset Signal Al…
mazzitano May 3, 2026
2018592
chore: trim verbose comments in MySQL source files
mazzitano May 3, 2026
fa51007
fix: persist mysql (file, pos, gtid_executed) checkpoint instead of h…
May 5, 2026
b8e8c95
security: gate mysql tls cert validation behind opt-in (default verify)
May 5, 2026
4ae6a05
fix: use CASE WHEN instead of FILTER (WHERE) in mysql snapshot progre…
May 5, 2026
191680c
feat: implement read-only DBLog reconciliation for mysql incremental …
May 5, 2026
b23ac0f
docs: mark mysql as beta in readme; add changelog entries for v2.3.0
May 5, 2026
de3be23
chore: release dbmazz v2.3.0
May 5, 2026
ea945cd
refactor(mysql): share parser GTID set via Arc<RwLock> for snapshot w…
dariomazzitelli-sys May 9, 2026
f503b57
fix(core): drop GtidSet arm from SourcePosition::is_ahead_of
dariomazzitelli-sys May 9, 2026
acb6d39
fix(mysql): close Notify race in ActiveChunks::await_drain
dariomazzitelli-sys May 9, 2026
e256c86
fix(mysql): derive snapshot chunk LOW/HIGH watermarks from consumer GTID
dariomazzitelli-sys May 9, 2026
66f7076
fix(mysql): commit-boundary checkpoints, BEGIN/COMMIT/ROLLBACK, heart…
dariomazzitelli-sys May 9, 2026
f0f791d
docs(mysql): document pre-merge correctness fixes in CHANGELOG and RE…
dariomazzitelli-sys May 9, 2026
d7eae77
test(mysql): integration tests for snapshot LOW watermark and concurr…
dariomazzitelli-sys May 9, 2026
f88b563
fix(mysql): map TIMESTAMP/TIMESTAMP2 columns to ISO strings, not raw …
dariomazzitelli-sys May 10, 2026
60540ec
fix(mysql): also handle TIMESTAMP arriving as MysqlValue::Bytes(epoch…
dariomazzitelli-sys May 10, 2026
5cc7ad6
docs: CHANGELOG entry for MySQL TIMESTAMP/TIMESTAMP2 ISO conversion
dariomazzitelli-sys May 10, 2026
e724d64
refactor(source): add create_source factory mirroring create_sink shape
dariomazzitelli-sys May 10, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,99 @@ All notable changes to dbmazz will be documented here.

## [Unreleased]

## [2.3.0] - 2026-05-04

### Added

- **MySQL source (BETA).** New CDC source connector that streams from MySQL
via binlog (ROW format, GTID-aware), supporting StarRocks, PostgreSQL, and
Snowflake sinks. Concurrent snapshot + CDC via the read-only DBLog
Incremental Snapshot algorithm. Requires `gtid_mode=ON` and
`binlog_format=ROW`. Setup, configuration, and BETA scope documented in
[`docs/mysql-source.md`](docs/mysql-source.md).
- **`source::create_source` factory** mirroring the existing
`connectors::sinks::create_sink` factory. Single dispatch point per
side of the pipeline; the engine now constructs sources via the
factory rather than ad-hoc match arms.

### Fixed

- MySQL source now persists `(binlog_file, position, gtid_executed)` as the
checkpoint, restoring restart correctness across binlog rotations and
daemon restarts. Earlier, the persisted "checkpoint" was a hex-encoded
byte offset mislabeled as a GTID and the parsed GTID was discarded.
- MySQL snapshot progress query no longer uses `FILTER (WHERE ...)`
(PostgreSQL-only syntax that MySQL ≤ 8.4 rejects with a parse error).
- MySQL CDC checkpoints are now persisted only at transaction commit
boundaries, never mid-transaction. The previous code persisted positions
per acknowledged record, including the in-flight `gtid_executed` added
on `GtidEvent`; a crash before the matching `XidEvent` advanced the
saved checkpoint past an uncommitted transaction and silently dropped it
on restart. (Debezium-faithful adaptation: the connector emits per-event
but commits the offset only at transaction boundaries.)
- DDL-only transactions (`CREATE TABLE`, `ALTER TABLE`, etc., which
terminate with `QueryEvent("COMMIT")` instead of `XidEvent`) now produce
a `BinlogEvent::Commit` boundary so the pipeline flushes and the
persisted checkpoint advances past the DDL.
- MySQL snapshot `await_drain` no longer deadlocks under concurrent
`try_drain` calls. The previous polling-then-awaiting pattern lost
`Notify::notify_waiters` wake-ups fired between the flag check and the
await; reproduced reliably under load and verified fixed by a
10 000-iteration race-stress unit test.
- MySQL snapshot chunk LOW/HIGH watermarks are now derived from the binlog
consumer's live GTID set (an `Arc<RwLock<GtidSet>>` shared with the
parser), not from `SELECT @@global.gtid_executed` against the source.
Eliminates the LOW-capture-vs-chunk-registration race that emitted
duplicate snapshot+CDC records for rows mutated during the window.
- MySQL heartbeat events now carry the live `(file, position,
gtid_executed)` triple and trigger snapshot drain checks so idle
databases don't hang the snapshot worker. Heartbeats previously emitted
a placeholder `SourcePosition::GtidSet("0")` that corrupted any
checkpoint persisting a heartbeat.
- MySQL `TableMapEvent` parsing preserves column ordinals when a column
type is unrecognised. Previously `extract_col_types` silently dropped
unknown columns via `filter_map`, shifting subsequent columns one slot
down and binding row values to the wrong column names — a silent
corruption bug for tables using a type mysql_common didn't yet
recognise. Unknown columns now produce a sentinel byte in their
original slot; downstream value decoding emits `Value::Null` for them
and a structured `ERROR` log surfaces the table+ordinal.
- MySQL CDC startup runs a `GTID_SUBSET(persisted, @@global.gtid_executed)`
probe; if the persisted set isn't a subset of the server's executed set
(binlog purge, server failover, or a pre-fix daemon's mid-transaction
checkpoint), the daemon now exits non-zero with operator-actionable
remediation rather than retry-looping forever.
- MySQL `TIMESTAMP` and `TIMESTAMP2` columns are now emitted as ISO-8601
formatted strings (`"YYYY-MM-DD HH:MM:SS"` UTC) instead of being passed
through as the raw epoch-seconds integer. Previously every row of a
table containing a `TIMESTAMP` column failed the PG sink's MERGE cast
(`(_data->>'created_at')::timestamp with time zone`), silently dropping
the entire batch and preventing any data from reaching the target.
Surfaced by the first MySQL→PG end-to-end run via `ez-cdc verify`.
This is the minimum-viable temporal fidelity for MySQL beta; the
forward-compatible `Value::Timestamp(i64 micros)` with `tz_aware`
semantics is scoped to `mysql-cdc-beta-to-ga`.
- Both wire-protocol shapes are handled: `MysqlValue::Int(epoch)`
(legacy `TIMESTAMP`, code `0x07`) and `MysqlValue::Bytes(epoch_ascii)`
(mysql_common 0.32.4 returns `TIMESTAMP2` (code `0x11`) as ASCII
epoch bytes in binlog mode). Plain `INT/BIGINT` columns remain
untouched — verified by a unit test asserting non-temporal int
columns keep their `Value::Int64` shape.

### Removed

- `SourcePosition::is_ahead_of` no longer attempts to order
`SourcePosition::GtidSet` values. GTID sets are partial orders (set
inclusion of UUID:range pairs); the previous lexicographic string
compare was meaningless. Callers needing partial-order semantics MUST
use `crate::source::mysql::gtid::GtidSet::is_superset_of` directly.

### Security

- MySQL source TLS certificate verification is now **on by default**. Set
`MYSQL_TLS_SKIP_VERIFY=true` to opt out (unsafe — for dev environments
only). The previous behaviour silently accepted any certificate.

## [2.2.0] - 2026-04-29

### Added
Expand Down
3 changes: 2 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "dbmazz"
version = "2.2.0"
version = "2.3.0"
edition = "2021"
license = "Elastic-2.0"
# Minimum Supported Rust Version.
Expand All @@ -10,6 +10,8 @@ rust-version = "1.91.1"
[features]
default = ["sink-starrocks", "sink-postgres", "sink-snowflake"]
sink-starrocks = ["dep:curl", "dep:mysql_async", "dep:openssl-sys"]
# --- Optional: MySQL source ---
mysql-source = ["dep:mysql_async", "dep:mysql_common", "mysql_async?/binlog"]
sink-postgres = []
sink-snowflake = [
"dep:reqwest", "dep:arrow", "dep:parquet",
Expand Down Expand Up @@ -70,8 +72,12 @@ aws-sigv4 = { version = "1.2", optional = true }
aws-credential-types = { version = "1.2", optional = true }
uuid = { version = "1", features = ["v4"], optional = true }

# --- Optional: MySQL source ---
mysql_common = { version = "=0.32.4", features = ["binlog"], optional = true }

[dev-dependencies]
serial_test = "3.0"
mysql_async = "0.34"

[profile.release]
debug = 1 # Line tables only (flamegraphs work, smaller binary)
Expand Down
58 changes: 58 additions & 0 deletions Dockerfile.mysql
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# syntax=docker/dockerfile:1.6
#
# Multi-stage build for dbmazz with mysql-source + sink-postgres features.
#
# This is an ALTERNATE Dockerfile for local dev / CI when you don't want
# to pre-compile the binary. The production release workflow still uses
# the main Dockerfile with pre-compiled musl-static binaries.
#
# Usage:
# docker build -t dbmazz-mysql:dev -f Dockerfile.mysql .
#
# For multi-arch builds (slower — QEMU emulates the Rust compiler):
# docker buildx build --platform linux/amd64,linux/arm64 \
# -t dbmazz-mysql:dev -f Dockerfile.mysql .
#
# Security: runs as non-root user (uid 65532), HEALTHCHECK configured.
# Binary: dynamically linked against glibc (debian:bookworm-slim).
# DEV NOTE: this differs from the production image (musl-static).
# Always validate against a musl-static build before release.

FROM rust:bookworm AS builder
WORKDIR /app

# ---- Layer 0: system dependencies for compilation ----
# openssl-sys (transitive via mysql_async) needs headers during build.
RUN apt-get update && apt-get install -y libssl-dev && rm -rf /var/lib/apt/lists/*

# ---- Layer 1: fetch dependencies (cached unless Cargo.toml/lock changes) ----
COPY Cargo.toml Cargo.lock ./
RUN mkdir -p src && touch src/lib.rs
# NOTE: cargo fetch does NOT support --features, so we fetch default deps here.
# Optional deps (mysql_async, mysql_common) will auto-fetch during build.
RUN cargo fetch --locked

# ---- Layer 2: real source + real build ----
COPY src/ src/
RUN cargo build --release --features mysql-source,sink-postgres --locked

# ====================================================================
# Runtime stage
# ====================================================================
FROM debian:bookworm-slim

RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl libssl3 \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --system --no-create-home --uid 65532 dbmazz

COPY --from=builder /app/target/release/dbmazz /usr/local/bin/dbmazz

USER dbmazz

EXPOSE 50051

HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 \
CMD curl -sf http://127.0.0.1:50051/api/v1/health || exit 1

ENTRYPOINT ["/usr/local/bin/dbmazz"]
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ Full Docker reference (env vars, healthcheck, persisting state, build-from-sourc
| PostgreSQL 12+ | **PostgreSQL 15+** | ✅ Stable | Binary `COPY` → raw table → `MERGE` normalizer; supports hard delete |
| PostgreSQL 12+ | **Snowflake** | ✅ Stable | Parquet → PUT (stage) → `COPY INTO` → background `MERGE`; JWT key-pair auth supported; requires `ALTER TABLE` privilege on target schema |
| PostgreSQL 12+ | S3 / Iceberg | 🚧 Roadmap | Tracked in [issues](https://github.com/ez-cdc/dbmazz/issues) |
| MySQL | * | 🚧 Roadmap | The source layer is generic; PostgreSQL is the only implementation today |
| MySQL 5.7+ / 8.0+ | All sinks | 🧪 Beta | Binlog-based with GTID-aware checkpointing. See [`docs/mysql-source.md`](docs/mysql-source.md). |

Adding a new sink is intentionally small: implement a 6-method `Sink` trait and CDC + snapshot work automatically. See [`docs/contributing-connectors.md`](docs/contributing-connectors.md).

Expand Down
117 changes: 117 additions & 0 deletions docs/mysql-source.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# MySQL source (BETA)

dbmazz can stream changes from MySQL 5.7+ / 8.0+ to any of the supported sinks (StarRocks, PostgreSQL, Snowflake) via the `mysql-source` cargo feature.

This document covers MySQL-specific setup, configuration, and the BETA scope. For general dbmazz architecture, see [architecture.md](architecture.md).

## Prerequisites

The source MySQL server **must** have:

| Setting | Required value | Why |
|---|---|---|
| `log_bin` | enabled (any non-empty value) | Binary log is the change stream |
| `binlog_format` | `ROW` | Statement / mixed formats don't carry full row state |
| `binlog_row_image` | `FULL` | Needed for `UPDATE` / `DELETE` reconciliation |
| `gtid_mode` | `ON` | Required for the read-only DBLog incremental snapshot |
| `enforce_gtid_consistency` | `ON` | Pairs with `gtid_mode=ON` |
| `server_id` | unique non-zero | Replication client identity |

Privileges required for the connection user: `REPLICATION SLAVE`, `REPLICATION CLIENT`, plus `CREATE`, `INSERT`, `UPDATE`, `DELETE` on the source database (dbmazz writes its checkpoint and snapshot-state tables there — `dbmazz_checkpoints` and `dbmazz_snapshot_state`).

## Configuration

```yaml
sources:
my-mysql:
type: mysql
url: mysql://user:password@host:3306/dbname
tables:
- orders
- order_items
tls_skip_verify: false # default; set true ONLY for dev MySQL without TLS
gtid_enabled: true # default
# server_id: 5500 # optional; dbmazz auto-assigns if omitted
```

Environment variables (set on the dbmazz container by `ez-cdc-cli`, or set directly when running dbmazz standalone):

| Env var | Default | Notes |
|---|---|---|
| `SOURCE_TYPE` | — | Must be `mysql` |
| `SOURCE_URL` | — | `mysql://user:pass@host:port/dbname` |
| `MYSQL_TLS_SKIP_VERIFY` | `false` | Disables TLS verification — dev only |
| `MYSQL_GTID_ENABLED` | `true` | Required for incremental snapshot |
| `MYSQL_SERVER_ID` | random in [5400, 6400) | Set explicitly when running multiple dbmazz instances against one source |

## Local development

Spin up a dev MySQL with the right flags in one line:

```bash
docker run -d --rm --name mysql-source \
-p 13306:3306 \
-e MYSQL_ALLOW_EMPTY_PASSWORD=1 \
-e MYSQL_DATABASE=dbmazz \
mysql:8.0 \
--gtid-mode=ON --enforce-gtid-consistency=ON \
--log-bin=mysql-bin --server-id=1 \
--binlog-format=ROW --binlog-row-image=FULL
```

The default `ghcr.io/ez-cdc/dbmazz:latest` image is built without the `mysql-source` cargo feature. For now, build a local image:

```bash
docker build -t dbmazz-mysql:dev -f Dockerfile.mysql .
```

Then point `ez-cdc verify` at it via `--image dbmazz-mysql:dev`. The release pipeline will eventually publish a `mysql-source`-enabled image; this manual step goes away then.

## How it works

dbmazz follows Debezium's MySQL connector design, adapted to dbmazz's single-binary architecture (no Kafka Connect, no signal table):

- **Binlog streaming** — ROW format, GTID-aware. Checkpoints are persisted as `(binlog_file, position, gtid_executed)` only at transaction commit boundaries; restart resumes from the last committed GTID set.
- **Incremental snapshot** — read-only DBLog (Andreakis & Papapanagiotou 2020), adapted to use the binlog consumer's live GTID set as low/high watermarks instead of a writable signal table. Concurrent CDC + snapshot is supported; per-PK reconciliation drops snapshot rows that lost a race to a concurrent binlog event.
- **Schema introspection** — `information_schema` query at startup; the schema is cached in-memory and used to map binlog row payloads to the engine's generic `CdcRecord` shape.

## BETA scope

What works today:

- Binlog streaming (INSERT / UPDATE / DELETE) for ROW format, GTID mode.
- Incremental snapshot for tables with single-column integer primary keys.
- Concurrent snapshot + CDC reconciliation.
- Crash-recovery startup probe (validates persisted GTID set vs `@@global.gtid_executed`).
- Verified end-to-end against PostgreSQL and StarRocks sinks via `ez-cdc verify` (Tier 1: A1-A4, B1/B1b/B2/B3, CDC, D4, D5, C10, H1).

What's known to be incomplete (tracked in `openspec/changes/mysql-cdc-beta-to-ga`):

- **Type fidelity**: `BIGINT UNSIGNED` overflow at the `i64` boundary; `DECIMAL` precision/scale not propagated from `information_schema`; `DATETIME` microseconds discarded; `ENUM`/`SET` semantics; full JSON typed roundtrip. The `C11` (Type roundtrip) verify check is expected to FAIL until this lands — use `ez-cdc verify --skip C11` in CI.
- **Snapshot bootstrap from arbitrary binlog position**: today the daemon resumes from the persisted checkpoint or starts at the binlog tail; no first-run bootstrap that walks backwards.
- **Cursor-based snapshot chunker**: today's chunker is range-based; cursor-based gives more uniform chunk sizes for non-contiguous PK distributions.
- **Non-integer primary keys**: composite, UUID, and string PKs are not yet supported in the snapshot path.

## Verifying

The `ez-cdc-cli` test harness has full MySQL support. After bringing up a MySQL container per the recipe above:

```bash
# Configure dbmazz to point at it
ez-cdc datasource add # interactive wizard, prompts for tls_skip_verify etc.

# Run the verify suite
ez-cdc verify --image dbmazz-mysql:dev \
--source my-mysql \
--sink <your-sink> \
--skip C11
```

See the `ez-cdc-cli` repository's README for the full verify command surface.

## Related documents

- [architecture.md](architecture.md) — how the engine, source, and sink layers fit together.
- [configuration.md](configuration.md) — env vars, pipeline tuning, sink-specific options.
- [contributing-connectors.md](contributing-connectors.md) — adding a new source or sink.
- [CHANGELOG.md](../CHANGELOG.md) — version-by-version notes including the MySQL beta milestone.
Loading