TsFile C++ batch read/write optimization#823
Open
ColinLeeo wants to merge 1 commit into
Open
Conversation
Brings together batch decode infrastructure, multi-value aligned read, parallel page decode, columnar tablet write, and SIMD micro-optimizations from the long-lived `final` branch into a single review-ready change. This change is a code snapshot, not a replay of `final` commit history -- the upstream history was a long sequence of WIP commits that wasn't fit for review. Supersedes #749, #754, #774. Read path - Decoder base gains batch APIs (read_batch_int32/int64/float/double, skip_*); PLAIN, TS2DIFF, Gorilla decoders implement them. TS2DIFF has block-level peeking so time filters can skip blocks without decoding. Gorilla adds a raw-pointer GorillaBitReader that bypasses ByteStream overhead. - ChunkReader / AlignedChunkReader add *_DECODE_TV_BATCH methods that decode time + value into a TsBlock in one pass, applying batch time filters before append. - AlignedChunkReader supports a multi-value mode: one time chunk + N value chunks decoded in a single pass, sharing the decoded timestamps and filter mask. SingleDeviceTsBlockReader auto-detects same-device measurements via VectorMeasurementColumnContext. - Optional page-level parallel decompression via a DecodeThreadPool + BlockingQueue when ENABLE_THREADS is set. Page-plan classification (SKIP / FULL_PASS / BOUNDARY) lets a scatter-free memcpy fast path fire when every row passes and no column has nulls. Write path - ValuePageWriter gains write_batch / write_string_batch that take timestamp+value+nullness arrays directly, removing the per-value append loop. Tablet exposes set_timestamps / set_column_values / set_column_string_repeated / reset for bulk reuse and switches StringColumn to an Arrow-compatible offset+buffer layout. - TS2DIFFEncoder::flush now packs all deltas with a single pack_bits_msb + write_buf instead of per-value write_bits, falling back to the scalar path for the rare bit_width > 56 case. - Int64Statistic::update_batch (NEON-accelerated min/max/sum). Encoding / SIMD - TS2DIFF batch decode adds AVX2 helpers via SIMDe (already on develop) for both i32 and i64; scalar fallback unchanged. - PLAIN byte-swap path uses ARM NEON (vrev64q_u8 / vrev32q_u8) when available, falling back to __builtin_bswap. - CMakeLists adds ENABLE_SIMD and turns on -O3 -march=native -flto in Release builds. Allocator / ByteStream - ByteStream caches page_mask_ (= page_size - 1) so the hot path uses a bitmask instead of modulo; wrap_from rounds buffer sizes up to a power of two so the mask remains correct. total_size_ widened to uint64_t to support files > 4GB. - UncompressedCompressor now copies its output instead of aliasing caller buffers, letting callers free input safely. C wrapper / Arrow - Trimmed unused metadata-export surface (TsFileStatisticBase, TimeseriesMetadata, DeviceTimeseriesMetadataEntry, tag-filter handles) out of the public C API. Internal tag filtering is unaffected. - arrow_c.cc simplified: per-row offset handling for sliced variable-length arrays in place of the InvertArrowBitmap copy. Tests / benchmarks - New tsfile_reader_table_batch_test.cc covers the TsBlock batch read path. gorilla_codec_test.cc adds Int32/Int64/Float batch decode tests. examples/cpp_examples adds bench_read.cpp/.h and an examples/read_perf_compare/ target. - Removed cwrapper_metadata_test.cc and common/path.cc (Path bodies inlined into path.h; the C metadata API they covered is gone). Compatibility - All new C++ methods are additions; no existing C++ API was removed. - C wrapper headers lost the metadata export / tag filter symbols listed above -- downstream callers (Python wrapper in particular) will want a sanity check before merge. - cpp/third_party/ intentionally left at develop's state so the recent MSVC compatibility fixes (WITH_STATIC_CRT OFF, CMP0054 NEW, CMAKE_POLICY_VERSION_MINIMUM=3.5, _MSC_VER guards) are preserved. Verification - cmake configure + make -j on macOS arm64 (AppleClang, C++11) builds cleanly: libtsfile.2.2.1.dev.dylib and TsFile_Test both link, zero errors, only unused-lambda-capture warnings in pre-existing tests. - Full TsFile_Test run and downstream Python binding load are left as pre-merge checks. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Brings together batch decode infrastructure, multi-value aligned read, parallel page decode, columnar tablet write, and SIMD micro-optimizations from the long-lived
finalbranch into a single review-ready change.This PR is a code snapshot, not a replay of
final's commit history — the upstream history was a long sequence of WIP commits that wasn't fit for review. Squashed into a single commit on purpose.Supersedes #749, #754, #774.
Changes by area
Read path
Decoderbase class gainsread_batch_int32/int64/float/doubleandskip_*APIs; PLAIN, TS2DIFF, and Gorilla decoders implement them. TS2DIFF exposes block-level peeking so time filters can skip whole blocks without decoding. Gorilla adds a raw-pointerGorillaBitReaderthat bypasses ByteStream overhead in the hot loop.ChunkReader/AlignedChunkReaderadd*_DECODE_TV_BATCHmethods that decode time + value into aTsBlockin one pass and apply batch time filters before append.AlignedChunkReadersupports one time chunk + N value chunks decoded in a single pass, sharing decoded timestamps and the filter mask.SingleDeviceTsBlockReaderauto-detects same-device measurements viaVectorMeasurementColumnContext.ENABLE_THREADSis set aDecodeThreadPool+BlockingQueuecan decompress and predecode pages in parallel. Page-plan classification (SKIP/FULL_PASS/BOUNDARY) lets a scatter-freememcpyfast path fire when every row passes and no column has nulls.Write path
ValuePageWriter::write_batch/write_string_batchtake timestamp + value + nullness arrays directly, removing the per-value append loop.Tabletexposesset_timestamps,set_column_values,set_column_string_repeated,resetfor bulk reuse, and switchesStringColumnto an Arrow-compatible offset + buffer layout.TS2DIFFEncoder::flushpacks all deltas with a singlepack_bits_msb+write_bufinstead of per-valuewrite_bits, falling back to the scalar path for the rarebit_width > 56case.Int64Statistic::update_batchadds NEON-accelerated min/max/sum.g_config_value_.parallel_write_enabled_controls whetherTsFileWriter::write_tabledispatches per-columnChunkWritertasks to a thread pool. On by default.Encoding / SIMD
vrev64q_u8/vrev32q_u8) when available, with__builtin_bswapas fallback.cpp/CMakeLists.txtaddsENABLE_SIMDand turns on-O3 -march=native -fltoin Release.Allocator / ByteStream
ByteStreamcachespage_mask_(= page_size − 1) so the hot path uses a bitmask instead of modulo;wrap_fromrounds buffer sizes up to a power of two so the mask remains correct.total_size_widened touint64_tto support files > 4 GB.UncompressedCompressornow copies its output instead of aliasing caller buffers, letting callers free the input safely.C wrapper / Arrow
TsFileStatisticBase,TimeseriesMetadata,DeviceTimeseriesMetadataEntry, tag-filter handles) out of the public C API. Internal tag filtering is unaffected.arrow_c.ccsimplified: per-row offset handling for sliced variable-length arrays in place of theInvertArrowBitmapcopy.Correctness fixes uncovered while validating this PR
These were independent latent bugs surfaced (via ASan +
TestNullInTable4/WriteDataWithEmptyField) while bringing this change into a green state. All small, defensive, no behavior change for the happy path:save_first_page_datadouble-free (all three ChunkWriters).get_cur_page_data()returns a shallow copy ofPageData;save_first_page_datawas caching that copy intofirst_page_data_while the sourcePageWriter::cur_page_data_kept the samecompressed_buf_/uncompressed_buf_pointers. On destroy both holders calledmem_freeon the same allocation. Fixed by addingPageWriter::release_cur_page_data()(nulls source pointers without freeing) and calling it from eachsave_first_page_dataafter the copy.SnappyCompressor/LZ4Compressorafter_compressfreed the wrong pointer. Both implementations didmem_free(compressed_buf_)(the cached member) instead ofmem_free(compressed_buf)(the parameter the caller is releasing). When the same compressor is reused across pages, the member can lag behind the caller-known buffer; the wrong free would either nuke a still-live allocation or crash onmem_free(nullptr). Fixed to free the parameter and only null the member when it still matches.Tests / benchmarks
tsfile_reader_table_batch_test.cccovers the TsBlock batch read path.gorilla_codec_test.ccaddsInt32BatchDecode/Int64BatchDecode/FloatBatchDecodetests.examples/cpp_examples/bench_read.cpp+.handexamples/read_perf_compare/for benchmarking.cwrapper_metadata_test.cc(covered the removed C metadata API) andcommon/path.cc(Path member bodies inlined intopath.h).Compatibility notes
cpp/third_party/is intentionally left at develop's state so the recent MSVC compatibility fixes (WITH_STATIC_CRT OFF,CMP0054 NEW,CMAKE_POLICY_VERSION_MINIMUM=3.5,_MSC_VERguards) are preserved.Verification
cmakeconfigure +make -jon macOS arm64 (AppleClang, C++11) builds cleanly:libtsfile.2.2.1.dev.dylibandTsFile_Testboth link, zero errors, onlyunused-lambda-capturewarnings in pre-existing tests.TsFile_Testfull run on macOS arm64 (Release): 496/496 tests pass (~91 s).TsFileTableReaderTest.TestNullInTable3fails when run alongside otherTestNullInTable*cases but passes in the full suite). These are not regressions from this PR — they exist onfinalanddevelopboth — but worth filing as a follow-up so isolatedctest -Rruns are deterministic.Test plan
TsFile_Testand confirm the existing suites still passlibtsfilebench_readagainst develop baseline; spot-check the throughput claims from Read Opt. #754🤖 Generated with Claude Code