Skip to content

[Bug]: UnionOne regresses indexed-write copy and varlen marshal performance vs 4.2 #29571

Description

@LeftHandCold

Is there an existing issue for the same bug?

Branch Name

main (comparison with 4.2-dev)

Commit ID

Version Product SHA BigData run
4.2-dev baseline 1a44f3db3056e32975fde86ca0ab69a094996a3f 36445406307
Earlier main d8152cb08d7e73316034c33aaf0e7bc01c176f91 36531964172
Main in the latest compared run 32f54981401fd3888702f2dab8702d2e62c6997a 36886052323

Actual Behavior

A repeatable vector write-path performance regression is confirmed. General merge uses UnionOne, which clears the VARLEN destination's disjoint-area proof. Main then uses canonical row-by-row marshal, including allocations for inline values that need no out-of-line area. Ordinary fixed-type UnionOne copying also becomes substantially more expensive.

This issue reports those measured local regressions. The slower BigData INSERT/DDL execution below is related workload evidence; we have not isolated the fraction of its SQL wall time caused by each vector change.

Repeated local A/B (same host, exact Go package source at each SHA)

8192 rows per operation; VARLEN values are 20-byte inline VARCHAR; destination is materialized with real UnionOne; marshal uses real PrepareMarshalBinary and MarshalTo into a reused, preallocated bytes.Buffer. Values are non-NULL. Runs were sequential, -benchtime=300ms -count=3; times below are medians.

Operation / 8192 rows 4.2-dev Earlier main Latest compared main
BIGINT UnionOne copy 110.107 us 204.358 us 207.052 us
VARCHAR marshal after UnionOne 5.610 us 317.014 us 316.244 us
VARCHAR UnionOne + marshal 181.260 us 606.833 us 629.381 us
VARCHAR marshal allocations 6 8233 8233
VARCHAR marshal allocated bytes 20 B approximately 455 KB approximately 455 KB
  • VARCHAR marshal is approximately 56x slower, with approximately one extra allocation per row.
  • Fixed BIGINT copy is approximately 1.88x slower, with zero Go allocations in all versions. Fixed BIGINT marshal itself remains approximately 1.3–1.5 us, 20 B, 6 allocations.
  • Same-main control: select the identical VARCHAR values using existing UnionInt32, which preserves VarlenaAreaIsDisjoint=true. Marshal returns to 5.705 us, 20 B, 6 allocations. Thus the allocation jump is specific to the canonical path following UnionOne, rather than the VARCHAR contents alone.

These are local component measurements, not claimed end-to-end SQL speedup percentages.

BigData execution evidence

The compared cases have identical test assets (5615d3c97496307c9b5027c84b528e8c321777e5), SQL/digest sequences, schemas and successful row-count/result checks. I3 inserts 999999998 rows into an initially empty table with BIGINT PK id, nonunique KEY(col3) and UNIQUE KEY(col4). Q7 operates on clones of a verified 1-billion-row base table.

Actual SQL / internal data execution, seconds 4.2-dev Earlier main Latest compared main
I3 bulk indexed INSERT (first statement) 5038.6 9013.4 7848.6
Q7 ADD PK(col4), internal table-copy INSERT 889.5 1406.3 1512.9
Q7 ADD PK(col3,col4), internal table-copy INSERT 999.2 1525.2 1504.3
Q7 CREATE INDEX(col3), internal backfill 310.0 634.2 618.3
Q7 CREATE UNIQUE INDEX(col4), internal backfill 311.3 501.0 699.0
Q7 CREATE UNIQUE INDEX(col4,col6), internal backfill 268.3 614.2 550.8

These are client-observed statement durations or server sql_executor exec durations, not GitHub job queue times. I3 and Q7 pass their result comparisons in these runs. I3 and Q7 overlap, so aggregate differences alone are insufficient to prove an individual kernel cause.

For Q7 CREATE INDEX(col3), outer-minus-backfill time is only approximately 0.77 / 0.84 / 0.92 seconds. The approximately 2x difference occurs inside data backfill, not the DDL lock/metadata wrapper. ADD PK precheck/other time is stable or improved while the copy phase regresses. Latest ADD/MODIFY/DROP COLUMN operations are near or faster than the baseline: this is not a claim that every DDL operation regresses.

Example server log evidence for the same regular-index backfill:

4.2:   sql_executor exec duration=5m9.993771938s  retry-times=0
main:  sql_executor exec duration=10m34.175845382s retry-times=0
latest:sql_executor exec duration=10m18.250641965s retry-times=0
SQL: INSERT INTO <hidden secondary index>
     SELECT serial_full(col3,__mo_fake_pk_col), __mo_fake_pk_col
     FROM big_data_test.table_basic_for_alter_1b_add_index;

Other Environment Information

  • Cluster: TKE, 3 CN + 1 TN; each CN requests/limits 14 CPU and 55 GiB.
  • Actual startup logs confirm GOMAXPROCS=14 in all three runs.
  • GOGC=200, GOMEMLIMIT=25000MiB, deployment manifest, cache settings and strict SQL executor source are the same in these comparisons.
  • Source defaults are unchanged: sink/sync worker limits 8/4, INSERT flush 64 MiB, sorted pipeline submit cap 128 MiB, block size 8192 rows.
  • Local benchmark: Linux/amd64, Intel i9-10900K, Go 1.26.4, default GOGC=100. Exact Go package sources were checked out separately; native libmo/third-party artifacts were reused from the local checkout. This is not a clean-native historical binary bisection. The same-main UnionInt32 control removes that cross-version native-artifact difference from the canonical-path comparison.
  • One isolated composite-index backfill window, after I3 finishes in both runs: 4.2 hot CN averages about 9.23 CPU, main about 5.71 CPU; main host has about 10 idle cores and zero steal. Resource competition does not fully explain that window. This does not establish equal actual SQL DOP.

Expected Behavior

Ordinary materialization into uniquely owned, disjoint destination storage should retain a safe bulk marshal path. Copying and marshaling plain values should avoid unnecessary per-row metadata/allocation work while preserving NULL, borrowing, aliasing, provenance and failure-path semantics.

Steps to Reproduce

  1. Check out each product SHA listed above in a separate checkout. Build that checkout's native CPU prerequisites with make cgo before independent reproduction.
  2. Save the tested benchmark below as pkg/container/vector/bench_bigdata_rca_test.go.
  3. Run the CGo-aware command below. Do not select MarshalUnionInt32Varchar on 4.2: the assertion is a main-only control because 4.2 does not preserve that metadata flag.
Self-contained, tested benchmark source
package vector

import (
	"bytes"
	"testing"

	"github.com/matrixorigin/matrixone/pkg/common/mpool"
	"github.com/matrixorigin/matrixone/pkg/container/types"
)

const bigDataRCARows = 8192

func bigDataRCASetup(b *testing.B, varchar bool) (*mpool.MPool, *Vector, *Vector) {
	b.Helper()
	mp := mpool.MustNewZero()
	typ := types.T_int64.ToType()
	if varchar {
		typ = types.T_varchar.ToType()
	}
	src := NewVec(typ)
	dst := NewVec(typ)
	if err := dst.PreExtend(bigDataRCARows, mp); err != nil {
		b.Fatal(err)
	}
	for i := 0; i < bigDataRCARows; i++ {
		var err error
		if varchar {
			err = AppendBytes(src, []byte("12345678901234567890"), false, mp)
		} else {
			err = AppendFixed(src, int64(i), false, mp)
		}
		if err != nil {
			b.Fatal(err)
		}
	}
	return mp, src, dst
}

func bigDataRCAUnion(b *testing.B, varchar bool) {
	mp, src, dst := bigDataRCASetup(b, varchar)
	defer src.Free(mp)
	defer dst.Free(mp)
	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		dst.ResetWithSameType()
		for row := 0; row < bigDataRCARows; row++ {
			if err := dst.UnionOne(src, int64(row), mp); err != nil {
				b.Fatal(err)
			}
		}
	}
}

func bigDataRCAMarshal(b *testing.B, varchar bool) {
	mp, src, dst := bigDataRCASetup(b, varchar)
	defer src.Free(mp)
	defer dst.Free(mp)
	for row := 0; row < bigDataRCARows; row++ {
		if err := dst.UnionOne(src, int64(row), mp); err != nil {
			b.Fatal(err)
		}
	}
	if varchar && dst.VarlenaAreaIsDisjoint() {
		b.Fatal("expected UnionOne to mark varlena area shared")
	}
	var buf bytes.Buffer
	buf.Grow(bigDataRCARows * 64)
	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		buf.Reset()
		plan, err := dst.PrepareMarshalBinary()
		if err != nil {
			b.Fatal(err)
		}
		if err := plan.MarshalTo(&buf); err != nil {
			b.Fatal(err)
		}
	}
}

func bigDataRCAUnionMarshal(b *testing.B, varchar bool) {
	mp, src, dst := bigDataRCASetup(b, varchar)
	defer src.Free(mp)
	defer dst.Free(mp)
	var buf bytes.Buffer
	buf.Grow(bigDataRCARows * 64)
	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		dst.ResetWithSameType()
		for row := 0; row < bigDataRCARows; row++ {
			if err := dst.UnionOne(src, int64(row), mp); err != nil {
				b.Fatal(err)
			}
		}
		buf.Reset()
		plan, err := dst.PrepareMarshalBinary()
		if err != nil {
			b.Fatal(err)
		}
		if err := plan.MarshalTo(&buf); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkBigDataRCAUnionVarchar(b *testing.B)        { bigDataRCAUnion(b, true) }
func BenchmarkBigDataRCAUnionInt64(b *testing.B)          { bigDataRCAUnion(b, false) }
func BenchmarkBigDataRCAMarshalVarchar(b *testing.B)      { bigDataRCAMarshal(b, true) }
func BenchmarkBigDataRCAMarshalInt64(b *testing.B)        { bigDataRCAMarshal(b, false) }
func BenchmarkBigDataRCAUnionMarshalVarchar(b *testing.B) { bigDataRCAUnionMarshal(b, true) }
func BenchmarkBigDataRCAUnionMarshalInt64(b *testing.B)   { bigDataRCAUnionMarshal(b, false) }

func BenchmarkBigDataRCAMarshalUnionInt32Varchar(b *testing.B) {
    mp, src, dst := bigDataRCASetup(b, true)
    defer src.Free(mp)
    defer dst.Free(mp)
    sels := make([]int32, bigDataRCARows)
    for row := range sels { sels[row] = int32(row) }
    if err := dst.UnionInt32(src, sels, mp); err != nil { b.Fatal(err) }
    if !dst.VarlenaAreaIsDisjoint() { b.Fatal("expected selection union to preserve disjoint varlena area") }
    var buf bytes.Buffer
    buf.Grow(bigDataRCARows * 64)
    b.ReportAllocs()
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        buf.Reset()
        plan, err := dst.PrepareMarshalBinary()
        if err != nil { b.Fatal(err) }
        if err := plan.MarshalTo(&buf); err != nil { b.Fatal(err) }
    }
}
root_dir=$(pwd)
export CGO_CFLAGS="-I${root_dir}/cgo -I${root_dir}/thirdparties/install/include"
export CGO_LDFLAGS="-L${root_dir}/thirdparties/install/lib"
export LD_LIBRARY_PATH="${root_dir}/cgo:${root_dir}/thirdparties/install/lib"
export GOWORK=off
# 4.2:
go test -mod=readonly -ldflags="-extldflags '-L${root_dir}/cgo -lmo -L${root_dir}/thirdparties/install/lib -Wl,-rpath,${root_dir}/cgo -Wl,-rpath,${root_dir}/thirdparties/install/lib -fopenmp'" -run '^$' -bench '^BenchmarkBigDataRCA(UnionInt64|MarshalVarchar|UnionMarshalVarchar)$' -benchmem -benchtime=300ms -count=3 -timeout=120s ./pkg/container/vector
# main: same command, with this bench selector:
# -bench '^BenchmarkBigDataRCA(UnionInt64|MarshalVarchar|UnionMarshalVarchar|MarshalUnionInt32Varchar)$'

The attached code uses actual vector APIs and synthetic values. An additional round-trip check was run successfully at all three SHAs: both UnionOne and UnionInt32 output decode to all 8192 original 20-byte values, and encoded lengths are 196642 bytes. The main-only control has VarlenaAreaIsDisjoint=true; all three UnionOne destinations have it false.

Additional information

Reachable source path

#28145 introduced the canonical marshal mechanism. #28724 already repairs the equivalent lost-proof problem in UnionInt32; the general-merge UnionOne path remains reproducibly expensive in both tested main SHAs. This does not identify a first-bad commit for the entire SQL workload.

Boundaries and follow-up validation

  • Earlier main d8152cb is already slow and does not contain the later change associated with [Bug]: Prepared stats admission repeatedly rebuilds plans; all five TPCC configurations lose 53-71% throughput #29564/[Bug]: Q9 join order regresses after Cartesian estimation; TPCH 1T grows from 144s to 813s #29565. Those bugs cannot explain the original observed write gap.
  • Actual physical-plan DOP, writer-stage elapsed times and an isolated patched/unpatched SQL run are still needed to quantify end-to-end contributions. Equal defaults/GOMAXPROCS do not prove equal per-plan DOP.
  • The fixed-key backfill also regresses, so canonical VARLEN marshal is not a complete explanation by itself. Same-type array/TEXT/BLOB casts are additional profile-correlated contributors, not separately quantified here.
  • Extra allocated bytes are cumulative transient Go allocations. There is no evidence here that inline canonical encoding increases S3 output bytes or causes an OOM.
  • Suggested acceptance: verify the owned/disjoint fast path and its allocation behavior, preserve NULL/borrowed/aliased fallback semantics, then compare isolated I3/Q7 executions with actual plan/DOP and sort/serialize/I/O timing before a full BigData acceptance run.

Related: #28659, #28724, #28145, #26133.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions