Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
127 changes: 127 additions & 0 deletions pkg/sink/codec/avro/avro_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,133 @@ func TestAvroLegacyDeleteUsesCachedValueSchema(t *testing.T) {
}
}

func TestAvroLegacyDeleteSharesTableInfoAcrossDecoders(t *testing.T) {
codecConfig := common.NewConfig(config.ProtocolAvro)
codecConfig.EnableTiDBExtension = true
codecConfig.AvroEnableWatermark = true
ctx := t.Context()
encoder, err := SetupEncoderAndSchemaRegistry4Testing(ctx, codecConfig)
require.NoError(t, err)
t.Cleanup(TeardownEncoderAndSchemaRegistry4Testing)

tableInfo := newAvroTableInfoForTest()
row := chunk.MutRowFromValues(int64(1), int64(18)).ToRow()
const topic = "shared-table-info"
require.NoError(t, encoder.AppendRowChangedEvent(ctx, topic,
newAvroRowEventForTest(tableInfo, 1024, chunk.Row{}, row)))
insert := encoder.Build()[0]
require.NoError(t, encoder.AppendRowChangedEvent(ctx, topic,
newAvroRowEventForTest(tableInfo, 1025, row, chunk.Row{})))
deleted := encoder.Build()[0]

for _, withWatermark := range []bool{false, true} {
t.Run("watermark="+strconv.FormatBool(withWatermark), func(t *testing.T) {
provider := common.NewTableInfoProvider()
d1 := NewDecoder(codecConfig, 0, encoder.schemaM, topic, nil).(*decoder)
d2 := NewDecoder(codecConfig, 0, encoder.schemaM, topic, nil).(*decoder)
d1.ShareTableInfo(provider)
d2.ShareTableInfo(provider)

d1.AddKeyValue(insert.Key, insert.Value)
insertEvent := d1.NextDMLMessage().ToDMLEvent()
t.Cleanup(insertEvent.PostFlush)

value := deleted.Value
if !withWatermark {
value = nil
}
d2.AddKeyValue(deleted.Key, value)
deleteEvent := d2.NextDMLMessage().ToDMLEvent()
t.Cleanup(deleteEvent.PostFlush)

require.Same(t, insertEvent.TableInfo, deleteEvent.TableInfo)
require.Equal(t, []commonType.RowType{commonType.RowTypeDelete}, deleteEvent.RowTypes)
require.Equal(t, 2, deleteEvent.Rows.NumCols())
require.Equal(t, int64(1), deleteEvent.Rows.GetRow(0).GetInt64(0))
require.True(t, deleteEvent.Rows.GetRow(0).IsNull(1))
common.RequireRowLocatorByPrimaryKey(t, deleteEvent.TableInfo, "id")
})
}
}

func TestAvroLegacyDeleteRespectsDDLInvalidation(t *testing.T) {
codecConfig := common.NewConfig(config.ProtocolAvro)
codecConfig.EnableTiDBExtension = true
codecConfig.AvroEnableWatermark = true
ctx := t.Context()
encoder, err := SetupEncoderAndSchemaRegistry4Testing(ctx, codecConfig)
require.NoError(t, err)
t.Cleanup(TeardownEncoderAndSchemaRegistry4Testing)

tableInfo := newAvroTableInfoForTest()
row := chunk.MutRowFromValues(int64(1), int64(18)).ToRow()
const topic = "ddl-invalidation"
require.NoError(t, encoder.AppendRowChangedEvent(ctx, topic,
newAvroRowEventForTest(tableInfo, 1024, chunk.Row{}, row)))
insert := encoder.Build()[0]

encodeDelete := func(ts uint64) *common.Message {
require.NoError(t, encoder.AppendRowChangedEvent(ctx, topic,
newAvroRowEventForTest(tableInfo, ts, row, chunk.Row{})))
return encoder.Build()[0]
}

for _, tc := range []struct {
name string
invalidate func(provider *common.TableInfoProvider)
}{
{
name: "AddDDL",
invalidate: func(provider *common.TableInfoProvider) {
provider.AddDDL("test", "person", 1025)
},
},
{
name: "InvalidateAll",
invalidate: func(provider *common.TableInfoProvider) {
provider.InvalidateAll(1025)
},
},
} {
t.Run(tc.name, func(t *testing.T) {
provider := common.NewTableInfoProvider()
d1 := NewDecoder(codecConfig, 0, encoder.schemaM, topic, nil).(*decoder)
d2 := NewDecoder(codecConfig, 0, encoder.schemaM, topic, nil).(*decoder)
d1.ShareTableInfo(provider)
d2.ShareTableInfo(provider)

d1.AddKeyValue(insert.Key, insert.Value)
insertEvent := d1.NextDMLMessage().ToDMLEvent()
t.Cleanup(insertEvent.PostFlush)

tc.invalidate(provider)

// CommitTs == DDL ts still sees the pre-DDL full layout.
beforeDDL := encodeDelete(1025)
d2.AddKeyValue(beforeDDL.Key, beforeDDL.Value)
beforeEvent := d2.NextDMLMessage().ToDMLEvent()
t.Cleanup(beforeEvent.PostFlush)
require.Equal(t, 2, beforeEvent.Rows.NumCols())

// CommitTs > DDL ts falls back to key-only layout without polluting cache.
afterDDL := encodeDelete(1026)
d2.AddKeyValue(afterDDL.Key, afterDDL.Value)
afterEvent := d2.NextDMLMessage().ToDMLEvent()
t.Cleanup(afterEvent.PostFlush)
require.Equal(t, 1, afterEvent.Rows.NumCols())

// Tombstone without watermark also avoids stale layout after a DDL.
d2.AddKeyValue(afterDDL.Key, nil)
tombstoneEvent := d2.NextDMLMessage().ToDMLEvent()
t.Cleanup(tombstoneEvent.PostFlush)
require.Equal(t, 1, tombstoneEvent.Rows.NumCols())

_, cachedAfterDDL := provider.ReadAt("test", "person", 1026)
require.Nil(t, cachedAfterDDL)
})
}
}

func TestAvroEnvelope(t *testing.T) {
t.Parallel()
avroCodec, err := GenCodec(`
Expand Down
39 changes: 22 additions & 17 deletions pkg/sink/codec/avro/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"encoding/binary"
"encoding/json"
"maps"
"math"
"math/big"
"strconv"
"strings"
Expand All @@ -41,14 +42,11 @@ import (
"go.uber.org/zap"
)

var tableIDAllocator = common.NewTableIDAllocator()

// decoderCodecCacheSize bounds the compiled codecs retained by each partition decoder.
// It keeps recently active routed-table schemas without retaining every historical version.
const decoderCodecCacheSize = 128

type decoder struct {
idx int
config *common.Config
topic string

Expand All @@ -68,15 +66,13 @@ type decoder struct {
// NewDecoder return an avro decoder
func NewDecoder(
config *common.Config,
idx int,
_ int,
schemaM schemamanager.SchemaManager,
topic string,
db *sql.DB,
) common.Decoder {
tableIDAllocator.Clean()
codecs, _ := lru.New(decoderCodecCacheSize)
return &decoder{
idx: idx,
config: config,
topic: topic,
schemaM: schemaM,
Expand All @@ -87,6 +83,11 @@ func NewDecoder(
}
}

// ShareTableInfo reads table info through the cache shared by all partitions.
func (d *decoder) ShareTableInfo(cache *common.TableInfoProvider) {
d.cache = cache
}

func (d *decoder) AddKeyValue(key, value []byte) {
if d.key != nil || d.value != nil {
log.Panic("add key/value to the decoder failed, since it's already set")
Expand Down Expand Up @@ -144,7 +145,7 @@ func (d *decoder) NextDMLMessage() *common.DMLMessage {
} else if operation, ok := valueMap[tidbOp]; ok && operation == updateOperation {
rowType = commonType.RowTypeUpdate
}
tableID := tableIDAllocator.Allocate(schemaName, tableName)
tableID := d.cache.AllocateTableID(schemaName, tableName)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return common.NewDMLMessage(tableID, schemaName, tableName, commitTs, rowType, func() *commonEvent.DMLEvent {
return d.assembleDMLEventFromDecoded(keyMap, valueMap, valueSchema, isDelete, hasValue, deleteCommitTs)
})
Expand Down Expand Up @@ -361,8 +362,14 @@ func assembleEvent(
commitTs = int64(deleteCommitTs)
}

lookupTs := uint64(commitTs)
if !hasValue && lookupTs == 0 {
// Legacy tombstones without watermark carry no commit-ts; use the
// newest active layout if no subsequent DDL invalidated it.
lookupTs = math.MaxUint64
}
event := new(commonEvent.DMLEvent)
event.TableInfo = queryTableInfo(cache, schemaName, tableName, uint64(commitTs), columns, keyMap, hasValue && precise)
event.TableInfo = queryTableInfo(cache, schemaName, tableName, lookupTs, columns, keyMap, hasValue && precise)
event.StartTs = uint64(commitTs)
event.CommitTs = uint64(commitTs)
event.PhysicalTableID = event.TableInfo.TableName.TableID
Expand Down Expand Up @@ -521,7 +528,7 @@ func queryTableInfo(
if tableInfo != nil {
return tableInfo
}
tableInfo = newTableInfo(schemaName, tableName, columns, keyMap)
tableInfo = newTableInfo(cache, schemaName, tableName, columns, keyMap)
// A key-only delete has the handle columns alone, and a NULL time column
// has no decimal yet; neither may define the layout of later rows.
if cacheable {
Expand All @@ -530,10 +537,10 @@ func queryTableInfo(
return tableInfo
}

func newTableInfo(schemaName, tableName string, columns []*timodel.ColumnInfo, keyMap map[string]any) *commonType.TableInfo {
func newTableInfo(cache *common.TableInfoProvider, schemaName, tableName string, columns []*timodel.ColumnInfo, keyMap map[string]any) *commonType.TableInfo {
tidbTableInfo := new(timodel.TableInfo)
tidbTableInfo.ID = tableIDAllocator.Allocate(schemaName, tableName)
tableIDAllocator.AddBlockTableID(schemaName, tableName, tidbTableInfo.ID)
tidbTableInfo.ID = cache.AllocateTableID(schemaName, tableName)
cache.AddBlockTableID(schemaName, tableName, tidbTableInfo.ID)
tidbTableInfo.Name = ast.NewCIStr(tableName)
tidbTableInfo.Columns = columns
indexColumns := make([]*timodel.IndexColumn, 0)
Expand Down Expand Up @@ -716,11 +723,9 @@ func (d *decoder) NextDDLEvent() *commonEvent.DDLEvent {
actionType := common.GetDDLActionType(result.Query)
result.Type = byte(actionType)

if d.idx == 0 {
tableIDAllocator.AddBlockTableID(result.SchemaName, result.TableName, tableIDAllocator.Allocate(result.SchemaName, result.TableName))
result.BlockedTables = common.GetBlockedTables(tableIDAllocator, result)
}
d.cache.AddDDL(result.SchemaName, result.TableName, result.FinishedTs)
d.cache.AddBlockTableID(result.SchemaName, result.TableName, d.cache.AllocateTableID(result.SchemaName, result.TableName))
result.BlockedTables = common.GetBlockedTables(d.cache, result)
d.cache.RecordDDL(result)
return result
}

Expand Down
59 changes: 57 additions & 2 deletions pkg/sink/codec/avro/decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package avro

import (
"encoding/binary"
"encoding/json"
"fmt"
"hash/crc32"
"strconv"
Expand All @@ -31,6 +32,8 @@ import (
"github.com/pingcap/ticdc/pkg/sink/codec/common"
"github.com/pingcap/ticdc/pkg/sink/codec/schemamanager"
"github.com/pingcap/ticdc/pkg/util"
timodel "github.com/pingcap/tidb/pkg/meta/model"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/types"
"github.com/pingcap/tidb/pkg/util/chunk"
"github.com/pingcap/tidb/pkg/util/rowcodec"
Expand Down Expand Up @@ -87,7 +90,7 @@ func TestDecodedTableInfoLocatesRowByPrimaryKey(t *testing.T) {
keyMap[key] = nil
}

tableInfo := newTableInfo("test", "t", columns, keyMap)
tableInfo := newTableInfo(common.NewTableInfoProvider(), "test", "t", columns, keyMap)
require.Equal(t, primaryKeys, tableInfo.GetPrimaryKeyColumnNames())
require.True(t, tableInfo.HasPKOrNotNullUK)
common.RequireRowLocatorByPrimaryKey(t, tableInfo, primaryKeys...)
Expand Down Expand Up @@ -350,7 +353,7 @@ func TestDecodedTableInfoWithoutKeyColumnsHasNoRowLocator(t *testing.T) {
columns, _, _, err := avroData2Columns(map[string]any{"a": int64(1), "b": int64(2)}, fields)
require.NoError(t, err)

tableInfo := newTableInfo("test", "t", columns, nil)
tableInfo := newTableInfo(common.NewTableInfoProvider(), "test", "t", columns, nil)
require.False(t, tableInfo.PKIsHandle())
require.Empty(t, tableInfo.GetIndices())
require.Empty(t, tableInfo.GetOrderedHandleKeyColumnIDs())
Expand Down Expand Up @@ -433,3 +436,55 @@ func TestUpdateWithoutBeforeValueRequiresKey(t *testing.T) {
require.ErrorContains(t, err, "handle")
}
}

func TestAvroNextDDLEventInvalidatesSharedCache(t *testing.T) {
provider := common.NewTableInfoProvider()
dec := NewDecoder(common.NewConfig(config.ProtocolAvro), 0, nil, "topic", nil).(*decoder)
dec.ShareTableInfo(provider)

t1 := commonType.WrapTableInfo("test", &timodel.TableInfo{ID: 1, Name: ast.NewCIStr("t1"), UpdateTS: 100})
t2 := commonType.WrapTableInfo("other", &timodel.TableInfo{ID: 2, Name: ast.NewCIStr("t2"), UpdateTS: 100})
provider.WriteTableInfo(t1)
provider.WriteTableInfo(t2)

payload, err := json.Marshal(&ddlEvent{
Query: "ALTER TABLE test.t1 EXCHANGE PARTITION p0 WITH TABLE test.t_normal",
Schema: "test",
Table: "t1",
CommitTs: 120,
})
require.NoError(t, err)
dec.AddKeyValue(nil, append([]byte{ddlByte}, payload...))
tp, hasNext := dec.HasNext()
require.True(t, hasNext)
require.Equal(t, common.MessageTypeDDL, tp)
_ = dec.NextDDLEvent()

_, before := provider.ReadAt("other", "t2", 120)
require.Same(t, t2, before)
_, afterT1 := provider.ReadAt("test", "t1", 121)
require.Nil(t, afterT1)
_, afterT2 := provider.ReadAt("other", "t2", 121)
require.Nil(t, afterT2)
}

func TestAvroNewDecoderDoesNotClearExistingDecoderState(t *testing.T) {
d1 := NewDecoder(common.NewConfig(config.ProtocolAvro), 0, nil, "topic", nil).(*decoder)
event := d1.assembleDMLEventFromDecoded(
map[string]any{"id": int64(1)},
map[string]any{"id": int64(1), tidbCommitTs: int64(100), tidbOp: insertOperation},
map[string]any{
"namespace": "default.test", "name": "person",
"fields": []any{
map[string]any{"name": "id", "type": map[string]any{"connect.parameters": map[string]any{"tidb_type": "INT"}}},
},
}, false, true, 0)
t.Cleanup(event.PostFlush)

blockedBefore := d1.cache.GetBlockedTables("test", "person")
require.Equal(t, []int64{event.PhysicalTableID}, blockedBefore)

d2 := NewDecoder(common.NewConfig(config.ProtocolAvro), 0, nil, "topic", nil).(*decoder)
require.Equal(t, blockedBefore, d1.cache.GetBlockedTables("test", "person"))
require.Empty(t, d2.cache.GetBlockedTables("test", "person"))
}
Loading
Loading