Skip to content

perf(hashmap): resolve nullable key encoding once per vector (#10181 steps 6, 6b) - #33344

Merged
mergify[bot] merged 16 commits into
matrixorigin:mainfrom
fengttt:type-vft-step6
Nov 28, 2026
Merged

mergify[bot] merged 16 commits into
matrixorigin:mainfrom
fengttt:type-vft-step6

Conversation

@fengttt

@fengttt fengttt commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Improvement

Which issue(s) this PR fixes:

issue #10181

What this PR does / why we need it:

Steps 6 and 6b of docs/design/20261126-type-vft.md: type dispatch on per-row loops. Every candidate was measured before changing anything.

Changed: nullable hash-key encoding

fillNullableStr is the general loop for hash-join and group-by keys when the key vector has NULLs or is const. It switched on the type id and re-read the vector's type, size, data, const flag and NULL bitmap on every row. It now resolves them once and runs a loop typed for the vector: float32, float64, other fixed-size, or varlena. The key bytes are unchanged.

BenchmarkFillNullableStr (256 rows with NULLs, 6 runs, median):

key type before after change
decimal128 1865 ns 1305 ns −30%
float32 2060 ns 1472 ns −29%
float64 1977 ns 1401 ns −29%
int32 ~1975 ns 1516 ns −23%
varchar 2152 ns 2159 ns ~0 (the copy dominates)

The old loop is kept in fill_nullable_legacy_test.go. TestFillNullableStrMatchesLegacy compares the encoded keys and the not-inserted marks across:

  • 15 key types;
  • plain, const and const-NULL vectors;
  • maps with and without NULL keys;
  • a start offset.

I checked it fails when a key byte changes.

Measured and left alone

These loops do far more work per row than a ~1 ns switch:

  • castToJSON: 42 ns/row for int64, and 25 ns/row even for the json-to-json append;
  • jsonToNumeric, which decodes JSON per row;
  • NormalizeL2Array, which does vector math per row;
  • the prepared-cursor estimators;
  • timewin, ivf_create, productl2.

Step 6b: MySQL result-row encoding, measured and left alone

The new BenchmarkColumnSlicesRows encodes 1024-row batches through the result-row path (appendResultSetTextRow2 / BinaryRow2): 37 ns/cell text and 27 ns/cell binary for int64, 107–124 ns/cell for mixed columns.

A CPU profile puts all type dispatch under 4%. The cost is elsewhere:

  • Conn.Append: 18%;
  • IsNull per cell: 11%;
  • fmt.Sprintf inside Datetime.String2 and Decimal64.Format: 15% of the mixed case;
  • per-cell allocations.

So per-column encoders aren't worth doing. The benchmark stays for a separate formatting change.

Tests

./pkg/common/hashmap/... and all of ./pkg/sql/colexec/... pass. Lint reports 0 issues on the changed packages.

🤖 Generated with Claude Code

fengttt and others added 11 commits November 26, 2026 11:50
Design and phased plan for issue matrixorigin#10181. Measures the 949 type-id
switches in pkg/, identifies the ones that run per row, and proposes an
Oid-indexed traits table in types, per-package operation tables with
completeness tests, and the exhaustive linter for the switches that stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eSwitchFamilies

Step 1 of docs/design/20261126-type-vft.md (matrixorigin#10181). optools/oidscan is a
standalone, standard-library-only module that scans pkg/ for switch
statements over types.T and reports their count, case-count histogram, the
ones inside a loop, and which of those have a loop-invariant type (the
worklist for moving dispatch out of row loops). It is a report, not a check.

The design doc now builds on the existing TestTypeSwitchFamilies check
(families, typeswitch:partial tags, shrinking baseline) instead of proposing
the exhaustive linter, and records steps 1 and 2 as done.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Step 2 of docs/design/20261126-type-vft.md (matrixorigin#10181).

- multi_update and preinsert each had a copy of the zero-temporal check
  that switched on the column type for every row. Both now call
  colexec.CheckZeroTemporalVector, which switches once per vector and runs
  a typed row loop. Error codes, messages and row numbers are unchanged.
- postdml decides how to quote the primary key once per batch instead of
  per row.
- deletion copied each deleted row's key by boxing it (getNonNullValue)
  and unboxing it again (AppendAny): two type switches per row, and the
  getNonNullValue copy panicked on key types it did not list (the
  low-precision floats, year, most vector types). The key is now copied
  with UnionOne, and that copy of getNonNullValue is removed.
- typeswitch_baseline.txt regenerated: removals only (the two deletion
  entries plus 12 entries already fixed upstream).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Step 3 of docs/design/20261126-type-vft.md (matrixorigin#10181).

traits_table.go holds one row per T_ constant: family flags, TypeLen,
FixedLength, the default type TryToType returns, and the String and
OidString names. String, OidString, TypeLen, FixedLength, TryToType, the
T.IsXxx predicates and Type.IsInt/IsUInt/IsFloat/IsDecimal read the table
instead of each switching on the type id. AllOids() lists the T_ constants
for other packages' completeness tests.

No change in behavior: the switch implementations are kept in
traits_legacy_test.go and TestTraitsMatchLegacy compares every method on
all 256 T values, including the panics for types with no size. A field
left out of a row means "absent" (panic, false or "unknown"), so a
forgotten size fails loudly. TestTraitsCoverEveryOid fails when a T_
constant has no row; TestTraitsFlagFamilies ties the float and vector
flags to the TestTypeSwitchFamilies families. Benchmarks: the table is
as fast as or faster than the switches (FixedLength 106 vs 124 ns,
IsFloat 31 vs 39 ns per pass over all types).

typeswitch_baseline.txt: two entries removed, both switches in types.go
that are now table rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
-list prints every type-id switch (file:line, function, type ids named,
default branch, inside a loop); -dir keeps the switches in files directly
in one directory. Used to pick the switches each step of
docs/design/20261126-type-vft.md moves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…able

Step 4 (pilot) of docs/design/20261126-type-vft.md (matrixorigin#10181).

type_ops.go has one row per type id with the Go element type that stores
it (fixedOps[T] or varlenOps), and lists the 7 type ids no operation here
supports. GetAny, AppendAny, Shrink, ShrinkByMask, Shuffle and
shuffleWithBufData read their per-type function from the table instead of
each switching over 47 type ids; all six had the same type-to-Go-type
mapping. Each keeps its own behavior for an unsupported type: GetAny
returns nil, AppendAny does nothing, the others panic with their own
message.

No change in behavior: the six switch implementations are kept in
type_ops_legacy_test.go, and TestTypeOpsMatchLegacy runs both on random
vectors (with NULLs and out-of-line varlenas) of every type id, comparing
values, vectors, errors and panics. A row with the wrong element type
fails it even when the size matches. TestTypeOpsCoverEveryOid fails when
a T_ constant is neither a row nor listed as unsupported; TestTypeOpsRows
checks each row's element size against types.T.TypeLen.

Benchmarks are within noise: GetAny +1% (int64) to -1% (Blockid),
Shrink unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ch onto the type-ops table

Step 4b of docs/design/20261126-type-vft.md (matrixorigin#10181).

- getUnionAllFunction: 853 lines of per-type closures become
  unionAllFixed[T] and unionAllVarlen, built per row of the table; T_any
  keeps its own closure. unionNsp moves to package level, unchanged.
- MakeAppendBytesFunc and NewFunctionResultWrapper read the fixed-size
  case from the table (varlena types are still handled first, as before).
- canonicalVectorTypeSize and isVarlenaMarshalType read the table instead
  of listing the type ids again.

getConstSetFunction stays a switch: its hand-written closures run per row
in SetJoinBatchValues, and the generic version measured about 1 ns (8%)
slower per call. TestConstSetCoversTypeOps ties it to the table instead:
it must return a function for every supported type id and panic for every
other one but T_any.

No change in behavior: the replaced functions are kept in
type_ops_legacy_test.go, and TestTypeOpsConstructorsMatchLegacy compares
them on every type id (union from plain, const and const-null sources
into a vector with a different area; append-bytes; function result;
canonical size with right and wrong sizes). Checked that it fails when a
varlena type is given the fixed-size union. Union benchmarks are within
+-1%.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ctly

Fixes matrixorigin#33336 (part of matrixorigin#33335).

containers.Vector was an interface implemented by a wrapper around
*vector.Vector. It is now an alias for *vector.Vector, the wrapper is
gone, and its methods are free functions in containers/vector.go with the
same behavior (GetValue, AppendValue, UpdateRow, Extend, Compact,
Window, CloneWindow, WriteVector/ReadVector, ...). GetDownstreamVector()
and ToTNVector() calls are removed: they were identity on the vector.
TAE Batch stays (matrixorigin#33337); its Vecs are now []*vector.Vector.

Release: Close() becomes ReleaseVector(v). A vector lent by a VectorPool
goes back to its pool; any other vector is freed with its own pool. To
keep pooled release safe without a field on Vector, the pool lends a
fresh vector struct holding the element's buffers and moves them back on
release; a package-level registry records what is lent. A stale second
release then finds an empty struct, so it can never reach a later
borrower of the same buffers, and release stays idempotent as Close was
(pnode.go relies on it).

Behavior changes, all deliberate:
- The wrapper copied a read-only vector on first write (copy-on-write).
  The mutating functions now panic on a read-only vector instead. The
  full TAE suite found two sites: checkpoint backup (replay.go) appends
  to loaded checkpoint vectors, so it now Dups a cache-backed one first,
  as the wrapper did; and TestNull1 updated a window of a mock batch.
- ReleaseVector frees a read-only vector too (dropping references and an
  owned null bitmap); the wrapper skipped Free for those, which leaked
  an owned null bitmap.
- VectorAllocated (used by Batch.Allocated) keeps the wrapper's 0 for a
  read-only vector; vector.Allocated reports referenced capacity.

The call sites were rewritten from compiler errors with a one-off tool
(each "X.M undefined" error located the call to rewrite), then reviewed
by hand: the former GetAllocator() calls (now MPool(), the same pool for
an owned vector), the CloneWindow calls that need a pool, Allocated(),
and every former ToTNVector site for copy-on-write.

Tests: release_test.go covers pooled, unpooled, read-only, placeholder
and closed-pool release, and that a stale release cannot affect the next
borrower. Full ./pkg/vm/engine/tae/..., ./pkg/objectio/...,
./pkg/publication/..., ./pkg/vm/engine/test/... and ./pkg/datasync/...
pass; containers passes under -race.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… table

Step 5 of docs/design/20261126-type-vft.md (matrixorigin#10181).

The vector table gains setAny, exported as vector.SetAny, and
vector.SupportsAny. TAE's getNonNullValue is now the support check plus
vector.GetAny, and UpdateValue the support check plus vector.SetAny with
its NULL handling unchanged. GenericUpdateFixedValue and
GenericUpdateBytes had no other users and are removed.

This fixes switches that had fallen behind the vector code:
getNonNullValue panicked ("No Support") on T_decimal256, T_geometry and
T_geometry32, and UpdateValue ("not supported") on those and T_year.
containers.GetValue and UpdateRow go through them.

The switch implementations are kept in value_access_legacy_test.go;
TestValueAccessMatchesLegacy compares them on every type id (same
values, vectors and panics, except that the formerly missing types now
work). TestSetAny covers the new vector operation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Step 6 of docs/design/20261126-type-vft.md (matrixorigin#10181).

fillNullableStr's general loop (key vectors with NULLs, or const) switched
on the type id and re-read the vector's type, size, data, const flag and
NULL bitmap on every row. It now resolves them once and runs a loop typed
for the vector: float32, float64, other fixed-size, varlena. The key
bytes are unchanged.

BenchmarkFillNullableStr (256 rows with NULLs, 6 runs, median):
  decimal128  1865 -> 1305 ns  -30%
  float32     2060 -> 1472 ns  -29%
  float64     1977 -> 1401 ns  -29%
  int32      ~1975 -> 1516 ns  -23%
  varchar     2152 -> 2159 ns   ~0 (dominated by the copy)

The old loop is kept in fill_nullable_legacy_test.go;
TestFillNullableStrMatchesLegacy compares the encoded keys and the
not-inserted marks for 15 key types, plain, const and const-NULL
vectors, maps with and without NULL keys, and a start offset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hmark

Step 6 measured every loop-invariant switch first. Only nullable hash-key
encoding was worth changing (previous commit). castToJSON (42 ns/row for
int64, 25 ns/row even for the json-to-json append), jsonToNumeric,
NormalizeL2Array, the prepared-cursor estimators, timewin, ivf_create and
productl2 do far more work per row than a ~1 ns switch.

Step 6b: BenchmarkColumnSlicesRows encodes 1024-row batches through the
result-row path (appendResultSetTextRow2 / BinaryRow2): 37 ns/cell text,
27 ns/cell binary for int64, 107-124 ns/cell for mixed columns. A CPU
profile puts all type dispatch under 4%; the cost is Conn.Append (18%),
IsNull per cell (11%), and fmt.Sprintf in Datetime.String2 and
Decimal64.Format (15% of the mixed case). Per-column encoders are
therefore not worth it; the benchmark stays for a formatting change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify

mergify Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

@XuPeng-SH

XuPeng-SH commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 74ab6d45ef37b0f4cc5f50ec800f049638eb20d2

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: 74ab6d45ef37b0f4cc5f50ec800f049638eb20d2

Assessment: approve

No actionable defects found. The optimization stays within the existing hash-key encoder, preserves the established key grammar, and adds no new runtime state. Its specialized loops add some repeated code, supported by the measured improvement on nullable fixed-width and float keys.

Model: gpt-6.1-terra / max

Session: 01a21f04-073f-77d1-8630-a593fb7859fd · slot 0 · generation 28

Validation:

  • Private /tmp and loopback preflight and git diff --check passed: checks/1795818437113919936-3.json and checks/1795818437085364009-3.json.

  • The full hashmap and keycodec package tests passed after building the repository-pinned jemalloc prerequisite: checks/1795818628503569451-3.json and hashmap-tests-native.log.

  • A test-only paired benchmark compared the candidate with the exact merge-base loop in one process. Median encoding times improved by approximately 18–39% for the tested fixed-width and float cases; the varchar control was essentially unchanged. All cases reported zero allocations: checks/1795818656253505001-3.json and paired-benchmark.log.

  • The frozen CI snapshot reports successful x86 unit, coverage, proxy, and multi-CN jobs. All three discussion keys and the claimed local receipts were reconciled in reconciliation.log.

Limitations:

  • The paired benchmark measures key encoding, not end-to-end query performance.

  • Initial local test attempts stopped on the host Go version and a missing native header; the required toolchain and native prerequisite were recovered before the passing run.

  • The pinned target includes one later, unrelated Sirius test-only commit; a combined merge result was not executed locally.

@mergify mergify Bot added the queued label Nov 27, 2026
@mergify

mergify Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as 3cc4ade at Sat 28 Nov, 00:10 UTC

1 h 36 min in the queue, 1 h 13 min of it CI.

So far

  • ✅ Entered the queue Fri 27 Nov, 22:34 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Passed · in place
  • ✅ Merged Sat 28 Nov, 00:10 · 3cc4ade · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

@mergify
mergify Bot merged commit 3cc4ade into matrixorigin:main Nov 28, 2026
37 checks passed
@mergify mergify Bot removed the queued label Nov 28, 2026
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 28, 2026
Upstream squash-merged the commits this branch stacked on (matrixorigin#33342,
matrixorigin#33343, matrixorigin#33344). The merged tree is upstream/main plus this branch's
step 7 change; the design-doc step table keeps main's row 6b and this
branch's row 7.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 28, 2026
Upstream squash-merged the commits this branch stacked on (matrixorigin#33342,
matrixorigin#33343, matrixorigin#33344, matrixorigin#33346). The merged tree is upstream/main plus this
branch's step 8 change, which applied cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 28, 2026
Picks up the step 8 branch, which now includes upstream/main (with
matrixorigin#33342, matrixorigin#33343, matrixorigin#33344 and matrixorigin#33346 squash-merged). Two uses of APIs
matrixorigin#33342 removed are updated: containers.AppendValue in mock.go becomes
Vector.MustAppendValue, and containers.Window in the decimal256 index
test becomes Vector.Window.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch was previously deployed

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

Labels

kind/enhancement size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants