diff --git a/cpp/src/common/arrow_batch.cc b/cpp/src/common/arrow_batch.cc new file mode 100644 index 000000000..8883712d5 --- /dev/null +++ b/cpp/src/common/arrow_batch.cc @@ -0,0 +1,355 @@ +/* + * 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. + */ +#include "common/arrow_batch.h" + +#include +#include +#include +#include + +#include "common/container/bit_map.h" +#include "common/schema.h" +#include "utils/date_utils.h" + +namespace common { +ArrowColumn::ArrowColumn(TSDataType type, uint32_t capacity) + : type_(type), + capacity_(capacity), + validity_((uint64_t(capacity) + 7) / 8, 0) { + if (variable()) { + offsets_.resize(uint64_t(capacity) + 1, 0); + } else { + uint64_t size = + type == BOOLEAN + ? (uint64_t(capacity) + 7) / 8 + : uint64_t(capacity) * + (type == INVALID_DATATYPE ? 0 : get_data_type_size(type)); + values_.resize((size + 7) / 8, 0); + } +} +bool ArrowColumn::variable() const { + return type_ == STRING || type_ == TEXT || type_ == BLOB; +} +bool ArrowColumn::is_null(uint32_t row) const { + return (validity_[row / 8] & (1U << (row % 8))) == 0; +} +void ArrowColumn::set_valid(uint32_t row) { + validity_[row / 8] |= uint8_t(1U << (row % 8)); +} +void ArrowColumn::set_valid_range(uint32_t begin, uint32_t count) { + while (count && begin % 8) { + set_valid(begin++); + --count; + } + if (count >= 8) { + std::memset(validity_.data() + begin / 8, 0xff, count / 8); + begin += (count / 8) * 8; + count %= 8; + } + while (count--) set_valid(begin++); +} +const char* ArrowColumn::native_value(uint32_t row, char* scratch, + uint32_t& size) const { + size = 0; + if (is_null(row)) return nullptr; + if (variable()) { + size = offsets_[row + 1] - offsets_[row]; + return size ? bytes_.data() + offsets_[row] : ""; + } + size = get_data_type_size(type_); + if (type_ == BOOLEAN) { + bool value = + (reinterpret_cast(values_.data())[row / 8] & + (1U << (row % 8))) != 0; + std::memcpy(scratch, &value, sizeof(value)); + return scratch; + } + const char* data = values() + uint64_t(row) * size; + if (type_ == DATE) { + int32_t days; + std::memcpy(&days, data, sizeof(days)); + int32_t value = DaysSinceEpochToYYYYMMDD(days); + std::memcpy(scratch, &value, sizeof(value)); + return scratch; + } + return data; +} +int ArrowColumn::set_native(uint32_t row, TSDataType source_type, + const char* data, uint32_t size) { + if (row >= capacity_) return E_INVALID_ARG; + if (variable()) { + if (row < string_rows_) return E_INVALID_ARG; + while (string_rows_ <= row) offsets_[string_rows_++] = bytes_.size(); + if (data != nullptr) { + if (uint64_t(bytes_.size()) + size > INT32_MAX) return E_OVERFLOW; + bytes_.insert(bytes_.end(), data, data + size); + set_valid(row); + } + offsets_[row + 1] = bytes_.size(); + return E_OK; + } + if (data == nullptr) return E_OK; + char* dest = + type_ == BOOLEAN + ? nullptr + : mutable_values() + uint64_t(row) * get_data_type_size(type_); + if (type_ == BOOLEAN) { + if (size != sizeof(bool)) return E_INVALID_ARG; + bool v; + std::memcpy(&v, data, sizeof(v)); + if (v) + reinterpret_cast(values_.data())[row / 8] |= 1U + << (row % 8); + } else if (type_ == DATE) { + if (size != sizeof(int32_t)) return E_INVALID_ARG; + int32_t v; + std::memcpy(&v, data, sizeof(v)); + v = YYYYMMDDToDaysSinceEpoch(v); + std::memcpy(dest, &v, sizeof(v)); + } else if (type_ == INT64 && source_type == INT32) { + int32_t v; + std::memcpy(&v, data, sizeof(v)); + int64_t promoted = v; + std::memcpy(dest, &promoted, sizeof(promoted)); + } else if (type_ == DOUBLE && source_type == FLOAT) { + float v; + std::memcpy(&v, data, sizeof(v)); + double promoted = v; + std::memcpy(dest, &promoted, sizeof(promoted)); + } else { + if (size != get_data_type_size(type_)) return E_TYPE_NOT_SUPPORTED; + std::memcpy(dest, data, size); + } + set_valid(row); + return E_OK; +} +int ArrowColumn::copy_selected(const ArrowColumn& source, + const std::vector& rows, + uint32_t begin, uint32_t count, + uint32_t destination) { + if (uint64_t(begin) + count > rows.size() || + uint64_t(destination) + count > capacity_) + return E_INVALID_ARG; + uint32_t n = 0; + while (n < count) { + uint32_t row = rows[begin + n]; + if (row >= source.capacity()) return E_INVALID_ARG; + uint32_t run = 1; + if (!variable() && type_ != BOOLEAN && type_ == source.type_ && + !source.is_null(row)) { + while (n + run < count && rows[begin + n + run] == row + run && + row + run < source.capacity() && !source.is_null(row + run)) + ++run; + uint32_t width = get_data_type_size(type_); + std::memcpy(mutable_values() + uint64_t(destination + n) * width, + source.values() + uint64_t(row) * width, + uint64_t(run) * width); + set_valid_range(destination + n, run); + } else { + char scratch[8]; + uint32_t size; + const char* data = source.native_value(row, scratch, size); + int ret = set_native(destination + n, source.type_, data, size); + if (ret != E_OK) return ret; + } + n += run; + } + return E_OK; +} +void ArrowColumn::finish(uint32_t rows) { + if (variable()) + while (string_rows_ <= rows) offsets_[string_rows_++] = bytes_.size(); +} +ArrowBatch::ArrowBatch(const std::vector& column_names, + const std::vector& types, uint32_t capacity) + : names(column_names) { + for (auto type : types) + columns.emplace_back(new ArrowColumn(type, capacity)); +} +void ArrowBatch::finish() { + for (auto& col : columns) col->finish(row_count); +} +namespace { +const char* format(TSDataType type) { + switch (type) { + case BOOLEAN: + return "b"; + case INT32: + return "i"; + case INT64: + return "l"; + case FLOAT: + return "f"; + case DOUBLE: + return "g"; + case DATE: + return "tdD"; + case TIMESTAMP: + return "tsn:"; + case TEXT: + case STRING: + return "u"; + case BLOB: + return "z"; + default: + return "n"; + } +} +struct ArrayOwner { + std::shared_ptr batch; + const void* buffers[3] = {}; + std::vector children; + ~ArrayOwner() { + for (auto* child : children) { + if (child->release) child->release(child); + delete child; + } + } +}; +struct SchemaOwner { + std::string name; + std::vector children; + ~SchemaOwner() { + for (auto* child : children) { + if (child->release) child->release(child); + delete child; + } + } +}; +void release_array(ArrowArray* array) { + array->release = nullptr; + delete static_cast(array->private_data); + array->private_data = nullptr; +} +void release_schema(ArrowSchema* schema) { + schema->release = nullptr; + delete static_cast(schema->private_data); + schema->private_data = nullptr; +} +void init_array(ArrowArray& array, const std::shared_ptr& batch) { + auto* owner = new ArrayOwner; + owner->batch = batch; + array = {}; + array.private_data = owner; + array.release = release_array; + array.length = batch->row_count; +} +void init_schema(ArrowSchema& schema, const std::string& name, + const char* fmt) { + std::unique_ptr owner(new SchemaOwner); + owner->name = name; + schema = {}; + schema.name = owner->name.c_str(); + schema.format = fmt; + schema.flags = 2; + schema.release = release_schema; + schema.private_data = owner.release(); +} +} // namespace +int ArrowBatch::export_to(ArrowArray* array, ArrowSchema* schema) { + if (!array) return E_INVALID_ARG; + *array = {}; + if (schema) *schema = {}; + try { + finish(); + init_array(*array, shared_from_this()); + if (schema) init_schema(*schema, "", "+s"); + auto* a = static_cast(array->private_data); + auto* s = + schema ? static_cast(schema->private_data) : nullptr; + a->children.reserve(columns.size()); + if (s) s->children.reserve(columns.size()); + for (size_t i = 0; i < columns.size(); ++i) { + std::unique_ptr child(new ArrowArray{}); + a->children.push_back(child.get()); + child.release(); + if (s) { + std::unique_ptr cs(new ArrowSchema{}); + s->children.push_back(cs.get()); + cs.release(); + } + init_array(*a->children.back(), shared_from_this()); + if (s) + init_schema(*s->children.back(), names[i], + format(columns[i]->type())); + auto& col = *columns[i]; + ArrowArray& out = *a->children.back(); + auto* ca = static_cast(out.private_data); + if (col.type() != INVALID_DATATYPE) + ca->buffers[out.n_buffers++] = col.validity(); + if (col.variable()) { + ca->buffers[out.n_buffers++] = col.offsets(); + ca->buffers[out.n_buffers++] = col.bytes(); + } else if (col.type() != INVALID_DATATYPE) + ca->buffers[out.n_buffers++] = col.values(); + out.null_count = + row_count - bitops::count_valid_bits(col.validity(), row_count); + out.buffers = ca->buffers; + } + array->n_buffers = 1; + array->buffers = a->buffers; + array->n_children = a->children.size(); + array->children = a->children.data(); + if (schema) { + schema->n_children = s->children.size(); + schema->children = s->children.data(); + } + return E_OK; + } catch (const std::bad_alloc&) { + if (array->release) array->release(array); + if (schema && schema->release) schema->release(schema); + return E_OOM; + } +} +int ArrowBatch::to_tsblock(TupleDesc& desc, TsBlock*& block, + storage::TableSchema* table_schema) const { + delete block; + block = nullptr; + desc.reset(); + for (size_t c = 0; c < columns.size(); ++c) { + if (table_schema) { + desc.push_back(c == 0 ? g_time_column_schema + : table_schema->get_column_schema(names[c])); + } else { + desc.push_back(ColumnSchema( + names[c], columns[c]->type(), + c == 0 ? ColumnCategory::TIME : ColumnCategory::FIELD)); + } + } + int ret = TsBlock::create_tsblock(&desc, block, row_count); + if (ret != E_OK) return ret; + RowAppender appender(block); + for (uint32_t r = 0; r < row_count; ++r) { + appender.add_row(); + for (size_t c = 0; c < columns.size(); ++c) { + char scratch[8]; + uint32_t size; + const char* data = columns[c]->native_value(r, scratch, size); + if (data) + appender.append(c, data, size); + else + appender.append_null(c); + } + } + for (uint32_t c = 0; c < columns.size(); ++c) + block->get_vector(c)->add_row_nums(row_count); + block->fill_trailling_nulls(); + return E_OK; +} +} // namespace common diff --git a/cpp/src/common/arrow_batch.h b/cpp/src/common/arrow_batch.h new file mode 100644 index 000000000..38652561d --- /dev/null +++ b/cpp/src/common/arrow_batch.h @@ -0,0 +1,88 @@ +/* + * 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. + */ +#ifndef COMMON_ARROW_BATCH_H +#define COMMON_ARROW_BATCH_H + +#include +#include + +#include "common/arrow_c_data.h" +#include "common/tsblock/tsblock.h" + +namespace storage { +class TableSchema; +} + +namespace common { + +// Mutable only while a batch is being built. Nulls have physical value slots; +// bitmaps use Arrow's least-significant-bit-first layout. +class ArrowColumn { + public: + ArrowColumn(TSDataType type, uint32_t capacity); + TSDataType type() const { return type_; } + uint32_t capacity() const { return capacity_; } + bool is_null(uint32_t row) const; + void set_valid(uint32_t row); + void set_valid_range(uint32_t begin, uint32_t count); + char* mutable_values() { return reinterpret_cast(values_.data()); } + const char* values() const { + return reinterpret_cast(values_.data()); + } + uint8_t* mutable_validity() { return validity_.data(); } + const uint8_t* validity() const { return validity_.data(); } + const int32_t* offsets() const { return offsets_.data(); } + const char* bytes() const { return bytes_.data(); } + bool variable() const; + // Return TsFile's native representation (DATE and BOOLEAN use scratch). + const char* native_value(uint32_t row, char* scratch, uint32_t& size) const; + int set_native(uint32_t row, TSDataType source_type, const char* data, + uint32_t size); + int copy_selected(const ArrowColumn& source, + const std::vector& rows, uint32_t begin, + uint32_t count, uint32_t destination); + void finish(uint32_t rows); + + private: + TSDataType type_; + uint32_t capacity_; + uint32_t string_rows_ = 0; + std::vector validity_; + std::vector values_; + std::vector offsets_; + std::vector bytes_; +}; + +// Data ownership travels with the exported ArrowArray, independently of the +// reader. Exporting wraps buffers; it does not copy or convert values. +class ArrowBatch : public std::enable_shared_from_this { + public: + ArrowBatch(const std::vector& names, + const std::vector& types, uint32_t capacity); + std::vector names; + std::vector> columns; + uint32_t row_count = 0; + void finish(); + int export_to(ArrowArray* array, ArrowSchema* schema); + int to_tsblock(TupleDesc& desc, TsBlock*& block, + storage::TableSchema* table_schema = nullptr) const; +}; + +} // namespace common +#endif diff --git a/cpp/src/common/arrow_c_data.h b/cpp/src/common/arrow_c_data.h new file mode 100644 index 000000000..9662ad93f --- /dev/null +++ b/cpp/src/common/arrow_c_data.h @@ -0,0 +1,57 @@ +/* + * 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. + */ +#ifndef COMMON_ARROW_C_DATA_H +#define COMMON_ARROW_C_DATA_H + +#include + +typedef struct arrow_schema { + // Array type description + const char* format; + const char* name; + const char* metadata; + int64_t flags; + int64_t n_children; + struct arrow_schema** children; + struct arrow_schema* dictionary; + + // Release callback + void (*release)(struct arrow_schema*); + // Opaque producer-specific data + void* private_data; +} ArrowSchema; + +typedef struct arrow_array { + // Array data description + int64_t length; + int64_t null_count; + int64_t offset; + int64_t n_buffers; + int64_t n_children; + const void** buffers; + struct arrow_array** children; + struct arrow_array* dictionary; + + // Release callback + void (*release)(struct arrow_array*); + // Opaque producer-specific data + void* private_data; +} ArrowArray; + +#endif diff --git a/cpp/src/common/container/bit_map.h b/cpp/src/common/container/bit_map.h index 90ed0e0b6..8b4bc1751 100644 --- a/cpp/src/common/container/bit_map.h +++ b/cpp/src/common/container/bit_map.h @@ -47,6 +47,19 @@ FORCE_INLINE int popcount8(uint8_t v) { #endif } +// Counts logical bits in an Arrow (LSB-first) bitmap, ignoring tail padding. +FORCE_INLINE uint32_t count_valid_bits(const uint8_t* data, uint32_t bits) { + uint32_t count = 0; + for (uint32_t i = 0; i < bits / 8; ++i) count += popcount8(data[i]); + if (bits % 8) count += popcount8(data[bits / 8] & ((1U << (bits % 8)) - 1)); + return count; +} +FORCE_INLINE uint8_t reverse_byte(uint8_t byte) { + byte = uint8_t((byte >> 4) | (byte << 4)); + byte = uint8_t(((byte & 0xcc) >> 2) | ((byte & 0x33) << 2)); + return uint8_t(((byte & 0xaa) >> 1) | ((byte & 0x55) << 1)); +} + FORCE_INLINE int ctz_nonzero(uint32_t v) { #if defined(__GNUC__) || defined(__clang__) return __builtin_ctz(v); diff --git a/cpp/src/common/schema.h b/cpp/src/common/schema.h index feb2eb799..1b46c2b1f 100644 --- a/cpp/src/common/schema.h +++ b/cpp/src/common/schema.h @@ -319,6 +319,9 @@ class TableSchema { } else if (RET_FAIL(common::SerializationUtil::read_i32( column_category, in))) { } + if (ret != common::E_OK) return ret; + column_pos_index_.emplace(column_schema->measurement_name_, + column_schemas_.size()); column_schemas_.emplace_back(column_schema); column_categories_.emplace_back( static_cast(column_category)); @@ -343,6 +346,12 @@ class TableSchema { return ret; } + common::ColumnCategory get_column_category(size_t index) const { + return column_categories_[index]; + } + common::TSDataType get_column_type(size_t index) const { + return column_schemas_[index]->data_type_; + } int32_t get_columns_num() const { return column_schemas_.size(); } int find_column_index(const std::string& column_name) { diff --git a/cpp/src/common/tsblock/tuple_desc.h b/cpp/src/common/tsblock/tuple_desc.h index d5458d85c..cb02746d2 100644 --- a/cpp/src/common/tsblock/tuple_desc.h +++ b/cpp/src/common/tsblock/tuple_desc.h @@ -64,8 +64,13 @@ class TupleDesc { FORCE_INLINE void push_back(const ColumnSchema& schema) { if (schema.column_category_ == ColumnCategory::TIME) { - ASSERT(time_column_index_ == -1); - time_column_index_ = static_cast(column_list_.size()); + // A projection may repeat the same registered TIME column. + if (time_column_index_ == -1) { + time_column_index_ = static_cast(column_list_.size()); + } else { + ASSERT(column_list_[time_column_index_].column_name_ == + schema.column_name_); + } } column_list_.push_back(schema); } @@ -116,6 +121,12 @@ class TupleDesc { if (removing_time) { time_column_index_ = -1; + for (size_t i = idx; i < column_list_.size(); ++i) { + if (column_list_[i].column_category_ == ColumnCategory::TIME) { + time_column_index_ = static_cast(i); + break; + } + } } else if (time_column_index_ != -1 && static_cast(idx) < time_column_index_) { --time_column_index_; diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index c2e6f2a0d..2b3bd7efa 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -1026,15 +1026,14 @@ bool tsfile_result_set_next(ResultSet result_set, ERRNO* err_code) { return has_next; } -ERRNO tsfile_result_set_get_next_tsblock_as_arrow(ResultSet result_set, - ArrowArray* out_array, - ArrowSchema* out_schema) { - if (result_set == nullptr || out_array == nullptr || - out_schema == nullptr) { +static ERRNO export_next_arrow_batch(ResultSet result_set, + ArrowArray* out_array, + ArrowSchema* out_schema) { + if (result_set == nullptr || out_array == nullptr) { return common::E_INVALID_ARG; } std::memset(out_array, 0, sizeof(*out_array)); - std::memset(out_schema, 0, sizeof(*out_schema)); + if (out_schema) std::memset(out_schema, 0, sizeof(*out_schema)); auto* r = static_cast(result_set); auto* table_result_set = dynamic_cast(r); @@ -1042,18 +1041,29 @@ ERRNO tsfile_result_set_get_next_tsblock_as_arrow(ResultSet result_set, return common::E_INVALID_ARG; } - common::TsBlock* tsblock = nullptr; - int ret = table_result_set->get_next_tsblock(tsblock); - if (ret != common::E_OK) { - return ret; - } + std::shared_ptr batch; + int ret = table_result_set->get_next_arrow_batch(batch); + if (ret != common::E_OK) return ret; + return batch->export_to(out_array, out_schema); +} - if (tsblock == nullptr) { - return common::E_NO_MORE_DATA; - } +ERRNO tsfile_result_set_get_next_arrow_batch(ResultSet result_set, + ArrowArray* out_array, + ArrowSchema* out_schema) { + if (!out_schema) return common::E_INVALID_ARG; + return export_next_arrow_batch(result_set, out_array, out_schema); +} - ret = arrow::TsBlockToArrowStruct(*tsblock, out_array, out_schema); - return ret; +ERRNO tsfile_result_set_get_next_arrow_array(ResultSet result_set, + ArrowArray* out_array) { + return export_next_arrow_batch(result_set, out_array, nullptr); +} + +ERRNO tsfile_result_set_get_next_tsblock_as_arrow(ResultSet result_set, + ArrowArray* out_array, + ArrowSchema* out_schema) { + return tsfile_result_set_get_next_arrow_batch(result_set, out_array, + out_schema); } #define TSFILE_RESULT_SET_GET_VALUE_BY_NAME_DEF(type) \ diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index ae84338a3..827f454bd 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -28,6 +28,8 @@ extern "C" { #include #include +#include "common/arrow_c_data.h" + typedef enum { TS_DATATYPE_BOOLEAN = 0, TS_DATATYPE_INT32 = 1, @@ -309,39 +311,6 @@ typedef struct TsFilePreparedLocator { uint32_t time_metadata_length; } TsFilePreparedLocator; -typedef struct arrow_schema { - // Array type description - const char* format; - const char* name; - const char* metadata; - int64_t flags; - int64_t n_children; - struct arrow_schema** children; - struct arrow_schema* dictionary; - - // Release callback - void (*release)(struct arrow_schema*); - // Opaque producer-specific data - void* private_data; -} ArrowSchema; - -typedef struct arrow_array { - // Array data description - int64_t length; - int64_t null_count; - int64_t offset; - int64_t n_buffers; - int64_t n_children; - const void** buffers; - struct arrow_array** children; - struct arrow_array* dictionary; - - // Release callback - void (*release)(struct arrow_array*); - // Opaque producer-specific data - void* private_data; -} ArrowArray; - typedef int32_t ERRNO; typedef int64_t Timestamp; @@ -1003,22 +972,32 @@ ResultSet tsfile_query_table_batch(TsFileReader reader, const char* table_name, bool tsfile_result_set_next(ResultSet result_set, ERRNO* error_code); /** - * @brief Gets the next TsBlock from batch ResultSet and converts it to Arrow - * format. + * @brief Exports the next native Arrow batch without copying its data buffers. * * @param result_set [in] Valid ResultSet handle from batch query * (tsfile_query_table_batch). * @param out_array [out] Pointer to ArrowArray pointer. Will be set to the - * converted Arrow array. + * exported Arrow array. * @param out_schema [out] Pointer to ArrowSchema pointer. Will be set to the - * converted Arrow schema. - * @return ERRNO - E_OK(0) on success, E_NO_MORE_DATA if no more blocks, or + * exported Arrow schema. + * @return ERRNO - E_OK(0) on success, E_NO_MORE_DATA if no more results, or * other error codes. * @note Caller should release ArrowArray and ArrowSchema by calling their * release callbacks when done. * @note This function should only be called on ResultSet obtained from * tsfile_query_table_batch with batch_size > 0. */ +ERRNO tsfile_result_set_get_next_arrow_batch(ResultSet result_set, + ArrowArray* out_array, + ArrowSchema* out_schema); + +/** Export the next array using the schema already obtained from this result + * set. The caller owns the array and must release it. Returns E_NO_MORE_DATA at + * EOF. */ +ERRNO tsfile_result_set_get_next_arrow_array(ResultSet result_set, + ArrowArray* out_array); + +// Compatibility alias for tsfile_result_set_get_next_arrow_batch. ERRNO tsfile_result_set_get_next_tsblock_as_arrow(ResultSet result_set, ArrowArray* out_array, ArrowSchema* out_schema); diff --git a/cpp/src/file/tsfile_io_reader.cc b/cpp/src/file/tsfile_io_reader.cc index 1c4cac29f..0ea712d4b 100644 --- a/cpp/src/file/tsfile_io_reader.cc +++ b/cpp/src/file/tsfile_io_reader.cc @@ -664,7 +664,6 @@ std::string TsFileIOReader::device_node_cache_key( int TsFileIOReader::get_cached_device_node(std::shared_ptr device_id, common::PageArena& pa, CachedDeviceNode& out) { - (void)pa; std::string dev_name = device_node_cache_key(device_id); { @@ -681,7 +680,7 @@ int TsFileIOReader::get_cached_device_node(std::shared_ptr device_id, int64_t device_ie_end_offset = 0; if (RET_FAIL(load_device_index_entry( std::make_shared(device_id), device_index_entry, - device_ie_end_offset))) { + device_ie_end_offset, &pa))) { return ret; } @@ -797,6 +796,14 @@ int TsFileIOReader::load_timeseries_index_for_ssi( int TsFileIOReader::load_device_index_entry( std::shared_ptr device_name, std::shared_ptr& device_index_entry, int64_t& end_offset) { + return load_device_index_entry(device_name, device_index_entry, end_offset, + nullptr); +} + +int TsFileIOReader::load_device_index_entry( + std::shared_ptr device_name, + std::shared_ptr& device_index_entry, int64_t& end_offset, + common::PageArena* result_pa) { int ret = E_OK; std::shared_ptr device_id_comparable = std::dynamic_pointer_cast(device_name); @@ -812,10 +819,12 @@ int TsFileIOReader::load_device_index_entry( auto index_node = it->second; if (index_node->node_type_ == LEAF_DEVICE) { ret = index_node->binary_search_children( - device_name, true, device_index_entry, end_offset); + device_name, true, device_index_entry, end_offset, + result_pa ? *result_pa : *index_node->pa_); } else { ret = search_from_internal_node(device_name, true, index_node, - device_index_entry, end_offset); + device_index_entry, end_offset, + result_pa); } if (ret == E_NOT_EXIST) { ret = E_DEVICE_NOT_EXIST; @@ -925,6 +934,17 @@ int TsFileIOReader::read_device_meta_index(int64_t start_offset, return ret; } +int TsFileIOReader::get_device_time_index(std::shared_ptr device_id, + TimeseriesIndex*& index, + common::PageArena& pa) { + index = nullptr; + CachedDeviceNode cached; + int ret = get_cached_device_node(device_id, pa, cached); + if (ret != common::E_OK) return ret; + if (!cached.is_aligned) return common::E_NOT_SUPPORT; + return get_time_column_metadata(cached.top_node, index, pa); +} + int TsFileIOReader::get_timeseries_indexes( std::shared_ptr device_id, const std::unordered_set& measurement_names, @@ -936,7 +956,7 @@ int TsFileIOReader::get_timeseries_indexes( int64_t measurement_ie_end_offset = 0; if (RET_FAIL(load_device_index_entry( std::make_shared(device_id), device_index_entry, - device_ie_end_offset))) { + device_ie_end_offset, &pa))) { return ret; } @@ -972,6 +992,14 @@ int TsFileIOReader::get_timeseries_indexes( } } + // A missing/empty projection has no aligned index to carry this owner. + // Release its heap-backed members while the caller's arena is still live. + auto destroy_index = [](TimeseriesIndex* index) { + if (index) index->~TimeseriesIndex(); + }; + std::unique_ptr unclaimed_time( + time_timeseries_index, destroy_index); + // A wide projection is served better by one pass over the measurement index // tree and one pread of the whole TimeseriesIndex range than by a binary // search, a pread, a deserialize into a scratch arena and a clone per @@ -992,6 +1020,11 @@ int TsFileIOReader::get_timeseries_indexes( std::unordered_map name_to_index; name_to_index.reserve(loaded_indexes.size()); for (ITimeseriesIndex* loaded : loaded_indexes) { + if (!measurement_names.count( + loaded->get_measurement_name().to_std_string())) { + static_cast(loaded)->~TimeseriesIndex(); + continue; + } if (is_aligned) { void* aligned_buf = pa.alloc(sizeof(AlignedTimeseriesIndex)); if (IS_NULL(aligned_buf)) { @@ -1008,6 +1041,7 @@ int TsFileIOReader::get_timeseries_indexes( loaded; } } + if (!name_to_index.empty()) unclaimed_time.release(); int64_t idx = 0; for (const auto& measurement_name : measurement_names) { const auto it = name_to_index.find(measurement_name); @@ -1048,6 +1082,7 @@ int TsFileIOReader::get_timeseries_indexes( dynamic_cast(timeseries_indexs[idx]); if (aligned_timeseries_index) { aligned_timeseries_index->time_ts_idx_ = time_timeseries_index; + unclaimed_time.release(); } } diff --git a/cpp/src/file/tsfile_io_reader.h b/cpp/src/file/tsfile_io_reader.h index 22283ebc5..68907c1a8 100644 --- a/cpp/src/file/tsfile_io_reader.h +++ b/cpp/src/file/tsfile_io_reader.h @@ -146,6 +146,10 @@ class TsFileIOReader { std::vector& timeseries_indexs, common::PageArena& pa); + // Internal scan preparation for time-only and missing-FIELD projections. + int get_device_time_index(std::shared_ptr device_id, + TimeseriesIndex*& index, common::PageArena& pa); + int get_device_timeseries_meta_by_offset( int64_t start_offset, int64_t end_offset, std::vector& timeseries_indexs, @@ -157,6 +161,11 @@ class TsFileIOReader { int64_t& end_offset); private: + int load_device_index_entry( + std::shared_ptr target_name, + std::shared_ptr& device_index_entry, + int64_t& end_offset, common::PageArena* result_pa); + FORCE_INLINE int64_t file_size() const { return read_file_->file_size(); } int load_tsfile_meta(); diff --git a/cpp/src/reader/arrow/query_scan_executor.cc b/cpp/src/reader/arrow/query_scan_executor.cc new file mode 100644 index 000000000..b4a55c2ce --- /dev/null +++ b/cpp/src/reader/arrow/query_scan_executor.cc @@ -0,0 +1,845 @@ +/* + * 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. + */ +#include "reader/arrow/query_scan_executor.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/thread_pool.h" +#include "reader/arrow/scan_page.h" +#include "reader/filter/table_field_filter.h" + +namespace storage { +using namespace common; +namespace { +struct ScanColumn { + std::string name; + TSDataType type = INVALID_DATATYPE; + bool projected = false; + std::vector pages; + // End of each value chunk's page range, paired with its shared time chunk. + std::vector> chunk_page_ends; + // Non-aligned merge cursor. Only the current physical page is decoded. + size_t next_page = 0; + size_t row = 0; + std::vector times; + std::shared_ptr values; +}; +struct ScanDevice { + DeviceQueryTask* task; + std::unique_ptr owned_task; + std::vector> prepared; + PageArena arena; + std::vector indexes; + TimeseriesIndex* time_index = nullptr; + std::vector times; + std::vector time_chunk_offsets; + std::vector time_page_starts; + std::set excluded_chunks; + std::vector columns; + std::shared_ptr device_input; + std::vector output_fields; + // Logical time page -> physical page index for every FIELD, or missing. + std::vector> value_pages; + bool aligned = false; + size_t page_cursor = 0; + explicit ScanDevice(DeviceQueryTask* t) : task(t) { + arena.init(1024, MOD_TSFILE_READER); + } + ~ScanDevice() { + if (!prepared.empty()) return; + std::set owned; + if (time_index) owned.insert(time_index); + for (auto* index : indexes) { + if (auto* a = dynamic_cast(index)) { + owned.insert(a->time_ts_idx_); + owned.insert(a->value_ts_idx_); + a->~AlignedTimeseriesIndex(); + } else if (auto* t = dynamic_cast(index)) + owned.insert(t); + } + for (auto* index : owned) + if (index) index->~TimeseriesIndex(); + } +}; +struct SelectedPage { + std::shared_ptr device; + size_t time_page = 0; + std::vector times; + std::vector selected; + std::vector> cached; + uint32_t consumed = 0; + uint32_t logical_rows = 0; + std::vector cache_rows; + std::vector> cursors; +}; +struct OutputSlice { + std::shared_ptr page; + uint32_t begin; + uint32_t count; + uint32_t destination; +}; +} // namespace +struct QueryScanExecutor::Impl { + std::unique_ptr tasks; + TsFileIOReader* io; + RandomAccessReadFile* file; + std::vector names; + std::vector types; + uint32_t batch_size; + std::unique_ptr time_filter; + std::unique_ptr field_filter; + AlignedFieldFilter* predicate; + int64_t offset; + int64_t limit; + int error = E_OK; + bool closed = false; + std::vector> ready_devices; + size_t ready_device_index = 0; + std::set predicate_columns; + std::set projected_columns; + + ArrowInputBudget input_usage; + std::vector output_sources, distinct_outputs; + size_t concurrency() const { +#ifdef ENABLE_THREADS + if (g_config_value_.parallel_read_enabled_ && g_thread_pool_ && + ThreadPool::current_worker_id() == SIZE_MAX) + return g_thread_pool_->num_threads(); +#endif + return 1; + } + // Submit at most the query's worker budget. Workers drain ready work; they + // never submit child tasks or wait for other jobs on the shared pool. + int run_tasks(size_t count, const std::function& work) { + size_t workers = std::min(count, concurrency()); + if (workers <= 1) { + for (size_t i = 0; i < count; ++i) { + int ret = work(i); + if (ret != E_OK) return ret; + } + return E_OK; + } +#ifdef ENABLE_THREADS + std::atomic next{0}; + std::atomic failure{E_OK}; + auto worker = [&]() { + try { + while (failure.load() == E_OK) { + size_t i = next.fetch_add(1); + if (i >= count) break; + int ret = work(i); + if (ret != E_OK) { + int expected = E_OK; + failure.compare_exchange_strong(expected, ret); + } + } + } catch (const std::bad_alloc&) { + failure.store(E_OOM); + } catch (...) { + failure.store(E_FILE_READ_ERR); + } + }; + std::vector> futures; + futures.reserve(workers); + try { + for (size_t i = 0; i < workers; ++i) + futures.push_back(g_thread_pool_->submit(worker)); + } catch (const std::bad_alloc&) { + failure.store(E_OOM); + } catch (...) { + failure.store(E_FILE_READ_ERR); + } + // Drain only this query's tasks, including on submission/decode errors, + // before any captured plan, output buffer, or file can be released. + for (auto& future : futures) future.get(); + return failure.load(); +#else + return E_OK; +#endif + } + std::shared_ptr device; + std::shared_ptr pending; + + Impl(std::unique_ptr t, TsFileIOReader* reader, + std::vector n, std::vector ty, uint32_t size, + Filter* tf, Filter* ff, int off, int lim) + : tasks(std::move(t)), + io(reader), + file(reader->get_read_file()), + names(std::move(n)), + types(std::move(ty)), + batch_size(size), + time_filter(tf), + field_filter(ff), + predicate(dynamic_cast(ff)), + offset(off), + limit(lim) { + if (time_filter && time_filter->is_unbounded_time_filter()) { + time_filter.reset(); + } + if (!time_filter && !field_filter && off == 0 && lim < 0) + input_usage = std::make_shared>(0); + names.insert(names.begin(), "time"); + types.insert(types.begin(), INT64); + projected_columns.insert(names.begin() + 1, names.end()); + std::map, size_t> first; + // The implicit timestamp has no corresponding projected FIELD. + output_sources.push_back(0); + distinct_outputs.push_back(0); + for (size_t c = 1; c < names.size(); ++c) { + auto found = first.emplace(std::make_pair(names[c], types[c]), c); + output_sources.push_back(found.first->second); + if (found.second) distinct_outputs.push_back(c); + } + if (predicate) + for (const auto& name : predicate->referenced_columns()) + predicate_columns.insert(name); + } + int bind_device(const std::shared_ptr& d) { + std::vector requested; + int ret = E_OK; + if (d->prepared.empty()) { + auto& fields = + d->task->get_column_mapping()->get_measurement_columns(); + requested.assign(fields.begin(), fields.end()); + d->indexes.resize(requested.size(), nullptr); + if (!fields.empty()) { + ret = io->get_timeseries_indexes(d->task->get_device_id(), + fields, d->indexes, d->arena); + if (ret != E_OK) return ret; + } + for (auto* index : d->indexes) { + if (auto* aligned = + dynamic_cast(index)) { + d->time_index = aligned->time_ts_idx_; + break; + } + } + if (d->time_index) { + d->aligned = true; + } else { + ret = io->get_device_time_index(d->task->get_device_id(), + d->time_index, d->arena); + if (ret != E_OK && ret != E_NOT_SUPPORT) return ret; + d->aligned = ret == E_OK; + } + } else { + requested.assign(names.begin() + 1, names.end()); + for (auto& source : d->prepared) + d->indexes.push_back(source->index()); + auto* aligned = + dynamic_cast(d->indexes.front()); + d->aligned = aligned != nullptr; + if (aligned) d->time_index = aligned->time_ts_idx_; + } + std::map positions; + for (const auto& name : requested) { + ScanColumn column; + column.name = name; + column.projected = projected_columns.count(name) != 0; + column.type = + d->task->get_table_schema()->get_column_schema(name).data_type_; + positions.emplace(name, d->columns.size()); + d->columns.push_back(std::move(column)); + } + d->output_fields.assign(names.size(), -1); + for (size_t c = 1; c < names.size(); ++c) { + auto position = positions.find(names[c]); + if (position != positions.end()) + d->output_fields[c] = position->second; + } + return E_OK; + } + int prefetch_dense_device(ScanDevice& d) { + if (!input_usage || !d.aligned || d.columns.size() < 512 || + d.columns.size() * 2 < + d.task->get_table_schema()->get_columns_num()) + return E_OK; + std::vector offsets; + auto collect = [&](SimpleList* chunks) { + if (!chunks) return; + for (auto it = chunks->begin(); it != chunks->end(); it++) { + int64_t pos = it.get()->offset_of_chunk_header_; + offsets.push_back(pos); + } + }; + if (d.time_index) collect(d.time_index->get_chunk_meta_list()); + for (auto* idx : d.indexes) { + if (idx && idx->is_aligned()) + collect(idx->get_value_chunk_meta_list()); + } + if (offsets.size() < 2) return E_OK; + std::sort(offsets.begin(), offsets.end()); + const int64_t first = offsets.front(), last = offsets.back(); + if (first < 0 || last <= first || last > file->file_size() || + uint64_t(last - first) > ArrowInputRange::MAX_QUERY_BYTES) + return E_OK; + for (size_t i = 1; i < offsets.size(); ++i) + if (offsets[i] - offsets[i - 1] > 1024 * 1024) return E_OK; + // The final header has no following offset. Plan that chunk separately. + return ArrowInputRange::read(*file, input_usage, first, last - first, + d.device_input); + } + bool time_range_matches(const Statistic* stat) const { + return !time_filter || !stat || + time_filter->satisfy_start_end_time(stat->start_time_, + stat->end_time_); + } + // Use the shared clock for aligned chunks: a value statistic omits NULLs. + // Evaluate the caller's filter before starting parallel page planning. + void select_chunks(ScanDevice& d) { + auto select = [&](ITimeseriesIndex* index, bool clock) { + auto* chunks = index->get_chunk_meta_list(); + if (!chunks) return; + for (auto it = chunks->begin(); it != chunks->end(); it++) { + auto* chunk = it.get(); + auto offset = chunk->offset_of_chunk_header_; + if (clock) d.time_chunk_offsets.push_back(offset); + auto* stat = chunk->statistic_; + if (!stat && chunks->size() == 1) stat = index->get_statistic(); + if (!time_range_matches(stat)) d.excluded_chunks.insert(offset); + } + }; + if (d.aligned) { + select(d.time_index, true); + } else if (time_filter) { + for (auto* index : d.indexes) + if (index) select(index, false); + } + } + int plan_column(ScanDevice& d, size_t c) { + const bool clock = c == d.columns.size(); + auto* index = clock ? d.time_index : d.indexes[c]; + if (!index) return E_OK; + auto* chunks = index->is_aligned() ? index->get_value_chunk_meta_list() + : index->get_chunk_meta_list(); + if (!chunks) return E_OK; + auto& pages = clock ? d.times : d.columns[c].pages; + auto* single_stat = + chunks->size() == 1 ? index->get_statistic() : nullptr; + size_t ordinal = 0; + for (auto it = chunks->begin(); it != chunks->end(); it++, ++ordinal) { + auto* chunk = it.get(); + size_t group = ordinal; + int64_t offset = chunk->offset_of_chunk_header_; + if (clock) { + d.time_page_starts.push_back(pages.size()); + } else if (d.aligned) { + // Complete value lists pair by ordinal, including empty chunks. + // Older sparse layouts omit a value chunk in some chunk groups. + if (chunks->size() != d.time_chunk_offsets.size()) { + auto next = + std::upper_bound(d.time_chunk_offsets.begin(), + d.time_chunk_offsets.end(), offset); + if (next == d.time_chunk_offsets.begin()) + return E_TSFILE_CORRUPTED; + group = next - d.time_chunk_offsets.begin() - 1; + } + offset = d.time_chunk_offsets[group]; + } + if (d.excluded_chunks.count(offset)) continue; + int ret = plan_arrow_pages(*file, *chunk, single_stat, pages, + input_usage, d.device_input); + if (ret != E_OK) return ret; + if (!clock && d.aligned) + d.columns[c].chunk_page_ends.emplace_back(group, pages.size()); + } + if (clock) d.time_page_starts.push_back(pages.size()); + return E_OK; + } + int align_pages(const std::shared_ptr& d) { + if (!d->aligned) return E_OK; + d->value_pages.resize(d->times.size(), + std::vector(d->columns.size(), -1)); + for (size_t c = 0; c < d->columns.size(); ++c) { + size_t first = 0; + for (const auto& chunk : d->columns[c].chunk_page_ends) { + size_t time_page = d->time_page_starts[chunk.first]; + size_t end = d->time_page_starts[chunk.first + 1]; + for (; first < chunk.second; ++first, ++time_page) { + if (time_page >= end || d->value_pages[time_page][c] != -1) + return E_TSFILE_CORRUPTED; + d->value_pages[time_page][c] = first; + } + } + } + return E_OK; + } + int prepare_window(std::vector>& devices) { + int ret = run_tasks(devices.size(), + [&](size_t i) { return bind_device(devices[i]); }); + if (ret != E_OK) return ret; + for (const auto& d : devices) { + select_chunks(*d); + ret = prefetch_dense_device(*d); + if (ret != E_OK) return ret; + } + std::vector> columns; + for (const auto& d : devices) + for (size_t c = 0; c <= d->columns.size(); ++c) + columns.emplace_back(d.get(), c); + ret = run_tasks(columns.size(), [&](size_t i) { + return plan_column(*columns[i].first, columns[i].second); + }); + if (ret != E_OK) return ret; + return run_tasks(devices.size(), + [&](size_t i) { return align_pages(devices[i]); }); + } + int next_device() { + device.reset(); + if (!tasks) return E_NO_MORE_DATA; + if (ready_device_index == ready_devices.size()) { + ready_devices.clear(); + ready_device_index = 0; + size_t count = (input_usage && names.size() >= 1024) + ? 1 + : std::min(8, concurrency()); + if (limit > 0) count = std::min(count, limit); + while (ready_devices.size() < count) { + bool available = false; + int ret = tasks->has_next(available); + if (ret != E_OK) return ret; + if (!available) break; + DeviceQueryTask* task = nullptr; + ret = tasks->next(task); + if (ret != E_OK) return ret; + if (!task) return E_OOM; + ready_devices.emplace_back(new ScanDevice(task)); + } + if (ready_devices.empty()) return E_NO_MORE_DATA; + int ret = prepare_window(ready_devices); + if (ret != E_OK) return ret; + } + device = std::move(ready_devices[ready_device_index++]); + return E_OK; + } + int decode_cached(SelectedPage& page, size_t c) { + if (page.cached[c]) return E_OK; + const auto& d = *page.device; + page.cached[c] = + std::make_shared(d.columns[c].type, page.times.size()); + int32_t physical = d.value_pages[page.time_page][c]; + if (physical < 0) return E_OK; + std::vector rows(page.times.size()); + std::iota(rows.begin(), rows.end(), 0); + int ret = decode_arrow_values(*file, d.columns[c].pages[physical], true, + page.times.size(), rows, 0, rows.size(), + *page.cached[c], 0); + page.cached[c]->finish(page.times.size()); + return ret; + } + int filter_page(SelectedPage& page, bool all_match = false) { + SelectionMask mask(page.times.size()); + mask.set_all(); + if (predicate && !all_match) { + std::vector views; + for (size_t c = 0; c < page.device->columns.size(); ++c) { + AlignedFieldFilter::ColumnView view; + view.name = page.device->columns[c].name; + view.type = page.device->columns[c].type; + view.arrow_column = page.cached[c].get(); + views.push_back(view); + } + int ret = + predicate->evaluate_columns(views, page.times.size(), mask); + if (ret != E_OK) return ret; + } + for (uint32_t r = 0; r < page.times.size(); ++r) { + if (!mask.test(r) || + (time_filter && !time_filter->satisfy_start_end_time( + page.times[r], page.times[r]))) + continue; + if (field_filter && !predicate) { + std::vector values; + std::vector> scratch(page.cached.size()); + for (size_t c = 0; c < page.cached.size(); ++c) { + uint32_t size; + const char* data = page.cached[c]->native_value( + r, scratch[c].data(), size); + values.push_back({page.device->columns[c].name, + page.device->columns[c].type, data, + size}); + } + bool matched = false; + int ret = evaluate_table_field_filter( + *field_filter, {page.times[r], values}, matched); + if (ret != E_OK) return ret; + if (!matched) continue; + } + page.selected.push_back(r); + } + page.logical_rows = page.times.size(); + page.cache_rows.resize(page.selected.size()); + std::iota(page.cache_rows.begin(), page.cache_rows.end(), 0); + for (size_t c = 0; c < page.cached.size(); ++c) { + if (!page.cached[c]) continue; + if (!page.device->columns[c].projected || page.selected.empty()) { + page.cached[c].reset(); + continue; + } + if (page.selected.size() != page.times.size()) { + auto compact = std::make_shared( + page.cached[c]->type(), page.selected.size()); + int ret = compact->copy_selected(*page.cached[c], page.selected, + 0, page.selected.size(), 0); + if (ret != E_OK) return ret; + compact->finish(page.selected.size()); + page.cached[c] = std::move(compact); + } + } + if (page.selected.size() != page.times.size()) { + std::vector accepted; + accepted.reserve(page.selected.size()); + for (uint32_t row : page.selected) + accepted.push_back(page.times[row]); + page.times = std::move(accepted); + } + return E_OK; + } + int aligned_page(std::shared_ptr& page) { + if (device->page_cursor == device->times.size()) return E_NO_MORE_DATA; + page = std::make_shared(); + page->device = device; + page->time_page = device->page_cursor++; + const auto& time = device->times[page->time_page]; + if (!time_range_matches(time.statistic.get())) return E_OK; + bool all_match = false; + if (predicate) { + std::map stats; + for (size_t c = 0; c < device->columns.size(); ++c) { + if (!predicate_columns.count(device->columns[c].name)) continue; + int p = device->value_pages[page->time_page][c]; + stats[device->columns[c].name] = + p < 0 ? nullptr + : device->columns[c].pages[p].statistic.get(); + } + int64_t rows = time.statistic ? time.statistic->count_ : 0; + if (!predicate->may_match(stats, rows)) return E_OK; + all_match = predicate->all_match(stats, rows); + } + int ret = decode_arrow_times(*file, time, true, page->times); + if (ret != E_OK) return ret; + page->cached.resize(device->columns.size()); + page->cursors.resize(device->columns.size()); + if (field_filter && !all_match) { + ret = run_tasks(device->columns.size(), [&](size_t c) { + if (predicate && + !predicate_columns.count(device->columns[c].name)) + return E_OK; + return decode_cached(*page, c); + }); + if (ret != E_OK) return ret; + } + return filter_page(*page, all_match); + } + + int refill(ScanColumn& column) { + while (column.row == column.times.size()) { + column.times.clear(); + column.values.reset(); + column.row = 0; + if (column.next_page == column.pages.size()) return E_NO_MORE_DATA; + const auto& page = column.pages[column.next_page++]; + if (!time_range_matches(page.statistic.get())) continue; + int ret = decode_arrow_times(*file, page, false, column.times); + if (ret != E_OK) return ret; + column.values = + std::make_shared(column.type, column.times.size()); + std::vector rows(column.times.size()); + std::iota(rows.begin(), rows.end(), 0); + ret = decode_arrow_values(*file, page, false, rows.size(), rows, 0, + rows.size(), *column.values, 0); + if (ret != E_OK) return ret; + column.values->finish(rows.size()); + } + return E_OK; + } + int merged_page(std::shared_ptr& page) { + // Non-aligned series use their union of timestamps. This bounded merge + // window is independent of the public result batch size. + const uint32_t window = 1024; + page = std::make_shared(); + page->device = device; + for (const auto& column : device->columns) + page->cached.emplace_back(new ArrowColumn(column.type, window)); + for (uint32_t row = 0; row < window; ++row) { + int64_t time = INT64_MAX; + bool found = false; + for (auto& column : device->columns) { + int ret = refill(column); + if (ret == E_NO_MORE_DATA) continue; + if (ret != E_OK) return ret; + time = std::min(time, column.times[column.row]); + found = true; + } + if (!found) break; + page->times.push_back(time); + for (size_t c = 0; c < device->columns.size(); ++c) { + auto& column = device->columns[c]; + if (column.row < column.times.size() && + column.times[column.row] == time) { + char scratch[8]; + uint32_t size; + const char* data = column.values->native_value( + column.row++, scratch, size); + int ret = page->cached[c]->set_native(row, column.type, + data, size); + if (ret != E_OK) return ret; + } + } + } + if (page->times.empty()) return E_NO_MORE_DATA; + for (auto& column : page->cached) column->finish(page->times.size()); + return filter_page(*page); + } + int next_page() { + pending.reset(); + for (;;) { + if (!device) { + int ret = next_device(); + if (ret != E_OK) return ret; + } + int ret = + device->aligned ? aligned_page(pending) : merged_page(pending); + if (ret == E_NO_MORE_DATA) { + device.reset(); + continue; + } + if (ret != E_OK) return ret; + if (pending->selected.empty()) continue; + if (offset > 0) { + uint32_t skip = + std::min(offset, pending->selected.size()); + pending->consumed = skip; + offset -= skip; + if (pending->consumed == pending->selected.size()) continue; + } + return E_OK; + } + } + int write_column(size_t output, const std::vector& slices, + ArrowColumn& column) { + ArrowReadWindow window; + std::vector read_ends(slices.size(), 0); + const ArrowPageLocation* next_page = nullptr; + // Coalesce only adjacent payloads needed by this output batch. Stop at + // skipped pages, cached predicate values and device/chunk boundaries. + for (size_t i = slices.size(); i-- > 0;) { + auto& page = *slices[i].page; + auto& d = *page.device; + int32_t c = d.output_fields[output]; + const ArrowPageLocation* current = nullptr; + if (c >= 0 && d.aligned && !page.cached[c]) { + int physical = d.value_pages[page.time_page][c]; + if (physical >= 0) current = &d.columns[c].pages[physical]; + } + if (current) { + read_ends[i] = current->offset + current->compressed_size; + if (next_page && + current->chunk_offset == next_page->chunk_offset && + read_ends[i] == next_page->header_offset) + read_ends[i] = read_ends[i + 1]; + } + next_page = current; + } + for (size_t i = 0; i < slices.size(); ++i) { + const auto& slice = slices[i]; + auto& page = *slice.page; + auto& d = *page.device; + auto schema = d.task->get_table_schema(); + const auto& name = names[output]; + if (output == 0 || d.task->get_column_mapping()->is_time(name)) { + std::memcpy(column.mutable_values() + + uint64_t(slice.destination) * sizeof(int64_t), + page.times.data() + slice.begin, + uint64_t(slice.count) * sizeof(int64_t)); + column.set_valid_range(slice.destination, slice.count); + } else if (d.task->get_column_mapping()->is_tag(name)) { + int pos = schema->find_id_column_order(name) + + !schema->is_virtual_table(); + auto id = d.task->get_device_id(); + std::string* tag = + pos >= 0 && size_t(pos) < id->get_split_seg_num() + ? id->get_split_segname_at(pos) + : nullptr; + for (uint32_t i = 0; i < slice.count; ++i) { + int ret = column.set_native(slice.destination + i, STRING, + tag ? tag->data() : nullptr, + tag ? tag->size() : 0); + if (ret != E_OK) return ret; + } + } else { + int32_t c = d.output_fields[output]; + if (c < 0) continue; + int ret = E_OK; + if (page.cached[c]) { + ret = column.copy_selected(*page.cached[c], page.cache_rows, + slice.begin, slice.count, + slice.destination); + } else { + int physical = d.value_pages[page.time_page][c]; + if (physical >= 0) { + if (!page.cursors[c]) + page.cursors[c].reset(new ArrowValueCursor( + *file, d.columns[c].pages[physical], true, + page.logical_rows)); + ret = page.cursors[c]->write( + page.selected, slice.begin, slice.count, column, + slice.destination, &window, read_ends[i]); + // Slices retain their pages until every column finishes + // the output batch. Release completed payloads now so a + // sparse selection cannot pin all contributing pages. + // Keep codec state only if a later batch can resume it. + if (slice.begin + slice.count == page.selected.size() || + limit == 0) + page.cursors[c].reset(); + } + } + if (ret != E_OK) return ret; + } + } + return E_OK; + } + int next(std::shared_ptr& result) { + result.reset(); + if (closed || limit == 0) return E_NO_MORE_DATA; + if (error != E_OK) return error; + std::vector slices; + uint32_t rows = 0; + while (rows < batch_size && limit != 0) { + if (!pending || pending->consumed == pending->selected.size()) { + int ret = next_page(); + if (ret == E_NO_MORE_DATA) break; + if (ret != E_OK) return ret; + } + uint32_t count = + std::min(batch_size - rows, pending->selected.size() - + pending->consumed); + if (limit >= 0) count = std::min(count, limit); + slices.push_back({pending, pending->consumed, count, rows}); + pending->consumed += count; + rows += count; + if (limit >= 0) limit -= count; + } + if (rows == 0) return E_NO_MORE_DATA; + auto batch = std::make_shared(names, types, rows); + batch->row_count = rows; + // Duplicate projections share an immutable result column and are + // decoded once. Each distinct column has exactly one writer. + for (size_t c = 0; c < output_sources.size(); ++c) + if (c != output_sources[c]) + batch->columns[c] = batch->columns[output_sources[c]]; + int ret = run_tasks(distinct_outputs.size(), [&](size_t i) { + size_t c = distinct_outputs[i]; + return write_column(c, slices, *batch->columns[c]); + }); + if (ret != E_OK) return ret; + batch->finish(); + result = std::move(batch); + return E_OK; + } +}; +QueryScanExecutor::QueryScanExecutor(std::unique_ptr tasks, + TsFileIOReader* io, + std::vector names, + std::vector types, + uint32_t batch_size, Filter* time_filter, + Filter* field_filter, int offset, + int limit) + : impl_(new Impl(std::move(tasks), io, std::move(names), std::move(types), + batch_size, time_filter, field_filter, offset, limit)) {} +QueryScanExecutor::~QueryScanExecutor() = default; +int QueryScanExecutor::bind_prepared( + const std::vector>& prepared) { + if (prepared.empty() || impl_->names.size() != prepared.size() + 1) + return E_INVALID_ARG; + for (size_t i = 0; i < prepared.size(); ++i) { + const auto& p = prepared[i]; + if (!p || !p->index()) return E_INVALID_ARG; + if (p->index()->get_data_type() == INVALID_DATATYPE || + p->index()->get_data_type() == VECTOR) + return E_TYPE_NOT_SUPPORTED; + if (prepared.size() > 1) { + const auto& a = prepared.front()->generation(); + const auto& b = p->generation(); + const auto& x = prepared.front()->locator(); + const auto& y = p->locator(); + if (!p->index()->is_aligned() || y.layout != 1 || + y.time_metadata_length == 0) + return E_NOT_SUPPORT; + if (a.mapped_index_identity != b.mapped_index_identity || + a.file_id != b.file_id || a.file_size != b.file_size || + a.file_fingerprint != b.file_fingerprint || + x.time_metadata_offset != y.time_metadata_offset || + x.time_metadata_length != y.time_metadata_length) + return E_INVALID_ARG; + } + } + std::vector columns; + for (size_t i = 1; i < impl_->names.size(); ++i) + columns.emplace_back(impl_->names[i], impl_->types[i], + ColumnCategory::FIELD); + auto schema = std::make_shared("prepared", columns); + auto mapping = std::make_shared(); + for (size_t i = 1; i < impl_->names.size(); ++i) + mapping->add(impl_->names[i], i - 1, *schema); + std::unique_ptr task(new DeviceQueryTask( + nullptr, + std::vector(impl_->names.begin() + 1, impl_->names.end()), + mapping, nullptr, schema)); + impl_->device = std::make_shared(task.get()); + impl_->device->owned_task = std::move(task); + impl_->device->prepared = prepared; + std::vector> devices{impl_->device}; + return impl_->prepare_window(devices); +} +int QueryScanExecutor::next(std::shared_ptr& batch) { + if (impl_->error != E_OK) { + batch.reset(); + return impl_->error; + } + int ret; + try { + ret = impl_->next(batch); + } catch (const std::bad_alloc&) { + ret = E_OOM; + } catch (...) { + ret = E_FILE_READ_ERR; + } + if (ret != E_OK && ret != E_NO_MORE_DATA) { + impl_->error = ret; + batch.reset(); + } + return ret; +} +void QueryScanExecutor::close() { + impl_->closed = true; + impl_->pending.reset(); + impl_->device.reset(); + impl_->ready_devices.clear(); + impl_->tasks.reset(); +} +} // namespace storage diff --git a/cpp/src/reader/arrow/query_scan_executor.h b/cpp/src/reader/arrow/query_scan_executor.h new file mode 100644 index 000000000..c175b2141 --- /dev/null +++ b/cpp/src/reader/arrow/query_scan_executor.h @@ -0,0 +1,48 @@ +/* + * 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. + */ +#ifndef READER_ARROW_QUERY_SCAN_EXECUTOR_H +#define READER_ARROW_QUERY_SCAN_EXECUTOR_H + +#include "common/arrow_batch.h" +#include "file/tsfile_io_reader.h" +#include "reader/prepared_series.h" +#include "reader/task/device_task_iterator.h" + +namespace storage { +// Query-wide output cursor. Device/page boundaries never end an output batch. +// The implementation owns filters and tasks; exported batches own only data. +class QueryScanExecutor { + public: + QueryScanExecutor(std::unique_ptr tasks, + TsFileIOReader* io, std::vector names, + std::vector types, + uint32_t batch_size, Filter* time_filter, + Filter* field_filter, int offset = 0, int limit = -1); + ~QueryScanExecutor(); + int bind_prepared( + const std::vector>& prepared); + int next(std::shared_ptr& batch); + void close(); + + private: + struct Impl; + std::unique_ptr impl_; +}; +} // namespace storage +#endif diff --git a/cpp/src/reader/arrow/scan_page.cc b/cpp/src/reader/arrow/scan_page.cc new file mode 100644 index 000000000..ec337b5a2 --- /dev/null +++ b/cpp/src/reader/arrow/scan_page.cc @@ -0,0 +1,525 @@ +/* + * 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. + */ +#include "reader/arrow/scan_page.h" + +#include +#include +#include + +#include "common/container/bit_map.h" +#include "compress/compressor_factory.h" +#include "encoding/decoder_factory.h" + +namespace storage { +using namespace common; +int ArrowInputRange::read(RandomAccessReadFile& file, + const ArrowInputBudget& usage, int64_t offset, + size_t length, + std::shared_ptr& input) { + if (!usage || !length || length > MAX_QUERY_BYTES) return E_OK; + size_t active = usage->load(); + while (active <= MAX_QUERY_BYTES - length) { + if (!usage->compare_exchange_weak(active, active + length)) continue; + std::shared_ptr buffer; + try { + buffer = std::make_shared(usage, offset, length); + } catch (const std::bad_alloc&) { + usage->fetch_sub(length); + // Optional prefetch may fall back to the ordinary page reader. + return E_OK; + } + int32_t actual = 0; + int ret = file.read(offset, buffer->bytes.get(), + static_cast(length), actual); + if (ret != E_OK) return ret; + if (actual != static_cast(length)) return E_FILE_READ_ERR; + input = std::move(buffer); + break; + } + return E_OK; +} +int ArrowReadWindow::read(RandomAccessReadFile& file, int64_t offset, + char* destination, int32_t size, int64_t end) { + if (offset < 0 || size < 0 || end < offset || end > file.file_size() || + size > end - offset) + return E_TSFILE_CORRUPTED; + if (size == 0) return E_OK; + if (offset >= offset_ && uint64_t(offset - offset_) <= bytes_.size() && + uint64_t(size) <= bytes_.size() - (offset - offset_)) { + std::memcpy(destination, bytes_.data() + offset - offset_, size); + return E_OK; + } + int32_t actual = 0; + if (size > 64 * 1024) { + int ret = file.read(offset, destination, size, actual); + return ret != E_OK ? ret : actual == size ? E_OK : E_FILE_READ_ERR; + } + offset_ = offset; + bytes_.resize(std::min(64 * 1024, end - offset)); + int ret = file.read(offset, bytes_.data(), bytes_.size(), actual); + if (ret != E_OK || actual != int64_t(bytes_.size())) { + bytes_.clear(); + return ret != E_OK ? ret : E_FILE_READ_ERR; + } + std::memcpy(destination, bytes_.data(), size); + return E_OK; +} +namespace { +struct DecoderDelete { + void operator()(Decoder* p) const { DecoderFactory::free(p); } +}; +struct CompressorDelete { + void operator()(Compressor* p) const { CompressorFactory::free(p); } +}; +using DecoderPtr = std::unique_ptr; +struct PageBytes { + std::unique_ptr compressor; + std::vector compressed; + char* data = nullptr; + uint32_t size = 0; + ~PageBytes() { + if (data) compressor->after_uncompress(data); + } + int read(RandomAccessReadFile& file, const ArrowPageLocation& page, + ArrowReadWindow* window = nullptr, int64_t read_end = 0) { + if (page.compressed_size == 0 || page.compressed_size > INT32_MAX) + return E_TSFILE_CORRUPTED; + if (page.compression < UNCOMPRESSED || page.compression > LZMA2) + return E_TSFILE_CORRUPTED; + compressor.reset(CompressorFactory::alloc_compressor(page.compression)); + if (!compressor) return E_NOT_SUPPORT; + int ret = compressor->reset(false); + if (ret != E_OK) return ret; + if (page.input) { + const auto& block = *page.input; + const int64_t rel = page.offset - block.offset; + if (rel < 0 || uint64_t(rel) + page.compressed_size > block.length) + return E_TSFILE_CORRUPTED; + ret = compressor->uncompress(page.input->bytes.get() + rel, + page.compressed_size, data, size); + if (ret != E_OK) return ret; + return size == page.uncompressed_size ? E_OK : E_TSFILE_CORRUPTED; + } + compressed.resize(page.compressed_size); + int32_t actual = 0; + if (window) { + ret = window->read(file, page.offset, compressed.data(), + page.compressed_size, read_end); + actual = page.compressed_size; + } else { + ret = file.read(page.offset, compressed.data(), + page.compressed_size, actual); + } + if (ret != E_OK) return ret; + if (actual != int32_t(page.compressed_size)) return E_FILE_READ_ERR; + ret = compressor->uncompress(compressed.data(), page.compressed_size, + data, size); + if (ret != E_OK) return ret; + return size == page.uncompressed_size ? E_OK : E_TSFILE_CORRUPTED; + } +}; +template +int read_header(RandomAccessReadFile& file, int64_t offset, int64_t end, + Parse parse, uint32_t& consumed, + ArrowReadWindow* window = nullptr) { + if (offset < 0 || offset >= end || end > file.file_size()) + return E_TSFILE_CORRUPTED; + uint64_t amount = std::min(256, end - offset); + for (;;) { + std::vector bytes(amount); + int ret; + if (window) { + ret = window->read(file, offset, bytes.data(), amount, end); + } else { + int32_t actual = 0; + ret = file.read(offset, bytes.data(), amount, actual); + if (ret == E_OK && actual != int64_t(amount)) ret = E_FILE_READ_ERR; + } + if (ret != E_OK) return ret; + ByteStream in; + in.wrap_from(bytes.data(), bytes.size()); + ret = parse(in); + if (ret == E_OK) { + consumed = in.read_pos(); + return E_OK; + } + if (!deserialize_buf_not_enough(ret) || + amount == uint64_t(end - offset) || amount >= INT32_MAX) + return ret; + amount = std::min(std::min(amount * 2, INT32_MAX), + end - offset); + } +} +int split_non_aligned(PageBytes& bytes, ByteStream& time, ByteStream& value) { + uint32_t time_size = 0; + int prefix = 0; + int ret = SerializationUtil::read_var_uint(time_size, bytes.data, + bytes.size, &prefix); + if (ret != E_OK) return ret; + if (uint64_t(prefix) + time_size > bytes.size) return E_TSFILE_CORRUPTED; + time.wrap_from(bytes.data + prefix, time_size); + value.wrap_from(bytes.data + prefix + time_size, + bytes.size - prefix - time_size); + return E_OK; +} +int read_numeric(Decoder& decoder, TSDataType type, char* data, uint32_t count, + ByteStream& in) { + switch (type) { + case INT32: + case DATE: + return decoder.read_exact_int32(reinterpret_cast(data), + count, in); + case INT64: + case TIMESTAMP: + return decoder.read_exact_int64(reinterpret_cast(data), + count, in); + case FLOAT: + return decoder.read_exact_float(reinterpret_cast(data), + count, in); + case DOUBLE: + return decoder.read_exact_double(reinterpret_cast(data), + count, in); + default: + return E_NOT_SUPPORT; + } +} +} // namespace +int plan_arrow_pages(RandomAccessReadFile& file, ChunkMeta& chunk, + Statistic* single_chunk_stat, + std::vector& pages, + const ArrowInputBudget& usage, + const std::shared_ptr& device_input) { + ChunkHeader header; + uint32_t used = 0; + int ret = E_OK; + int64_t start = chunk.offset_of_chunk_header_; + bool mapped = device_input && start >= device_input->offset && + uint64_t(start - device_input->offset) < device_input->length; + if (mapped) { + int64_t rel = start - device_input->offset; + ByteStream in; + in.wrap_from(device_input->bytes.get() + rel, + device_input->length - rel); + ret = header.deserialize_from(in); + used = in.read_pos(); + } else + ret = read_header( + file, chunk.offset_of_chunk_header_, file.file_size(), + [&header](ByteStream& in) { + header = ChunkHeader(); + return header.deserialize_from(in); + }, + used); + if (ret != E_OK) return ret; + uint8_t marker = static_cast(header.chunk_type_) & 0x3f; + if (marker != CHUNK_HEADER_MARKER && + marker != ONLY_ONE_PAGE_CHUNK_HEADER_MARKER) + return E_TSFILE_CORRUPTED; + if (header.encoding_type_ < PLAIN || header.encoding_type_ > ALP) + return E_TSFILE_CORRUPTED; + int64_t offset = chunk.offset_of_chunk_header_ + used; + if (header.data_size_ > uint64_t(file.file_size() - offset)) + return E_TSFILE_CORRUPTED; + int64_t end = offset + header.data_size_; + if (end > file.file_size() || end < offset) return E_TSFILE_CORRUPTED; + bool single = marker == ONLY_ONE_PAGE_CHUNK_HEADER_MARKER; + ArrowReadWindow window; + std::shared_ptr input; + const size_t amount = end - offset; + if (mapped && + uint64_t(end - device_input->offset) <= device_input->length) { + input = device_input; + } else if (usage && amount > 0 && amount <= 256 * 1024) { + ret = ArrowInputRange::read(file, usage, offset, amount, input); + if (ret != E_OK) return ret; + } + while (offset < end) { + const int64_t header_offset = offset; + PageHeader ph; + if (input) { + ByteStream in; + in.wrap_from(input->bytes.get() + (offset - input->offset), + end - offset); + ret = ph.deserialize_from(in, !single, header.data_type_); + used = in.read_pos(); + } else + ret = read_header( + file, offset, end, + [&ph, &header, single](ByteStream& in) { + ph.reset(); + return ph.deserialize_from(in, !single, header.data_type_); + }, + used, &window); + if (ret != E_OK) return ret; + offset += used; + if (uint64_t(ph.compressed_size_) > uint64_t(end - offset)) + return E_TSFILE_CORRUPTED; + ArrowPageLocation page; + page.chunk_offset = chunk.offset_of_chunk_header_; + page.header_offset = header_offset; + page.input = input; + page.offset = offset; + page.compressed_size = ph.compressed_size_; + page.uncompressed_size = ph.uncompressed_size_; + page.type = header.data_type_; + page.encoding = header.encoding_type_; + page.compression = header.compression_type_; + Statistic* stat = ph.statistic_; + ph.statistic_ = nullptr; + if (!stat && single && page.compressed_size) { + Statistic* source = + chunk.statistic_ ? chunk.statistic_ : single_chunk_stat; + if (source) { + stat = StatisticFactory::alloc_statistic(header.data_type_); + if (!stat) return E_OOM; + clone_statistic(source, stat, header.data_type_); + } + } + page.statistic.reset(stat, [](Statistic* p) { + if (p) StatisticFactory::free(p); + }); + pages.push_back(std::move(page)); + offset += ph.compressed_size_; + if (single && offset != end) return E_TSFILE_CORRUPTED; + } + return E_OK; +} +int decode_arrow_times(RandomAccessReadFile& file, + const ArrowPageLocation& page, bool aligned, + std::vector& times) { + times.clear(); + PageBytes bytes; + int ret = bytes.read(file, page); + if (ret != E_OK) return ret; + ByteStream in, values; + if (aligned) + in.wrap_from(bytes.data, bytes.size); + else if ((ret = split_non_aligned(bytes, in, values)) != E_OK) + return ret; + DecoderPtr decoder( + aligned ? DecoderFactory::alloc_value_decoder(page.encoding, INT64) + : DecoderFactory::alloc_time_decoder()); + if (!decoder) return E_NOT_SUPPORT; + int64_t buffer[1024]; + while (decoder->has_remaining(in)) { + int actual = 0; + ret = decoder->read_batch_int64(buffer, 1024, actual, in); + if (ret != E_OK) return ret; + if (actual <= 0 || actual > 1024) return E_TSFILE_CORRUPTED; + times.insert(times.end(), buffer, buffer + actual); + if (times.size() > INT32_MAX) return E_OVERFLOW; + } + return E_OK; +} +struct ArrowValueCursor::Impl { + RandomAccessReadFile& file; + ArrowPageLocation page; + bool aligned; + uint32_t page_rows; + uint32_t source = 0; + bool initialized = false; + PageBytes bytes; + ByteStream in; + const uint8_t* bitmap = nullptr; + DecoderPtr decoder; + PageArena strings; + Impl(RandomAccessReadFile& f, ArrowPageLocation p, bool a, uint32_t rows) + : file(f), page(std::move(p)), aligned(a), page_rows(rows) { + strings.init(512, MOD_TSFILE_READER); + } + int initialize(ArrowReadWindow* window, int64_t read_end) { + int ret = bytes.read(file, page, window, read_end); + if (ret != E_OK) return ret; + ByteStream times; + if (aligned) { + if (bytes.size < 4) return E_TSFILE_CORRUPTED; + uint32_t size = SerializationUtil::read_ui32(bytes.data); + uint64_t bitmap_size = (uint64_t(size) + 7) / 8; + if (size != page_rows || 4 + bitmap_size > bytes.size) + return E_TSFILE_CORRUPTED; + bitmap = reinterpret_cast(bytes.data + 4); + in.wrap_from(bytes.data + 4 + bitmap_size, + bytes.size - 4 - bitmap_size); + } else if ((ret = split_non_aligned(bytes, times, in)) != E_OK) + return ret; + decoder.reset( + DecoderFactory::alloc_value_decoder(page.encoding, page.type)); + if (!decoder) return E_NOT_SUPPORT; + initialized = true; + return E_OK; + } + int write(const std::vector& rows, uint32_t begin, uint32_t count, + ArrowColumn& output, uint32_t destination, + ArrowReadWindow* window, int64_t read_end) { + if (uint64_t(begin) + count > rows.size() || + uint64_t(destination) + count > output.capacity()) + return E_INVALID_ARG; + if (page.compressed_size == 0 || count == 0) return E_OK; + int ret = E_OK; + if (!initialized && (ret = initialize(window, read_end)) != E_OK) + return ret; + auto valid = [this](uint32_t row) { + return !bitmap || (bitmap[row / 8] & (0x80U >> (row % 8))); + }; + uint64_t scratch[1024]; + // Selected rows are strictly increasing. Matching endpoints establish a + // dense slice. + if (aligned && page.type == DOUBLE && output.type() == DOUBLE && + count <= 1024 && !(source % 8) && !(destination % 8) && + !(count % 8) && rows[begin] == source && + uint64_t(source) + count <= page_rows && + rows[begin + count - 1] == source + count - 1) { + const uint8_t* mask = bitmap + source / 8; + const uint32_t non_null = bitops::count_valid_bits(mask, count); + double* dest = reinterpret_cast(output.mutable_values()) + + destination; + double compact[1024]; + if (non_null == count) { + ret = decoder->read_exact_double(dest, count, in); + if (ret != E_OK) return ret; + output.set_valid_range(destination, count); + } else { + if (non_null && (ret = decoder->read_exact_double( + compact, non_null, in)) != E_OK) + return ret; + auto* valid_bits = output.mutable_validity() + destination / 8; + unsigned j = 0, index = 0; + while (j < count / 8) { + unsigned start = j; + while (j < count / 8 && mask[j] == 0xff) ++j; + if (j > start) { + const unsigned len = (j - start) * 8; + std::memcpy(dest + start * 8, compact + index, + len * sizeof(double)); + std::memset(valid_bits + start, 0xff, j - start); + index += len; + } + if (j == count / 8) break; + const uint8_t byte = mask[j]; + valid_bits[j] = bitops::reverse_byte(byte); + for (unsigned bit = 0; bit < 8; ++bit) + if (byte & (0x80U >> bit)) + dest[8 * j + bit] = compact[index++]; + ++j; + } + } + source += count; + return E_OK; + } + uint32_t selected = 0; + for (; source < page_rows && selected < count;) { + bool keep = selected < count && rows[begin + selected] == source; + if (selected < count && rows[begin + selected] < source) + return E_INVALID_ARG; + if (!valid(source)) { + if (keep) { + ret = output.set_native(destination + selected, page.type, + nullptr, 0); + if (ret != E_OK) return ret; + ++selected; + } + ++source; + continue; + } + bool numeric = page.type == INT32 || page.type == INT64 || + page.type == FLOAT || page.type == DOUBLE || + page.type == TIMESTAMP || page.type == DATE; + uint32_t run = 1; + if (numeric) { + while (source + run < page_rows && run < 1024 && + valid(source + run)) { + bool next_keep = + keep ? selected + run < count && + rows[begin + selected + run] == source + run + : !(selected < count && + rows[begin + selected] == source + run); + if (!next_keep) break; + ++run; + } + bool direct = + keep && page.type == output.type() && page.type != DATE; + char* dest = direct ? output.mutable_values() + + uint64_t(destination + selected) * + get_data_type_size(page.type) + : reinterpret_cast(scratch); + ret = read_numeric(*decoder, page.type, dest, run, in); + if (ret != E_OK) return ret; + if (keep) { + if (direct) + output.set_valid_range(destination + selected, run); + else + for (uint32_t k = 0; k < run; ++k) { + uint32_t width = get_data_type_size(page.type); + ret = output.set_native(destination + selected + k, + page.type, dest + k * width, + width); + if (ret != E_OK) return ret; + } + selected += run; + } + } else if (page.type == BOOLEAN) { + bool value; + ret = decoder->read_boolean(value, in); + if (ret != E_OK) return ret; + if (keep) { + ret = output.set_native(destination + selected++, page.type, + reinterpret_cast(&value), + sizeof(value)); + if (ret != E_OK) return ret; + } + } else if (page.type == STRING || page.type == TEXT || + page.type == BLOB) { + String value; + ret = decoder->read_String(value, strings, in); + if (ret != E_OK) return ret; + if (keep) { + ret = output.set_native(destination + selected++, page.type, + value.len_ ? value.buf_ : "", + value.len_); + if (ret != E_OK) return ret; + } + strings.reset(); + } else + return E_NOT_SUPPORT; + source += run; + } + return selected == count ? E_OK : E_TSFILE_CORRUPTED; + } +}; +ArrowValueCursor::ArrowValueCursor(RandomAccessReadFile& file, + ArrowPageLocation page, bool aligned, + uint32_t page_rows) + : impl_(new Impl(file, std::move(page), aligned, page_rows)) {} +ArrowValueCursor::~ArrowValueCursor() = default; +int ArrowValueCursor::write(const std::vector& rows, uint32_t begin, + uint32_t count, ArrowColumn& output, + uint32_t destination, ArrowReadWindow* window, + int64_t read_end) { + return impl_->write(rows, begin, count, output, destination, window, + read_end); +} +int decode_arrow_values(RandomAccessReadFile& file, + const ArrowPageLocation& page, bool aligned, + uint32_t page_rows, const std::vector& rows, + uint32_t begin, uint32_t count, ArrowColumn& output, + uint32_t destination) { + ArrowValueCursor cursor(file, page, aligned, page_rows); + return cursor.write(rows, begin, count, output, destination); +} +} // namespace storage diff --git a/cpp/src/reader/arrow/scan_page.h b/cpp/src/reader/arrow/scan_page.h new file mode 100644 index 000000000..11d662692 --- /dev/null +++ b/cpp/src/reader/arrow/scan_page.h @@ -0,0 +1,102 @@ +/* + * 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. + */ +#ifndef READER_ARROW_SCAN_PAGE_H +#define READER_ARROW_SCAN_PAGE_H + +#include + +#include "common/arrow_batch.h" +#include "common/tsfile_common.h" +#include "file/random_access_read_file.h" + +namespace storage { +using ArrowInputBudget = std::shared_ptr>; +// One immutable compressed file range, charged once even when many pages share +// it. +struct ArrowInputRange { + static const size_t MAX_QUERY_BYTES = 160u * 1024 * 1024; + static int read(RandomAccessReadFile& file, const ArrowInputBudget& usage, + int64_t offset, size_t length, + std::shared_ptr& input); + ArrowInputBudget usage; + int64_t offset; + std::unique_ptr bytes; + size_t length; + ArrowInputRange(const ArrowInputBudget& u, int64_t o, size_t n) + : usage(u), offset(o), bytes(new char[n]), length(n) {} + ~ArrowInputRange() { usage->fetch_sub(length); } +}; + +struct ArrowPageLocation { + int64_t chunk_offset = 0; + int64_t header_offset = 0; + int64_t offset = 0; + uint32_t compressed_size = 0; + uint32_t uncompressed_size = 0; + common::TSDataType type = common::INVALID_DATATYPE; + common::TSEncoding encoding = common::INVALID_ENCODING; + common::CompressionType compression = common::INVALID_COMPRESSION; + std::shared_ptr statistic; + std::shared_ptr input; +}; +// Task-local read-ahead, capped at 64 KiB regardless of projection width or +// selected page count. The caller supplies the last byte range it needs; no +// buffer escapes into a page plan or a decoder retained by an output batch. +class ArrowReadWindow { + public: + int read(RandomAccessReadFile& file, int64_t offset, char* destination, + int32_t size, int64_t end); + + private: + std::vector bytes_; + int64_t offset_ = 0; +}; +// Plans own their page statistics and borrow no parser buffers. +int plan_arrow_pages(RandomAccessReadFile& file, ChunkMeta& chunk, + Statistic* single_chunk_stat, + std::vector& pages, + const ArrowInputBudget& usage = {}, + const std::shared_ptr& device_input = {}); +int decode_arrow_times(RandomAccessReadFile& file, + const ArrowPageLocation& page, bool aligned, + std::vector& times); +// Retains decompression and codec state when an output batch ends mid-page. +// A column task owns its cursor exclusively; no mutable decoder is shared. +class ArrowValueCursor { + public: + ArrowValueCursor(RandomAccessReadFile& file, ArrowPageLocation page, + bool aligned, uint32_t page_rows); + ~ArrowValueCursor(); + int write(const std::vector& rows, uint32_t begin, uint32_t count, + common::ArrowColumn& output, uint32_t destination, + ArrowReadWindow* window = nullptr, int64_t read_end = 0); + + private: + struct Impl; + std::unique_ptr impl_; +}; +// Rows are ordered logical page positions. Non-NULL numeric runs can decode +// straight into the final Arrow buffer, including partial-page output slices. +int decode_arrow_values(RandomAccessReadFile& file, + const ArrowPageLocation& page, bool aligned, + uint32_t page_rows, const std::vector& rows, + uint32_t begin, uint32_t count, + common::ArrowColumn& output, uint32_t destination); +} // namespace storage +#endif diff --git a/cpp/src/reader/column_mapping.h b/cpp/src/reader/column_mapping.h index 621f8756c..2e0e5e02d 100644 --- a/cpp/src/reader/column_mapping.h +++ b/cpp/src/reader/column_mapping.h @@ -32,7 +32,7 @@ class ColumnMapping { } common::ColumnCategory column_category = - schema.get_column_categories()[column_index]; + schema.get_column_category(column_index); column_pos_map[column_name].push_back(index); if (column_category == common::ColumnCategory::TAG) { diff --git a/cpp/src/reader/device_meta_iterator.cc b/cpp/src/reader/device_meta_iterator.cc index e57111e32..17a15e6d3 100644 --- a/cpp/src/reader/device_meta_iterator.cc +++ b/cpp/src/reader/device_meta_iterator.cc @@ -93,9 +93,8 @@ int DeviceMetaIterator::next( } int DeviceMetaIterator::load_results() { - while (!meta_index_nodes_.empty()) { + while (result_cache_.empty() && !meta_index_nodes_.empty()) { auto pending = meta_index_nodes_.front(); - meta_index_nodes_.pop(); auto meta_data_index_node = pending.first; const auto& node_type = meta_data_index_node->node_type_; int ret = common::E_OK; @@ -106,6 +105,13 @@ int DeviceMetaIterator::load_results() { } else { ret = common::E_INVALID_NODE_TYPE; } + if (ret == common::E_OK && + node_type == MetaIndexNodeType::LEAF_DEVICE && + next_leaf_child_ < meta_data_index_node->children_.size()) { + break; + } + meta_index_nodes_.pop(); + next_leaf_child_ = 0; if (pending.second) { meta_data_index_node->~MetaIndexNode(); } @@ -119,7 +125,8 @@ int DeviceMetaIterator::load_results() { int DeviceMetaIterator::load_leaf_device(MetaIndexNode* meta_index_node) { int ret = common::E_OK; const auto& leaf_children = meta_index_node->children_; - for (size_t i = 0; i < leaf_children.size(); i++) { + while (next_leaf_child_ < leaf_children.size()) { + const size_t i = next_leaf_child_++; std::shared_ptr child = leaf_children[i]; if (id_filter_ != nullptr) { if (!id_filter_->satisfyRow( @@ -141,6 +148,7 @@ int DeviceMetaIterator::load_leaf_device(MetaIndexNode* meta_index_node) { device_id->split_table_name(); } result_cache_.push(std::make_pair(device_id, child_node)); + break; } } return ret; diff --git a/cpp/src/reader/device_meta_iterator.h b/cpp/src/reader/device_meta_iterator.h index 00d5a8b86..f9e6845a4 100644 --- a/cpp/src/reader/device_meta_iterator.h +++ b/cpp/src/reader/device_meta_iterator.h @@ -86,6 +86,7 @@ class DeviceMetaIterator { common::PageArena pa_; bool should_split_device_name; + size_t next_leaf_child_ = 0; int read_error_ = common::E_OK; bool direct_lookup_done_; std::shared_ptr direct_device_id_; diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index afa6bbb72..0a3252867 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -810,6 +810,10 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, uint32_t row_count, SelectionMask& mask) const { if (column.type == common::INVALID_DATATYPE) return common::E_INVALID_ARG; + if (column.arrow_column != nullptr && + static_cast(column.row_offset) + row_count > + column.arrow_column->capacity()) + return common::E_INVALID_ARG; if ((column.notnull_bitmap != nullptr && static_cast(column.row_offset) + row_count > static_cast(column.notnull_bitmap_size) * 8U) || @@ -830,7 +834,12 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, const char* data = nullptr; uint32_t len = 0; - if (!is_null) { + char arrow_scratch[8]; + if (column.arrow_column != nullptr) { + data = column.arrow_column->native_value(source_row, arrow_scratch, + len); + is_null = data == nullptr; + } else if (!is_null) { if (nonnull_index >= column.value_count) return common::E_INVALID_ARG; if (column.type == common::STRING || column.type == common::TEXT || diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 659d165b2..f070860df 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -27,6 +27,7 @@ #include #include +#include "common/arrow_batch.h" #include "common/tsblock/tsblock.h" #include "reader/filter/filter.h" #include "reader/filter/selection_mask.h" @@ -45,6 +46,7 @@ class AlignedFieldFilter : public Filter { enum class CompareOp { EQ, NE, LT, LE, GT, GE }; struct ColumnView { + const common::ArrowColumn* arrow_column = nullptr; std::string name; common::TSDataType type = common::INVALID_DATATYPE; const char* fixed_values = nullptr; diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 8ecc1256d..5d55c1005 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -68,7 +68,7 @@ int TableQueryExecutor::query(const std::string& table_name, delete field_filter; return common::E_COLUMN_NOT_EXIST; } - data_types.push_back(table_schema->get_data_types()[ind]); + data_types.push_back(table_schema->get_column_type(ind)); } if (auto* aligned_filter = dynamic_cast(field_filter)) { @@ -87,25 +87,18 @@ int TableQueryExecutor::query(const std::string& table_name, lower_case_column_names, table_root, column_mapping, meta_data_querier_, tag_filter, table_schema)); - std::unique_ptr tsblock_reader; - switch (table_query_ordering_) { - case TableQueryOrdering::DEVICE: - tsblock_reader = std::unique_ptr( - new DeviceOrderedTsBlockReader( - std::move(device_task_iterator), meta_data_querier_, - block_size_, tsfile_io_reader_, time_filter, field_filter)); - break; - case TableQueryOrdering::TIME: - default: - delete time_filter; - delete field_filter; - ret_qds = nullptr; - return common::E_UNSUPPORTED_ORDER; + if (table_query_ordering_ != TableQueryOrdering::DEVICE) { + delete time_filter; + delete field_filter; + ret_qds = nullptr; + return common::E_UNSUPPORTED_ORDER; } - assert(tsblock_reader != nullptr); - ret_qds = - new TableResultSet(std::move(tsblock_reader), lower_case_column_names, - data_types, return_mode_); + std::unique_ptr scan(new QueryScanExecutor( + std::move(device_task_iterator), tsfile_io_reader_, + lower_case_column_names, data_types, block_size_, time_filter, + field_filter)); + ret_qds = new TableResultSet(std::move(scan), lower_case_column_names, + data_types, return_mode_, table_schema); return ret; } @@ -152,7 +145,7 @@ int TableQueryExecutor::query(const std::string& table_name, delete field_filter; return common::E_COLUMN_NOT_EXIST; } - data_types.push_back(table_schema->get_data_types()[ind]); + data_types.push_back(table_schema->get_column_type(ind)); } if (auto* aligned_filter = dynamic_cast(field_filter)) { @@ -171,26 +164,18 @@ int TableQueryExecutor::query(const std::string& table_name, lower_case_column_names, table_root, column_mapping, meta_data_querier_, tag_filter, table_schema)); - std::unique_ptr tsblock_reader; - switch (table_query_ordering_) { - case TableQueryOrdering::DEVICE: - tsblock_reader = std::unique_ptr( - new DeviceOrderedTsBlockReader(std::move(device_task_iterator), - meta_data_querier_, block_size_, - tsfile_io_reader_, time_filter, - field_filter, offset, limit)); - break; - case TableQueryOrdering::TIME: - default: - delete time_filter; - delete field_filter; - ret_qds = nullptr; - return common::E_UNSUPPORTED_ORDER; + if (table_query_ordering_ != TableQueryOrdering::DEVICE) { + delete time_filter; + delete field_filter; + ret_qds = nullptr; + return common::E_UNSUPPORTED_ORDER; } - assert(tsblock_reader != nullptr); - ret_qds = - new TableResultSet(std::move(tsblock_reader), lower_case_column_names, - data_types, return_mode_); + std::unique_ptr scan(new QueryScanExecutor( + std::move(device_task_iterator), tsfile_io_reader_, + lower_case_column_names, data_types, block_size_, time_filter, + field_filter, offset, limit)); + ret_qds = new TableResultSet(std::move(scan), lower_case_column_names, + data_types, return_mode_, table_schema); return ret; } @@ -289,22 +274,18 @@ int TableQueryExecutor::query_on_tree( std::unique_ptr(new DeviceTaskIterator( schema->get_measurement_names(), index_nodes, column_mapping, meta_data_querier_, nullptr, schema)); - std::unique_ptr tsblock_reader; - switch (table_query_ordering_) { - case TableQueryOrdering::DEVICE: - tsblock_reader = std::unique_ptr( - new DeviceOrderedTsBlockReader( - std::move(device_task_iterator), meta_data_querier_, - block_size_, tsfile_io_reader_, time_filter, nullptr)); - break; - case TableQueryOrdering::TIME: - default: - ret = common::E_UNSUPPORTED_ORDER; + if (table_query_ordering_ != TableQueryOrdering::DEVICE) { + delete time_filter; + ret_qds = nullptr; + return common::E_UNSUPPORTED_ORDER; } - assert(tsblock_reader != nullptr); - ret_qds = new TableResultSet(std::move(tsblock_reader), - schema->get_measurement_names(), - schema->get_data_types()); + std::unique_ptr scan(new QueryScanExecutor( + std::move(device_task_iterator), tsfile_io_reader_, + schema->get_measurement_names(), datatypes, block_size_, time_filter, + nullptr)); + ret_qds = + new TableResultSet(std::move(scan), schema->get_measurement_names(), + datatypes, return_mode_, schema); return ret; } diff --git a/cpp/src/reader/table_result_set.cc b/cpp/src/reader/table_result_set.cc index 63c598c61..0ca008363 100644 --- a/cpp/src/reader/table_result_set.cc +++ b/cpp/src/reader/table_result_set.cc @@ -53,7 +53,38 @@ int TableResultSet::next(bool& has_next) { return ret; } +int TableResultSet::ensure_arrow_batch() { + if (closed_) return common::E_NO_MORE_DATA; + if (read_error_ != common::E_OK) return read_error_; + if (arrow_batch_) return common::E_OK; + int ret = scan_->next(arrow_batch_); + if (ret != common::E_OK && ret != common::E_NO_MORE_DATA) read_error_ = ret; + arrow_row_ = 0; + return ret; +} + +int TableResultSet::get_next_arrow_batch( + std::shared_ptr& batch) { + batch.reset(); + if (!scan_ || return_mode_ != RETURN_BATCH) return common::E_INVALID_ARG; + int ret = ensure_arrow_batch(); + if (ret == common::E_OK) batch = std::move(arrow_batch_); + return ret; +} + int TableResultSet::next_internal(bool& has_next) { + if (scan_) { + if (return_mode_ == RETURN_ROW && row_ready_) { + ++arrow_row_; + row_ready_ = false; + row_materialized_ = false; + if (arrow_row_ == arrow_batch_->row_count) arrow_batch_.reset(); + } + int ret = ensure_arrow_batch(); + has_next = ret == common::E_OK; + row_ready_ = has_next && return_mode_ == RETURN_ROW; + return ret == common::E_NO_MORE_DATA ? common::E_OK : ret; + } if (return_mode_ != RETURN_ROW) { return tsblock_reader_->has_next(has_next); } @@ -108,11 +139,23 @@ int TableResultSet::next_internal(bool& has_next) { } void TableResultSet::materialize_current_row() { - uint32_t len = 0; - bool null = false; row_record_->reset(); // RowRecord owns only the current row; release its previous string copies. pa_.reset(); + if (scan_) { + for (size_t c = 0; c < arrow_batch_->columns.size(); ++c) { + char scratch[8]; + uint32_t size; + auto& column = *arrow_batch_->columns[c]; + const char* data = column.native_value(arrow_row_, scratch, size); + if (data) + row_record_->get_field(c)->set_value( + column.type(), const_cast(data), size, pa_); + } + return; + } + uint32_t len = 0; + bool null = false; for (uint32_t i = 0; i < row_iterator_->get_column_count(); ++i) { const auto value = row_iterator_->read(i, &len, &null); if (!null) { @@ -134,6 +177,8 @@ bool TableResultSet::is_null(const std::string& column_name) { bool TableResultSet::is_null(uint32_t column_index) { ASSERT(1 <= column_index && column_index <= row_record_->get_col_num()); if (!row_ready_) return true; + if (scan_) + return arrow_batch_->columns[column_index - 1]->is_null(arrow_row_); return row_iterator_->is_null_at(column_index - 1); } @@ -148,6 +193,16 @@ bool TableResultSet::is_null(uint32_t column_index) { // bytes into the result. #define TSFILE_FAST_PRIMITIVE_READ(TYPE, DFLT) \ if (!row_ready_) return DFLT; \ + if (scan_) { \ + auto& col = *arrow_batch_->columns[column_index - 1]; \ + ASSERT(common::TypeMatch(col.type())); \ + char scratch[8]; \ + uint32_t size; \ + const char* data = col.native_value(arrow_row_, scratch, size); \ + TYPE value = DFLT; \ + if (data) std::memcpy(&value, data, sizeof(value)); \ + return value; \ + } \ common::Vector* vec = row_iterator_->get_vector(column_index - 1); \ ASSERT(common::TypeMatch(vec->get_vector_type())); \ if (vec->has_null() && vec->is_null(row_iterator_->get_row_id())) \ @@ -192,6 +247,21 @@ std::shared_ptr TableResultSet::get_metadata() { } int TableResultSet::get_next_tsblock(common::TsBlock*& block) { + if (scan_) { + block = nullptr; + std::shared_ptr batch; + int ret = get_next_arrow_batch(batch); + if (ret != common::E_OK) return ret; + common::TsBlock* converted = adapted_block_.release(); + ret = batch->to_tsblock(adapted_desc_, converted, table_schema_.get()); + adapted_block_.reset(converted); + if (ret != common::E_OK) { + read_error_ = ret; + return ret; + } + block = converted; + return common::E_OK; + } int ret = common::E_OK; block = nullptr; if (read_error_ != common::E_OK) { @@ -230,6 +300,9 @@ void TableResultSet::close() { return; } closed_ = true; + if (scan_) scan_->close(); + arrow_batch_.reset(); + adapted_block_.reset(); if (tsblock_reader_) { tsblock_reader_->close(); } diff --git a/cpp/src/reader/table_result_set.h b/cpp/src/reader/table_result_set.h index b42b69c3f..bfed35e2c 100644 --- a/cpp/src/reader/table_result_set.h +++ b/cpp/src/reader/table_result_set.h @@ -20,6 +20,7 @@ #define READER_TABLE_RESULT_SET_H #include +#include "reader/arrow/query_scan_executor.h" #include "reader/block/tsblock_reader.h" #include "reader/result_set.h" @@ -39,6 +40,19 @@ class TableResultSet : public ResultSet { return_mode_(return_mode) { init(); } + explicit TableResultSet(std::unique_ptr scan, + std::vector column_names, + std::vector data_types, + int return_mode = RETURN_ROW, + std::shared_ptr table_schema = nullptr) + : scan_(std::move(scan)), + table_schema_(std::move(table_schema)), + column_names_(std::move(column_names)), + data_types_(std::move(data_types)), + return_mode_(return_mode) { + init(); + } + int get_next_arrow_batch(std::shared_ptr& batch); ~TableResultSet() override; int next(bool& has_next) override; bool is_null(const std::string& column_name) override; @@ -66,6 +80,13 @@ class TableResultSet : public ResultSet { // caller actually requests the RowRecord (or a non-fast accessor). void materialize_current_row(); + int ensure_arrow_batch(); + std::unique_ptr scan_; + std::shared_ptr arrow_batch_; + uint32_t arrow_row_ = 0; + std::shared_ptr table_schema_; + common::TupleDesc adapted_desc_; + std::unique_ptr adapted_block_; std::unique_ptr tsblock_reader_; common::RowIterator* row_iterator_ = nullptr; common::TsBlock* tsblock_ = nullptr; diff --git a/cpp/src/reader/tsfile_executor.cc b/cpp/src/reader/tsfile_executor.cc index c2aa8d8cd..bd7912a09 100644 --- a/cpp/src/reader/tsfile_executor.cc +++ b/cpp/src/reader/tsfile_executor.cc @@ -131,19 +131,18 @@ int TsFileExecutor::execute_prepared( if (prepared == nullptr || offset < 0) { return E_INVALID_ARG; } - auto tsblock_reader = std::unique_ptr( - new PreparedSeriesTsBlockReader()); - int ret = tsblock_reader->init(&io_reader_, prepared, - new TimeBetween(start_time, end_time, false), - offset, limit, block_rows); - if (ret != E_OK) { - return ret; - } std::vector column_names(1, column_name); + if (!prepared->index()) return E_INVALID_ARG; std::vector data_types( - 1, tsblock_reader->value_data_type()); - ret_qds = new TableResultSet(std::move(tsblock_reader), column_names, - data_types, RETURN_BATCH); + 1, prepared->index()->get_data_type()); + std::unique_ptr scan(new QueryScanExecutor( + nullptr, &io_reader_, column_names, data_types, + block_rows ? block_rows : 65536, + new TimeBetween(start_time, end_time, false), nullptr, offset, limit)); + int ret = scan->bind_prepared({prepared}); + if (ret != E_OK) return ret; + ret_qds = new TableResultSet(std::move(scan), column_names, data_types, + RETURN_BATCH); return E_OK; } @@ -157,26 +156,22 @@ int TsFileExecutor::execute_prepared_multi( return E_INVALID_ARG; } - auto tsblock_reader = std::unique_ptr( - new PreparedSeriesTsBlockReader()); - int ret = tsblock_reader->init_multi( - &io_reader_, prepared, new TimeBetween(start_time, end_time, false), - offset, limit, block_rows); - if (ret != E_OK) { - return ret; - } - std::vector column_names; - column_names.reserve(prepared.size()); + std::vector data_types; for (const auto& entry : prepared) { + if (!entry || !entry->index()) return E_INVALID_ARG; column_names.push_back( entry->index()->get_measurement_name().to_std_string()); + data_types.push_back(entry->index()->get_data_type()); } - std::vector data_types = - tsblock_reader->value_data_types(); - ret_qds = - new TableResultSet(std::move(tsblock_reader), std::move(column_names), - std::move(data_types), RETURN_BATCH); + std::unique_ptr scan(new QueryScanExecutor( + nullptr, &io_reader_, column_names, data_types, + block_rows ? block_rows : 65536, + new TimeBetween(start_time, end_time, false), nullptr, offset, limit)); + int ret = scan->bind_prepared(prepared); + if (ret != E_OK) return ret; + ret_qds = new TableResultSet(std::move(scan), column_names, data_types, + RETURN_BATCH); return E_OK; } diff --git a/cpp/src/utils/date_utils.h b/cpp/src/utils/date_utils.h index 77323812e..2925c2d8b 100644 --- a/cpp/src/utils/date_utils.h +++ b/cpp/src/utils/date_utils.h @@ -21,47 +21,39 @@ #include -#include - namespace common { -// Convert TsFile YYYYMMDD integer to days since Unix epoch (1970-01-01). +// March-based Gregorian years put the leap day at the end of the year. +// One 400-year cycle contains 146097 days. Day 719468 is 1970-01-01 +// when counted from 0000-03-01. inline int32_t YYYYMMDDToDaysSinceEpoch(int32_t yyyymmdd) { int year = yyyymmdd / 10000; - int month = (yyyymmdd % 10000) / 100; - int day = yyyymmdd % 100; - - std::tm date = {}; - date.tm_year = year - 1900; - date.tm_mon = month - 1; - date.tm_mday = day; - date.tm_hour = 12; - date.tm_isdst = -1; - - std::tm epoch = {}; - epoch.tm_year = 70; - epoch.tm_mon = 0; - epoch.tm_mday = 1; - epoch.tm_hour = 12; - epoch.tm_isdst = -1; - - time_t t1 = mktime(&date); - time_t t2 = mktime(&epoch); - return static_cast((t1 - t2) / (60 * 60 * 24)); + const int month = yyyymmdd / 100 % 100; + const int day = yyyymmdd % 100; + if (month <= 2) --year; + const int era = (year >= 0 ? year : year - 399) / 400; + const int year_of_era = year - era * 400; + const int march_month = month + (month > 2 ? -3 : 9); + const int day_of_year = (153 * march_month + 2) / 5 + day - 1; + return era * 146097 + year_of_era * 365 + year_of_era / 4 - + year_of_era / 100 + day_of_year - 719468; } -// Convert days since Unix epoch back to YYYYMMDD integer format. inline int32_t DaysSinceEpochToYYYYMMDD(int32_t days) { - std::tm epoch = {}; - epoch.tm_year = 70; - epoch.tm_mon = 0; - epoch.tm_mday = 1; - epoch.tm_hour = 12; - epoch.tm_isdst = -1; - time_t epoch_t = mktime(&epoch); - time_t target_t = epoch_t + static_cast(days) * 24 * 60 * 60; - std::tm* d = localtime(&target_t); - return (d->tm_year + 1900) * 10000 + (d->tm_mon + 1) * 100 + d->tm_mday; + const int64_t absolute_day = static_cast(days) + 719468; + const int64_t era = + (absolute_day >= 0 ? absolute_day : absolute_day - 146096) / 146097; + const int day_of_era = static_cast(absolute_day - era * 146097); + const int year_of_era = (day_of_era - day_of_era / 1460 + + day_of_era / 36524 - day_of_era / 146096) / + 365; + const int day_of_year = + day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + const int march_month = (5 * day_of_year + 2) / 153; + const int day = day_of_year - (153 * march_month + 2) / 5 + 1; + const int month = march_month + (march_month < 10 ? 3 : -9); + const int64_t year = era * 400 + year_of_era + (month <= 2); + return static_cast(year * 10000 + month * 100 + day); } } // namespace common diff --git a/cpp/test/common/datatype/date_converter_test.cc b/cpp/test/common/datatype/date_converter_test.cc index 11cece1e1..45cacf8f9 100644 --- a/cpp/test/common/datatype/date_converter_test.cc +++ b/cpp/test/common/datatype/date_converter_test.cc @@ -22,6 +22,7 @@ #include "common/datatype/value.h" #include "common/record.h" +#include "utils/date_utils.h" namespace common { @@ -38,6 +39,18 @@ class DateConverterTest : public ::testing::Test { int32_t valid_int_{}; }; +TEST(ArrowDateTest, CivilDatesRoundTripAcrossTheSupportedRange) { + const int32_t cases[][2] = { + {10000101, -354285}, {19000301, -25508}, {19691231, -1}, + {19700101, 0}, {20000229, 11016}, {20240701, 19905}, + {99991231, 2932896}, + }; + for (const auto& date : cases) { + EXPECT_EQ(YYYYMMDDToDaysSinceEpoch(date[0]), date[1]); + EXPECT_EQ(DaysSinceEpochToYYYYMMDD(date[1]), date[0]); + } +} + // Test normal date conversion TEST_F(DateConverterTest, DateToIntValidDate) { int32_t result; diff --git a/cpp/test/reader/aligned_field_filter_regression_test.cc b/cpp/test/reader/aligned_field_filter_regression_test.cc index 265a075aa..02b8e8f33 100644 --- a/cpp/test/reader/aligned_field_filter_regression_test.cc +++ b/cpp/test/reader/aligned_field_filter_regression_test.cc @@ -1013,25 +1013,15 @@ TEST_P(AlignedFieldFilterRegressionTest, EXPECT_EQ(actual, expected); } -// A block that cannot hold even one row has no supported capacity; the read -// must surface an error instead of reporting empty successful blocks forever. -TEST_P(AlignedFieldFilterRegressionTest, UnusableTsBlockCapacityReportsError) { +// Table scans now own Arrow batches. The legacy TsBlock scratch budget must +// neither truncate rows nor constrain the public output batch size. +TEST_P(AlignedFieldFilterRegressionTest, + LegacyTsBlockCapacityDoesNotConstrainArrow) { g_config_value_.tsblock_max_memory_ = 8; write_missing_columns(); - LocalRandomAccessReadFile file; - ASSERT_EQ(file.open(filename_), E_OK); - TableQueryExecutor executor(&file, std::get<1>(GetParam())); - ResultSet* result = nullptr; - int ret = executor.query("t", {"v", "ghost"}, nullptr, nullptr, nullptr, 0, - -1, result); - if (ret == E_OK) { - ASSERT_NE(result, nullptr); - bool next = false; - ret = result->next(next); - EXPECT_FALSE(next); - executor.destroy_query_data_set(result); - } - EXPECT_EQ(ret, E_INVALID_ARG); + Rows actual = scan({"v", "ghost"}, nullptr); + ASSERT_FALSE(actual.empty()); + for (const auto& row : actual) EXPECT_EQ(row[2], kNull); } INSTANTIATE_TEST_SUITE_P(RowAndBatchParallelModes, diff --git a/cpp/test/reader/arrow_query_scan_test.cc b/cpp/test/reader/arrow_query_scan_test.cc new file mode 100644 index 000000000..082f89fb1 --- /dev/null +++ b/cpp/test/reader/arrow_query_scan_test.cc @@ -0,0 +1,771 @@ +/* + * 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. + */ +#include + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +#include "common/arrow_batch.h" +#include "common/tablet.h" +#include "common/thread_pool.h" +#include "compress/uncompressed_compressor.h" +#include "file/local_random_access_read_file.h" +#include "file/tsfile_io_writer.h" +#include "file/write_file.h" +#include "reader/arrow/scan_page.h" +#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/time_operator.h" +#include "reader/table_query_executor.h" +#include "writer/tsfile_table_writer.h" + +namespace { +using namespace common; +using namespace storage; +TEST(ArrowBatchTest, ExportSharesBuffersAndOwnsData) { + auto batch = std::make_shared( + std::vector{"v", "flag", "text", "missing"}, + std::vector{INT64, BOOLEAN, STRING, INVALID_DATATYPE}, 3); + int64_t value = 42; + ASSERT_EQ(batch->columns[0]->set_native(0, INT64, + reinterpret_cast(&value), 8), + E_OK); + bool flag = true; + ASSERT_EQ(batch->columns[1]->set_native(2, BOOLEAN, + reinterpret_cast(&flag), 1), + E_OK); + ASSERT_EQ(batch->columns[2]->set_native(1, STRING, "abc", 3), E_OK); + batch->row_count = 3; + const char* original = batch->columns[0]->values(); + ArrowArray array{}; + ArrowSchema schema{}; + ASSERT_EQ(batch->export_to(&array, &schema), E_OK); + EXPECT_EQ(array.children[0]->buffers[1], original); + batch.reset(); + EXPECT_EQ(static_cast(array.children[0]->buffers[1])[0], + 42); + EXPECT_EQ(array.children[0]->null_count, 2); + EXPECT_EQ(static_cast(array.children[1]->buffers[1])[0], 4); + auto* offsets = static_cast(array.children[2]->buffers[1]); + EXPECT_EQ(offsets[0], 0); + EXPECT_EQ(offsets[1], 0); + EXPECT_EQ(offsets[2], 3); + EXPECT_EQ(offsets[3], 3); + EXPECT_STREQ(schema.children[3]->format, "n"); + EXPECT_EQ(array.children[3]->n_buffers, 0); + EXPECT_EQ(array.children[3]->null_count, 3); + array.release(&array); + schema.release(&schema); + EXPECT_EQ(array.release, nullptr); + EXPECT_EQ(schema.release, nullptr); +} +class ArrowQueryScanTest : public ::testing::Test { + protected: + void SetUp() override { + libtsfile_init(); + saved_ = g_config_value_; + g_config_value_.page_writer_max_point_num_ = 3; + g_config_value_.time_compress_type_ = UNCOMPRESSED; +#ifdef _WIN32 + const auto process_id = _getpid(); +#else + const auto process_id = getpid(); +#endif + filename_ = + std::string("arrow_query_scan_") + + ::testing::UnitTest::GetInstance()->current_test_info()->name() + + "_" + std::to_string(process_id) + ".tsfile"; +#ifdef ENABLE_GZIP + const CompressionType label_compression = GZIP; +#else + const CompressionType label_compression = UNCOMPRESSED; +#endif + const std::vector columns{ + {"id", STRING, UNCOMPRESSED, PLAIN, ColumnCategory::TAG}, + {"v", INT64, UNCOMPRESSED, PLAIN, ColumnCategory::FIELD}, + {"p", INT64, UNCOMPRESSED, PLAIN, ColumnCategory::FIELD}, + {"label", STRING, label_compression, DICTIONARY, + ColumnCategory::FIELD}}; + TableSchema schema("t", columns); + WriteFile file; + ASSERT_EQ(file.create(filename_, O_WRONLY | O_CREAT | O_TRUNC, 0666), + E_OK); + TsFileTableWriter writer(&file, &schema); + for (int d = 0; d < 2; ++d) { + Tablet tablet("t", {"id", "v", "p", "label"}, + {STRING, INT64, INT64, STRING}, + {ColumnCategory::TAG, ColumnCategory::FIELD, + ColumnCategory::FIELD, ColumnCategory::FIELD}, + 7); + for (int r = 0; r < 7; ++r) { + ASSERT_EQ(tablet.add_timestamp(r, r), E_OK); + ASSERT_EQ(tablet.add_value(r, "id", d == 0 ? "a" : "b"), E_OK); + if (r != 3) + ASSERT_EQ(tablet.add_value(r, "v", int64_t(d * 100 + r)), + E_OK); + ASSERT_EQ(tablet.add_value(r, "p", int64_t(r % 2)), E_OK); + if (r % 3 != 1) + ASSERT_EQ( + tablet.add_value(r, "label", r % 3 == 0 ? "" : "value"), + E_OK); + } + ASSERT_EQ(writer.write_table(tablet), E_OK); + } + ASSERT_EQ(writer.close(), E_OK); + } + void TearDown() override { + std::remove(filename_.c_str()); + g_config_value_ = saved_; + libtsfile_destroy(); + } + std::string filename_; + ConfigValue saved_; +}; +TEST_F(ArrowQueryScanTest, ExactBatchesCrossDevicesAndRetainOwnership) { + LocalRandomAccessReadFile file; + ASSERT_EQ(file.open(filename_), E_OK); + TableQueryExecutor executor(&file, 5); + ResultSet* raw = nullptr; + ASSERT_EQ(executor.query("t", {"id", "v"}, nullptr, nullptr, nullptr, raw), + E_OK); + std::unique_ptr result(raw); + auto* table = dynamic_cast(raw); + std::vector> held; + for (uint32_t expected : {5U, 5U, 4U}) { + std::shared_ptr batch; + ASSERT_EQ(table->get_next_arrow_batch(batch), E_OK); + ASSERT_EQ(batch->row_count, expected); + held.push_back(batch); + } + std::shared_ptr end; + EXPECT_EQ(table->get_next_arrow_batch(end), E_NO_MORE_DATA); + result.reset(); + file.close(); + char scratch[8]; + uint32_t size; + int64_t value; + std::memcpy(&value, held[1]->columns[2]->native_value(2, scratch, size), 8); + EXPECT_EQ(value, 100); + EXPECT_TRUE(held[0]->columns[2]->is_null(3)); + EXPECT_FALSE(held[0]->columns[2]->is_null(2)); +} +TEST_F(ArrowQueryScanTest, DictionaryStringsPreserveEmptyValuesAndNulls) { + LocalRandomAccessReadFile file; + ASSERT_EQ(file.open(filename_), E_OK); + TableQueryExecutor executor(&file, 4); + ResultSet* raw = nullptr; + ASSERT_EQ(executor.query("t", {"label"}, nullptr, nullptr, nullptr, raw), + E_OK); + std::unique_ptr result(raw); + auto* table = dynamic_cast(raw); + unsigned rows = 0; + std::shared_ptr batch; + int ret; + while ((ret = table->get_next_arrow_batch(batch)) == E_OK) { + for (unsigned r = 0; r < batch->row_count; ++r, ++rows) { + char scratch[8]; + uint32_t size = 0; + const char* value = + batch->columns[1]->native_value(r, scratch, size); + const unsigned pattern = rows % 7 % 3; + if (pattern == 1) { + EXPECT_EQ(value, nullptr); + } else { + ASSERT_NE(value, nullptr); + EXPECT_EQ(std::string(value, size), + pattern == 0 ? "" : "value"); + } + } + } + EXPECT_EQ(ret, E_NO_MORE_DATA); + EXPECT_EQ(rows, 14U); +} +TEST_F(ArrowQueryScanTest, + UnprojectedPredicateOffsetAndLimitCountSelectedRows) { + LocalRandomAccessReadFile file; + ASSERT_EQ(file.open(filename_), E_OK); + TableQueryExecutor executor(&file, 3); + auto filter = + AlignedFieldFilter::compare("p", AlignedFieldFilter::CompareOp::EQ, + AlignedFieldFilter::Literal::int64(1)); + ResultSet* raw = nullptr; + ASSERT_EQ(executor.query("t", {"v"}, nullptr, nullptr, filter.release(), 1, + 4, raw), + E_OK); + std::unique_ptr result(raw); + auto* table = dynamic_cast(raw); + std::shared_ptr first, last; + ASSERT_EQ(table->get_next_arrow_batch(first), E_OK); + ASSERT_EQ(table->get_next_arrow_batch(last), E_OK); + EXPECT_EQ(first->row_count, 3); + EXPECT_EQ(last->row_count, 1); + EXPECT_TRUE(first->columns[1]->is_null(0)); + EXPECT_TRUE(last->columns[1]->is_null(0)); + char scratch[8]; + uint32_t size; + int64_t value; + std::memcpy(&value, first->columns[1]->native_value(2, scratch, size), 8); + EXPECT_EQ(value, 101); +} +// Observe concurrency at the byte source, so decoding-only parallelism cannot +// satisfy this regression. A short delay lets independent reads overlap. +class ObservedReadFile : public RandomAccessReadFile { + public: + LocalRandomAccessReadFile source; + std::atomic active{0}; + std::atomic peak{0}; + std::atomic rejected{0}; + std::set forbidden; + std::map reads; + std::mutex reads_mutex; + int64_t peak_compressor_bytes = 0; + bool observe = false; + bool is_opened() const override { return source.is_opened(); } + int64_t file_size() const override { return source.file_size(); } + const std::string& file_path() const override { return source.file_path(); } + int generation(uint64_t& size, uint64_t& fingerprint) const override { + return source.generation(size, fingerprint); + } + void close() override { source.close(); } + int read(int64_t offset, char* data, int32_t size, + int32_t& actual) override { + { + std::lock_guard lock(reads_mutex); + ++reads[offset]; + peak_compressor_bytes = + std::max(peak_compressor_bytes, + ModStat::get_instance().get_stat(MOD_COMPRESSOR_OBJ)); + } + if (forbidden.count(offset)) { + ++rejected; + actual = 0; + return E_FILE_READ_ERR; + } + int now = ++active; + int maximum = peak.load(); + while (maximum < now && !peak.compare_exchange_weak(maximum, now)) { + } + if (observe) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + int ret = source.read(offset, data, size, actual); + --active; + return ret; + } +}; +TEST_F(ArrowQueryScanTest, ProjectedTimeFieldAndTsBlockSchema) { + const std::vector columns{ + {"id", STRING, UNCOMPRESSED, PLAIN, ColumnCategory::TAG}, + {"time", INT64, UNCOMPRESSED, PLAIN, ColumnCategory::FIELD}, + {"clock", TIMESTAMP, UNCOMPRESSED, PLAIN, ColumnCategory::TIME}}; + TableSchema schema("t", columns); + { + WriteFile file; + ASSERT_EQ(file.create(filename_, O_WRONLY | O_CREAT | O_TRUNC, 0666), + E_OK); + TsFileTableWriter writer(&file, &schema); + Tablet tablet("t", {"id", "time"}, {STRING, INT64}, + {ColumnCategory::TAG, ColumnCategory::FIELD}, 1); + ASSERT_EQ(tablet.add_timestamp(0, 17), E_OK); + ASSERT_EQ(tablet.add_value(0, "id", "a"), E_OK); + ASSERT_EQ(tablet.add_value(0, "time", int64_t(10000)), E_OK); + ASSERT_EQ(writer.write_table(tablet), E_OK); + ASSERT_EQ(writer.close(), E_OK); + } + LocalRandomAccessReadFile file; + ASSERT_EQ(file.open(filename_), E_OK); + TableQueryExecutor executor(&file, 1); + ResultSet* raw = nullptr; + ASSERT_EQ(executor.query("t", {"id", "time", "time", "clock", "clock"}, + nullptr, nullptr, nullptr, raw), + E_OK); + std::unique_ptr result(raw); + TsBlock* block = nullptr; + ASSERT_EQ(result->get_next_tsblock(block), E_OK); + auto* desc = block->get_tuple_desc(); + EXPECT_EQ(desc->get_column_category(1), ColumnCategory::TAG); + EXPECT_EQ(desc->get_column_category(2), ColumnCategory::FIELD); + EXPECT_EQ(desc->get_column_schema(2).compression_, UNCOMPRESSED); + EXPECT_EQ(desc->get_column_schema(2).encoding_, PLAIN); + EXPECT_EQ(desc->get_column_category(4), ColumnCategory::TIME); + EXPECT_EQ(desc->get_column_category(5), ColumnCategory::TIME); + EXPECT_EQ(desc->get_time_column_index(), 4); + RowIterator row(block); + const int64_t expected[] = {17, 0, 10000, 10000, 17, 17}; + for (uint32_t c : {0U, 2U, 3U, 4U, 5U}) { + uint32_t size; + bool is_null; + const char* data = row.read(c, &size, &is_null); + ASSERT_FALSE(is_null); + ASSERT_EQ(size, sizeof(int64_t)); + int64_t actual; + std::memcpy(&actual, data, size); + EXPECT_EQ(actual, expected[c]); + } +} + +TEST_F(ArrowQueryScanTest, LimitStopsBeforeNextDeviceMetadata) { + ObservedReadFile file; + ASSERT_EQ(file.source.open(filename_), E_OK); + TsFileIOReader metadata; + ASSERT_EQ(metadata.init(&file), E_OK); + TsFileMeta* meta = nullptr; + ASSERT_EQ(metadata.get_tsfile_meta(meta), E_OK); + auto root = meta->table_metadata_index_node_map_.at("t"); + ASSERT_EQ(root->children_.size(), 2U); + file.forbidden.insert(root->children_[1]->get_offset()); + + g_config_value_.parallel_read_enabled_ = true; + TableQueryExecutor executor(&file, 32); + ResultSet* raw = nullptr; + ASSERT_EQ(executor.query("t", {"v"}, nullptr, nullptr, nullptr, 0, 1, raw), + E_OK); + std::unique_ptr result(raw); + TsBlock* block = nullptr; + ASSERT_EQ(result->get_next_tsblock(block), E_OK); + EXPECT_EQ(block->get_row_count(), 1U); + EXPECT_EQ(result->get_next_tsblock(block), E_NO_MORE_DATA); + EXPECT_EQ(file.rejected.load(), 0); +} + +template +void flush_aligned_chunk(TsFileIOWriter& file, Writer& chunk, std::string name, + TSDataType type) { + ASSERT_EQ(chunk.end_encode_chunk(), E_OK); + ASSERT_EQ(file.start_flush_chunk(chunk.get_chunk_data(), name, type, PLAIN, + UNCOMPRESSED, chunk.num_of_pages()), + E_OK); + ASSERT_EQ(file.flush_chunk(chunk.get_chunk_data()), E_OK); + ASSERT_EQ(file.end_flush_chunk(chunk.get_chunk_statistic()), E_OK); +} + +TEST_F(ArrowQueryScanTest, ColumnOrderedChunksPairAndPruneBySharedTime) { + { + WriteFile output; + ASSERT_EQ(output.create(filename_, O_WRONLY | O_CREAT | O_TRUNC, 0666), + E_OK); + TsFileIOWriter writer; + ASSERT_EQ(writer.init(&output), E_OK); + ASSERT_EQ(writer.start_file(), E_OK); + std::vector columns{ + {"v", INT64, UNCOMPRESSED, PLAIN, ColumnCategory::FIELD}}; + writer.get_schema()->register_table_schema( + std::make_shared("t", columns)); + auto device = std::make_shared( + std::vector{"t"}); + ASSERT_EQ(writer.start_flush_chunk_group(device, true), E_OK); + for (int64_t t : {0, 1}) { + TimeChunkWriter chunk; + ASSERT_EQ(chunk.init("", PLAIN, UNCOMPRESSED), E_OK); + ASSERT_EQ(chunk.write(t), E_OK); + ASSERT_NO_FATAL_FAILURE( + flush_aligned_chunk(writer, chunk, "", VECTOR)); + } + for (int64_t t : {0, 1}) { + ValueChunkWriter chunk; + ASSERT_EQ(chunk.init("v", INT64, PLAIN, UNCOMPRESSED), E_OK); + ASSERT_EQ(chunk.write(t, 100 + t, false), E_OK); + ASSERT_NO_FATAL_FAILURE( + flush_aligned_chunk(writer, chunk, "v", INT64)); + } + ASSERT_EQ(writer.end_flush_chunk_group(true), E_OK); + ASSERT_EQ(writer.end_file(), E_OK); + } + + ObservedReadFile file; + ASSERT_EQ(file.source.open(filename_), E_OK); + std::vector time_offsets, value_offsets; + { + TsFileIOReader metadata; + ASSERT_EQ(metadata.init(&file), E_OK); + TsFileMeta* meta = nullptr; + ASSERT_EQ(metadata.get_tsfile_meta(meta), E_OK); + auto root = meta->table_metadata_index_node_map_.at("t"); + auto id = root->children_.front()->get_device_id(); + PageArena arena; + arena.init(1024, MOD_TSFILE_READER); + std::vector indexes(1); + ASSERT_EQ(metadata.get_timeseries_indexes(id, {"v"}, indexes, arena), + E_OK); + auto* index = dynamic_cast(indexes[0]); + ASSERT_NE(index, nullptr); + auto* times = index->get_time_chunk_meta_list(); + auto* values = index->get_value_chunk_meta_list(); + for (auto it = times->begin(); it != times->end(); it++) + time_offsets.push_back(it.get()->offset_of_chunk_header_); + for (auto it = values->begin(); it != values->end(); it++) + value_offsets.push_back(it.get()->offset_of_chunk_header_); + index->time_ts_idx_->~TimeseriesIndex(); + index->value_ts_idx_->~TimeseriesIndex(); + index->~AlignedTimeseriesIndex(); + } + ASSERT_EQ(time_offsets.size(), 2U); + ASSERT_EQ(value_offsets.size(), 2U); + TableQueryExecutor executor(&file, 8); + for (int64_t start : {0, 1, 2}) { + if (start > 0) { + file.forbidden.insert(time_offsets[start - 1]); + file.forbidden.insert(value_offsets[start - 1]); + } + ResultSet* raw = nullptr; + ASSERT_EQ(executor.query("t", {"v"}, new TimeBetween(start, 10, false), + nullptr, nullptr, raw), + E_OK); + std::unique_ptr result(raw); + TsBlock* block = nullptr; + if (start < 2) { + ASSERT_EQ(result->get_next_tsblock(block), E_OK); + ASSERT_EQ(block->get_row_count(), 2U - start); + RowIterator rows(block); + for (int64_t t = start; t < 2; ++t) { + for (int c : {0, 1}) { + bool is_null; + uint32_t size; + const char* data = rows.read(c, &size, &is_null); + ASSERT_FALSE(is_null); + ASSERT_EQ(size, sizeof(int64_t)); + int64_t actual; + std::memcpy(&actual, data, size); + EXPECT_EQ(actual, c == 0 ? t : 100 + t); + } + rows.next(); + } + } + EXPECT_EQ(result->get_next_tsblock(block), E_NO_MORE_DATA); + EXPECT_EQ(file.rejected.load(), 0); + } +} + +TEST_F(ArrowQueryScanTest, MetadataLookupsUseTaskOwnedMemory) { + LocalRandomAccessReadFile file; + ASSERT_EQ(file.open(filename_), E_OK); + TsFileIOReader metadata; + ASSERT_EQ(metadata.init(&file), E_OK); + TsFileMeta* file_meta = nullptr; + ASSERT_EQ(metadata.get_tsfile_meta(file_meta), E_OK); + auto root = file_meta->table_metadata_index_node_map_.at("t"); + auto entry = std::dynamic_pointer_cast( + root->children_.front()); + ASSERT_NE(entry, nullptr); + const auto footer_bytes = root->pa_->get_total_used_bytes(); + for (int query = 0; query < 8; ++query) { + PageArena arena; + arena.init(1024, MOD_TSFILE_READER); + std::vector indexes(1, nullptr); + ASSERT_EQ(metadata.get_timeseries_indexes(entry->device_id_, {"v"}, + indexes, arena), + E_OK); + auto* index = dynamic_cast(indexes[0]); + ASSERT_NE(index, nullptr); + TimeseriesIndex* time = nullptr; + ASSERT_EQ( + metadata.get_device_time_index(entry->device_id_, time, arena), + E_OK); + ASSERT_NE(time, nullptr); + time->~TimeseriesIndex(); + index->time_ts_idx_->~TimeseriesIndex(); + index->value_ts_idx_->~TimeseriesIndex(); + index->~AlignedTimeseriesIndex(); + EXPECT_EQ(root->pa_->get_total_used_bytes(), footer_bytes); + } +} +class WindowReadFile : public RandomAccessReadFile { + public: + std::string data = std::string(256 * 1024, '\0'); + std::string path = "memory"; + std::vector> reads; + bool fail = false; + bool short_read = false; + WindowReadFile() { + for (size_t i = 0; i < data.size(); ++i) data[i] = char(i % 251); + } + bool is_opened() const override { return true; } + int64_t file_size() const override { return data.size(); } + const std::string& file_path() const override { return path; } + int generation(uint64_t& size, uint64_t& fingerprint) const override { + size = data.size(); + fingerprint = 1; + return E_OK; + } + void close() override {} + int read(int64_t offset, char* output, int32_t size, + int32_t& actual) override { + reads.emplace_back(offset, size); + actual = fail ? 0 : short_read ? size - 1 : size; + if (actual) std::memcpy(output, data.data() + offset, actual); + return fail ? E_FILE_READ_ERR : E_OK; + } +}; +TEST(ArrowInputRangeTest, ChargesSharedBytesAndReleasesReservationOnError) { + WindowReadFile file; + auto budget = std::make_shared>(0); + std::shared_ptr input; + ASSERT_EQ(ArrowInputRange::read(file, budget, 17, 64, input), E_OK); + ASSERT_TRUE(input); + EXPECT_EQ(std::memcmp(input->bytes.get(), file.data.data() + 17, 64), 0); + auto held = input; + input.reset(); + EXPECT_EQ(budget->load(), 64U); + held.reset(); + EXPECT_EQ(budget->load(), 0U); + budget->store(ArrowInputRange::MAX_QUERY_BYTES - 10); + EXPECT_EQ(ArrowInputRange::read(file, budget, 17, 11, input), E_OK); + EXPECT_FALSE(input); + EXPECT_EQ(file.reads.size(), 1U); + budget->store(0); + file.short_read = true; + EXPECT_EQ(ArrowInputRange::read(file, budget, 17, 64, input), + E_FILE_READ_ERR); + EXPECT_FALSE(input); + EXPECT_EQ(budget->load(), 0U); +} +TEST(ArrowReadWindowTest, CoalescesWithinBoundsAndBypassesLargeReads) { + WindowReadFile file; + ArrowReadWindow window; + std::vector output(100 * 1024); + ASSERT_EQ(window.read(file, 100, output.data(), 100, 200000), E_OK); + ASSERT_EQ(file.reads.size(), 1U); + EXPECT_EQ(file.reads[0], std::make_pair(int64_t(100), int32_t(64 * 1024))); + ASSERT_EQ(window.read(file, 60000, output.data(), 100, 200000), E_OK); + EXPECT_EQ(std::memcmp(output.data(), file.data.data() + 60000, 100), 0); + EXPECT_EQ(file.reads.size(), 1U); + ASSERT_EQ(window.read(file, 70000, output.data(), 100, 70123), E_OK); + EXPECT_EQ(file.reads.back(), std::make_pair(int64_t(70000), int32_t(123))); + ASSERT_EQ(window.read(file, 80000, output.data(), output.size(), 200000), + E_OK); + EXPECT_EQ(file.reads.back().second, int32_t(output.size())); + EXPECT_EQ( + std::memcmp(output.data(), file.data.data() + 80000, output.size()), 0); + EXPECT_EQ(window.read(file, 70000, output.data(), 100, 70099), + E_TSFILE_CORRUPTED); +} +TEST(ArrowReadWindowTest, FailedAndShortReadsAreNeverCached) { + WindowReadFile file; + ArrowReadWindow window; + char output[100]; + for (bool short_read : {false, true}) { + file.fail = !short_read; + file.short_read = short_read; + EXPECT_EQ(window.read(file, 100, output, 100, 1000), E_FILE_READ_ERR); + } + file.fail = file.short_read = false; + EXPECT_EQ(window.read(file, 100, output, 100, 1000), E_OK); + EXPECT_EQ(file.reads.size(), 3U); + EXPECT_EQ(std::memcmp(output, file.data.data() + 100, 100), 0); +} +#ifdef ENABLE_THREADS +TEST_F(ArrowQueryScanTest, QueryParallelismIncludesFileReads) { + ASSERT_NE(g_thread_pool_, nullptr); + ASSERT_GT(g_thread_pool_->num_threads(), 1U); + g_config_value_.parallel_read_enabled_ = true; + ObservedReadFile file; + ASSERT_EQ(file.source.open(filename_), E_OK); + file.observe = true; + TableQueryExecutor executor(&file, 10); + ResultSet* raw = nullptr; + ASSERT_EQ( + executor.query("t", {"id", "v", "p"}, nullptr, nullptr, nullptr, raw), + E_OK); + std::unique_ptr result(raw); + auto* table = dynamic_cast(raw); + std::shared_ptr batch; + ASSERT_EQ(table->get_next_arrow_batch(batch), E_OK); + EXPECT_EQ(batch->row_count, 10U); + EXPECT_GT(file.peak.load(), 1); +} +#endif +TEST_F(ArrowQueryScanTest, + PredicatePruningDoesNotReadOutputPayloadAndErrorsAreTerminal) { + ObservedReadFile file; + ASSERT_EQ(file.source.open(filename_), E_OK); + { + TsFileIOReader metadata; + ASSERT_EQ(metadata.init(&file), E_OK); + TsFileMeta* file_meta = nullptr; + ASSERT_EQ(metadata.get_tsfile_meta(file_meta), E_OK); + PageArena arena; + arena.init(1024, MOD_TSFILE_READER); + std::vector indexes(1, nullptr); + auto root = file_meta->table_metadata_index_node_map_.at("t"); + ASSERT_FALSE(root->children_.empty()); + auto entry = std::dynamic_pointer_cast( + root->children_.front()); + ASSERT_NE(entry, nullptr); + auto id = entry->device_id_; + EXPECT_EQ(id->get_device_name(), "t.a"); + ASSERT_EQ(metadata.get_timeseries_indexes(id, {"v"}, indexes, arena), + E_OK); + auto* index = dynamic_cast(indexes[0]); + ASSERT_NE(index, nullptr); + auto* chunks = index->get_value_chunk_meta_list(); + std::vector pages; + for (auto it = chunks->begin(); it != chunks->end(); it++) + ASSERT_EQ(plan_arrow_pages(file, *it.get(), index->get_statistic(), + pages), + E_OK); + ASSERT_FALSE(pages.empty()); + for (auto& page : pages) file.forbidden.insert(page.offset); + index->time_ts_idx_->~TimeseriesIndex(); + index->value_ts_idx_->~TimeseriesIndex(); + index->~AlignedTimeseriesIndex(); + } + g_config_value_.parallel_read_enabled_ = true; + TableQueryExecutor executor(&file, 5); + for (int64_t threshold : {99, 1, 0}) { + auto filter = AlignedFieldFilter::compare( + "p", AlignedFieldFilter::CompareOp::GT, + AlignedFieldFilter::Literal::int64(threshold == 1 ? 0 : threshold)); + if (threshold == 1) + filter = AlignedFieldFilter::and_filter( + std::move(filter), AlignedFieldFilter::compare( + "p", AlignedFieldFilter::CompareOp::EQ, + AlignedFieldFilter::Literal::int64(0))); + ResultSet* raw = nullptr; + ASSERT_EQ( + executor.query("t", {"v"}, nullptr, nullptr, filter.release(), raw), + E_OK); + std::unique_ptr result(raw); + auto* table = dynamic_cast(raw); + std::shared_ptr batch; + if (threshold != 0) { + EXPECT_EQ(table->get_next_arrow_batch(batch), E_NO_MORE_DATA); + EXPECT_EQ(file.rejected.load(), 0); + } else { + EXPECT_EQ(table->get_next_arrow_batch(batch), E_FILE_READ_ERR); + EXPECT_FALSE(batch); + int reads = file.rejected.load(); + EXPECT_GT(reads, 0); + EXPECT_EQ(table->get_next_arrow_batch(batch), E_FILE_READ_ERR); + EXPECT_EQ(file.rejected.load(), reads); + } + } +} + +TEST_F(ArrowQueryScanTest, SmallBatchesResumeEachPayloadWithoutRereading) { + ObservedReadFile file; + ASSERT_EQ(file.source.open(filename_), E_OK); + TableQueryExecutor executor(&file, 1); + ResultSet* raw = nullptr; + ASSERT_EQ(executor.query("t", {"v", "p"}, nullptr, nullptr, nullptr, raw), + E_OK); + std::unique_ptr result(raw); + auto* table = dynamic_cast(raw); + for (int row = 0; row < 14; ++row) { + std::shared_ptr batch; + ASSERT_EQ(table->get_next_arrow_batch(batch), E_OK); + ASSERT_EQ(batch->row_count, 1U); + char scratch[8]; + uint32_t size; + int64_t value; + std::memcpy(&value, batch->columns[2]->native_value(0, scratch, size), + 8); + EXPECT_EQ(value, (row % 7) % 2); + EXPECT_EQ(batch->columns[1]->is_null(0), row % 7 == 3); + // Metadata may be visited by more than one planner. Payload offsets + // are first seen only when a result batch needs their values; a later + // batch within the same page must do no additional file I/O. + if (row == 0) { + std::lock_guard lock(file.reads_mutex); + file.reads.clear(); + } else if (row < 3) { + std::lock_guard lock(file.reads_mutex); + EXPECT_TRUE(file.reads.empty()); + } + } + std::shared_ptr end; + EXPECT_EQ(table->get_next_arrow_batch(end), E_NO_MORE_DATA); +} + +#ifdef ENABLE_MEM_STAT +TEST_F(ArrowQueryScanTest, LimitReleasesUnfinishedPageBuffers) { + g_config_value_.parallel_read_enabled_ = true; + LocalRandomAccessReadFile file; + ASSERT_EQ(file.open(filename_), E_OK); + TableQueryExecutor executor(&file, 5); + ResultSet* raw = nullptr; + ASSERT_EQ( + executor.query("t", {"v", "p"}, nullptr, nullptr, nullptr, 0, 1, raw), + E_OK); + std::unique_ptr result(raw); + auto* table = dynamic_cast(raw); + const int64_t baseline = + ModStat::get_instance().get_stat(MOD_COMPRESSOR_OBJ); + std::shared_ptr batch; + ASSERT_EQ(table->get_next_arrow_batch(batch), E_OK); + ASSERT_EQ(batch->row_count, 1U); + EXPECT_EQ(ModStat::get_instance().get_stat(MOD_COMPRESSOR_OBJ), baseline); + std::shared_ptr end; + EXPECT_EQ(table->get_next_arrow_batch(end), E_NO_MORE_DATA); +} + +TEST_F(ArrowQueryScanTest, SparseBatchesReleaseCompletedPageBuffers) { + g_config_value_.parallel_read_enabled_ = false; + ObservedReadFile file; + ASSERT_EQ(file.source.open(filename_), E_OK); + TableQueryExecutor executor(&file, 3); + auto filter = + AlignedFieldFilter::compare("p", AlignedFieldFilter::CompareOp::EQ, + AlignedFieldFilter::Literal::int64(0)); + ResultSet* raw = nullptr; + ASSERT_EQ(executor.query("t", {"v", "v", "p"}, nullptr, nullptr, + filter.release(), raw), + E_OK); + std::unique_ptr result(raw); + auto* table = dynamic_cast(raw); + const int64_t baseline = + ModStat::get_instance().get_stat(MOD_COMPRESSOR_OBJ); + const int64_t expected_values[] = {0, 2, 4, 6, 100, 102, 104, 106}; + uint32_t row = 0; + for (uint32_t expected : {3U, 3U, 2U}) { + std::shared_ptr batch; + ASSERT_EQ(table->get_next_arrow_batch(batch), E_OK); + ASSERT_EQ(batch->row_count, expected); + EXPECT_EQ(batch->columns[1], batch->columns[2]); + for (uint32_t i = 0; i < expected; ++i, ++row) { + char scratch[8]; + uint32_t size; + int64_t value; + ASSERT_FALSE(batch->columns[1]->is_null(i)); + std::memcpy(&value, + batch->columns[1]->native_value(i, scratch, size), 8); + EXPECT_EQ(value, expected_values[row]); + } + // Every batch ends at the last selected row of a page, even though + // some pages still have rejected physical rows. No payload is needed + // across these boundaries, including while the Arrow batch is held. + EXPECT_EQ(ModStat::get_instance().get_stat(MOD_COMPRESSOR_OBJ), + baseline); + } + // The next read allocates its compressor before requesting its payload. + // In serial execution all previous payloads must already be released, + // even when several pages contribute to the same exact-size batch. + EXPECT_LE(file.peak_compressor_bytes, + baseline + int64_t(sizeof(UncompressedCompressor))); + std::shared_ptr end; + EXPECT_EQ(table->get_next_arrow_batch(end), E_NO_MORE_DATA); +} +#endif + +} // namespace diff --git a/cpp/test/reader/table_read_failure_test.cc b/cpp/test/reader/table_read_failure_test.cc index 99d02669b..d038e2e75 100644 --- a/cpp/test/reader/table_read_failure_test.cc +++ b/cpp/test/reader/table_read_failure_test.cc @@ -76,9 +76,10 @@ class FailingReadFile : public storage::RandomAccessReadFile { } int read(int64_t offset, char* buffer, int32_t size, int32_t& read_size) override { - ++reads; + const int read_number = ++reads; read_size = 0; - if (fail_at > 0 && (persistent ? reads >= fail_at : reads == fail_at)) { + if (fail_at > 0 && + (persistent ? read_number >= fail_at : read_number == fail_at)) { failed = true; return short_read ? common::E_OK : common::E_FILE_READ_ERR; } @@ -91,11 +92,11 @@ class FailingReadFile : public storage::RandomAccessReadFile { } void close() override { opened_ = false; } - int reads = 0; + std::atomic reads{0}; int fail_at = 0; bool persistent = false; bool short_read = false; - bool failed = false; + std::atomic failed{false}; private: const std::vector& bytes_; @@ -247,8 +248,7 @@ TEST_P(TableReadFailureTest, EveryReadFailureReachesCaller) { filter ? 30 : std::get<1>(GetParam()) * 30); for (bool persistent : {false, true}) { for (bool short_read : {false, true}) { - for (int fail_at = baseline.open_reads + 1; - fail_at <= baseline.reads; ++fail_at) { + for (int fail_at = baseline.open_reads + 1;; ++fail_at) { SCOPED_TRACE(::testing::Message() << filter << ":" << batch_size << ":" << persistent << ":" << short_read << ":" @@ -257,7 +257,15 @@ TEST_P(TableReadFailureTest, EveryReadFailureReachesCaller) { ASSERT_NO_FATAL_FAILURE(scan(filter, batch_size, fail_at, persistent, short_read, failed)); - EXPECT_TRUE(failed.failed); + // Concurrent misses in the shared index cache can + // change the number of physical reads between scans. + if (failed.reads < fail_at) { + EXPECT_FALSE(failed.failed); + EXPECT_EQ(failed.ret, common::E_OK); + EXPECT_EQ(failed.rows, baseline.rows); + break; + } + ASSERT_TRUE(failed.failed); EXPECT_EQ(failed.ret, common::E_FILE_READ_ERR); } } diff --git a/python/tests/test_batch_arrow.py b/python/tests/test_batch_arrow.py index 70911efe0..c66243399 100644 --- a/python/tests/test_batch_arrow.py +++ b/python/tests/test_batch_arrow.py @@ -28,6 +28,30 @@ from tsfile import TsFileTableWriter, TsFileReader +def test_arrow_result_reuses_schema_across_nullable_double_batches(tmp_path): + path = str(tmp_path / "dense.tsfile") + schema = TableSchema( + "t", [ColumnSchema("v", TSDataType.DOUBLE, ColumnCategory.FIELD)] + ) + values = [None if row % 11 in (0, 1) else row + 0.5 for row in range(83)] + with TsFileTableWriter(path, schema) as writer: + tablet = Tablet(["v"], [TSDataType.DOUBLE], len(values)) + for row, value in enumerate(values): + tablet.add_timestamp(row, row) + if value is not None: + tablet.add_value_by_name("v", row, value) + writer.write_table(tablet) + + with TsFileReader(path) as reader: + with reader.query_table("t", ["v"], batch_size=32) as result: + batches = list(iter(result.read_arrow_record_batch, None)) + + assert [len(b) for b in batches] == [32, 32, 19] + assert all(b.schema.equals(batches[0].schema) for b in batches) + assert [v for b in batches for v in b.column(1).to_pylist()] == values + assert sum(b.column(1).null_count for b in batches) == values.count(None) + + def test_batch_read_arrow_basic(): file_path = "test_batch_arrow_basic.tsfile" table = TableSchema( @@ -72,12 +96,14 @@ def test_batch_read_arrow_basic(): total_rows = 0 batch_count = 0 + batch_lengths = [] while True: table = result_set.read_arrow_batch() if table is None: break batch_count += 1 + batch_lengths.append(len(table)) assert isinstance(table, pa.Table) assert len(table) > 0 total_rows += len(table) @@ -89,7 +115,7 @@ def test_batch_read_arrow_basic(): assert "value2" in column_names assert total_rows == 1000 - assert batch_count > 0 + assert batch_lengths == [256, 256, 256, 232] result_set.close() reader.close() diff --git a/python/tsfile/tsfile_cpp.pxd b/python/tsfile/tsfile_cpp.pxd index 12e72075c..c49fd9b0e 100644 --- a/python/tsfile/tsfile_cpp.pxd +++ b/python/tsfile/tsfile_cpp.pxd @@ -512,7 +512,8 @@ cdef extern from "cwrapper/tsfile_cwrapper.h": void* private_data # Arrow batch reading function - ErrorCode tsfile_result_set_get_next_tsblock_as_arrow(ResultSet result_set, + ErrorCode tsfile_result_set_get_next_arrow_array(ResultSet result_set, ArrowArray* out_array) nogil + ErrorCode tsfile_result_set_get_next_arrow_batch(ResultSet result_set, ArrowArray* out_array, ArrowSchema* out_schema) nogil diff --git a/python/tsfile/tsfile_reader.pyx b/python/tsfile/tsfile_reader.pyx index 0b8750089..e5dcf65f4 100644 --- a/python/tsfile/tsfile_reader.pyx +++ b/python/tsfile/tsfile_reader.pyx @@ -78,6 +78,7 @@ cdef class ResultSetPy: # ResultSet from C interface. cdef ResultSet result cdef object metadata + cdef object _arrow_schema # Tag filter handle owned by this result set (freed on close). cdef TagFilterHandle _tag_filter_handle @@ -102,6 +103,7 @@ cdef class ResultSetPy: """ cdef ResultSetMetaData metadata_c self.result = result + self._arrow_schema = None metadata_c = tsfile_result_set_get_metadata(self.result) try: self.metadata = from_c_result_set_meta_data(metadata_c) @@ -188,42 +190,42 @@ cdef class ResultSetPy: return df def read_arrow_record_batch(self): - """Read one native TsBlock as an Arrow RecordBatch.""" + """Read one native Arrow RecordBatch (batch_size rows, except at EOF).""" self.check_result_set_invalid() cdef ArrowArray arrow_array cdef ArrowSchema arrow_schema cdef ErrorCode code = 0 - cdef ErrorCode err_code = 0 + cdef bint need_schema = self._arrow_schema is None memset(&arrow_array, 0, sizeof(ArrowArray)) memset(&arrow_schema, 0, sizeof(ArrowSchema)) - - with nogil: - code = tsfile_result_set_get_next_tsblock_as_arrow( - self.result, &arrow_array, &arrow_schema) - - if code == RET_NO_MORE_DATA: - return None - if code != RET_OK: - check_error(code) - - if arrow_schema.release == NULL or arrow_array.release == NULL: - raise RuntimeError("Arrow conversion returned invalid schema or array") - try: - schema_ptr = &arrow_schema - array_ptr = &arrow_array - return pa.RecordBatch._import_from_c(array_ptr, schema_ptr) - except Exception as e: + with nogil: + if need_schema: + code = tsfile_result_set_get_next_arrow_batch( + self.result, &arrow_array, &arrow_schema) + else: + code = tsfile_result_set_get_next_arrow_array(self.result, &arrow_array) + if code == RET_NO_MORE_DATA: + return None + if code != RET_OK: + check_error(code) + if arrow_array.release == NULL or (need_schema and arrow_schema.release == NULL): + raise RuntimeError("Arrow export returned invalid schema or array") + schema = &arrow_schema if need_schema else self._arrow_schema + batch = pa.RecordBatch._import_from_c(&arrow_array, schema) + if need_schema: + self._arrow_schema = batch.schema + return batch + finally: if arrow_array.release != NULL: arrow_array.release(&arrow_array) if arrow_schema.release != NULL: arrow_schema.release(&arrow_schema) - raise e def read_arrow_batch(self): - """Read one native TsBlock as an Arrow Table.""" + """Read one native Arrow batch as an Arrow Table.""" batch = self.read_arrow_record_batch() if batch is None: return None @@ -340,6 +342,7 @@ cdef class ResultSetPy: reader.notify_result_set_discard(self) self.result = NULL + self._arrow_schema = None self.valid = False def set_invalid_result_set(self): @@ -435,7 +438,7 @@ cdef class TsFileReaderPy: ``TSFILE_QUERY_CACHE_SIZE`` (default 1024, 0 disables it). :param tag_filter: Optional TagFilter to filter by TAG column values. - :param batch_size: <= 0 for row-by-row mode; > 0 for batch (TsBlock) mode. + :param batch_size: <= 0 for row-by-row mode; > 0 sets returned rows per Arrow batch (the last batch may be shorter). :return: query result handler. """ cdef ResultSet result diff --git a/skills/tsfile/references/c.md b/skills/tsfile/references/c.md index ceba30afc..391cacc39 100644 --- a/skills/tsfile/references/c.md +++ b/skills/tsfile/references/c.md @@ -53,3 +53,9 @@ Use this reference only for the C wrapper around the C++ implementation. Read - Verify the wrapper and linked C++ library come from compatible builds. - Compile and run the maintained C examples before adapting them into another build system. + +For table batch queries, call `tsfile_result_set_get_next_arrow_batch` to receive +the first array and schema. A consumer that retains the imported schema can call +`tsfile_result_set_get_next_arrow_array` for each subsequent batch of the same +result set. Release each exported array independently. Both functions return +`E_NO_MORE_DATA` at end of results. diff --git a/skills/tsfile/references/dataframe-arrow.md b/skills/tsfile/references/dataframe-arrow.md index 89521de99..0e06bf310 100644 --- a/skills/tsfile/references/dataframe-arrow.md +++ b/skills/tsfile/references/dataframe-arrow.md @@ -33,6 +33,9 @@ Use the current Python binding and its tests as the API authority. - Use `references/java-tools.md` instead for Arrow file import through the Java `arrow2tsfile` command. +TsFile `DATE` maps to Arrow `date32`. Conversion preserves the calendar date +across host time zones and daylight-saving changes. + ## pandas Conversion ```python @@ -107,7 +110,44 @@ with TsFileTableWriter("output.tsfile", schema) as writer: writer.write_arrow_batch(record_batch_or_table) ``` -Use `batch_size > 0` for Arrow reads. Arrow writes accept a +Use `batch_size > 0` for Arrow reads. It specifies returned result rows after +filtering and OFFSET/LIMIT: every batch has that many rows except the final +batch at end of results. Batches may cross devices, chunks, and pages. Internal +scan windows and scratch memory are independent of this setting. + +C++ table scans build Arrow-layout buffers directly. Python imports these +buffers without a TsBlock conversion; batches retain ownership after the +result set or reader closes. Each result set reuses its first imported PyArrow schema +for subsequent batches. Retaining batches retains their memory. Native +`get_next_tsblock()` preserves the projected table column schemas, including TAG +and explicitly projected TIME columns. A projected INT64 FIELD named `time` +retains its stored values in its own output position after the implicit timestamp. + +When parallel reads are enabled, the query schedules device metadata and column +page planning, then whole column read/decompress/decode/write tasks on the +shared pool. Device tasks are fetched in windows as the result is consumed. +A time range can exclude a whole chunk before its pages are read. Aligned scans +use the shared time chunk's range, including timestamps with NULL field values. +Output order is stable. Aligned FIELD predicates first prune by +page statistics, then decode only predicate columns to compute a shared row +selection; output-only columns are decoded only for pages with accepted rows. +Selection is separate from Arrow null validity: exported batches contain only +selected rows. A page decoder resumes across small output batches without +rereading the payload. Each column releases its page payload and decoder after +writing that page's last selected row (or reaching LIMIT), even when the output +batch spans many sparsely selected pages. Only a page that still has rows for a +later batch retains its decoder state. Unknown statistics remain candidates. +Non-aligned sources retain timestamp union semantics and use a bounded merge +window. + +Unfiltered scans without OFFSET or LIMIT can reuse compressed input across page +planning and output. A query can retain up to 160 MiB of shared compressed ranges, +including contiguous ranges for wide aligned projections. This budget covers +cached input bytes. Decoders and the returned Arrow buffers use additional memory. +Time and field predicates use task-local read-ahead windows of up to 64 KiB. +Coalescing for filtered output stops at skipped pages and chunk boundaries. + +Arrow writes accept a `pyarrow.RecordBatch` or `pyarrow.Table`; include the registered time column and match all remaining columns to the Table schema. Use the wrapper writer when possible so it resolves the time-column index from the schema.