zeroshade commented on code in PR #1469: URL: https://github.com/apache/arrow-go/pull/1469#discussion_r4721800126
########## parquet/internal/cdc/chunker.go: ########## @@ -0,0 +1,489 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package cdc implements content-defined chunking, which splits Parquet data +// pages at boundaries derived from the data itself, so identical content yields +// identical pages even when it is written at different offsets. +package cdc + +//go:generate go run gearhash_gen.go + +import ( + "encoding/binary" + "fmt" + "math/bits" + "unsafe" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/endian" + "github.com/apache/arrow-go/v18/parquet" + "github.com/apache/arrow-go/v18/parquet/file" +) + +// Chunk is a run of consecutive levels, and the value slots they cover, that +// belong in the same data page. +type Chunk struct { + LevelOffset int64 + ValueOffset int64 + NumLevels int64 + NumValues int64 +} + +// Chunker splits a column's data into content-defined chunks. +type Chunker struct { + minSize int64 + maxSize int64 + mask uint64 + + // state is column-global: it is never reset between calls, so chunking can + // continue across successive writes. + state state +} + +// state is the part of the chunker that changes while rolling. The chunking +// loops work on a local copy that is passed to the helpers by value, which lets +// the compiler keep it in registers: it must keep at most 4 fields and never +// have its address taken. +type state struct { + hash uint64 + nthRun int + size int64 + matched bool +} + +// NewChunker validates opts and returns a Chunker that uses them. +func NewChunker(opts parquet.CDCOptions) (*Chunker, error) { + mask, err := calculateMask(opts.MinChunkSize, opts.MaxChunkSize, opts.NormLevel) + if err != nil { + return nil, err + } + return &Chunker{ + minSize: opts.MinChunkSize, + maxSize: opts.MaxChunkSize, + mask: mask, + }, nil +} + +// calculateMask derives the boundary mask from the chunk size bounds, aiming +// for an average chunk size of (minSize+maxSize)/2 after skipping minSize bytes. +func calculateMask(minSize, maxSize int64, normLevel int) (uint64, error) { + if minSize < 0 { + return 0, fmt.Errorf("%w: cdc: min chunk size must be non-negative, got %d", arrow.ErrInvalid, minSize) + } + if maxSize <= minSize { + return 0, fmt.Errorf("%w: cdc: max chunk size must be greater than min chunk size, got min %d and max %d", arrow.ErrInvalid, minSize, maxSize) + } + target := uint64((maxSize - minSize) / 2 / numGearTables) + maskBits := max(bits.Len64(target)-1, 0) + effectiveBits := maskBits - normLevel + if effectiveBits < 1 || effectiveBits > 63 { + return 0, fmt.Errorf("%w: cdc: the number of bits in the CDC mask must be between 1 and 63, got %d", arrow.ErrInvalid, effectiveBits) + } + return ^uint64(0) << (64 - effectiveBits), nil +} + +// roll feeds the bytes of one value into the rolling hash. While the current +// chunk is still below the minimum size the hash is left untouched. +func (c *Chunker) roll(s state, value []byte) state { + s.size += int64(len(value)) + if s.size < c.minSize { + return s + } + table, mask := &gearTables[s.nthRun], c.mask + for _, b := range value { + s.hash = s.hash<<1 + table[b] + s.matched = s.matched || s.hash&mask == 0 + } + return s +} + +// rollLevel feeds a definition or repetition level, as 2 little-endian bytes. +func (c *Chunker) rollLevel(s state, level int16) state { + s.size += 2 + if s.size < c.minSize { + return s + } + table := &gearTables[s.nthRun] + h1 := s.hash<<1 + table[byte(level)] + s.hash = h1<<1 + table[byte(uint16(level)>>8)] + s.matched = s.matched || h1&c.mask == 0 || s.hash&c.mask == 0 + return s +} + +// needNewChunk reports whether a chunk boundary should be placed before the +// value that was just rolled. A boundary needs the mask to match numGearTables +// times, each time with a different gear table, which approximates a normal +// distribution of chunk sizes. The maximum chunk size is a hard limit. The +// rolling hash is deliberately never reset. +func (c *Chunker) needNewChunk(s state) (state, bool) { + if s.matched { + s.matched = false + s.nthRun++ + if s.nthRun >= numGearTables { + s.nthRun = 0 + s.size = 0 + return s, true + } + } + if s.size >= c.maxSize { + s.size = 0 + return s, true + } + return s, false +} + +// chunkList collects the chunks of one Chunks call. +type chunkList struct { + chunks []Chunk + prevOffset int64 + prevValueOffset int64 +} + +// cut ends the current chunk before the given level and value slot. A cut at +// the very first level yields an empty chunk. +func (l *chunkList) cut(offset, valueOffset int64) { + l.chunks = append(l.chunks, Chunk{l.prevOffset, l.prevValueOffset, offset - l.prevOffset, valueOffset - l.prevValueOffset}) + l.prevOffset, l.prevValueOffset = offset, valueOffset +} + +// finish ends the last chunk, unless it would be empty, and returns the chunks. +func (l *chunkList) finish(numLevels, numValues int64) []Chunk { + if l.prevOffset < numLevels { + l.cut(numLevels, numValues) + } + return l.chunks +} + +// valueSource gives access to the values of one Chunks call. Fixed-width values +// of 1, 2, 4 or 8 bytes are read as words, so that the chunking loops can roll +// them inline; every other type is rolled by the roll function. +type valueSource struct { + data []byte // raw value buffer, read by word when width > 0 + width int // byte width of a word value, or 0 when roll is used + roll func(s state, i int64) state // rolls the value in slot i + // required, when set, chunks the n values of a column without levels in a + // loop specialized for the value type. + required func(n int64) []Chunk +} + +// word returns the value in slot i. It is rolled least significant byte first, +// hashing its little-endian bytes: what Arrow C++ hashes on little-endian hosts. +func (v valueSource) word(i int64) uint64 { Review Comment: Nit: worth a comment that 8-byte multi-field types (e.g. `DAY_TIME` intervals) hash different bytes on big-endian hosts than on little-endian ones, since the word is read as a single native `uint64`. `pqarrow` doesn't write those types today, so a comment is enough. ########## parquet/pqarrow/encode_arrow.go: ########## @@ -369,10 +389,56 @@ func WriteArrowToColumn(ctx context.Context, cw file.ColumnChunkWriter, leafArr } }() - if leafArr.DataType().ID() == arrow.DICTIONARY { - return writeDictionaryArrow(arrCtx, cw, leafArr, defLevels, repLevels, maybeParentNulls) + write := func(values arrow.Array, defLevels, repLevels []int16) error { + if values.DataType().ID() == arrow.DICTIONARY { + return writeDictionaryArrow(arrCtx, cw, values, defLevels, repLevels, maybeParentNulls) + } + return writeDenseArrow(arrCtx, cw, values, defLevels, repLevels, maybeParentNulls) + } + + if chunker == nil { + return write(leafArr, defLevels, repLevels) } - return writeDenseArrow(arrCtx, cw, leafArr, defLevels, repLevels, maybeParentNulls) + + // Every column writer of the file package ends pages this way; it isn't part + // of the ColumnChunkWriter interface so that other implementations still fit. + pager, ok := cw.(interface{ FlushCurrentPage() error }) + if !ok { + return fmt.Errorf("%w: pqarrow: content-defined chunking needs a column writer that can end pages, got %T", arrow.ErrNotImplemented, cw) + } + chunks, err := chunker.Chunks(colLevelInfo, defLevels, repLevels, leafArr) + if err != nil { + return err + } + + // writeChunk writes the levels and values of one chunk. Its deferred + // Release frees the value slice even when the write panics. + writeChunk := func(chunk cdc.Chunk) error { + var chunkDef, chunkRep []int16 + if defLevels != nil { + chunkDef = defLevels[chunk.LevelOffset : chunk.LevelOffset+chunk.NumLevels] + } + if repLevels != nil { + chunkRep = repLevels[chunk.LevelOffset : chunk.LevelOffset+chunk.NumLevels] + } + values := array.NewSlice(leafArr, chunk.ValueOffset, chunk.ValueOffset+chunk.NumValues) + defer values.Release() + return write(values, chunkDef, chunkRep) + } + + // A page ends between consecutive chunks; an empty first chunk only ends the + // page left open by the previous write. + for i, chunk := range chunks { + if i > 0 { + if err := pager.FlushCurrentPage(); err != nil { + return err + } + } + if err := writeChunk(chunk); err != nil { Review Comment: Nit: an empty first chunk now goes through `write` with zero levels and values (the previous version skipped it). It's harmless and tests pass, but an `if chunk.NumLevels > 0` guard would avoid sending a zero-length write down the dense/dictionary paths. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
