Skip to content

Latest commit

 

History

History
359 lines (279 loc) · 14.8 KB

README.md

File metadata and controls

359 lines (279 loc) · 14.8 KB

TsFile Python Document

TsFile Logo

Introduction

This directory contains the Python implementation of TsFile. The Python version is built on the CPP version and uses the Cython package to integrate TsFile's read and write capabilities into the Python environment. Users can read and write TsFile as easily as they use read_csv and write_csv in Pandas.

The source code can be found in the ./tsfile directory. Files ending with .pyx are Cython wrapper code, and tsfile/__init__.py exports the public API together with the pure-Python modules (constants.py, schema.py, tablet.py, tsfile_table_writer.py, and the dataset/ package). You can find an example of reading and writing in examples/example.py.

How to make contributions

Using pylint to check Python code is recommended. However, there is no suitable style checking tool for Cython code, and this part of the code should be consistent with the Python style required by pylint.

Feature List

  • In pywrapper, invoke the batch reading interface implemented in CPP version of TsFile.
  • Supports writing multiple DataFrames into one single TsFile.

Build

Before constructing Python version of TsFile, it is necessary to build CPP version of TsFile first, because Python version of TsFile relies on the shared library files provided by CPP version of TsFile.

Build by mvn in root directory:

mvn -P with-cpp,with-python clean verify

Build by python command:

python setup.py build_ext --inplace

Sanitizer builds

To build the C++ library and every Python native extension with AddressSanitizer/LeakSanitizer and run the ownership scenarios in isolated subprocesses, see SANITIZER.md:

./mvnw -P with-python -Dtsfile.sanitizer=address -Dbuild.type=RelWithDebInfo \
  -Dbuild.test=OFF clean test-compile

Dataset read resource limits

TsFileDataFrame accepts keyword-only resource options when use_index=True:

from tsfile import TsFileDataFrame

with TsFileDataFrame(
    ["part1.tsfile", "part2.tsfile"],
    use_index=True,
    max_prepared_series=32,
    descriptor_cache_size=32,
    max_open_files=16,
    query_workers=4,
) as frame:
    values = frame[0][:]
Parameter Environment variable Default Allowed values
max_prepared_series TSFILE_DATAFRAME_MAX_PREPARED_SERIES 4096 Integer >= 0
descriptor_cache_size TSFILE_DATAFRAME_DESCRIPTOR_CACHE_SIZE 4096 Integer >= 0
max_open_files TSFILE_DATAFRAME_MAX_OPEN_FILES 16 Integer >= 1
query_workers TSFILE_DATAFRAME_QUERY_WORKERS min(4, os.cpu_count() or 1) Integer >= 1
query_parallel_min_rows TSFILE_DATAFRAME_QUERY_PARALLEL_MIN_ROWS 8192 Integer >= 1

An explicit parameter takes precedence over its environment variable. None uses the environment variable, or the built-in default if it is unset. Options are resolved once when constructing the frame; later environment changes do not affect it. Subsets share their parent's runtime and limits. Invalid values raise an error before dataset files or indexes are opened. Explicit resource options require use_index=True; the default non-indexed mode ignores these environment variables.

The prepared-series cache retains parsed native series metadata. It evicts the least recently used idle entries and releases their native handles. Active queries and dependent series pin shared time metadata, so the entry count can temporarily exceed the limit until those queries finish. This is an entry-count limit per runtime, not a process-wide memory limit. A value of 0 disables retention after use. descriptor_cache_size bounds each of the named-descriptor and series-route caches; 0 disables both. max_open_files bounds open readers, and query_workers=1 runs query groups serially. Multiple runtimes or worker processes have separate limits.

File-level properties

TsFileWriter and TsFileTableWriter accept binary properties while they are open. The setter accepts bytes only. Readers return dict[str, bytes | None], preserving null and empty values separately.

with TsFileWriter("example.tsfile") as writer:
    writer.add_tsfile_property("binary-property", b"\x01\x00\xff")

with TsFileReader("example.tsfile") as reader:
    properties = reader.get_tsfile_properties()

Values do not carry a data type; use an explicit portable encoding when storing numbers or structures.

Dataset indexes

Enable the persistent dataset index with use_index=True. The first open builds the index; subsequent opens reuse it. By default, trust_index=True assumes the indexed TsFiles will not change and skips source file size, modification time, and generation checks during index loading and queries. Index format and locator bounds are always checked.

from tsfile import TsFileDataFrame

with TsFileDataFrame("dataset/", use_index=True) as dataset:
    series = dataset[0]

# Check source generations when loading the index and acquiring readers.
with TsFileDataFrame("dataset/", use_index=True, trust_index=False) as dataset:
    series = dataset[0]

With trust_index=False, a stale index is rebuilt when the dataset opens; changes detected while acquiring a query reader raise an error. trust_index is keyword-only and has no effect when use_index=False, which remains the default.

Local File Read Backend

Python readers inherit the process-wide backend setting when they open a file. PREAD is the default to preserve the traditional positioned-read behavior, MMAP requires memory mapping, and AUTO prefers mapping with a fallback to PREAD.

from tsfile import FileReadBackend, TsFileReader, set_file_read_backend

set_file_read_backend(FileReadBackend.MMAP)
with TsFileReader("example.tsfile") as reader:
    ...

# The configuration-dictionary API is equivalent.
from tsfile import set_tsfile_config
set_tsfile_config({"file_read_backend_": FileReadBackend.AUTO})

The setting only affects readers opened afterward. Do not modify or truncate a file while it is open through the memory-mapped backend.

For large column scans on local files, MMAP (or AUTO) avoids one page-cache copy per page read and measured about 25% higher scan throughput than the default PREAD path in our profiling runs; remote sources are unaffected.

Parallel read, write and worker pool

from tsfile import (
    get_parallel_read_enabled,
    set_parallel_read_enabled,
    set_parallel_write_enabled,
    set_thread_count,
)

set_parallel_read_enabled(False)   # applies to subsequent reads
set_parallel_write_enabled(True)
set_thread_count(4)                # 1..64; applies immediately
print(get_parallel_read_enabled())

The switches and the worker pool are read without synchronization, so set them before starting queries or writes. set_thread_count() must not be called while a reader, writer or result set is in use. All three values are also available through get_tsfile_config() / set_tsfile_config() as parallel_read_enabled_, parallel_write_enabled_ and thread_count_.

Seekable binary file objects

TsFileReader also accepts a seekable binary file object. This allows remote files opened by libraries such as fsspec to be read without first copying the whole file to local storage.

import fsspec
from tsfile import TsFileReader

with fsspec.open("s3://bucket/example.tsfile", "rb") as source:
    with TsFileReader(source) as reader:
        result = reader.query_table("table_name", ["column_name"])

The object must provide seek(), tell(), and explicitly sized binary read(size) operations. The caller owns the object: TsFileReader keeps it alive while in use, preserves its cursor position, and does not close it. The local FileReadBackend setting does not apply to file objects.

File-object sources are served through a block cache, so a remote object is read in block-sized ranges with sequential read-ahead instead of one small request per page header or page. A full scan issues roughly file_size / block_size requests. The cache is configured process-wide through get_tsfile_config() / set_tsfile_config() and applies to readers opened afterwards:

Key Default Meaning
read_cache_enabled_ True Serve file-object sources through the block cache
read_cache_block_size_ 262144 Block size in bytes, clamped to 4 KiB..64 MiB
read_cache_capacity_ 268435456 Per-reader byte budget shared by cached blocks and in-flight transfers; below one block disables the cache
read_cache_max_readahead_blocks_ 8 Maximum sequential read-ahead in extra blocks (0–64)
from tsfile import set_tsfile_config

# 1 MiB blocks, 64 MiB budget, and up to four extra blocks of read-ahead.
set_tsfile_config({
    "read_cache_block_size_": 1 << 20,
    "read_cache_capacity_": 64 << 20,
    "read_cache_max_readahead_blocks_": 4,
})

Local paths are not routed through the cache; they are served by pread/mmap.

TsFileWriter accepts a writable binary file object as well, which lets a TsFile be written straight to an object store:

import fsspec
from tsfile import TsFileWriter

with fsspec.open("s3://bucket/output.tsfile", "wb") as target:
    with TsFileWriter(target) as writer:
        writer.register_table(table_schema)
        writer.write_table(tablet)

TsFileTableWriter (the schema-bound table writer) accepts a writable file object in the same way.

The target must provide write() and tell(). When it is seekable its existing content is discarded; a forward-only stream (for example a pipe) is accepted only while it is positioned at 0. A failing flush() is reported as FileSyncError instead of being ignored. As with the reader, the caller owns the object and closes it.

Object storage (s3:// and oss://)

When the library is built with libcurl 7.42 or newer, TsFileReader can read an object using HTTP range requests and SigV4 signing. Use s3_available() to check support at runtime.

from tsfile import TsFileReader, s3_available

if s3_available():
    with TsFileReader(
        "oss://bucket/path/example.tsfile",
        s3={
            "region": "cn-beijing",
            "access_key_id": "...",
            "secret_access_key": "...",
        },
    ) as reader:
        result = reader.query_table("table_name", ["column_name"])

The s3 mapping accepts endpoint, region, access_key_id, secret_access_key, session_token, path_style, connect_timeout_ms, request_timeout_ms, max_retries and prefetch_threads (default 4). Set prefetch_threads=0 for synchronous reads. By default, oss:// uses virtual-hosted addressing and s3:// uses path-style addressing. The path_style option overrides either default. Values missing from the mapping fall back to TSFILE_S3_ENDPOINT, AWS_ENDPOINT_URL_S3, AWS_ENDPOINT_URL, TSFILE_S3_REGION, AWS_REGION, AWS_DEFAULT_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN. With an OSS or S3 region but no endpoint the reader derives the service address, including s3.oss-<region>.aliyuncs.com for Alibaba OSS and amazonaws.com.cn for AWS China. The AWS credential variables apply as a group when all credential fields are omitted. If any credential is supplied in s3, both key fields are required. Set both keys to empty strings to select anonymous access explicitly. For explicit signed access, pass the key pair and its optional session token together. Opening requires a strong ETag, and each range request uses it with If-Match. If the object changes, reopen the reader to query the new version. oss:// URIs are read through the same S3-compatible API. Partial responses must describe the requested byte range and object size. When the server sends a full response, the reader consumes bytes only through the requested end offset. Reading near the end of such an object can require transferring most of it.

Opening an object reader snapshots its cache configuration. Network reads and worker shutdown release the Python GIL. Calls on a reader and its results run one at a time. Closing the reader waits for the current call and invalidates its results. Use separate readers for concurrent queries. For signed requests to custom or S3 Transfer Acceleration endpoints, specify the bucket region. HTTP 408, 429 and transient server/transport failures can be retried; other 4xx responses end the request immediately.

Single-thread builds perform read-ahead synchronously. With thread support, object reads reuse the block cache described above and add background prefetch: while a scan moves forward, prefetch_threads workers fetch contiguous block groups in parallel, so a full scan issues roughly file_size / (block_size × max_readahead_blocks) requests with several in flight.

Repeated point queries

A batch query whose tag filter selects exactly one device caches the resolved field columns on the reader. Repeated queries for the same (table, tag filter, columns) skip the device and timeseries-index lookup; one column is served by query_prepared, several aligned columns by query_prepared_multi. The cache is an LRU bounded by TSFILE_QUERY_CACHE_SIZE (default 1024; 0 disables it), and results are unchanged. Queries that also select a TAG column, row-by-row queries, filters that select zero or several devices, and projections of 16 or more field columns keep the regular path.

reader = TsFileReader("data.tsfile")
for start, end in windows:
    with reader.query_table(
        "sensors", ["value"], start, end,
        tag_filter=tag_eq("device", "dev_a"), batch_size=4096,
    ) as result:
        ...

For explicit control, reader.prepare_table_series(table, column, tag_filter) resolves one column once and returns a handle usable with reader.query_prepared(...); reader.query_prepared_multi([...]) serves several aligned columns together. The filter must select exactly one device; otherwise the automatic cache is bypassed.