Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
650b501
perf: reduce database clone catalog and workspace overhead
gouhongshen Nov 26, 2026
3f8350a
perf: clone independent database tables concurrently
gouhongshen Nov 26, 2026
058ffcd
fix: adapt clone row writes to current batch interfaces
gouhongshen Nov 26, 2026
972c658
perf: preallocate bounded database clone workers
gouhongshen Nov 26, 2026
52d0af7
Merge branch 'main' into codex/clone-db-perf
mergify[bot] Nov 26, 2026
cfae995
fix: preserve physical column names in clone row writes
gouhongshen Nov 26, 2026
ee81373
fix: reuse frontend panic boundary for clone workers
gouhongshen Nov 26, 2026
d2a67da
build: pin clone worker and SIMD linter boundaries
gouhongshen Nov 26, 2026
6c76fb2
fix: cancel failed commit spill groups before joining
gouhongshen Nov 26, 2026
df47b04
fix: roll back clone panics and skip hidden index IDs
gouhongshen Nov 27, 2026
12aa687
fix: keep hidden clone offsets out of user auto increment metadata
gouhongshen Nov 27, 2026
3c38673
ci: refresh clone checks after coverage admission fix
gouhongshen Nov 27, 2026
8ac9b8c
perf: bind branch source privileges without execution planning
gouhongshen Nov 27, 2026
9821f10
perf: import small clone tails through the transaction workspace
gouhongshen Nov 27, 2026
66eec78
fix: preserve destination column layout for inline clone tails
gouhongshen Nov 27, 2026
5a18596
perf: combine database clone metadata and inline tail paths
gouhongshen Nov 30, 2026
0a610dd
merge: sync clone optimization with current main
gouhongshen Nov 30, 2026
0808aa9
perf: reuse branch admission and batch clone bookkeeping
gouhongshen Nov 30, 2026
92d6788
perf: complete data branch clone optimizations
gouhongshen Nov 30, 2026
ee589de
merge: align complete clone optimizations with current main
gouhongshen Nov 30, 2026
c960394
fix: adapt clone tail filtering to current vector API
gouhongshen Nov 30, 2026
fbdd5a2
Merge remote-tracking branch 'upstream/main' into codex/clone-db-perf
gouhongshen Dec 1, 2026
bc0d814
perf: retain small deletes and share bounded spill execution
gouhongshen Dec 1, 2026
e1c2acd
test: allocate delete spill fixtures through workspace owner
gouhongshen Dec 1, 2026
afd5c4e
Merge remote-tracking branch 'upstream/main' into codex/clone-db-perf
gouhongshen Dec 1, 2026
80717d6
fix: release catalog tuple allocations on view definition failure
gouhongshen Dec 1, 2026
b21b431
perf: replenish bounded workspace spill writers on completion
gouhongshen Dec 1, 2026
722598e
test: make tombstone metadata fixture independent of spill policy
gouhongshen Dec 1, 2026
43a7c4f
fix: preserve catalog routing across planning and isolate restart fix…
gouhongshen Dec 1, 2026
2bfd4b9
test: release idle shared fixtures before clone restart
gouhongshen Dec 1, 2026
0670a52
merge: preserve clone tail reads with upstream schema evolution
gouhongshen Dec 1, 2026
17ee79d
merge: retain clone tracing across common package removal
gouhongshen Dec 1, 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
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -1570,7 +1570,7 @@ install-static-check-tools:
echo 'Prebuilt golangci-lint unavailable; installing the pinned version from source' >&2; \
fi; \
GOBIN="$(GOPATH)/bin" go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0
@GOBIN="$(GOPATH)/bin" go install github.com/matrixorigin/linter/cmd/molint@v0.0.0-20261115233300-147a3f213653
@GOBIN="$(GOPATH)/bin" go install github.com/matrixorigin/linter/cmd/molint@v0.0.0-20261126093024-ec9ba83de34d
@GOBIN="$(GOPATH)/bin" go install github.com/apache/skywalking-eyes/cmd/license-eye@v0.4.0

FRONTEND_MOCKGEN = $(CGO_OPTS) CGO_LDFLAGS="-L$(THIRDPARTIES_INSTALL_DIR)/lib -L$(CGO_DIR) -Wl,-rpath,$(CGO_DIR) -Wl,-rpath,$(THIRDPARTIES_INSTALL_DIR)/lib" GOWORK=off $(GOPATH)/bin/mockgen -build_flags="$(GO_MODULE_MODE)"
Expand Down
88 changes: 88 additions & 0 deletions docs/design/20261127-clone-transaction-tail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# 数据库克隆的事务内尾部写入

状态:已实现。设计版本 4,2026-11-27,已完成设计及实现自审。

## 问题与目标

`DATA BRANCH CREATE DATABASE` 和表克隆通过 `TableMetaReader` 复用源对象。
不可变对象直接复制引用;内存行、可追加对象里的可见行以及删除记录需要物化。
当前物化器对每张物理表的数据、删除记录分别创建 `CNS3Writer`,最终 `Sync`
即使只有几行也会各写一个对象。表和索引较多时,远端请求的固定延迟主导耗时。

目标是让少量尾部复用事务已有的行写入及溢写机制,消除逐表小对象同步写入。
成功必须仍表示整个克隆事务完成持久化,不提前返回,不转为后台克隆。
公开 SQL、目录、对象文件和事务 RPC 格式不变。

## 归属与方案

- `TableMetaReader` 仍负责源快照、事务写边界和可追加对象的可见性过滤。
- `CNS3Writer` 仍负责超过现有内存阈值的对象溢写及失败清理。复用其底层
`Sinker.TakeStagedBatches`,转移尚未物化的尾部所有权,不另建缓存或调度器。
- 纯元数据读取继续返回对象元数据。克隆调用显式选择保留事务尾部的读取接口,
同步返回已生成的对象元数据,并在该 reader 中暂存少量行批次;超过保留预算
的批次仍由 writer 正常 Sync,不把整个 writer 的最大内存缓冲转交 reader。
- `table_clone` 先登记共享及已生成的数据对象,再登记对象形式的删除记录,
然后交付暂存的行级删除,最后交付新行。这样新行的主键去重能够看到已有删除。
- 工作区的语句收尾排序也必须保留该依赖:目录操作之后,克隆引用的源对象登记
先于删除,其次才是新行。仅改变调用顺序不够,普通 DML 的删除优先排序会在
提交前重排它们。在文件写入准入时,根据现有 clone cache 冻结该 Entry 的源对象
登记事实;排序只读该事实,不能在比较过程中查询仍可能被并行克隆更新的 cache。
该事实只存在于事务工作区,普通事务排序、RPC 和落盘记录不变。
- 目标 `txnTable` 通过已有工作区写入路径接收行;总工作区达到现有阈值时,
原有溢写和提交机制负责持久化。不能为小尾部放宽工作区阈值或对象准入。
- 行批次使用目标表的 `GetOriginCaseName`,与普通 INSERT 一致。规划器的小写列名
只用于绑定和读取,不能作为 TN 行写入的物理列名;大写和混合大小写列同样适用。
根据列名将源向量投影到目标物理列顺序,不能假设两者下标相同:重建表会将复合
主键移到后追加列之后。投影视图只借用源向量,工作区复制完成后仍由 reader 释放原批次。

## 删除记录与共享对象

重写的数据已应用源快照和事务内删除,并获得新 rowid;指向被重写源行的旧
删除记录不应再作用于目标。只有指向目标已经登记的数据对象的行级删除需要交付。
目标事务已有按表隔离的 `cnObjsSummary` 可证明对象登记,无须新增对象索引。

克隆删除必须直接记录为目标事务的行级删除,不能走普通 `Delete` 对 CN 未提交
对象的压缩逻辑。共享对象在目标事务中也会登记为 CN 对象;普通删除可能重写
这些大对象,抵消收益。专用的内部交付方法只接受克隆事务,复制至工作区池,
按已登记对象过滤,再复用 `writeTnPartitionCopy`;不改变普通 DML 删除行为。

TN 收到元数据登记时,对象先存在该表的事务工作区,尚未发布到 Catalog。
行级删除的 WAR 检查必须识别同一工作区 `statsMap` 已登记的对象:它们是本事务
自己的对象,不需要再次从已提交目录查找。只有明确存在于该表工作区的对象可
走此分支;其他对象仍执行原目录查找及 WAR 检查,找不到仍报错。
这支持已有 RPC 中元数据导入加行删除的组合,不新增协议字段或放行未知对象。

已落盘、可共享的删除对象仍复用引用。历史视图、外键及索引的现有克隆流程不变。

## 所有权、边界与失败

- reader 接管从 writer 取出的批次;批次保留原 mpool,交付后和关闭时由 reader
清理,禁止改变 `Batch`、`Vector` 或其编码。
- 数据和删除记录各最多保留 Sinker 的默认暂存预算(当前 16 MiB);超过预算
仍走 writer 的正常落盘路径。单个 reader 暂存最多两份,不随数据库表数增长。
克隆消费一张物理表后立即交付并释放,不把整个数据库尾部保存在 reader 中。
- 工作区复制后的批次归工作区,其预算、准入、提交及回滚路径保持有效。
- 任意读、写、交付或提交错误返回原错误;已登记文件和工作区数据由原事务回滚
所有者处理。reader 关闭负责尚未交付的批次,writer 仍负责其对象清理。
- 没有跨请求状态、后台工作、重试或 fallback;取消沿已有 context 传播。
- 运行中的源表变化仍受同一快照和捕获的事务写边界约束;不可引用整个可追加文件
来绕过可见性过滤。

## 验证

1. 公共 `DATA BRANCH CREATE DATABASE`:不可变基底加少量插入、更新、删除,
带普通索引和视图;核对目标内容、索引读取、源库不变以及后续修改隔离。
2. 原实现在禁止克隆 CN 新建对象时失败;小尾部新路径在相同条件下成功。
这是请求削减的行为反例,不能用固定源码形状或墙钟阈值作门禁。
3. 组件覆盖内存及可追加对象的快照过滤、事务内写边界、共享对象删除、关闭前
未交付数据、目标交付失败和取消。复用已有对象准入、回滚与可见性 fixture。
4. 检查超过阈值的溢写及提交错误,避免通过尾部策略绕过对象清理、工作区预算。
5. 独立性能实验分别记录新对象请求、阶段和整条 SQL 耗时;存储延迟模拟必须
明确标注。只有整条 SQL 完成和持久化后才停止计时。

## 设计评审结论

版本 4 自审通过,允许进入实现验证。该方案复用现有 Sinker、目标事务预算和
持久化协议;新增的短期所有权局限于单个 reader。没有新增文件格式或分布式状态。
实现交付仍要求上述删除语义、错误清理和公开 SQL 证据全部通过;若行级删除无法
安全应用于新登记对象,应回到设计解决,不能以吞错或重试原物化路径掩盖问题。
2 changes: 1 addition & 1 deletion pkg/catalog/tuplesGen.go
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ func GenCreateTableTuple(tbl Table, m *mpool.MPool, packer *types.Packer) (*batc
}
idx = MO_TABLES_VIEWDEF_IDX
bat.Vecs[idx] = vector.NewVec(MoTablesTypes[idx], m) // viewdef
if err := vector.AppendBytes(bat.Vecs[idx], []byte(tbl.Viewdef), false, m); err != nil {
if err = vector.AppendBytes(bat.Vecs[idx], []byte(tbl.Viewdef), false, m); err != nil {
return nil, err
}
idx = MO_TABLES_CONSTRAINT_IDX
Expand Down
29 changes: 29 additions & 0 deletions pkg/catalog/tuplesParse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package catalog

import (
"slices"
"strings"
"testing"

"github.com/matrixorigin/matrixone/pkg/common/mpool"
Expand All @@ -27,6 +28,34 @@ import (
"github.com/stretchr/testify/require"
)

func TestGenCreateTableTupleReleasesRejectedAllocation(t *testing.T) {
registry, err := mpool.NewAllocationAccountRegistry(1, 128)
require.NoError(t, err)
account, err := registry.Open(64 << 10)
require.NoError(t, err)
m := mpool.MustNewZero()
t.Cleanup(func() { mpool.DeleteMPool(m) })
view, err := m.WithAccount(account, mpool.AllocationOwnerMin, mpool.AllocationSiteMin, mpool.AllocationCapacityClassDefault)
require.NoError(t, err)
packer := types.NewPacker()
defer packer.Close()
before := account.Snapshot().Used
bat, err := GenCreateTableTuple(Table{TableId: 10001, Viewdef: strings.Repeat("x", 1<<20)}, view, packer)
require.Error(t, err)
require.Nil(t, bat)
require.Equal(t, before, account.Snapshot().Used, "rejected tuples must release their earlier column allocations")
require.Zero(t, m.CurrNB())
// The same account remains usable after the rejected CREATE.
bat, err = GenCreateTableTuple(Table{TableId: 10002, Viewdef: "select 1"}, view, packer)
require.NoError(t, err)
require.Equal(t, "select 1", string(bat.Vecs[MO_TABLES_VIEWDEF_IDX].GetBytesAt(0)))
bat.Clean(view)
require.Equal(t, before, account.Snapshot().Used)
account.Seal()
_, err = registry.Finalize(account)
require.NoError(t, err)
}

func TestGenCreateTableTuplePreservesExplicitCreatedTime(t *testing.T) {
m := mpool.MustNew("created-time")
packer := types.NewPacker()
Expand Down
11 changes: 10 additions & 1 deletion pkg/defines/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,8 +399,17 @@ func IsIndexMaintenanceViewBinding(ctx context.Context) bool {
return value
}

type authorizationViewBindingKey struct{}

// WithAuthorizationViewBinding keeps stored expressions unevaluated while
// resolving their source dependencies for an authorization-only query.
func WithAuthorizationViewBinding(ctx context.Context) context.Context {
return context.WithValue(ctx, authorizationViewBindingKey{}, true)
}

func IsNoEvaluationViewBinding(ctx context.Context) bool {
return IsPublicationViewBinding(ctx) || IsIndexMaintenanceViewBinding(ctx)
authorization, _ := ctx.Value(authorizationViewBindingKey{}).(bool)
return authorization || IsPublicationViewBinding(ctx) || IsIndexMaintenanceViewBinding(ctx)
}

// Sp variable scope
Expand Down
11 changes: 10 additions & 1 deletion pkg/defines/view_binding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,18 @@ func TestPersistentViewBindingScope(t *testing.T) {
require.Same(t, binding, WithPersistentViewBinding(binding))
require.False(t, IsPublicationViewBinding(binding))
require.False(t, IsNoEvaluationViewBinding(binding))
account, err := GetAccountId(binding)
authorization := WithAuthorizationViewBinding(binding)
require.True(t, IsNoEvaluationViewBinding(authorization))
require.False(t, IsNoEvaluationViewBinding(binding), "authorization scope must not alter its parent")
require.False(t, IsPublicationViewBinding(authorization))
require.False(t, IsIndexMaintenanceViewBinding(authorization))
account, err := GetAccountId(authorization)
require.NoError(t, err)
require.Equal(t, uint32(42), account)
account, err = GetAccountId(binding)
require.NoError(t, err)
require.Equal(t, uint32(42), account)
cancel()
require.ErrorIs(t, binding.Err(), context.Canceled)
require.ErrorIs(t, authorization.Err(), context.Canceled)
}
31 changes: 29 additions & 2 deletions pkg/embed/clone_database_benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ import (
)

func BenchmarkCloneDatabaseManyTables(b *testing.B) {
benchmarkCloneDatabaseManyTables(b, false)
}

func BenchmarkDataBranchCreateDatabaseManyTables(b *testing.B) {
benchmarkCloneDatabaseManyTables(b, true)
}

func benchmarkCloneDatabaseManyTables(b *testing.B, branch bool) {
b.Cleanup(func() { require.NoError(b, CloseBaseClusterTests()) })
RunBaseClusterTests(b, func(cluster Cluster) {
cn, err := cluster.GetCNService(0)
require.NoError(b, err)
Expand All @@ -50,6 +59,9 @@ func BenchmarkCloneDatabaseManyTables(b *testing.B) {
if storage == "empty" {
cardinalities = append(cardinalities, 500, 1000)
}
if storage == "unflushed" {
cardinalities = append(cardinalities, 1000)
}
for _, tables := range cardinalities {
b.Run(fmt.Sprintf("%s/tables=%d", storage, tables), func(b *testing.B) {
exec := func(statement string) {
Expand All @@ -58,6 +70,10 @@ func BenchmarkCloneDatabaseManyTables(b *testing.B) {
}
const source = "clone_benchmark_source"
const target = "clone_benchmark_target"
cloneSQL := "create database " + target + " clone " + source
if branch {
cloneSQL = "data branch create database " + target + " from " + source
}
exec("drop database if exists " + target)
exec("drop database if exists " + source)
exec("create database " + source)
Expand All @@ -83,14 +99,25 @@ func BenchmarkCloneDatabaseManyTables(b *testing.B) {
}
}
b.ResetTimer()
for range b.N {
_, err := cloneConn.ExecContext(ctx, "create database "+target+" clone "+source)
for iteration := range b.N {
started := time.Now()
_, err := cloneConn.ExecContext(ctx, cloneSQL)
elapsed := time.Since(started)
require.NoError(b, err)
b.StopTimer()
b.Logf("%s iteration=%d completed in %s", cloneSQL, iteration+1, elapsed)
var count int
err = conn.QueryRowContext(ctx, "select count(*) from mo_catalog.mo_tables where reldatabase = '"+target+"'").Scan(&count)
require.NoError(b, err)
require.Equal(b, tables, count)
if storage == "unflushed" || storage == "flushed" {
for table := range tables {
var id, value int
err := conn.QueryRowContext(ctx, fmt.Sprintf("select id, v from %s.t%d", target, table)).Scan(&id, &value)
require.NoError(b, err)
require.Equal(b, [2]int{1, 10}, [2]int{id, value}, "table t%d", table)
}
}
exec("drop database " + target)
b.StartTimer()
}
Expand Down
Loading
Loading