Skip to content

ddl, mvservice: backport materialized view maintenance fixes#68947

Merged
ti-chi-bot[bot] merged 4 commits into
pingcap:feature/release-8.5-materialized-viewfrom
windtalker:cp_for_mv_2
Jun 4, 2026
Merged

ddl, mvservice: backport materialized view maintenance fixes#68947
ti-chi-bot[bot] merged 4 commits into
pingcap:feature/release-8.5-materialized-viewfrom
windtalker:cp_for_mv_2

Conversation

@windtalker
Copy link
Copy Markdown
Contributor

@windtalker windtalker commented Jun 4, 2026

What problem does this PR solve?

Issue Number: ref #18023

Problem Summary:

This PR backports several materialized view maintenance fixes to the release-8.5 materialized view feature branch.

What changed and how does it work?

  • Ignore stale MV service infosync entries after node restarts, so the maintainer does not treat stale internal sessions as active workers.
  • Add the required Bazel metadata for the MV service dependency changes.
  • Reject partitioning DDL and EXCHANGE PARTITION on materialized-view-related tables where the operation can break MV metadata or MV log semantics.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

Unit tests and checks:

  • go test ./pkg/executor/test/ddl -run 'Test(ExchangePartitionRejectsMaterializedViewRelatedTable|AlterTablePartitioningRejectsMaterializedViewBaseTable)$' -tags=intest,deadlock -count=1
  • make bazel_lint_changed

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Please refer to Release Notes Language Style Guide to write a quality release note.

Fix stale MV service node bookkeeping and reject unsupported partition DDL on materialized-view-related tables.

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced validation for materialized view operations to prevent duplicate column definitions and block invalid partition modifications when materialized views are present.
    • Improved server discovery deduplication to ensure consistency when handling distributed operations across multiple instances.

@ti-chi-bot ti-chi-bot Bot added release-note Denotes a PR that will be considered when it comes time to generate release notes. size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. labels Jun 4, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 4, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds DDL validation for materialized view logs (duplicate-column detection and partition/exchange constraints) and implements server deduplication in mvservice by extending serverInfo with network metadata and timestamp fields, then deduplicating servers by execution identity to resolve fast-restart conflicts.

Changes

Materialized View DDL Validation

Layer / File(s) Summary
Duplicate Column Detection in MV Logs
pkg/ddl/executor.go, pkg/ddl/schematracker/dm_tracker.go, pkg/executor/test/ddl/materialized_view_ddl_test.go
When creating a materialized view log, duplicate column names (case-insensitive) in s.Cols are now detected and rejected early with ErrColumnExists before column definitions are built. Test validates rejection of CREATE MATERIALIZED VIEW LOG ... (id, id) statements.
Partition and Exchange MV Constraints
pkg/ddl/executor.go, pkg/executor/test/ddl/materialized_view_ddl_test.go
AlterTablePartitioning and RemovePartitioning now perform materialized-view dependency checks before modifying partition metadata. EXCHANGE PARTITION enforces MV constraints via a new helper that rejects tables with MaterializedViewLog, MaterializedView, or MaterializedViewShadow roles and validates base-table MV dependencies. Tests assert partition and exchange operations fail with appropriate error messages when MV dependencies exist.

Server Deduplication in mvservice

Layer / File(s) Summary
Extended Server Info Data Shape
pkg/mvservice/server_maintainer.go, pkg/mvservice/service_helper.go, pkg/mvservice/BUILD.bazel
serverInfo struct now includes IP, Port, and StartTimestamp fields in addition to ID, expanding the data shape of server discovery payloads. Import of disttaskutil is added to support execution identity computation.
Server Deduplication by Execution Identity
pkg/mvservice/service_helper.go, pkg/mvservice/task_handler_test.go, pkg/mvservice/BUILD.bazel
New latestServerInfosByInstance helper deduplicates server entries by computed execution identity, filtering nil entries and resolving fast-restart conflicts by keeping the entry with the newest StartTimestamp for each instance. getAllServerInfo now delegates to this helper. Test verifies that multiple entries for the same instance are reduced to the newest based on StartTimestamp.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Executor as DDL Executor
  participant Tracker as Schema Tracker
  
  Client->>Executor: CREATE MATERIALIZED VIEW LOG (col1, col1)
  Executor->>Executor: Check duplicates in s.Cols
  Executor->>Executor: Return ErrColumnExists
  Note over Executor: Validation blocks creation
Loading
sequenceDiagram
  participant Client
  participant Executor as DDL Executor
  participant Validator as MV Constraint Checker
  
  Client->>Executor: ALTER TABLE t PARTITION BY ...
  Executor->>Validator: checkBaseTableMaterializedViewDependencyConstraints
  Validator->>Validator: Check for MView/MLog dependencies
  alt Has MV Dependencies
    Validator->>Executor: Return error
  else No MV Dependencies
    Executor->>Executor: Proceed with partition change
  end
Loading
sequenceDiagram
  participant Discovery as Server Discovery
  participant Helper as Service Helper
  participant Dedup as Deduplication Logic
  
  Discovery->>Helper: getAllServerInfo()
  Helper->>Dedup: latestServerInfosByInstance(serverMap)
  Dedup->>Dedup: For each server, compute execution ID
  Dedup->>Dedup: Keep newest StartTimestamp per instance
  Dedup->>Helper: Return deduplicated map
  Helper->>Discovery: Return deduplicated servers
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • pingcap/tidb#68766: Modifies CreateMaterializedViewLog in the same files; main PR adds duplicate-column detection while retrieved PR clears inherited column flags and tightens SUM-over-temporal validation.
  • pingcap/tidb#68819: Overlaps at CreateMaterializedViewLog code paths in pkg/ddl/executor.go and pkg/ddl/schematracker/dm_tracker.go; main PR adds duplicate-column validation while retrieved PR changes MLog table-name resolution.

Suggested labels

size/XL, lgtm

Suggested reviewers

  • gengliqi
  • solotzg
  • wshwsh12

Poem

🐰 A rabbit hops through mview logs with care,
Detecting doubles floating in the air—
And when partitions dance where mvs dwell,
She blocks the swap with a firm "none shall pass" spell.
Through server dedup, the newest thoughts survive,
Each instance keeps what makes it truly alive! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: backporting materialized view maintenance fixes to the DDL executor and MV service packages.
Description check ✅ Passed The description follows the template structure with issue reference, problem summary, what changed section, completed test checklist, side effects assessment, and release notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

Error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions
The command is terminated due to an error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@tiprow
Copy link
Copy Markdown

tiprow Bot commented Jun 4, 2026

Hi @windtalker. Thanks for your PR.

PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test all.

I understand the commands that are listed here.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
pkg/executor/test/ddl/materialized_view_ddl_test.go (1)

63-75: ⚡ Quick win

Add test case for case-insensitive duplicate columns.

The duplicate column detection is case-insensitive (using c.L in the implementation), but this test only covers exact duplicates (id, id). Add a test case for mixed-case duplicates to verify the case-insensitive behavior.

✅ Suggested additional test case
 func TestCreateMaterializedViewLogRejectsDuplicateColumns(t *testing.T) {
 	store := testkit.CreateMockStore(t)
 	tk := testkit.NewTestKit(t, store)
 	tk.MustExec("use test")
 
 	tk.MustExec(`create table t_dup (
   id bigint not null primary key,
   g1 int not null
 )`)
 
 	err := tk.ExecToErr("create materialized view log on t_dup (id, id)")
 	require.ErrorContains(t, err, "Duplicate column name")
+
+	// Verify case-insensitive duplicate detection
+	err = tk.ExecToErr("create materialized view log on t_dup (id, ID)")
+	require.ErrorContains(t, err, "Duplicate column name")
+
+	err = tk.ExecToErr("create materialized view log on t_dup (g1, G1)")
+	require.ErrorContains(t, err, "Duplicate column name")
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/executor/test/ddl/materialized_view_ddl_test.go` around lines 63 - 75,
Add a second assertion to TestCreateMaterializedViewLogRejectsDuplicateColumns
that verifies case-insensitive duplicate detection by attempting to create the
materialized view log with the same column name in different case (e.g., "create
materialized view log on t_dup (id, ID)") and asserting tk.ExecToErr returns an
error containing "Duplicate column name"; locate this in the existing
TestCreateMaterializedViewLogRejectsDuplicateColumns function and reuse the same
test setup (store, tk, and table t_dup) so the new
ExecToErr/require.ErrorContains line mirrors the existing duplicate-check
assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pkg/executor/test/ddl/materialized_view_ddl_test.go`:
- Around line 63-75: Add a second assertion to
TestCreateMaterializedViewLogRejectsDuplicateColumns that verifies
case-insensitive duplicate detection by attempting to create the materialized
view log with the same column name in different case (e.g., "create materialized
view log on t_dup (id, ID)") and asserting tk.ExecToErr returns an error
containing "Duplicate column name"; locate this in the existing
TestCreateMaterializedViewLogRejectsDuplicateColumns function and reuse the same
test setup (store, tk, and table t_dup) so the new
ExecToErr/require.ErrorContains line mirrors the existing duplicate-check
assertion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 10254a95-18fb-41ac-a8e6-1bc25ac2bf54

📥 Commits

Reviewing files that changed from the base of the PR and between f30199f and 73b10f3.

📒 Files selected for processing (7)
  • pkg/ddl/executor.go
  • pkg/ddl/schematracker/dm_tracker.go
  • pkg/executor/test/ddl/materialized_view_ddl_test.go
  • pkg/mvservice/BUILD.bazel
  • pkg/mvservice/server_maintainer.go
  • pkg/mvservice/service_helper.go
  • pkg/mvservice/task_handler_test.go

@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Jun 4, 2026

@solotzg: adding LGTM is restricted to approvers and reviewers in OWNERS files.

Details

In response to this:

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@codecov
Copy link
Copy Markdown

codecov Bot commented Jun 4, 2026

Codecov Report

❌ Patch coverage is 85.89744% with 11 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (feature/release-8.5-materialized-view@f30199f). Learn more about missing BASE report.

Additional details and impacted files
@@                            Coverage Diff                             @@
##             feature/release-8.5-materialized-view     #68947   +/-   ##
==========================================================================
  Coverage                                         ?   57.6700%           
==========================================================================
  Files                                            ?       1812           
  Lines                                            ?     655605           
  Branches                                         ?          0           
==========================================================================
  Hits                                             ?     378088           
  Misses                                           ?     251288           
  Partials                                         ?      26229           
Flag Coverage Δ
integration 37.6207% <34.6153%> (?)
unit 72.0124% <79.4871%> (?)

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

Components Coverage Δ
dumpling 52.9278% <0.0000%> (?)
parser ∅ <0.0000%> (?)
br 63.4491% <0.0000%> (?)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Contributor

@xzhangxian1008 xzhangxian1008 left a comment

Choose a reason for hiding this comment

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

LGTM

@ti-chi-bot ti-chi-bot Bot added the needs-1-more-lgtm Indicates a PR needs 1 more LGTM. label Jun 4, 2026
@windtalker
Copy link
Copy Markdown
Contributor Author

/test unit-test

@tiprow
Copy link
Copy Markdown

tiprow Bot commented Jun 4, 2026

@windtalker: PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test.

Details

In response to this:

/test unit-test

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@windtalker
Copy link
Copy Markdown
Contributor Author

/test pull-unit-test-ddlv1

@tiprow
Copy link
Copy Markdown

tiprow Bot commented Jun 4, 2026

@windtalker: PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test.

Details

In response to this:

/test pull-unit-test-ddlv1

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Jun 4, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: gengliqi, solotzg, xzhangxian1008
Once this PR has been reviewed and has the lgtm label, please assign gmhdbjd for approval. For more information see the Code Review Process.
Please ensure that each of them provides their approval before proceeding.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@ti-chi-bot ti-chi-bot Bot added lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Jun 4, 2026
@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Jun 4, 2026

[LGTM Timeline notifier]

Timeline:

  • 2026-06-04 06:15:54.475096308 +0000 UTC m=+422255.545413688: ☑️ agreed by xzhangxian1008.
  • 2026-06-04 06:33:28.050747106 +0000 UTC m=+423309.121064516: ☑️ agreed by gengliqi.

@ti-chi-bot ti-chi-bot Bot merged commit 7a3b5d9 into pingcap:feature/release-8.5-materialized-view Jun 4, 2026
21 of 22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm release-note Denotes a PR that will be considered when it comes time to generate release notes. size/XL Denotes a PR that changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants