From f67ef0c0b70f16baeb49d64b7b1c1e96a497df96 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Tue, 1 Dec 2026 14:58:35 -0800 Subject: [PATCH] mq: map a topic's record type to an Iceberg table layout The topictable package lays out the table a topic's compacted history goes into. Its columns are _partition, _offset, _ts_ns, _ts (a timestamptz copy of _ts_ns to partition on) and _key, then the record's fields, or _value for a schemaless topic. Scalars map to their Iceberg counterparts, TIMESTAMP to timestamptz, records to structs and repeated fields or list types to lists, with required-ness taken from the field. A DECIMAL field has no precision or scale of its own, so it takes the decimal(38, 18) the topic's parquet files already use. The spec is identity(_partition) and day(_ts), the sort order _partition then _offset, and the seaweedfs.mq.topic property names the owning topic. CheckSchema says whether an existing table can hold a topic's rows, matching columns by name so the ids a table assigns do not matter. Co-Authored-By: Claude Opus 5.5 --- weed/mq/topictable/layout.go | 245 ++++++++++++++++++++++++++++ weed/mq/topictable/layout_test.go | 257 ++++++++++++++++++++++++++++++ 2 files changed, 502 insertions(+) create mode 100644 weed/mq/topictable/layout.go create mode 100644 weed/mq/topictable/layout_test.go diff --git a/weed/mq/topictable/layout.go b/weed/mq/topictable/layout.go new file mode 100644 index 0000000000..91ff12e165 --- /dev/null +++ b/weed/mq/topictable/layout.go @@ -0,0 +1,245 @@ +// Package topictable lays out the Iceberg table that holds an MQ topic's +// compacted history: its columns, partition spec, sort order and the property +// that ties it to the topic. +package topictable + +import ( + "errors" + "fmt" + + "github.com/apache/iceberg-go" + "github.com/apache/iceberg-go/table" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" + "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" +) + +// TopicProperty is the table property naming the topic that owns the table, +// as .. +const TopicProperty = "seaweedfs.mq.topic" + +// System columns, ahead of the record's own. +const ( + PartitionColumn = "_partition" // /-, the partition directory name + OffsetColumn = "_offset" + TsNsColumn = "_ts_ns" + TsColumn = "_ts" // _ts_ns as a timestamp, for day partitioning + KeyColumn = "_key" + ValueColumn = "_value" // the whole message of a schemaless topic +) + +// TsDayField is the partition field day(_ts). +const TsDayField = "_ts_day" + +// A DECIMAL field carries no precision or scale, so every one takes the +// decimal the topic's parquet files are written with. +const ( + DecimalPrecision = 38 + DecimalScale = 18 +) + +// TopicPropertyValue is TopicProperty's value for t. +func TopicPropertyValue(t topic.Topic) string { + return t.String() +} + +// Schema maps a topic's record type to the table's columns: the system +// columns, then the record's fields, or _value for a schemaless topic (a nil +// record type). Field ids are numbered fresh from 1; the table renumbers them +// on create and they are matched by name after that. +func Schema(recordType *schema_pb.RecordType) (*iceberg.Schema, error) { + fields := []iceberg.NestedField{ + {Name: PartitionColumn, Type: iceberg.PrimitiveTypes.String, Required: true}, + {Name: OffsetColumn, Type: iceberg.PrimitiveTypes.Int64, Required: true}, + {Name: TsNsColumn, Type: iceberg.PrimitiveTypes.Int64, Required: true}, + {Name: TsColumn, Type: iceberg.PrimitiveTypes.TimestampTz, Required: true}, + {Name: KeyColumn, Type: iceberg.PrimitiveTypes.Binary}, + } + if recordType == nil { + fields = append(fields, iceberg.NestedField{Name: ValueColumn, Type: iceberg.PrimitiveTypes.Binary}) + } else { + for _, field := range recordType.Fields { + if isSystemColumn(field.Name) { + return nil, fmt.Errorf("field %s: name is reserved for a system column", field.Name) + } + mapped, err := mapField(field) + if err != nil { + return nil, err + } + fields = append(fields, mapped) + } + } + return iceberg.AssignFreshSchemaIDs(iceberg.NewSchema(0, fields...), nil) +} + +func isSystemColumn(name string) bool { + switch name { + case PartitionColumn, OffsetColumn, TsNsColumn, TsColumn, KeyColumn, ValueColumn: + return true + } + return false +} + +func mapField(field *schema_pb.Field) (iceberg.NestedField, error) { + if field.Name == "" { + return iceberg.NestedField{}, errors.New("field without a name") + } + fieldType, err := mapType(field.Type) + if err != nil { + return iceberg.NestedField{}, fmt.Errorf("field %s: %w", field.Name, err) + } + if field.IsRepeated { + fieldType = &iceberg.ListType{Element: fieldType} + } + return iceberg.NestedField{Name: field.Name, Type: fieldType, Required: field.IsRequired}, nil +} + +func mapType(t *schema_pb.Type) (iceberg.Type, error) { + switch kind := t.GetKind().(type) { + case *schema_pb.Type_ScalarType: + return mapScalar(kind.ScalarType) + case *schema_pb.Type_RecordType: + if kind.RecordType == nil || len(kind.RecordType.Fields) == 0 { + return nil, errors.New("record without fields") + } + fields := make([]iceberg.NestedField, 0, len(kind.RecordType.Fields)) + for _, field := range kind.RecordType.Fields { + mapped, err := mapField(field) + if err != nil { + return nil, err + } + fields = append(fields, mapped) + } + return &iceberg.StructType{FieldList: fields}, nil + case *schema_pb.Type_ListType: + element, err := mapType(kind.ListType.GetElementType()) + if err != nil { + return nil, fmt.Errorf("list element: %w", err) + } + return &iceberg.ListType{Element: element}, nil + } + return nil, fmt.Errorf("unsupported type %v", t) +} + +func mapScalar(scalar schema_pb.ScalarType) (iceberg.Type, error) { + switch scalar { + case schema_pb.ScalarType_BOOL: + return iceberg.PrimitiveTypes.Bool, nil + case schema_pb.ScalarType_INT32: + return iceberg.PrimitiveTypes.Int32, nil + case schema_pb.ScalarType_INT64: + return iceberg.PrimitiveTypes.Int64, nil + case schema_pb.ScalarType_FLOAT: + return iceberg.PrimitiveTypes.Float32, nil + case schema_pb.ScalarType_DOUBLE: + return iceberg.PrimitiveTypes.Float64, nil + case schema_pb.ScalarType_BYTES: + return iceberg.PrimitiveTypes.Binary, nil + case schema_pb.ScalarType_STRING: + return iceberg.PrimitiveTypes.String, nil + case schema_pb.ScalarType_TIMESTAMP: + return iceberg.PrimitiveTypes.TimestampTz, nil + case schema_pb.ScalarType_DATE: + return iceberg.PrimitiveTypes.Date, nil + case schema_pb.ScalarType_TIME: + return iceberg.PrimitiveTypes.Time, nil + case schema_pb.ScalarType_DECIMAL: + return iceberg.DecimalTypeOf(DecimalPrecision, DecimalScale), nil + } + return nil, fmt.Errorf("unsupported scalar type %v", scalar) +} + +// PartitionSpec is identity(_partition), day(_ts) over schema. +func PartitionSpec(schema *iceberg.Schema) (iceberg.PartitionSpec, error) { + partition, ts, err := systemFieldIDs(schema, PartitionColumn, TsColumn) + if err != nil { + return iceberg.PartitionSpec{}, err + } + return iceberg.NewPartitionSpec( + iceberg.PartitionField{SourceIDs: []int{partition}, FieldID: iceberg.PartitionDataIDStart, Name: PartitionColumn, Transform: iceberg.IdentityTransform{}}, + iceberg.PartitionField{SourceIDs: []int{ts}, FieldID: iceberg.PartitionDataIDStart + 1, Name: TsDayField, Transform: iceberg.DayTransform{}}, + ), nil +} + +// SortOrder is _partition, _offset ascending over schema, so a data file +// holds one partition's contiguous offset range. +func SortOrder(schema *iceberg.Schema) (table.SortOrder, error) { + partition, offset, err := systemFieldIDs(schema, PartitionColumn, OffsetColumn) + if err != nil { + return table.SortOrder{}, err + } + return table.NewSortOrder(table.InitialSortOrderID, []table.SortField{ + {SourceIDs: []int{partition}, Transform: iceberg.IdentityTransform{}, Direction: table.SortASC, NullOrder: table.NullsFirst}, + {SourceIDs: []int{offset}, Transform: iceberg.IdentityTransform{}, Direction: table.SortASC, NullOrder: table.NullsFirst}, + }) +} + +func systemFieldIDs(schema *iceberg.Schema, a, b string) (int, int, error) { + fieldA, ok := schema.FindFieldByName(a) + if !ok { + return 0, 0, fmt.Errorf("schema has no %s column", a) + } + fieldB, ok := schema.FindFieldByName(b) + if !ok { + return 0, 0, fmt.Errorf("schema has no %s column", b) + } + return fieldA.ID, fieldB.ID, nil +} + +// CheckSchema reports whether a table with columns tableSchema can hold the +// rows of a topic laid out as want: every column want has is in the table by +// name with the same type, nullable wherever want's is, and every other table +// column is nullable. Field ids are not compared. +func CheckSchema(tableSchema, want *iceberg.Schema) error { + return checkFields("", tableSchema.Fields(), want.Fields()) +} + +func checkFields(parent string, have, want []iceberg.NestedField) error { + byName := make(map[string]iceberg.NestedField, len(have)) + for _, field := range have { + byName[field.Name] = field + } + for _, field := range want { + name := parent + field.Name + got, ok := byName[field.Name] + if !ok { + return fmt.Errorf("table has no column %s", name) + } + delete(byName, field.Name) + if got.Required && !field.Required { + return fmt.Errorf("table column %s is required, the topic's is optional", name) + } + if err := checkType(name, got.Type, field.Type); err != nil { + return err + } + } + for _, field := range have { + if _, extra := byName[field.Name]; extra && field.Required { + return fmt.Errorf("table column %s is required and not in the topic", parent+field.Name) + } + } + return nil +} + +func checkType(name string, have, want iceberg.Type) error { + switch want := want.(type) { + case *iceberg.StructType: + got, ok := have.(*iceberg.StructType) + if !ok { + return fmt.Errorf("table column %s is %s, the topic's is %s", name, have, want) + } + return checkFields(name+".", got.FieldList, want.FieldList) + case *iceberg.ListType: + got, ok := have.(*iceberg.ListType) + if !ok { + return fmt.Errorf("table column %s is %s, the topic's is %s", name, have, want) + } + if got.ElementRequired && !want.ElementRequired { + return fmt.Errorf("table column %s has required elements, the topic's are optional", name) + } + return checkType(name+".element", got.Element, want.Element) + } + if !want.Equals(have) { + return fmt.Errorf("table column %s is %s, the topic's is %s", name, have, want) + } + return nil +} diff --git a/weed/mq/topictable/layout_test.go b/weed/mq/topictable/layout_test.go new file mode 100644 index 0000000000..3eb08960b9 --- /dev/null +++ b/weed/mq/topictable/layout_test.go @@ -0,0 +1,257 @@ +package topictable + +import ( + "strings" + "testing" + + "github.com/apache/iceberg-go" + "github.com/apache/iceberg-go/table" + "github.com/seaweedfs/seaweedfs/weed/mq/schema" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" + "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" +) + +func scalarField(name string, scalar schema_pb.ScalarType, required bool) *schema_pb.Field { + return &schema_pb.Field{Name: name, Type: &schema_pb.Type{Kind: &schema_pb.Type_ScalarType{ScalarType: scalar}}, IsRequired: required} +} + +func mustSchema(t *testing.T, recordType *schema_pb.RecordType) *iceberg.Schema { + t.Helper() + s, err := Schema(recordType) + if err != nil { + t.Fatal(err) + } + return s +} + +func field(t *testing.T, s *iceberg.Schema, name string) iceberg.NestedField { + t.Helper() + f, ok := s.FindFieldByName(name) + if !ok { + t.Fatalf("no column %s in %s", name, s) + } + return f +} + +func TestSystemColumnsLeadEverySchema(t *testing.T) { + for _, recordType := range []*schema_pb.RecordType{nil, {Fields: []*schema_pb.Field{scalarField("a", schema_pb.ScalarType_INT32, true)}}} { + s := mustSchema(t, recordType) + want := []struct { + name string + typ iceberg.Type + required bool + }{ + {PartitionColumn, iceberg.PrimitiveTypes.String, true}, + {OffsetColumn, iceberg.PrimitiveTypes.Int64, true}, + {TsNsColumn, iceberg.PrimitiveTypes.Int64, true}, + {TsColumn, iceberg.PrimitiveTypes.TimestampTz, true}, + {KeyColumn, iceberg.PrimitiveTypes.Binary, false}, + } + fields := s.Fields() + for i, w := range want { + got := fields[i] + if got.Name != w.name || !got.Type.Equals(w.typ) || got.Required != w.required { + t.Fatalf("column %d is %s %s required=%v, want %s %s required=%v", i, got.Name, got.Type, got.Required, w.name, w.typ, w.required) + } + } + ids := map[int]bool{} + for _, f := range fields { + if f.ID <= 0 || ids[f.ID] { + t.Fatalf("field %s has id %d, want a fresh positive id", f.Name, f.ID) + } + ids[f.ID] = true + } + } +} + +func TestSchemalessTopicStoresTheValue(t *testing.T) { + s := mustSchema(t, nil) + if s.NumFields() != 6 { + t.Fatalf("%d columns, want the system columns and %s", s.NumFields(), ValueColumn) + } + if v := field(t, s, ValueColumn); !v.Type.Equals(iceberg.PrimitiveTypes.Binary) || v.Required { + t.Fatalf("%s is %s required=%v", ValueColumn, v.Type, v.Required) + } +} + +func TestEveryScalarMaps(t *testing.T) { + want := map[schema_pb.ScalarType]iceberg.Type{ + schema_pb.ScalarType_BOOL: iceberg.PrimitiveTypes.Bool, + schema_pb.ScalarType_INT32: iceberg.PrimitiveTypes.Int32, + schema_pb.ScalarType_INT64: iceberg.PrimitiveTypes.Int64, + schema_pb.ScalarType_FLOAT: iceberg.PrimitiveTypes.Float32, + schema_pb.ScalarType_DOUBLE: iceberg.PrimitiveTypes.Float64, + schema_pb.ScalarType_BYTES: iceberg.PrimitiveTypes.Binary, + schema_pb.ScalarType_STRING: iceberg.PrimitiveTypes.String, + schema_pb.ScalarType_TIMESTAMP: iceberg.PrimitiveTypes.TimestampTz, + schema_pb.ScalarType_DATE: iceberg.PrimitiveTypes.Date, + schema_pb.ScalarType_TIME: iceberg.PrimitiveTypes.Time, + schema_pb.ScalarType_DECIMAL: iceberg.DecimalTypeOf(DecimalPrecision, DecimalScale), + } + if len(want) != len(schema_pb.ScalarType_name) { + t.Fatalf("%d scalar types mapped, schema_pb has %d", len(want), len(schema_pb.ScalarType_name)) + } + recordType := &schema_pb.RecordType{} + for scalar := range want { + recordType.Fields = append(recordType.Fields, scalarField(strings.ToLower(scalar.String()), scalar, false)) + } + s := mustSchema(t, recordType) + for scalar, typ := range want { + if got := field(t, s, strings.ToLower(scalar.String())); !got.Type.Equals(typ) { + t.Errorf("%s maps to %s, want %s", scalar, got.Type, typ) + } + } +} + +func TestDecimalIsTheParquetDecimal(t *testing.T) { + s := mustSchema(t, &schema_pb.RecordType{Fields: []*schema_pb.Field{scalarField("price", schema_pb.ScalarType_DECIMAL, true)}}) + d, ok := field(t, s, "price").Type.(iceberg.DecimalType) + if !ok || d.Precision() != 38 || d.Scale() != 18 { + t.Fatalf("price is %s, want decimal(38, 18)", field(t, s, "price").Type) + } +} + +func TestRequiredFollowsTheField(t *testing.T) { + s := mustSchema(t, &schema_pb.RecordType{Fields: []*schema_pb.Field{ + scalarField("must", schema_pb.ScalarType_STRING, true), + scalarField("may", schema_pb.ScalarType_STRING, false), + }}) + if !field(t, s, "must").Required || field(t, s, "may").Required { + t.Fatalf("must required=%v may required=%v", field(t, s, "must").Required, field(t, s, "may").Required) + } +} + +func TestNestedRecordIsAStruct(t *testing.T) { + inner := schema.RecordTypeBegin().WithField("city", schema.TypeString).WithField("zip", schema.TypeInt32).RecordTypeEnd() + inner.Fields[0].IsRequired = true + s := mustSchema(t, &schema_pb.RecordType{Fields: []*schema_pb.Field{ + {Name: "address", Type: &schema_pb.Type{Kind: &schema_pb.Type_RecordType{RecordType: inner}}, IsRequired: true}, + }}) + address := field(t, s, "address") + st, ok := address.Type.(*iceberg.StructType) + if !ok || !address.Required { + t.Fatalf("address is %s required=%v", address.Type, address.Required) + } + if len(st.FieldList) != 2 { + t.Fatalf("address has %d fields", len(st.FieldList)) + } + city, zip := field(t, s, "address.city"), field(t, s, "address.zip") + if !city.Type.Equals(iceberg.PrimitiveTypes.String) || !city.Required || !zip.Type.Equals(iceberg.PrimitiveTypes.Int32) || zip.Required { + t.Fatalf("city %s required=%v, zip %s required=%v", city.Type, city.Required, zip.Type, zip.Required) + } +} + +func TestListsMap(t *testing.T) { + s := mustSchema(t, &schema_pb.RecordType{Fields: []*schema_pb.Field{ + {Name: "tags", Type: schema.TypeString, IsRepeated: true}, + {Name: "scores", Type: schema.ListOf(schema.TypeDouble), IsRequired: true}, + {Name: "matrix", Type: schema.ListOf(schema.TypeInt64), IsRepeated: true}, + }}) + tags, ok := field(t, s, "tags").Type.(*iceberg.ListType) + if !ok || !tags.Element.Equals(iceberg.PrimitiveTypes.String) || tags.ElementRequired { + t.Fatalf("tags is %s", field(t, s, "tags").Type) + } + scores, ok := field(t, s, "scores").Type.(*iceberg.ListType) + if !ok || !scores.Element.Equals(iceberg.PrimitiveTypes.Float64) || !field(t, s, "scores").Required { + t.Fatalf("scores is %s", field(t, s, "scores").Type) + } + matrix, ok := field(t, s, "matrix").Type.(*iceberg.ListType) + if !ok { + t.Fatalf("matrix is %s", field(t, s, "matrix").Type) + } + if inner, ok := matrix.Element.(*iceberg.ListType); !ok || !inner.Element.Equals(iceberg.PrimitiveTypes.Int64) { + t.Fatalf("matrix is %s, want a list of lists of long", matrix) + } +} + +func TestSchemaRefusesWhatItCannotMap(t *testing.T) { + for name, recordType := range map[string]*schema_pb.RecordType{ + "system column": {Fields: []*schema_pb.Field{scalarField(OffsetColumn, schema_pb.ScalarType_INT64, true)}}, + "empty record": {Fields: []*schema_pb.Field{{Name: "r", Type: &schema_pb.Type{Kind: &schema_pb.Type_RecordType{RecordType: &schema_pb.RecordType{}}}}}}, + "no type": {Fields: []*schema_pb.Field{{Name: "x"}}}, + "unnamed": {Fields: []*schema_pb.Field{scalarField("", schema_pb.ScalarType_INT64, true)}}, + "unknown scalar": {Fields: []*schema_pb.Field{scalarField("x", schema_pb.ScalarType(99), true)}}, + } { + if _, err := Schema(recordType); err == nil { + t.Errorf("%s: mapped", name) + } + } +} + +func TestPartitionSpecAndSortOrder(t *testing.T) { + s := mustSchema(t, &schema_pb.RecordType{Fields: []*schema_pb.Field{scalarField("a", schema_pb.ScalarType_INT32, true)}}) + spec, err := PartitionSpec(s) + if err != nil { + t.Fatal(err) + } + if spec.NumFields() != 2 { + t.Fatalf("spec has %d fields", spec.NumFields()) + } + identity, day := spec.Field(0), spec.Field(1) + if identity.SourceID() != field(t, s, PartitionColumn).ID || identity.Transform != (iceberg.IdentityTransform{}) || identity.Name != PartitionColumn { + t.Fatalf("first partition field %v", identity) + } + if day.SourceID() != field(t, s, TsColumn).ID || day.Transform != (iceberg.DayTransform{}) || day.Name != TsDayField { + t.Fatalf("second partition field %v", day) + } + + order, err := SortOrder(s) + if err != nil { + t.Fatal(err) + } + var sources []int + for _, f := range order.Fields() { + if f.Transform != (iceberg.IdentityTransform{}) || f.Direction != table.SortASC { + t.Fatalf("sort field %s", &f) + } + sources = append(sources, f.SourceID()) + } + if len(sources) != 2 || sources[0] != field(t, s, PartitionColumn).ID || sources[1] != field(t, s, OffsetColumn).ID { + t.Fatalf("sorted by %v, want _partition then _offset", sources) + } + + // the layout binds into new table metadata as-is + if _, err := table.NewMetadata(s, &spec, order, "s3://b/ns/t", iceberg.Properties{TopicProperty: TopicPropertyValue(topic.NewTopic("ns", "t"))}); err != nil { + t.Fatal(err) + } +} + +func TestCheckSchema(t *testing.T) { + base := &schema_pb.RecordType{Fields: []*schema_pb.Field{ + scalarField("id", schema_pb.ScalarType_INT64, true), + scalarField("name", schema_pb.ScalarType_STRING, false), + }} + tableSchema := mustSchema(t, base) + if err := CheckSchema(tableSchema, mustSchema(t, base)); err != nil { + t.Fatalf("same layout: %v", err) + } + // a table renumbered by its create still matches by name + renumbered, err := iceberg.AssignFreshSchemaIDs(tableSchema, func() func() int { n := 100; return func() int { n++; return n } }()) + if err != nil { + t.Fatal(err) + } + if err := CheckSchema(renumbered, mustSchema(t, base)); err != nil { + t.Fatalf("renumbered: %v", err) + } + // a required topic field fits an optional column + stricter := &schema_pb.RecordType{Fields: []*schema_pb.Field{scalarField("id", schema_pb.ScalarType_INT64, true), scalarField("name", schema_pb.ScalarType_STRING, true)}} + if err := CheckSchema(tableSchema, mustSchema(t, stricter)); err != nil { + t.Fatalf("stricter topic: %v", err) + } + + for name, rt := range map[string]*schema_pb.RecordType{ + "added field": {Fields: append(base.Fields[:2:2], scalarField("extra", schema_pb.ScalarType_INT32, false))}, + "changed type": {Fields: []*schema_pb.Field{scalarField("id", schema_pb.ScalarType_INT32, true), base.Fields[1]}}, + "optional topic": {Fields: []*schema_pb.Field{scalarField("id", schema_pb.ScalarType_INT64, false), base.Fields[1]}}, + "dropped require": {Fields: []*schema_pb.Field{base.Fields[1]}}, + "schemaless": nil, + } { + if err := CheckSchema(tableSchema, mustSchema(t, rt)); err == nil { + t.Errorf("%s: compatible", name) + } + } + // an optional column the topic no longer has is fine + if err := CheckSchema(tableSchema, mustSchema(t, &schema_pb.RecordType{Fields: base.Fields[:1]})); err != nil { + t.Fatalf("dropped optional field: %v", err) + } +}