Skip to content

feat(vector): add shared dictionary storage and row selections - #32394

Merged
XuPeng-SH merged 19 commits into
matrixorigin:mainfrom
aunjgr:feat/dictionary-vector-core
Nov 9, 2026
Merged

XuPeng-SH merged 19 commits into
matrixorigin:mainfrom
aunjgr:feat/dictionary-vector-core

Conversation

@aunjgr

@aunjgr aunjgr commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Closes #32383. Part of #32379.

What this PR does / why we need it:

Adds in-memory dictionary vectors with immutable shared bases and validated int64 row selections. Composed selections reference one base and preserve row order, repeated rows, NULL/grouping state, string provenance and prepared-value metadata. Empty output retains no payload backing.

Stores the dictionary descriptor through the existing data lease, preserving main's Vector field layout and 480-byte header allocation on the pinned amd64 Go profile. The descriptor has its own reference count, prevents resurrection after final release, and releases its base and selection exactly once. Retained backing estimates are counted once.

Promotes exclusively owned payload into existing buffer leases and keeps its physical allocation charge until final release. External decoder/cache backings use the existing capacity lease for full-backing pin admission; a refused pin falls back to accounted materialization, including a small selected copy when a full base copy cannot fit.

Provides fixed-width and varlen read views plus explicit transactional flattening and copy-on-write. Physical accessors reject dictionaries without allocating implicitly. Serialization uses the existing flat/constant formats. Readers preserve accepted legacy class-2 row buffers by decoding them as flat vectors across whole-column, copied, streaming, V1 and object-window paths. This foundation enables no SQL dictionary producers; consumer migration and producer enablement follow separately.

Design

Implements the representation/ownership stage of the reviewed series design. The approved lease-backed ownership revision is recorded in docs/design/dictionary-vector-core.md.

Validation

Focused tests cover composition, repeated/reordered rows, constants, NULL/grouping, inline/area strings, provenance, source reuse, legacy aliases, external pin admission/refusal, selected fallback, allocation failure, physical-access boundaries, serialization rejection, legacy class-2 read compatibility and object-window cleanup. Retained-holder, non-resurrection, overflow and concurrent-release cases prove the descriptor lifecycle. The checked empty physical-column regression remains covered.

Vector, batch, Arrow and multi_update owning-package checks pass. Focused shared-owner race stress and the vector owning-package race check pass. Reflection and an escaped-header allocation probe match main: 480 bytes, 33 fields, 480 B/op. Changed-code coverage is checked with the CI parser against the unchanged 75% gate; current results are appended as comments. The optimized service builds with Go 1.27.1, and the full repository static gate passes.

Performance acceptance remains isolated main versus this foundation, all Q1–Q22 plus Total, five independent process pairs per SF10/SF100 memory/disk profile, cold full suites excluded, no spill/swap/OOM, Holm query checks and a separate Total check. Source-pinned results and any remaining blockers are appended as comments. No producer speedup or Q6 root-cause claim is made here.

This comment has been minimized.

This comment has been minimized.

This comment has been minimized.

This comment has been minimized.

@aunjgr aunjgr changed the title Add immutable dictionary vector storage and read views feat(vector): add shared dictionary storage and row selections Nov 9, 2026

aunjgr commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the reported P2 in ac5af16c4c3c13136480dcc2a2c6e5fb05323c72 using the requester-approved compatibility design: valid legacy class-2 row buffers decode successfully as FLAT. These encodings contain one physical value slot per row and no dictionary base/selection. The materialized output therefore never calls SetClass(DICTIONARY) without backing. The DICTIONARY enum retains value 2.

The shared binary layout covers checked, trusted and copied reads. V1 and streaming readers normalize before installing the class, and objectio's V1/V2 window path applies the same physical interpretation. Constants and constant NULLs retain their representation. Input bytes are not rewritten, and existing unknown-class, bounds, NULL and payload validation remains in place. Real in-memory dictionaries retain their immutable base/selection contract and use explicit materialization at physical serialization boundaries.

Regression evidence: the pre-fix tests reproduced valid-input errors and both streaming/window unbacked-dictionary panics. TestLegacyClassDecodeNormalization, TestReadOneBlockAllColumnsWindowNormalizesLegacyClass and the updated dictionary round trip now pass. Tiny fixtures cover fixed-width, varlen and JSON data, NULLs, constant controls, unknown classes, whole/buffered/spill paths, input immutability, pool cleanup and spill closure.

Full vector and objectio owning suites pass with atomic coverage (1.498s and 4.999s). The CI parser reports 308/391 modified lines covered, 78.77%, against the unchanged 75% gate. The mandatory full pre-push static gate passes with zero issues after merging latest main normally. Existing sharing/race, 480-byte header and source-pinned TPC-H evidence is retained; this fix adds no row kernel, representation field, producer or format. Fresh CI is required for this head.

@XuPeng-SH

XuPeng-SH commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: ac5af16c4c3c13136480dcc2a2c6e5fb05323c72

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: ac5af16c4c3c13136480dcc2a2c6e5fb05323c72

Assessment: approve

Legacy class-2 normalization resolves the prior decoder panic while preserving compatibility. The lease-backed design reuses existing ownership/accounting and preserves Vector layout. No unresolved findings remain.

Model: gpt-6.1-sol / max

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

Validation:

  • Current-head vector and objectio suites passed: 396 and 158 top-level tests, count=1, using the supplied isolation executor. Receipts and logs are reconciled in validation-ledger.json.

  • Reviewed all 16 changed files, linked issues and 17 discussion entries; discussion-assessment.json covers every key exactly once.

  • Reused prior shared-owner race evidence after verifying unchanged implementation and dependencies apart from the enum rename.

  • Reused supplied SF10/SF100 neutral qualification and successful current CI evidence; skipped and neutral contexts were not counted as passes.

  • Isolation preflight, native provenance and final source/receipt audits passed. Source remains unchanged.

Limitations:

  • No local SQL/TPC-H campaign was run; raw benchmark samples, CI logs and coverage inputs were unavailable.

  • This foundation enables no SQL dictionary producers; consumer migration and producer enablement remain later stages.

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

mergify Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · pull request dequeued

41 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Mon 9 Nov, 17:07 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 17:48 · 1f5f52c

Reason

Pull request #32394 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

To get back in the queue

  • Push a change if one is needed: the pull request is queued again once its queue conditions match.
  • If no change is needed, tick the box below to queue it again as it is.

Merge conditions not met when it left the queue

  • any of · required by GitHub branch protection:
    • check-neutral = CI Required
    • check-skipped = CI Required
    • check-success = CI Required

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request
2 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection

Times in UTC · dashboard · how the merge queue works

@XuPeng-SH
XuPeng-SH merged commit bf08648 into matrixorigin:main Nov 9, 2026
@mergify mergify Bot added dequeued and removed queued labels Nov 9, 2026
mergify Bot pushed a commit that referenced this pull request Nov 10, 2026
…ng (#32098)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [x] Improvement
- [ ] Documentation
- [x] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Related to #30844. Part of #32379.

## What this PR does / why we need it:

Reject impossible integer-key rows in eligible unfiltered local scans before payload routing and hash probing. Collect a complete necessary domain from an independent filtered primary-key scan and propagate it through proven INNER-join equality lineage, including a component of a composite join. Existing row/block/runtime-filtered readers keep their current path; composing membership before their predicates belongs to the separate reader integration. Keep the exact join, SQL types, join order, estimates and placement unchanged.

Use one query-generation-owned Bloom filter per domain, sized from its estimate and admitted with all producer/probe scratch under the execution budget and a combined 64 MiB query cap. Publish immutable membership only after every actual source worker completes. Each target retains the strict 10% build-cardinality/probe-NDV gate, using completed source keys; stop optional construction early with PASS when every target is already unprofitable. Unknown hints, unsupported topology, partial construction and optional admission failure use ordinary execution; genuine query errors retain their outcome.

Apply completed membership in TableScan with reusable scratch and ordinary NULL/constant semantics. Preserve existing join-map readiness, cancellation and scope ownership. Remap optional annotations through the optimizer's final node compaction using node identity, then independently revalidate them before binding to actual scans. Keep unproven computed projections on ordinary execution and remove the superseded private-per-producer shuffle hook.

## Design

[Approved early-domain design and completed-cardinality amendment](https://github.com/matrixorigin/matrixone/blob/daea95132c/docs/design/20261109-early-runtime-filter-domains.md). The separate dictionary foundation is #32394; this implementation enables no dictionary producers and does not depend on it.

Current consumer-cost boundary and final-compaction implementation notes are versioned in [the implementation design](https://github.com/matrixorigin/matrixone/blob/db399919ca/docs/design/20261109-early-runtime-filter-domains.md).

## Validation

Owning planner/compiler, Bloom/runtime-domain and TableScan tests, focused lifecycle race stress, and a self-contained SQL BVT cover lineage, final node renumbering, duplicate/NULL/constant/empty keys, unsafe boundaries, independent source fanout, partial preparation, cost/budget fallback and cleanup. Live activation/work diagnostics and all benchmark evidence are appended in the conversation.

## Performance acceptance

The replacement passes the declared source-pinned [SF10 acceptance](#32098 (comment)) and [SF100 acceptance](#32098 (comment)): a confirmed Q9 memory-profile wall-time benefit at both scales, with no confirmed Q1–Q22 or Total regression in either memory/disk profile. Five independent process pairs per profile, cold full suites excluded, Holm query checks and a separate Total check. Any SF100 spill invalidates the run. Benchmark scripts execute/drain and collect resources without data/schema/row/result verification. Historical variants and their former acceptance rules remain in comments; they do not qualify this replacement.


Approved-by: fengttt <[email protected]>
Approved-by: XuPeng-SH <[email protected]>
mergify Bot pushed a commit that referenced this pull request Nov 10, 2026
…32405)

## What type of PR is this?

- [x] API-change
- [ ] BUG
- [x] Improvement
- [ ] Documentation
- [x] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Closes #32384. Part of #32379.

## What this PR does / why we need it:

Adds per-child dictionary input capabilities and explicit normalization before unsupported consumers or external roots. Only dictionary producers own conversion state: Call retires prior private output, and ExecProjection normalizes its final batch before publication. Ordinary OperatorBase layout and vm.Exec remain identical to main. Capability configuration is folded into preparation; executable operator identity and wire opcodes are preserved.

Copies selected logical rows into privately owned flat vectors without mutating borrowed input or expression-owned headers. Preserves constants, NULL/grouping, string/prepared metadata, batch markers and auxiliary payload under the declared allocation account. Protobuf encoding uses a constant's physical value count with its logical broadcast length.

Runtime cleanup detaches conversion output across producer Reset, including reset that clears producer state, then retires it after work stops. Free retires output before account disposal. Cancellation before Call uses framework terminal cleanup. Existing flat spill/network/protobuf formats and explicit serialization materialization remain in place. No production dictionary producer is enabled.

## Dependencies and design

Builds on merged #32394. The diff against main contains only the compatibility-boundary stage. The requester-approved producer-owned revision is documented in `docs/design/dictionary-vector-boundaries.md` and implemented in `540e7aa80a`.

Implements the compatibility stage of the [approved design](https://github.com/matrixorigin/matrixone/blob/adebe845cb4a77d97cf7dd0ae4b2efaf87dc224a/docs/design/20261109-dictionary-vector-execution.md). Runtime ownership and the default consumer matrix are documented in `docs/design/dictionary-vector-boundaries.md`. Draft development may stack; qualification and production readiness remain isolated after prerequisites merge.

## Validation

Focused tests cover logical row order/repetition, mixed string/constant batches, NULL/grouping and expression metadata, independent storage, explicit accounts, partial allocation failures, current/legacy/spill/protobuf boundaries, and constant NULL/empty inputs. Runtime tests cover unknown and per-child capable consumers, root output, projection, flat pass-through and terminal cleanup. A real frontend Output callback checks normalization and early-failure pipeline cleanup.

Vector, batch, VM, pipeline, dependent and compiler owning-package tests pass. Full pre-push static checks and focused lifecycle race checks are recorded in the appended validation comment.

Performance acceptance is pending. This stays draft until fresh CI and the neutral SF10/SF100 memory/disk gate pass, with all Q1–Q22 plus Total, five matched process pairs, cold suites excluded, Holm query checks and separate Total checks, and no SF100 spill. No speedup is claimed by this foundation.


Approved-by: XuPeng-SH <[email protected]>
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 24, 2026
It pinned that the checked fixed-column accessor keeps a backed empty slice
for a zero-row vector, a behavior added for the dictionary vectors of
matrixorigin#32394. That code is gone from vector, and no caller depends on the empty
view's capacity or nil-ness; ordinary accessor use is covered elsewhere.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 24, 2026
Class 2 was DIST, declared in matrixorigin#8367 but never assigned to a vector, then
DICTIONARY (matrixorigin#32394 to matrixorigin#33027), which PrepareMarshalBinary refused to
serialize. No encoder ever wrote class byte 2, so the decode-time remap of
"legacy row-buffer class 2" to FLAT defended against data that never
existed.

Remove LegacyRowBufferClass, decodedPhysicalClass and the SetClass panic;
UnmarshalBinaryV1 and objectio's legacy column reader now reject any class
above CONSTANT, and validateVectorBinary rejects class 2 like any unknown
class. Every class actually written decodes as before.

legacy_class_test.go is deleted. Its decoder round trip (fixed, varlen,
JSON, const, const NULL through UnmarshalBinary, Trusted, WithCopy, V1 and
WithReader), unknown-class rejection and the input-bytes-untouched check
move to vector_test.go as TestVectorDecodersRoundTrip. The objectio window
test drops the legacy case and is renamed TestReadOneBlockAllColumnsWindowClass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit that referenced this pull request Nov 24, 2026
## What type of PR is this?

- [x] Code Refactoring

## Which issue(s) this PR fixes:

issue #33086

## What this PR does / why we need it

Vector validated native Unicode (`utf8mb4_unicode_ci` /
`utf8_unicode_ci`) text itself, on every append **and every copy**, and
turned off several copy fast paths for Unicode columns just to keep that
check. Copies re-validated values their source vector had already
admitted. This PR moves the check to where text values are produced,
like the JSON validation removed in #33023.

**Removed from vector (`vector.go`)**
- The check in `AppendBytesWithWriter`, `BuildVarlenaFromByteSlice`
(used by `AppendBytes` / `AppendStringList`) and
`BuildVarlenaFromVarlena`.
- The Unicode-only opt-outs of fast paths: the inline copy in
`TryUnionFlatFixedRows`, the empty-area/inline branches of union, and
`canPregrowRawByteList`.

**Added at the boundaries** (an audit showed `AppendBytes` was the only
guard for these inputs)
- `FunctionResult` byte writers (`AppendBytes`, `AppendMultiBytes`,
`AppendMustBytesValue`, `AppendBytesWithWriter`). All function and cast
results go through these, including non-assignment casts (`func_cast`
only validates in assignment mode). No function writes result bytes
through vector directly.
- LOAD DATA / external text fields: new `appendFieldText` in
`external.go`.
- Parquet: `appendParquetVarlenValue` already checked UTF-8 for
CHAR/VARCHAR; it now also enforces the utf8mb3 repertoire and covers
TEXT.

Values read from storage were validated when written, and key encoding
(`serial`, `index_util`) validates on its own.

**Tests**
- Deleted `vector/collation_metadata_test.go` and
`vector/collation_value_test.go`.
- The wire-format collation metadata round trip moved into
`vector_test.go` as `TestVectorWireFormatsKeepCollationMetadata`.
- The rejection rules are now `TestValidateCollationValue` in
`pkg/container/types`.
- New `TestFunctionResultValidatesUnicodeText` and
`TestFileInputValidatesUnicodeText`. Removing each new check fails every
bad case (12 and 6 subtests).
- The function test framework's "current vector rollback" subtest used
invalid Unicode only to force a mid-construction failure; it now uses a
capped pool.

## Open question for reviewers

Copies now rely on the source vector already having the destination's
exact type. A path that unions a legacy-charset vector into a Unicode
vector without a cast would no longer be caught. The audit found no such
path, and `BuildVarlenaFromVarlena` already documented the same-type
requirement, but this is the main residual risk.

`FunctionResult` still lives in `pkg/container/vector/functionTools.go`,
so the function-result check is physically in the vector package, though
it belongs to the function framework.

## Validation

- `mo-cgo-test ./pkg/container/... ./pkg/sql/plan/function/...
./pkg/sql/colexec/... ./pkg/sql/util/... ./pkg/common/collation/...`:
pass
- `mo-cgo-test -run '^TestUnicodeCollation' ./pkg/tests/sqlintegration/`
(`TestUnicodeCollationConsumerContract`): pass
- `go build ./pkg/...`, `go vet`, `golangci-lint` on vector, types,
external, function: clean

## Second commit: remove race-detector-only code (7bafa42)

Code must behave the same with and without `-race`; a real race is a bug
to fix.

- Removed race-only switches: vector `compile_config_*.go` (+ its two
debug checks and `typed_read_typecheck_test.go`), readutil
`compile_config_{race,no_race}.go` (sorted-rowid assert), `common/util`
`build_type_{debug,release}.go` (`Debug`, `RaceDetectorEnabled`), and
group `sanityCheck` (only ran under `util.Debug`).
- Dropped every `!race` build tag and race skip from tests. `-race`
reports no data race in the affected packages. Tests the race runtime
perturbs (it drops some `sync.Pool` puts on purpose) now assert what
holds in both modes: fulltext2 counts buffers taken vs. returned;
catalog subtracts seek-key pool refills; the matmul length test allows a
small pool-refill tolerance.
- **Real fix found on the way:** `vectorMatmulParseBound` missed sonic's
pooled optdec parser (~2.1 MB) that the first vecblock-JSON decode after
a GC allocates. A cold one-query parse allocated 2,104,984 bytes against
a 30,900-byte bound. Added `vectorMatmulJSONDecoderScratch` for
JSON-format queries; `TestVectorMatmulParseBoundCoversParse` now checks
`bound >= committed config + score scratch + one parser` and a truly
cold parse, including a one-query shape. JSON-query configurations now
reserve ~2.1 MB more during the parse; only the retained configuration
stays charged.

Validation: changed packages pass in normal and `-race` runs;
vector_matmul tests in compile, plan, function and sqlintegration pass;
`golangci-lint` clean.

## Third commit: delete `fixed_col_test.go` (35ed100)

It pinned that `MustFixedColWithTypeCheck` keeps a backed empty slice
for a zero-row vector, a behavior added for the dictionary vectors of
#32394. That code is gone from vector; no caller depends on the empty
view's capacity or nil-ness, and ordinary accessor use is covered
elsewhere.

## Fourth commit: remove the never-written legacy class 2 (638b177)

Class 2 was `DIST`, declared in #8367 but never assigned to a vector,
then `DICTIONARY` (#32394 to #33027), which `PrepareMarshalBinary`
refused to serialize. No encoder ever wrote class byte 2, so decoding it
as FLAT defended against data that never existed.

- Removed `LegacyRowBufferClass`, `decodedPhysicalClass` and the
`SetClass` panic. `UnmarshalBinaryV1` and objectio's legacy column
reader reject any class above `CONSTANT`; `validateVectorBinary` rejects
class 2 like any unknown class. Every class actually written decodes as
before.
- `legacy_class_test.go` is deleted. Its valuable part moved to
`vector_test.go` as `TestVectorDecodersRoundTrip`: a round trip of
fixed, varlen, JSON, const and const-NULL vectors through all five
decoders (including `UnmarshalWithReader`, tested nowhere else),
unknown-class rejection, and a check that decoding never rewrites the
caller's input bytes.
- The objectio window test drops the legacy case and is renamed
`TestReadOneBlockAllColumnsWindowClass`.

Validation: vector and objectio packages pass in normal and `-race`
runs; `golangci-lint` clean.

## Fifth commit: merge low-precision float tests (4db2a0c)

`lowprec_const_test.go` and `lowprec_float_test.go` are combined into
`lowprec_test.go`. The tests stay: they cover vector code specific to
bf16/float16/float8/float4 (const-set and union,
`GetLowPrecisionFloatAt` used by CDC, ISCP, export and data branch, the
decoder type allowlist, and the `RowToString` helper used by
`TestRowToString`). The marshal round trip now frees its decoded vectors
and checks the pool is empty.

## Sixth commit: combine marshal tests (46f01e8)

`marshal_selection_test.go` and `marshal_bench_test.go` are merged into
`marshal_test.go`: the tests that check `UnionInt32`/`UnionOne` results
take the right marshal path (bulk for disjoint payloads, canonical for
shared const payloads) and decode to the selected rows, plus both
`MarshalBinary` benchmarks.
`TestUnionOneConstDestinationDoesNotAcquireDisjointProof` is renamed
`TestUnionOneConstDestinationStaysConst`, since the cached disjoint
proof it named was removed in #33033. The two tests that do not marshal
(`UnionOne` into a read-only window, a refused `UnionOne` allocation
keeping existing rows) move to `unionbatch_fastpath_test.go` with the
other union tests.

## Seventh commit: merge mpool tests into `mpool_test.go` (4b6a531)

`mpool_contract_test.go` (a vector allocates only from its own pool;
nil-pool vectors are read-only; windows share bytes while `CloneWindow`
and owned decodes copy) and the accounted-view fixtures from
`mpool_view_fixtures_test.go` are combined into `mpool_test.go`.
Leftovers from when vectors carried an account are dropped:
`newAccountedTestVector` was only `NewVec`, so its seven call sites call
`NewVec` directly, and the never-set `class` field of
`testVectorAllocationAccount` is replaced by
`AllocationCapacityClassDefault`.

## Eighth commit: move rollback tests into `vector_test.go` (e4eb415)

`rollback_error_test.go` is deleted; its two tests move next to
`TestAppendCheckpointRollback`.
`TestRollbackAppendRejectsBeforeMutation` checks that an invalid append
checkpoint is rejected before any mutation, with an invariant error that
callers (parquet reader, vector append paths) never classify as a
retryable capacity failure.
`TestAppendAllocatorLimitReturnsErrorAndKeepsPrefix` checks that an
allocator-limit failure keeps its sentinel through the rollback and
keeps earlier rows. A stale comment in `RollbackAppend` about keeping a
"proof" fail-closed (the cached disjoint flag removed in #33033) is
dropped.

## Ninth commit: fold `scan_followup_test.go` into `vector_test.go`
(ee64e88)

The `GetMinMaxValue` tests from #30338 move next to `TestBoolMinMax` as
`TestGetMinMaxValueFixed`, `TestGetMinMaxValueConst` and
`TestGetMinMaxValueInt64Windows`. They cover the int64 kernel for flat,
null-free columns of 32+ rows (sizes around its threshold, windows at an
offset, every value order), the bool early exit, NULL masks, read-only
backing, and that the call does not modify the vector. The
`GetMinMaxValue` benchmarks stay (`BenchmarkGetMinMaxValue`,
`BenchmarkGetMinMaxValueInt64Distributions`); the raw-loop controls, the
UTF-8 counting cases (they measure `lengthutf8`, which has its own
benchmark), and the read-only and constant variants are dropped.

## Tenth commit: unrolled min/max for every integer type and
float32/float64 (1d9ad0f)

The 4-accumulator `GetMinMaxValue` kernel was int64-only. It now covers
every integer-backed type (int8-64, uint8-64, bit, date, year, datetime,
time, timestamp, enum) through `IntegerGetMinAndMax`, and
float32/float64 through `floatMinMaxNoNull`, which uses plain
comparisons from ±Inf so NaN is skipped exactly as before (an all-NaN
column still reports no comparable value; a +0/-0 tie may report either
zero). Both apply to flat, null-free columns of at least 32 rows; the
kernels move from `scan_minmax.go` to `minmax.go`.

Four accumulators measured best among 1, 2, 4 and 8, and the reslicing
loop beat an index loop. Speedup of `GetMinMaxValue` on arm64, null-free
random columns:

| rows | int8 | int16 | int32 | int64 | float32 | float64 |
|---|---|---|---|---|---|---|
| 128 | 1.49x | 1.33x | 1.41x | 1.40x | 1.96x | 1.74x |
| 2048 | 1.54x | 1.56x | 1.34x | 1.37x | 2.51x | 2.50x |
| 65536 | 1.54x | 1.54x | 1.35x | 1.37x | 2.64x | 2.65x |

`TestGetMinMaxValueUnrolledKernels` checks all 17 types against a plain
loop (960 subtests); breaking the integer tail, the float "found" flag
or the float starting values each fails it.
`BenchmarkGetMinMaxValueByType` covers each width.

Note for a follow-up: scalar Go is at about 0.46 ns per element at every
width. A clang `-O3` C kernel via cgo measured ~40x (int8), ~10x (int32)
and ~2.5x (int64) faster at 65536 rows, but loses below a few hundred
rows and for floats, so it would need a row threshold and explicit float
handling.

## Eleventh commit: merge `search_gallop_test.go` into `search_test.go`
(382b93f)

The galloping prefix-IN tests (`CollectOffsetsByPrefixInFactory` against
the linear and merge references) and their helpers move into
`search_test.go` next to the other `search.go` tests. `search.go` itself
stays in vector: all of its functions are used by the primary-key block
filter in `readutil/pk_filter.go` and by objectio's cached-vector
search.

## Twelfth commit: drop older-writer handling from the selected-rows
codec (4701fbc)

`selection_codec.go` stays: it lets group/aggregate spill and
materialized sources write selected rows without first copying them into
a new vector, so spill can proceed when the memory budget is exhausted.
But every record is written and read by the same process within one
query, so data from an older writer cannot exist. The decoder's handling
of the retired kind, binary-string and string-source metadata fields,
the legacy ROLLUP grouping bit and their trailers is removed; NULL is
now the only defined bit and any other header or row-flag bit is
rejected. `MarshalSelectedFlagsTo`, which had no production caller, is
removed with the tests that covered only it or older-writer data.

Benchmarks (median of 6-10 runs, arm64): fixed-width encode/decode and
sparse encode unchanged; text decode unchanged to 12% faster (nullable
strings); group spill writer unchanged.

## Thirteenth commit: reorganize vector test files (7dcdae4)

Small test files are merged into the file for the code they test (24
test files become 15):

| file | now also contains |
|---|---|
| `union_test.go` (from `union_fixed_test.go`) | `union_fixed_rows`,
`unionbatch_fastpath`, `union_fixed_bench` tests |
| `append_test.go` | `append_bench_test.go` |
| `marshal_test.go` | `unmarshal_bench_test.go` |
| `search_test.go` | the `CollectOffsetsBy*` tests from `utils_test.go`
|
| `functionTool_test.go` | `function_parameter_conversion_test.go` |
| `vector_test.go` | `shrink_negate_boundary`, `area_disjoint`,
`typed_read`, `vector_narrow` tests |

`BenchmarkUnmarshal` and the one-row accessor benchmarks
(`BenchmarkToTypedSlice`, `BenchmarkToFixedCol`,
`BenchmarkMustFixedCol`) are deleted; `BenchmarkVectorUnmarshalBinary`
and `BenchmarkVectorTypedRead` cover them at scale. All other tests and
benchmarks are kept (211 functions before, 207 after: the four
benchmarks and one rename). Stale wording is fixed: the union test's
"lease" backing is now "external", "borrowed"/"lender"/"proof" comments
describe read-only vectors and computed disjointness, and
`TestVarlenaAreaIsDisjointIsComputedFromDescriptors` is renamed
`TestVarlenaAreaIsDisjointEdgeCases`. `bulk_copy_test.go` and
`clone_compact_test.go` are reworked on a separate branch and left
unchanged here.

## Fourteenth commit: drop redundant `vector_test.go` tests and split it
by topic (f1cd8ed)

Each package test was run alone with coverage. Tests in `vector_test.go`
that cover no code another test does not, and assert little beyond "no
error", are deleted: `TestLength` (it asserted a field it had just set),
`TestConst`, `TestDup`, `TestAppend`, `TestAppendBytes`,
`TestAppendArray`, `TestUnionOne`, `TestStrMarshalAndUnMarshal`,
`TestArrayMarshalAndUnMarshal` and `TestProtoVector`. Their paths are
value-checked by `union_test.go` (which uses `UnionOne` as its
reference), `marshal_test.go`, `mpool_test.go` and
`TestVectorDecodersRoundTrip` (which round-trips through proto).
`TestSize` and `TestCapacityForUntypedNull` become
`TestSizeAndCapacity`, which checks real fixed and varlena sizes.
Regression tests with no unique coverage but a specific assertion are
kept.

Topic tests move out of `vector_test.go` (5703 lines to 4025):

| Destination | Moved |
|---|---|
| `union_test.go` | union marker, metadata, preflight and capacity
tests, union benchmarks; `TestMisc` renamed `TestUnionAllFixedSizeTypes`
|
| `lowprec_test.go` | the low-precision float ordering, NaN min/max and
access tests |
| `minmax_test.go` (new) | `GetMinMaxValue` tests, fixtures and
benchmarks |

Package coverage is unchanged apart from blocks reached only by the
randomized `TestUnion2VectorVarlen`.

## Fifteenth commit: drop redundant union tests (a402266)

Same per-test coverage method as the previous commit, applied to
`union_test.go`. Deleted: `TestUnionBatchVarlenFastPath` (the no-null
twin of `TestUnionBatchNullFastPath`, which checks the same seeded
target against the same per-row `UnionOne` oracle plus nulls),
`TestUnionOneEmptyMarkerSets` (fixed-width `UnionOne` copies, checked
more thoroughly by `TestFixedSourceRowsMatchUnionOne` and
`TestUnionFixedSelection`) and
`TestUnionOneNullDoesNotClearWindowOwnerDescriptor` (windows are
read-only, so it only checked that appending to one fails, which
`mpool_test.go` covers). `TestUnionBroadcastAndPregrow` becomes
`TestUnionVarlenGatherAndBroadcast`: its full-range `UnionBatch` case
duplicated the null fast-path test, and its `AppendMultiFixed` case
moves to `append_test.go` as `TestAppendMultiFixedBroadcast`.

Tests and benchmarks named after the removed marker sets and metadata
are renamed: `TestUnionOneSourceShapes`,
`TestUnionOneAndMultiMixedSources`, `BenchmarkUnionOne`,
`BenchmarkUnionMulti`, `BenchmarkUnionBatchVarlenInline`. Package
coverage is unchanged (apart from the randomized
`TestUnion2VectorVarlen` blocks noted above).

## Sixteenth commit: drop a duplicate marshal test, move marshal tests
(c2e0d70)

`TestUnionSelectionKeepsConstVarlenaAliased` repeated the second half of
`TestUnionOneConstVarlenaCopiesIndependentPayloads` (a const selected
twice through `UnionInt32` shares its payload and marshals canonically)
and is deleted. The marshal, unmarshal and wire-format tests move from
`vector_test.go` to `marshal_test.go`:
`TestOwnedVarlenaMarshalKeepsBulkLayout`,
`TestNullableFixedWidthMarshalDoesNotCastAsVarlena`,
`TestMarshalAndUnMarshal`, `TestMarshalBinarySizeRejectsInvalidVector`,
the `TestUnmarshalBinary*` tests,
`TestVectorWireFormatsKeepCollationMetadata` and
`TestVectorDecodersRoundTrip`. Two stale comments are fixed: the
owned-varlena marshal benchmark no longer calls itself the "non-Arrow
control", and a window is described as a read-only reference that
marshals only its rows.

## Seventeenth commit: keep `unsafe` out of reorganized test files
(a60c5b5)

SCA's `checkunsafe` allows the `unsafe` import only in listed files. The
reorganization had renamed `functionTool_test.go` (listed) and moved a
min/max helper using `unsafe.Sizeof` into `minmax_test.go` (not listed).
The original file name is restored, the area-backing check compares
`&area[0]` with `require.Same`, and the signed minimum is found by
shifting 1 up to the sign bit, so neither file imports `unsafe`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Subtask]: Add dictionary vector representation and immutable ownership

3 participants