mvs,domain,server,session,metrics: add Materialized View Service (MVS) framework and runtime integration#66242
mvs,domain,server,session,metrics: add Materialized View Service (MVS) framework and runtime integration#66242solotzg wants to merge 56 commits intopingcap:feature/release-8.5-materialized-viewfrom
Conversation
Signed-off-by: Zhigao TONG <tongzhigao@pingcap.com>
|
@solotzg: PRs from untrusted users cannot be marked as trusted with DetailsIn 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. |
Signed-off-by: Zhigao TONG <tongzhigao@pingcap.com>
|
@solotzg: PRs from untrusted users cannot be marked as trusted with DetailsIn 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 Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## feature/release-8.5-materialized-view #66242 +/- ##
==========================================================================
Coverage ? 57.6939%
==========================================================================
Files ? 1801
Lines ? 642388
Branches ? 0
==========================================================================
Hits ? 370619
Misses ? 246557
Partials ? 25212
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Signed-off-by: Zhigao TONG <tongzhigao@pingcap.com>
Signed-off-by: Zhigao TONG <tongzhigao@pingcap.com>
Signed-off-by: Zhigao TONG <tongzhigao@pingcap.com>
|
/test mysql-test |
|
@solotzg: PRs from untrusted users cannot be marked as trusted with DetailsIn 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. |
Signed-off-by: Zhigao TONG <tongzhigao@pingcap.com>
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
Signed-off-by: Zhigao TONG <tongzhigao@pingcap.com>
What problem does this PR solve?
Issue Number: ref #18023
Problem Summary:
Materialized View Service (MVS) lacked a complete end-to-end server implementation. The scheduler, executor, ownership assignment, runtime operations, observability, and metadata bootstrap needed to be implemented and wired across domain/session/server.
What changed and how does it work?
pkg/mvs.int64ownership keys via fixed-width binary bytes.mysql.tidb_mview_refresh_infoandmysql.tidb_mlog_purge_info.GET/POST /mvservice/settings.Check List
Tests
Side effects
Documentation
Release note
MVS Design
This document describes the current Materialized View Service (MVS) implementation in TiDB.
It is generated from the latest code under:
pkg/mvs/*pkg/domain/domain.gopkg/server/handler/mvhandler/mv_service_handler.gopkg/session/bootstrap.go1. Scope and Responsibilities
MVS is an in-memory scheduler/executor for two background task types:
mv_refresh)mvlog_purge)Core responsibilities:
2. Architecture Overview
Main modules:
pkg/mvs/service.go: scheduler state, task queues, rebuild/reschedule logicpkg/mvs/service_runtime.go: main run loop, timers, wake-up behaviorpkg/mvs/task_executor.go: worker pool, queue, timeout/backpressure behaviorpkg/mvs/server_maintainer.go: TiDB node membership and ownership mappingpkg/mvs/consistenthash.go: hash ring implementationpkg/mvs/impl.go: real task handlers (RefreshMV,PurgeMVLog), SQL helpers, registrationpkg/mvs/metrics_reporter.go: metric flushing + event/duration observerspkg/mvs/service_config.go: constructor config + runtime settings APIspkg/mvs/task_backpressure.go: CPU/memory backpressure controllerpkg/mvs/utils.go:Notifier+ genericPriorityQueue3. Integration and Lifecycle
3.1 Domain wiring
Domain.Init()registers MVS before DDL notifier starts:pkg/domain/domain.go:mvs.RegisterMVS(do.ctx, do.ddlNotifier.RegisterHandler, do.sysSessionPool, do.notifyMVSMetadataChange)RegisterMVS(...)(pkg/mvs/impl.go) does:MVServicewith default config + default backpressure thresholds.NotifyDDLChange()once to force an initial metadata refresh.notifier.MVServiceHandlerID), currently handling:meta.ActionCreateMaterializedViewLogonDDLHandled()so domain can fan out notification to other nodes via etcd.3.2 Service start
sessionboot flow starts MVS through domain:pkg/session/session.go:dom.StartMVService()StartMVService()launches two goroutines:mvService.RunwatchMVSMetaChange3.3 Cross-node notification
Domain uses etcd key
/tidb/mvs/ddl:notifyMVSMetadataChange()watchMVSMetaChange()When watcher receives an event, it calls
mvService.NotifyDDLChange().4. Scheduler Data Model
MVServicemaintains two independent in-memory queues:pending map[int64]mvItem+PriorityQueue[*mv]pending map[int64]mvLogItem+PriorityQueue[*mvLog]Task structs:
mv:ID,nextRefresh,refreshInterval,orderTs,retryCountmvLog:ID,baseTableID,nextPurge,purgeInterval,orderTs,retryCountScheduling key:
orderTs(Unix ms), smaller means earlier executionmaxNextScheduleTsindicates a task has been dispatched and is considered running5. Run Loop Semantics
Main loop (
MVService.Run) processes:Per iteration:
serverRefreshInterval) viasch.refresh().fetchInterval)ddlDirty)fetchAllMVMeta).fetchExecTasks).TaskExecutor.min(nextFetchTime, nextDueTime).If metadata fetch fails,
lastRefreshis still updated to avoid tight retry loops.6. Ownership and Consistent Hashing
6.1 Membership model
ServerConsistentHashkeeps:ConsistentHashringIt supports:
sch.init())sch.refresh())Available)6.2 Key handling
Available(key any)accepts:string: hashed as raw bytes of the stringint64: hashed as fixed-width 8-byte binary (big-endian)ConsistentHash.GetNodenow takes[]bytedirectly.7. Task Dispatch and Reschedule Rules
7.1 Due task collection
fetchExecTasks(now)scans each priority queue head-first:orderTs == maxNextScheduleTs)orderTs > now)orderTs = maxNextScheduleTsand dispatch7.2 Refresh task
Execution path:
mv-refresh/<mvID>mh.RefreshMV(...)Result handling:
retryCount++, exponential backoff reschedulenextRefresh.IsZero(): task removed7.3 Purge task
Execution path:
mvlog-purge/<mvLogID>mh.PurgeMVLog(...)Result handling mirrors refresh logic.
Each completion path triggers
notifier.Wake()to accelerate next scheduling cycle.8. Task Executor Semantics
TaskExecutorincludes:8.1 Timeout behavior
If task timeout is configured and reached:
Timeout does not cancel SQL execution directly.
8.2 Backpressure behavior
Backpressure is checked before taking task from queue.
If blocked, worker sleeps for reported delay and retries.
Default controller:
CPUMemBackpressureController.9. Metadata Fetch and Rebuild
Metadata fetch entry:
fetchAllTiDBMLogPurge()frommysql.tidb_mlog_purge_infofetchAllTiDBMViews()frommysql.tidb_mview_refresh_infoRebuild behavior:
orderTsand heap positionOwnership filtering is applied after fetch via
sch.Available(id).10. Handler SQL Semantics
10.1 RefreshMV
serverHelper.RefreshMV(...):mvIDREFRESH MATERIALIZED VIEW ... WITH SYNC MODE FASTNEXT_TIMEfrommysql.tidb_mview_refresh_infoIf metadata no longer exists, returns zero next time (task should be removed).
10.2 PurgeMVLog
PurgeMVLog(ctx, sctx, mvLogID, autoPurge):PurgeStartWith,PurgeNext)LAST_SUCCESS_READ_TSOFOR UPDATE)nextPurge.IsZero()means no further schedule is needed.11. Runtime Settings API
HTTP endpoint:
GET/POST /mvservice/settingspkg/server/handler/mvhandler/mv_service_handler.goSupported runtime settings:
Handler behavior:
MVServicesetters12. Metrics and Events
Metrics are defined in
pkg/metrics/mv.goand flushed byserverHelper.reportMetrics.Covered dimensions:
MVServiceRunEventCounterVec)13. Bootstrap Metadata Tables
Bootstrap creates/maintains:
mysql.tidb_mview_refresh_infomysql.tidb_mlog_purge_infomysql.tidb_mview_refresh_histmysql.tidb_mlog_purge_hist(see
pkg/session/bootstrap.go)14. Testing Model
time_proxywrappers.intestbuild uses mock time module (time_proxy_intest.go) for deterministic timer tests.pkg/mvs/*_test.gocovers:15. Current Constraints / TODO
ActionCreateMaterializedViewLog; other MV-related metadata events are TODO.