Skip to content

VReplication: reload the schema at a DDL only once MySQL has committed it - #21887

Merged
mattlord merged 20 commits into
mainfrom
fix-21883-reload-after-ddl-commit
Nov 23, 2026
Merged

mattlord merged 20 commits into
mainfrom
fix-21883-reload-after-ddl-commit

Conversation

@mattlord

@mattlord mattlord commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Description

A vstreamer reloads the schema engine as soon as it reads a schema-changing DDL from the binlog, at the DDL's position (ReloadAt). But MySQL sends a transaction's binlog events to the binlog dump threads once the binlog is synced, before the storage engine commit, and with semi-sync AFTER_SYNC the commit then waits for a replica's acknowledgement. A reload in that window doesn't see the DDL:

  • For an Online DDL cutover, the renamed-over table still has its old create_time, so the reload finds nothing to reload.
  • ReloadAtEx still records the DDL's position as reloaded, so every other vstream's ReloadAt for that position skips its reload.
  • The schema tracker then saves the pre-DDL schema as the DDL's version. Every vstream that later replays across the DDL decodes the rows after it with the old columns. When columns were dropped, the values are sent under the wrong names, with no error.

This PR adds Engine.ReloadAtDDL, which the vstreamer now calls for a DDL in place of ReloadAt. It waits until MySQL has committed the DDL, then reloads at its position:

  • What it waits for: only the DDL's own GTID, through the existing Conn.WaitUntilPosition (WAIT_FOR_EXECUTED_GTID_SET). @@gtid_executed includes a transaction only once it has committed and is visible. The rest of the stream's position can contain GTIDs this server never executes, such as errant GTIDs in the position a stream started from, so waiting for the whole position could block forever.
  • No extra work when nothing is pending: it waits only if the engine hasn't already reloaded at the position. That earlier reload already waited, so normally the first vstream to reach a DDL waits and the others don't.
    • This relies on transactions committing in binlog order, which holds with binlog_order_commits=ON, MySQL's default.
    • With it off, a later DDL can commit first, and a reload at it can skip the wait for an earlier DDL that hasn't committed yet. That's no worse than today.
  • One wait per DDL: the vstreams that reach a DDL before any reload at it share one wait, on one connection rather than a pooled one, so a DDL costs one connection per tablet however many vstreams reach it. Each caller still stops waiting when its own context ends. The wait runs before the engine's mutex is taken.
    • The shared wait (singleflight, keyed by the DDL's GTID) runs in a goroutine that the DDL's first waiter starts. It can outlive its callers: it ends when the DDL commits, when the reload timeout passes, or if its connection fails.
    • A vstream that reaches the DDL after the shared wait ends but before the reload lands opens a short connection, whose wait returns at once.
  • Cancellation: the wait query doesn't watch its context, so the connection is closed when the context ends. That covers a vstream that is closing, and a MySQL that has stopped answering.
  • Bound: the wait is bounded by --schema-change-reload-timeout (30s by default), the same bound as the reload itself. If the DDL hasn't committed by then, the reload fails and so does the vstream, which its client retries. Today it would have silently loaded the wrong schema.
    • Each time the schema tracker's or the messager's vstream fails this way, it can leave a goroutine behind, holding one binlog event, until the tracker closes or the messager stops its vstream. Any other error that ends one of their vstreams can do the same today: it's an existing bug in the vstreamer's event loop, which this PR doesn't change.
  • Visibility: a wait longer than a second is logged as a warning, with the GTID and how long it took. Each shared wait is also timed under a new DDLCommitWait type of the Waits timings, next to the tablet's other waits. It isn't under SchemaReload, whose totals count only reloads.
  • MySQL GTIDs only: the file position and MariaDB waits follow a replica's SQL thread, which doesn't advance on a primary. Streams with those flavors keep today's behavior, and so the bug.

Backport: the bug goes back to the original historian, and it saves wrong schema versions silently. I think this is worth backporting to release-23.0 and release-24.0. On release-23.0 the vstreamer calls ReloadAt(context.Background(), ...) and ignores its error, so the backport there needs a small adaptation.

Motivation

How do you use Vitess? (pick one)

  • In production
  • In staging or development
  • Evaluating it
  • I don't use Vitess

Did you run this change against a real Vitess deployment? Not against a deployment. #21883 has the reproduction.

Related Issue(s)

Checklist

  • "Backport to:" labels have been added if this change should be back-ported to release branches
  • If this change is to be back-ported to previous releases, a justification is included in the PR description
  • Tests were added or are not required
  • Did the new or modified tests pass consistently locally and on CI?
  • Documentation was added or is not required

Deployment Notes

A vstream that reaches a schema-changing DDL now waits until MySQL has committed the DDL before it goes on. This affects VReplication, the VStream API and the schema tracker.

  • How long: normally milliseconds; with semi-sync, up to the replica's acknowledgement.
  • Cost: one short-lived MySQL connection per schema-changing DDL, shared by the vstreams that reach it.
  • Timeout: --schema-change-reload-timeout (30s by default) now bounds that wait as well as the reload, so a reload after a DDL can take up to twice that. If the DDL hasn't committed by then, the vstream fails with an error instead of continuing with a schema that doesn't include the DDL.
    • Streams from an external MySQL source (externalConnections in --tablet-config) always use the 30s default, for the wait as for the reload, because their engines use the default tablet settings.
    • A vstream sends no heartbeats while it waits, as while it reloads. With the timeout at about 10 minutes or more, VTGate's 10-minute liveness check can end a VStream before the wait times out, if none of its shards sends anything else in the meantime.
  • Monitoring: the Waits timings have a new DDLCommitWait type that times each of those waits (vttablet_waits_bucket{type="DDLCommitWait"} and its _sum and _count in Prometheus).

AI Disclosure

This PR was written with Claude Code.

A vstreamer reloads the schema engine as soon as it reads a schema-changing
DDL from the binlog, at the DDL's position. But MySQL sends a transaction's
binlog events to the binlog dump threads once the binlog is synced, before
the storage engine commit, and with semi-sync AFTER_SYNC the commit then
waits for a replica's acknowledgement. A reload in that window doesn't see
the DDL: for an Online DDL cutover, the renamed-over table still has its old
create_time. ReloadAtEx still records the DDL's position as reloaded, so the
other vstreams skip their reloads, and the schema tracker saves the pre-DDL
schema as the DDL's version, which every later replay across the DDL then
decodes its rows with.

The vstreamer now calls a new Engine.ReloadAtDDL, which first waits until
MySQL has committed the DDL's own GTID (WAIT_FOR_EXECUTED_GTID_SET:
@@gtid_executed includes a transaction only once it has committed). It waits
only for that GTID, because the rest of a stream's position can hold GTIDs
this server never executes, and only when the engine hasn't already reloaded
at the position. The wait runs on its own connection without holding the
engine's mutex, is bounded by --schema-change-reload-timeout, and closes the
connection when its context ends, since the wait query doesn't watch it. A
wait over a second is logged. File position and MariaDB GTIDs aren't waited
on: those waits follow a replica's SQL thread, which doesn't advance on a
primary.

The vstreamer tests' createSchemaVersionTable helper now creates
_vt.schema_version as the sidecar database does, with an AUTO_INCREMENT id,
which the schema tracker's insert needs after TestVersion drops the table.

Fixes #21883

Signed-off-by: Matt Lord <mattalord@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 5, 2026 23:49
@github-actions github-actions Bot added this to the v25.0.0 milestone Nov 5, 2026
@vitess-bot vitess-bot Bot added NeedsWebsiteDocsUpdate What it says NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels Nov 5, 2026
@vitess-bot

vitess-bot Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@mattlord mattlord changed the title schema: reload at a DDL only once MySQL has committed it VReplication: reload the schema at a DDL only once MySQL has committed it Nov 5, 2026
@mattlord mattlord added Backport to: release-23.0 Needs to be backport to release-23.0 Backport to: release-24.0 Needs to be backport to release-24.0 and removed NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsWebsiteDocsUpdate What it says NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required Component: VTTablet labels Nov 5, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Concurrent vstreams waiting on the same DDL can each open an unpooled MySQL connection, potentially exhausting max_connections and disrupting streams and other database access.

1 open issue
What changed in this PR

This PR addresses #21883 by delaying DDL-triggered schema reloads until MySQL has committed the DDL, preventing the schema tracker from saving pre-DDL definitions.

Changes:

  • Add a bounded commit wait for the DDL’s own MySQL GTID before reloading.
  • Pass the current transaction’s GTID from the vstreamer to the schema engine.
  • Add regression coverage and align the schema-version test table with the sidecar definition.
File Description
go/​vt/​vttablet/​tabletserver/​vstreamer/​vstreamer.go Track the current GTID and use the DDL-aware reload.
go/​vt/​vttablet/​tabletserver/​vstreamer/​vstreamer_test.go Test schema visibility during delayed commits and correct the test table definition.
go/​vt/​vttablet/​tabletserver/​schema/​engine.go Wait for DDL commit with timeout, cancellation, and slow-wait logging.
go/​vt/​vttablet/​tabletserver/​schema/​engine_test.go Cover GTID waits, cached reloads, timeouts, and non-MySQL fallback.

Review effort: Balanced

@codecov

codecov Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.33333% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.73%. Comparing base (70c7a72) to head (59ee424).
⚠️ Report is 837 commits behind head on main.

Files with missing lines Patch % Lines
go/vt/vttablet/tabletserver/schema/engine.go 92.85% 3 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main   #21887       +/-   ##
===========================================
+ Coverage   69.67%   80.73%   +11.06%     
===========================================
  Files        1614       29     -1585     
  Lines      216793     5310   -211483     
===========================================
- Hits       151044     4287   -146757     
+ Misses      65749     1023    -64726     
Flag Coverage Δ
partial 80.73% <93.33%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…ach it

Each vstream that reached a DDL before any reload at it opened its own
unpooled MySQL connection to wait for the DDL to commit. While the commit is
held for a semi-sync acknowledgement, that is one connection per vstream for
up to --schema-change-reload-timeout, and then again on every retry, at the
moment the primary is already short of connections.

The waits for a DDL are now coalesced by its GTID with singleflight: the
vstreams that reach it share one wait on one connection, and each still stops
waiting when its own context ends. The shared wait runs on a context that no
single caller can cancel, so it can outlive its callers: it ends when MySQL
commits the DDL, when the reload timeout passes, or if its connection fails.
A caller that joins late shares the first wait's deadline, and its error no
longer claims it waited for the whole timeout.

Signed-off-by: Matt Lord <mattalord@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 6, 2026 00:47

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Correctness depends on MySQL binlog/commit visibility affecting persistent schema history, while the real-MySQL semi-sync regression and connection timeout behavior require runtime validation beyond static review.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 6, 2026 18:45
TestOpenAndReload started the second caller of ReloadAtDDL in a
goroutine and didn't wait for it to join the shared wait for the DDL.
The DDL commits only after the third caller's 200ms deadline, so a
second caller that wasn't scheduled until the shared wait had ended
would have started a wait of its own and failed the test, though the
wait is shared correctly.

Pass the second caller a context that records when its Done channel is
first asked for, which waitForDDLCommit does only once it is waiting,
and wait for that before cancelling the vstream that started the wait.

Signed-off-by: Matt Lord <mattalord@gmail.com>
Copilot AI max review requested due to automatic review settings November 13, 2026 00:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed to evaluate external-MySQL streams ignoring the configured timeout and long DDL waits blocking heartbeats, potentially terminating client streams.

No open issues 🎉

1 resolved since last review

Review effort: Max

inelpandzic
inelpandzic previously approved these changes Nov 16, 2026
Signed-off-by: Matt Lord <mattalord@gmail.com>
Copilot AI max review requested due to automatic review settings November 20, 2026 22:46

@maxenglander maxenglander left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Matt, this looks good to me. I traced the wait for tablet vstreams, external MySQL sources and the binlog server connector. In each case it waits on the same MySQL that the binlog comes from, or it's skipped. One small non-blocking note inline.

// waits, since the totals of the SchemaReload timings count only reloads.
start := time.Now()
defer se.env.Stats().WaitTimings.Record("DDLCommitWait", start)
ctx, cancel := context.WithTimeout(ctx, se.reloadTimeout)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For external MySQL sources, se.reloadTimeout seems to always be the 30s default here. externalConnector.Get builds its schema engine from tabletenv.NewDefaultConfig(), and vreplication.NewEngine only passes it config.ExternalConnections. So --schema-change-reload-timeout doesn't apply to these streams, even though its help text now says it bounds this wait. That's already true of their reload on main, so the wait just inherits it. I think it would be nice to pass the configured timeout into the external connector, which would fix both. Fine with me in this PR or a follow-up, also open to neither if you think it's a non-issue.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review, Max, and for tracing all three paths! You're right: externalConnector.Get builds its engines' env from tabletenv.NewDefaultConfig(), so streams from an external source always get the 30s default, for the reload and now for the wait too. It isn't only this flag, though. Apart from the connection parameters, every tabletenv setting those engines read is the default there, such as --queryserver-config-schema-reload-time and --vreplication-copy-phase-max-innodb-history-list-length. Some, like --track-schema-versions, don't suit an external MySQL, so I think the fix needs to decide which of the tablet's settings an external source should follow. I'd rather do that in a follow-up than plumb this one setting through in a PR that we're backporting, so I'll open an issue for it. In the meantime, I've noted the 30s bound for external sources in the PR description.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed as #22117.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The DDL commit wait can block heartbeats long enough to terminate VStreams, while timeout handling can leak throttler goroutines and allow sends on a closed channel.

2 open issues

Review effort: Max

@mattlord
mattlord merged commit 1e5ae1a into main Nov 23, 2026
155 checks passed
@mattlord
mattlord deleted the fix-21883-reload-after-ddl-commit branch November 23, 2026 16:31
@promptless

promptless Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Promptless documentation updates

mattlord added a commit that referenced this pull request Nov 23, 2026
The cherry-pick conflicted in three places, and the bot also added the whole v25.0.0 release summary.

- vstreamer.go: on release-24.0, eventGTID is already a replication.GTID, assigned directly in parseEvent at the GTID event and cleared at format description, rotate, stop and previous-GTIDs events. main formats it into a string through setEventGTID, which #21887 extended to record a separate gtid field. Kept release-24.0's eventGTID, dropped the gtid field and setEventGTID, and pass vs.eventGTID to ReloadAtDDL. It carries the same DDL GTID.
- engine_test.go: import block. Kept release-24.0's strings import alongside #21887's sync and sync/atomic.
- engine.go: added the log/slog import, which main already had and the new slow-wait log needs.
- changelog/25.0/25.0.0/summary.md: removed. The file does not exist on release-24.0.

Signed-off-by: Matt Lord <mattalord@gmail.com>
mattlord added a commit that referenced this pull request Nov 23, 2026
In vstreamer.go, release-23.0 keeps eventGTID as a replication.GTID, set and cleared at the same binlog events as main's new gtid field, so the gtid field and the setEventGTID change are dropped and the DDL handler passes vs.eventGTID to ReloadAtDDL. The reload at a DDL is best effort on release-23.0 (main's error check and rebuildPlans come from #19204), so the error is still not returned; it is logged unless the stream was cancelled. The call uses the stream's context rather than context.Background(), so that a stream cancel does not wait out the DDL commit wait.

In engine.go, log.Warningf replaces the slog-style log.Warn, which release-23.0 does not have.

In engine_test.go, the imports keep release-23.0's strings and add sync and sync/atomic.

In vstreamer_test.go, only TestSchemaReloadWaitsForDDLCommit and the four helpers it uses are kept (createSchemaVersionTable as #21887 changed it, isolateSchemaVersionTable, insertSchemaVersionRow and makeHistorianMinimalTable). The historian startup tests and helpers from #19697, which is not on release-23.0, are dropped. The replication and schema imports are added, and one comment is reworded, since release-23.0's tracker streams from the current position.

The 25.0.0 changelog summary is dropped, since release-23.0 does not have it.

Signed-off-by: Matt Lord <mattalord@gmail.com>
mattlord added a commit that referenced this pull request Nov 23, 2026
…QL has committed it (#21887) (#22143)

Signed-off-by: Matt Lord <mattalord@gmail.com>
Co-authored-by: vitess-bot[bot] <108069721+vitess-bot[bot]@users.noreply.github.com>
Co-authored-by: Matt Lord <mattalord@gmail.com>
mattlord added a commit that referenced this pull request Nov 23, 2026
…QL has committed it (#21887) (#22142)

Signed-off-by: Matt Lord <mattalord@gmail.com>
Co-authored-by: vitess-bot[bot] <108069721+vitess-bot[bot]@users.noreply.github.com>
Co-authored-by: Matt Lord <mattalord@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug Report: Schema tracker can save the pre-DDL schema when its stream reads a DDL from the binlog before the DDL commits

7 participants