Skip to content

[C++][Python] Add cached range reads for S3-compatible object storage - #1159

Merged
ColinLeeo merged 10 commits into
apache:developfrom
ColinLeeo:feat/oss-range-reader
Dec 1, 2026
Merged

ColinLeeo merged 10 commits into
apache:developfrom
ColinLeeo:feat/oss-range-reader

Conversation

@ColinLeeo

@ColinLeeo ColinLeeo commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

What changes

C++ and Python readers can open TsFiles on S3-compatible object stores. The native reader uses signed HTTP range requests, reuses connections and retries transient failures. Object keys keep their literal path segments. Each range request uses the strong ETag from HEAD so a reader cannot combine versions after an overwrite. Python accepts s3:// and oss:// URIs and exposes the endpoint, credentials and prefetch settings.

A bounded block cache coalesces small reads and reads ahead for sequential access. Python file-like and PyArrow sources also use the cache. The aligned chunk reader and Gorilla decoder reduce CPU work when materializing batches.

Local MinIO benchmark

The benchmark compared base revision 6c4ad792 and review fix 8208e183 on one 952,782,342-byte synthetic TsFile with 48 devices, 30 double fields and 4.8 million rows. The full scan materialized all fields. The narrow query returned one field and 60 rows for a single device and time range. Each latency is the median of seven measurements after a warm-up. Trials ran in randomized order over loopback HTTP, using a fresh client process and reader each time. Timing starts before opening the reader and ends after consuming the Arrow results and closing the reader. Every configuration matched the local-file result digest for both queries.

Speedup is relative to the base revision using PyArrow for the same query. Peak RSS is the median of the per-process high-water marks and includes Python, Arrow, decoded batches and the block cache. Range GET counts were collected in a separate verified pass.

TsFile version and MinIO read path Full scan (speedup) Full scan range GETs Full scan peak RSS Narrow query (speedup) Narrow query range GETs Narrow query peak RSS
Before this PR (6c4ad7922), via PyArrow S3FileSystem 31.882 s (1.00×) 59,055 176 MiB 19.32 ms (1.00×) 35 105 MiB
With this PR, via PyArrow S3FileSystem 3.804 s (8.38×) 3,462 445 MiB 7.72 ms (2.50×) 4 102 MiB
With this PR, via native S3 (background prefetch off) 2.052 s (15.53×) 3,462 439 MiB 4.33 ms (4.46×) 4 98 MiB
With this PR, via native S3 (4 background prefetch threads) 2.278 s (14.00×) 3,463 434 MiB 4.41 ms (4.38×) 4 98 MiB

The native reader used the same 256 MiB block-cache capacity in both modes. Four prefetch threads increased median latency by 11.0% for the full scan and 1.9% for the narrow query in this run. The cache increased data transferred for the narrow query from 138,354 to 1,199,622 bytes.

Same logical data in Parquet

An earlier run, before the background cache eviction fix, compared the native TsFile reader with PyArrow 19.0.1's Parquet reader on the same MinIO server. Each Parquet file had one row group per device. Both queries returned matching Arrow results. The Parquet reader used six CPU threads and four I/O threads. The TsFile reader used six decode threads and four prefetch threads.

Format and encoding Object size (decimal MB) Full scan Narrow query
TsFile 952.8 1.864 s 2.97 ms
Parquet, Snappy 1,495.1 0.827 s 8.44 ms
Parquet, Zstd level 3 1,318.1 0.730 s 8.13 ms
Parquet, Zstd level 3 with byte-stream split for doubles 835.5 0.498 s 6.94 ms

With Zstd level 3 and byte-stream split, Parquet completed the full scan 3.74× faster than TsFile. For the narrow query, TsFile was 2.33× faster than that Parquet configuration.

Verification

  • Ran the full Java, C++ and Python Maven build with LZMA2 enabled on Linux. CTest reported 1,920 passes, three fixture-dependent skips and ten disabled cases in the regular build. The three fixture-dependent cases were exercised separately. The Python suite passed 685 tests, including the native HTTP range-reader tests.
  • The Linux C++ sanitizer run recorded 1,921 passes, three fixture-dependent skips and ten disabled cases, with no AddressSanitizer errors. Clang UBSan emitted recoverable diagnostics in 21 tests at six locations in unchanged reader and codec code or SIMDe headers. The Python instrumentation check verified six native binaries, and all 15 sanitizer ownership tests passed, including the leak and use-after-free positive controls.
  • Ran the repository's encoding and compression fixture matrix. C++ validated all 1,672 Java-written fixtures, including Gorilla data. Java validated all 1,626 C++-written fixtures.
  • Spotless and Cppcheck passed. C++ and Python CodeQL analysis was repeated for the fixes. The native reader also returned all 60 reference rows from the public test fixture over HTTP/2. A worker-start fault injection verified that a failure creating the second thread propagates after joining the first worker.

Review follow-up

  • Installed static SDKs now propagate libcurl. TsFile::CURL wraps CURL::libcurl the way the bundled codecs are wrapped, so TsFileStaticDependencies-<CONFIG>.cmake emits find_dependency(CURL) and pkg-config lists libcurl under Libs.private. S3 is enabled only when find_package(CURL) defines CURL::libcurl (CMake 3.12+), so the CMake 3.11 baseline never links an unresolvable target. The installed-consumer fixture now references s3_support_available(), which makes a missing dependency fail the install test.
  • A partially specified credential pair, or a session token without keys, is rejected instead of silently sending anonymous requests.
  • s3:// and oss:// scheme names are matched case-insensitively.
  • Region derivation skips the fips, dualstack, accesspoint and object-lambda qualifier labels: s3-fips.us-east-1.amazonaws.com now derives us-east-1 instead of fips.
  • S3ReadFile::read no longer builds an error string it discards. The READMEs now say that open() reports details through error and that read() reports a generic read error after its retries.
  • The ReadCacheOptions::prefetch_threads comment describes the contiguous block group the workers actually request, and the generation fingerprint uses the real FNV-1a 64-bit offset basis.
  • CLI: no cpp/tools or java/tools change applies. The CLI opens local paths only, and the new entry points (open_s3_read_file, make_cached_read_file) are library-level APIs; s3:// support in the CLI would be a separate feature with its own option surface.

Follow-up verification

On macOS with CMake 3.31 and libcurl 8.7.1:

  • Release build with tests: 1,913 tests ran, 1,910 passed, three fixture-dependent skips and ten disabled cases.
  • After the fixes, S3SigningTest, S3RandomAccessReadFileTest, CachedRandomAccessReadFileTest and Sha256Test pass, including the new fips/dual-stack/access-point, uppercase-scheme and half-credential cases.
  • Static install round trip: configure with TSFILE_BUILD_SHARED=OFF, cmake --install, then the InstalledConsumer fixture (which now calls s3_support_available()) configures, links and runs. The binary records a libcurl.4.dylib load command, and pkg-config --static --libs libtsfile lists libcurl.
  • ./mvnw -P with-cpp verify, the CI entry point, passes: 1,922 CTest cases with 0 failures, plus Checkstyle, Spotless and RAT.
  • Python sources did not change in this follow-up; the Python suite was not rerun for this commit.

Add native s3:// and oss:// read support, plus a caching layer for sources
whose per-page reads are far more expensive than memory copies.

- CachedRandomAccessReadFile: block-aligned LRU cache with adaptive
  sequential read-ahead, single-flight loads, a thread-local single-block
  fast path that serves most reads without the cache lock, and optional
  background prefetch workers that fetch contiguous block groups in
  parallel for native object-storage sources.
- Native S3/OSS backend over libcurl (ENABLE_S3, on when libcurl is
  found): SigV4 signing backed by an in-tree SHA-256/HMAC, connection
  pooling, retries with backoff, anonymous access, s3:// and oss:// URI
  parsing, and region derivation from the endpoint host.
- Python: TsFileReader("s3://bucket/key", s3={...}) with TSFILE_S3_* /
  AWS_* environment fallbacks, s3_available(), and read_cache_* config
  keys; opening an object releases the GIL while the HEAD request runs.
- Reader: group parallel value-column decode tasks per worker instead of
  one task per column, count null-bitmap prefixes byte-wise, and add a
  two-bit control peek plus a single-run fast path to Gorilla batch decode.
- Docs, unit and integration tests, and CI dependency updates for libcurl.

Verified locally: 1896 C++ tests and 677 Python tests pass; clang-format
and Black checks are clean.
Export libcurl from static installs: wrap CURL::libcurl in a TsFile::CURL
interface target, enable S3 only when that target exists, and let
TsFileStaticDependencies and pkg-config record the link requirement. The
installed-consumer fixture now references s3_support_available(), so a
missing dependency fails the install test.

Also reject a half-specified credential pair instead of sending anonymous
requests, match s3:// and oss:// schemes case-insensitively, skip
fips/dualstack/accesspoint/object-lambda qualifier labels when deriving the
region, and drop the read() diagnostic that was formatted and discarded.
Correct the prefetch comment and the FNV-1a offset basis, and cover the
fixes with unit tests.
@ColinLeeo
ColinLeeo requested a max review from Copilot November 30, 2026 16:03

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Copilot AI 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.

Comment thread python/tsfile/python_s3_read_file.cc Resolved
Comment thread python/tsfile/python_s3_read_file.cc Resolved
Comment thread cpp/src/file/s3_signing.cc Resolved
Comment thread cpp/src/file/s3_signing.cc Resolved
Comment thread cpp/src/reader/aligned_chunk_reader.cc Resolved
Comment thread python/tests/test_s3_reader.py Resolved
Comment thread python/tsfile/python_s3_read_file.cc Resolved

Copilot AI 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.

Copilot AI 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.

🔵 Needs a closer look

Exported-struct growth risks out-of-bounds access in existing binaries, while unsynchronized reader operations allow concurrent calls or close() to free native state still in use.

No open issues 🎉

5 previously missed issues

In code that hasn't changed since last review

High severity Preserve ConfigValue ABI by keeping cache settings outside the struct

cpp/​src/​common/​config/​config.h:95

Adding these members enlarges the exported ConfigValue while the shared-library ABI version remains 1. An existing Linux executable may reserve the old size for g_config_value_ through an ELF copy relocation, leaving the new library's cache-field accesses outside that storage. Keep the settings outside this struct behind accessors, following cpp/src/common/global.h:221–226, and update the Python bindings and bridges to use them.

High severity Synchronize reader operations while the GIL is released

python/​tsfile/​python_reader_source.h:88

These GIL releases let another thread mutate or close the same reader while a native operation is still running. Concurrent metadata queries can free an arena buffer still being filled, and concurrent close() can delete the reader and source in use. Protect complete reader operations, including metadata result copying, query-executor replacement and close(), with per-reader synchronization that releases the GIL while waiting.

Medium severity Install curl development headers in the shared SDK build hook

.github/​workflows/​wheels.yml:129

This installs the curl development package only for development wheels; .github/workflows/native-packages.yml:1334–1336 invokes the same SDK hook without this step, and that hook also omits libcurl-devel. Release builds without those headers silently disable native S3 because CURL discovery is optional. Move this prerequisite into packaging/scripts/build_python_sdk.sh so development and release wheels build the same backend.

Medium severity Do not infer the S3 region from global acceleration endpoints

cpp/​src/​file/​s3_signing.cc:239

Not every s3-* AWS hostname encodes a region. For the valid S3 Transfer Acceleration endpoint s3-accelerate.amazonaws.com, this returns accelerate, so a signed request without an explicit region is sent with an invalid credential scope and fails. Exclude global service qualifiers such as accelerate and require the caller to provide the bucket's actual region when it cannot be derived.

Medium severity Reject incomplete explicitly supplied credential sets

python/​tsfile/​s3.py:116

A single explicitly empty credential field is accepted as anonymous access: for example, {"access_key_id": ""} or {"session_token": ""} discards otherwise valid environment credentials and sends unsigned requests. Reject any explicitly specified credential set unless both key fields are present; the explicit anonymous form can still be two empty keys.

3 resolved since last review

Review effort: Max

@ColinLeeo
ColinLeeo merged commit f7a60f1 into apache:develop Dec 1, 2026
49 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants