From 4e47594ad8a8cc3b3f82edecbba7a59333548783 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Mon, 30 Nov 2026 18:31:19 +0800 Subject: [PATCH 01/10] fix(python): push FIELD predicates into table queries Python table-model queries only accepted TAG predicates; FIELD value filtering existed only inside the C++ table query executor. - cwrapper: add a FieldFilterHandle API over AlignedFieldFilter (create checked/and/or/not/free) plus tsfile_query_table_with_filters and tsfile_reader_query_table_by_row_with_filters. Handles are borrowed and deep-copied per query, so callers keep ownership. - TsFileReader: query/queryByRow overloads taking a FIELD filter; the executor owns it once invoked and the reader deletes it on the validation paths that return earlier. - AlignedFieldFilter: add clone() for the copy-per-query contract. - Python: new field_filter module (field_eq/field_neq/ordered, field_between/field_not_between, field_is_null/field_is_not_null, compose with &, |, ~); query_table and query_table_by_row accept field_filter=. Values normalize as bool/int64/double/string, with TypeMismatchError, ColumnNotExistError and InvalidArgumentError for bad column/type/operator combinations; None is rejected in favour of the IS NULL predicates. - Tests: cwrapper C API coverage (selection, composition, reuse, errors, by-row paging) and Python DSL plus end-to-end query tests (scalar, Arrow batch, by-row, NULL semantics, type errors). - Skills: document FIELD filters for Python, C and C++. The CLI keeps --tag-filter only: this change adds a Python-side query option and does not alter existing CLI-visible behavior, so no CLI command/option synchronization is applicable. --- cpp/src/cwrapper/tsfile_cwrapper.cc | 294 ++++++++++++ cpp/src/cwrapper/tsfile_cwrapper.h | 140 ++++++ cpp/src/reader/filter/aligned_field_filter.cc | 18 + cpp/src/reader/filter/aligned_field_filter.h | 6 + cpp/src/reader/tsfile_reader.cc | 33 +- cpp/src/reader/tsfile_reader.h | 23 + cpp/test/cwrapper/cwrapper_extended_test.cc | 205 ++++++++ python/tests/test_field_filter.py | 144 ++++++ python/tests/test_field_filter_query.py | 452 ++++++++++++++++++ python/tsfile/__init__.py | 13 + python/tsfile/field_filter.py | 255 ++++++++++ python/tsfile/tsfile_cpp.pxd | 54 +++ python/tsfile/tsfile_py_cpp.pxd | 9 + python/tsfile/tsfile_py_cpp.pyx | 63 +++ python/tsfile/tsfile_reader.pyx | 169 ++++++- .../tsfile/references/properties-filters.md | 36 +- skills/tsfile/references/python.md | 5 + 17 files changed, 1905 insertions(+), 14 deletions(-) create mode 100644 python/tests/test_field_filter.py create mode 100644 python/tests/test_field_filter_query.py create mode 100644 python/tsfile/field_filter.py diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index c2e6f2a0d..aa670581f 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -43,6 +43,7 @@ #include "common/statistic.h" #include "common/tablet.h" #include "common/tsfile_common.h" +#include "reader/filter/aligned_field_filter.h" #include "reader/filter/tag_filter.h" #include "reader/result_set.h" #include "reader/table_result_set.h" @@ -3010,6 +3011,299 @@ ResultSet tsfile_query_table_with_tag_filter( return table_result_set; } +// ============== Field Filter API Implementation ============== + +namespace { + +storage::AlignedFieldFilter::CompareOp to_field_compare_op(FieldFilterOp op, + bool* valid) { + using CompareOp = storage::AlignedFieldFilter::CompareOp; + *valid = true; + switch (op) { + case FIELD_FILTER_EQ: + return CompareOp::EQ; + case FIELD_FILTER_NEQ: + return CompareOp::NE; + case FIELD_FILTER_LT: + return CompareOp::LT; + case FIELD_FILTER_LTEQ: + return CompareOp::LE; + case FIELD_FILTER_GT: + return CompareOp::GT; + case FIELD_FILTER_GTEQ: + return CompareOp::GE; + default: + *valid = false; + return CompareOp::EQ; + } +} + +// Builds the native literal for a comparison. Returns false for an unknown +// literal type or a NULL string payload. +bool to_field_literal(const FieldFilterValue& value, + storage::AlignedFieldFilter::Literal* literal) { + using Literal = storage::AlignedFieldFilter::Literal; + switch (value.type) { + case FIELD_FILTER_VALUE_BOOL: + *literal = Literal::boolean(value.bool_value); + return true; + case FIELD_FILTER_VALUE_INT64: + *literal = Literal::int64(value.int64_value); + return true; + case FIELD_FILTER_VALUE_DOUBLE: + *literal = Literal::float64(value.double_value); + return true; + case FIELD_FILTER_VALUE_STRING: + if (value.string_value == nullptr) { + return false; + } + *literal = Literal::string( + std::string(value.string_value, value.string_length)); + return true; + default: + return false; + } +} + +// Copies a FIELD filter handle into a filter owned by the query call. The +// table query executor (and the result set) owns the filter it receives, so +// the caller's handle cannot be handed over directly. +storage::Filter* clone_field_filter(FieldFilterHandle field_filter, + ERRNO* err_code) { + auto* native = dynamic_cast( + static_cast(field_filter)); + if (native == nullptr) { + *err_code = common::E_INVALID_ARG; + return nullptr; + } + storage::AlignedFieldFilter::Ptr copy = native->clone(); + if (copy == nullptr) { + *err_code = common::E_OOM; + return nullptr; + } + return copy.release(); +} + +} // namespace + +ERRNO tsfile_field_filter_create_checked(TsFileReader reader, + const char* table_name, + const char* column_name, + FieldFilterOp op, + const FieldFilterValue* value, + FieldFilterHandle* out_filter) { + if (out_filter != nullptr) { + *out_filter = nullptr; + } + if (reader == nullptr || table_name == nullptr || column_name == nullptr || + out_filter == nullptr) { + return common::E_INVALID_ARG; + } + const bool needs_value = + op != FIELD_FILTER_IS_NULL && op != FIELD_FILTER_IS_NOT_NULL; + if (needs_value && value == nullptr) { + return common::E_INVALID_ARG; + } + using FieldFilter = storage::AlignedFieldFilter; + try { + auto* r = static_cast(reader); + std::shared_ptr schema; + int ret = r->get_table_schema(table_name, schema); + if (ret != common::E_OK) { + return ret; + } + if (schema == nullptr) { + return common::E_TABLE_NOT_EXIST; + } + + FieldFilter::Ptr filter; + if (op == FIELD_FILTER_IS_NULL) { + filter = FieldFilter::is_null(column_name); + } else if (op == FIELD_FILTER_IS_NOT_NULL) { + filter = FieldFilter::is_not_null(column_name); + } else { + bool valid_op = true; + const FieldFilter::CompareOp compare_op = + to_field_compare_op(op, &valid_op); + if (!valid_op) { + return common::E_INVALID_ARG; + } + FieldFilter::Literal literal; + if (!to_field_literal(*value, &literal)) { + return common::E_INVALID_ARG; + } + filter = FieldFilter::compare(column_name, compare_op, + std::move(literal)); + } + if (filter == nullptr) { + return common::E_OOM; + } + // Resolve the column and bind the literal against its declared type so + // bad column names, non-FIELD columns and type mismatches surface here + // instead of during iteration. + ret = filter->bind(*schema); + if (ret == common::E_NOT_SUPPORT) { + return common::E_TYPE_NOT_MATCH; + } + if (ret != common::E_OK) { + return ret; + } + *out_filter = static_cast(filter.release()); + return common::E_OK; + } catch (const std::bad_alloc&) { + return common::E_OOM; + } catch (...) { + return common::E_FILE_READ_ERR; + } +} + +FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, + FieldFilterHandle right) { + if (left == nullptr || right == nullptr) { + return nullptr; + } + // Borrow both inputs: the returned node owns deep copies, so the caller's + // handles stay valid and can be freed independently. + try { + return static_cast( + storage::AlignedFieldFilter::and_filter( + static_cast(left)->clone(), + static_cast(right)->clone()) + .release()); + } catch (...) { + return nullptr; + } +} + +FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, + FieldFilterHandle right) { + if (left == nullptr || right == nullptr) { + return nullptr; + } + try { + return static_cast( + storage::AlignedFieldFilter::or_filter( + static_cast(left)->clone(), + static_cast(right)->clone()) + .release()); + } catch (...) { + return nullptr; + } +} + +FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter) { + if (filter == nullptr) { + return nullptr; + } + try { + return static_cast( + storage::AlignedFieldFilter::not_filter( + static_cast(filter)->clone()) + .release()); + } catch (...) { + return nullptr; + } +} + +void tsfile_field_filter_free(FieldFilterHandle filter) { + if (filter != nullptr) { + delete static_cast(filter); + } +} + +ResultSet tsfile_query_table_with_filters( + TsFileReader reader, const char* table_name, char** columns, + uint32_t column_num, Timestamp start_time, Timestamp end_time, int offset, + int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, + int batch_size, ERRNO* err_code) { + if (err_code == nullptr) { + return nullptr; + } + *err_code = common::E_INVALID_ARG; + if (reader == nullptr || table_name == nullptr || columns == nullptr || + column_num == 0 || offset < 0 || batch_size < 0) { + return nullptr; + } + try { + std::vector column_names; + column_names.reserve(column_num); + for (uint32_t i = 0; i < column_num; ++i) { + if (columns[i] == nullptr) { + return nullptr; + } + column_names.emplace_back(columns[i]); + } + storage::ResultSet* result_set = nullptr; + const int normalized_limit = limit < 0 ? -1 : limit; + storage::Filter* field_copy = nullptr; + if (field_filter != nullptr) { + field_copy = clone_field_filter(field_filter, err_code); + if (field_copy == nullptr) { + return nullptr; + } + } + *err_code = static_cast(reader)->query( + table_name, column_names, start_time, end_time, offset, + normalized_limit, result_set, + static_cast(tag_filter), field_copy, batch_size); + if (*err_code != common::E_OK) { + return nullptr; + } + return result_set; + } catch (const std::bad_alloc&) { + *err_code = common::E_OOM; + return nullptr; + } catch (...) { + *err_code = common::E_FILE_READ_ERR; + return nullptr; + } +} + +ResultSet tsfile_reader_query_table_by_row_with_filters( + TsFileReader reader, const char* table_name, char** column_names, + int column_names_len, int offset, int limit, TagFilterHandle tag_filter, + FieldFilterHandle field_filter, int batch_size, ERRNO* err_code) { + if (err_code == nullptr) { + return nullptr; + } + *err_code = common::E_INVALID_ARG; + if (reader == nullptr || table_name == nullptr || column_names == nullptr || + column_names_len <= 0 || offset < 0 || batch_size < 0) { + return nullptr; + } + try { + std::vector columns; + columns.reserve(static_cast(column_names_len)); + for (int i = 0; i < column_names_len; ++i) { + if (column_names[i] == nullptr) { + return nullptr; + } + columns.emplace_back(column_names[i]); + } + storage::ResultSet* result_set = nullptr; + storage::Filter* field_copy = nullptr; + if (field_filter != nullptr) { + field_copy = clone_field_filter(field_filter, err_code); + if (field_copy == nullptr) { + return nullptr; + } + } + *err_code = static_cast(reader)->queryByRow( + table_name, columns, offset, limit, result_set, + static_cast(tag_filter), field_copy, batch_size); + if (*err_code != common::E_OK) { + return nullptr; + } + return result_set; + } catch (const std::bad_alloc&) { + *err_code = common::E_OOM; + return nullptr; + } catch (...) { + *err_code = common::E_FILE_READ_ERR; + return nullptr; + } +} + #ifdef __cplusplus } #endif diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index ae84338a3..c31e57508 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -293,6 +293,7 @@ typedef void* TsRecord; typedef void* ResultSet; typedef void* TagFilterHandle; +typedef void* FieldFilterHandle; typedef void* PreparedSeriesHandle; typedef struct TsFilePreparedLocator { @@ -983,6 +984,38 @@ ResultSet tsfile_reader_query_table(TsFileReader reader, const char* table_name, TagFilterHandle tag_filter, int batch_size, ERRNO* err_code); +/** + * @brief Query table data with TAG and FIELD filters. + * + * Both filters are optional. FIELD predicates are pushed down into the table + * query executor: aligned devices use batch/page evaluation, non-aligned + * devices evaluate merged rows. The FIELD filter never matches NULL values; + * use FIELD_FILTER_IS_NULL / FIELD_FILTER_IS_NOT_NULL for that. + * + * @param tag_filter [in] Optional TAG filter, borrowed for the duration of the + * query and the returned result set. Free it with + * tsfile_tag_filter_free() after the result set is closed. + * @param field_filter [in] Optional FIELD filter. The handle is borrowed: the + * wrapper copies it, so the caller keeps ownership and must free it + * with tsfile_field_filter_free(). + * @return ResultSet handle on success; NULL on failure with *err_code set. + */ +ResultSet tsfile_query_table_with_filters( + TsFileReader reader, const char* table_name, char** columns, + uint32_t column_num, Timestamp start_time, Timestamp end_time, int offset, + int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, + int batch_size, ERRNO* err_code); + +/** + * @brief Row-limit table query with TAG and FIELD filters. + * + * Ownership matches tsfile_query_table_with_filters(). + */ +ResultSet tsfile_reader_query_table_by_row_with_filters( + TsFileReader reader, const char* table_name, char** column_names, + int column_names_len, int offset, int limit, TagFilterHandle tag_filter, + FieldFilterHandle field_filter, int batch_size, ERRNO* err_code); + ResultSet tsfile_query_table_batch(TsFileReader reader, const char* table_name, char** columns, uint32_t column_num, Timestamp start_time, Timestamp end_time, @@ -1370,6 +1403,113 @@ ResultSet tsfile_query_table_with_tag_filter( uint32_t column_num, Timestamp start_time, Timestamp end_time, TagFilterHandle tag_filter, int batch_size, ERRNO* err_code); +// ---------- FIELD Filter API ---------- +// +// FIELD filters select table rows by FIELD-column values. They compose with +// TAG filters and are evaluated by the native table query executor. A +// comparison never matches NULL; use FIELD_FILTER_IS_NULL / +// FIELD_FILTER_IS_NOT_NULL for NULL checks. +// +// Ownership: every create/compose function returns an owning handle. Free it +// with tsfile_field_filter_free(). The and/or/not functions borrow their +// inputs and return a new filter owning deep copies, so every input handle +// stays owned by the caller. Query functions borrow the handle and copy it +// before execution, so a handle may be reused and must be freed by the caller. + +/** + * @brief FIELD filter comparison operators. + */ +typedef enum { + FIELD_FILTER_EQ = 0, + FIELD_FILTER_NEQ = 1, + FIELD_FILTER_LT = 2, + FIELD_FILTER_LTEQ = 3, + FIELD_FILTER_GT = 4, + FIELD_FILTER_GTEQ = 5, + FIELD_FILTER_IS_NULL = 6, + FIELD_FILTER_IS_NOT_NULL = 7, +} FieldFilterOp; + +/** + * @brief Literal type carried by a FieldFilterValue. + */ +typedef enum { + FIELD_FILTER_VALUE_BOOL = 0, + FIELD_FILTER_VALUE_INT64 = 1, + FIELD_FILTER_VALUE_DOUBLE = 2, + FIELD_FILTER_VALUE_STRING = 3, +} FieldFilterValueType; + +/** + * @brief Comparison literal for tsfile_field_filter_create_checked(). + * + * Only the member selected by @c type is read. @c string_value is borrowed + * for the duration of the call. INT64 and DOUBLE literals bind to any numeric + * FIELD type using Java's number-narrowing rules. + */ +typedef struct { + FieldFilterValueType type; + bool bool_value; + int64_t int64_value; + double double_value; + const char* string_value; + uint32_t string_length; +} FieldFilterValue; + +/** + * @brief Create a FIELD predicate and return the error code directly. + * + * @param reader [in] Reader handle used to resolve the table schema. + * @param table_name [in] Table whose schema declares the FIELD column. + * @param column_name [in] Case-insensitive FIELD column name. + * @param op [in] Comparison operator (FieldFilterOp). + * @param value [in] Comparison literal. Ignored and may be NULL for + * FIELD_FILTER_IS_NULL / FIELD_FILTER_IS_NOT_NULL. + * @param out_filter [out] Required; set to NULL on failure. + * @return E_OK on success, E_INVALID_ARG for a bad handle/name/operator or a + * non-FIELD column, E_COLUMN_NOT_EXIST for an unknown column, + * E_TYPE_NOT_MATCH when the literal type cannot bind to the column + * type, E_TABLE_NOT_EXIST for an unknown table. + */ +ERRNO tsfile_field_filter_create_checked(TsFileReader reader, + const char* table_name, + const char* column_name, + FieldFilterOp op, + const FieldFilterValue* value, + FieldFilterHandle* out_filter); + +/** + * @brief Logical AND of two FIELD filters. + * + * Borrows both inputs and returns a new filter that owns deep copies, so the + * caller keeps and must still free both handles. Returns NULL on failure. + */ +FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, + FieldFilterHandle right); + +/** + * @brief Logical OR of two FIELD filters. + * + * Borrows both inputs and returns a new filter that owns deep copies, so the + * caller keeps and must still free both handles. Returns NULL on failure. + */ +FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, + FieldFilterHandle right); + +/** + * @brief Logical NOT of a FIELD filter. + * + * Borrows the input and returns a new filter that owns a deep copy, so the + * caller keeps and must still free the handle. Returns NULL on failure. NULL + * rows never satisfy a negated predicate. + */ +FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter); + +/** + * @brief Free a FIELD filter handle. + */ +void tsfile_field_filter_free(FieldFilterHandle filter); + // Close and free resource. void free_tablet(Tablet* tablet); void free_tsfile_result_set(ResultSet* result_set); diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index afa6bbb72..d1dfc8f0b 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -363,6 +363,24 @@ AlignedFieldFilter::Ptr AlignedFieldFilter::negate(Ptr node) { return node; } +AlignedFieldFilter::Ptr AlignedFieldFilter::clone() const { + switch (kind_) { + case Kind::COMPARISON: + case Kind::IS_NULL: + case Kind::IS_NOT_NULL: + return Ptr(new AlignedFieldFilter(kind_, column_, compare_op_, + literal_, negated_)); + case Kind::AND: + case Kind::OR: + return Ptr( + new AlignedFieldFilter(kind_, left_ ? left_->clone() : nullptr, + right_ ? right_->clone() : nullptr)); + case Kind::NOT: + return Ptr(new AlignedFieldFilter(Kind::NOT, nullptr, nullptr)); + } + return Ptr(new AlignedFieldFilter(Kind::NOT, nullptr, nullptr)); +} + std::vector AlignedFieldFilter::referenced_columns() const { std::vector columns; std::set seen_columns; diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 659d165b2..76aa96030 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -87,6 +87,12 @@ class AlignedFieldFilter : public Filter { static Ptr or_filter(Ptr left, Ptr right); static Ptr not_filter(Ptr child); + // Deep copy, including the bound literal and negation state. The table + // query executor takes ownership of the filter it runs, so a caller that + // keeps its own filter (for example a C binding handle reused across + // queries) must hand over a clone instead of the original. + Ptr clone() const; + Kind kind() const { return kind_; } CompareOp compare_op() const { return compare_op_; } const std::string& column() const { return column_; } diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index 4a39a9f23..147c24ebd 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -249,6 +249,18 @@ int TsFileReader::query(const std::string& table_name, int64_t start_time, int64_t end_time, int offset, int limit, ResultSet*& result_set, Filter* tag_filter, int batch_size) { + return query(table_name, columns_names, start_time, end_time, offset, limit, + result_set, tag_filter, /*field_filter=*/nullptr, batch_size); +} + +int TsFileReader::query(const std::string& table_name, + const std::vector& columns_names, + int64_t start_time, int64_t end_time, int offset, + int limit, ResultSet*& result_set, Filter* tag_filter, + Filter* field_filter, int batch_size) { + // The executor takes ownership of the field filter once it is invoked; + // delete it on the validation paths that return before that. + std::unique_ptr field_filter_guard(field_filter); if (tsfile_executor_ == nullptr) { return E_INVALID_ARG; } @@ -271,9 +283,9 @@ int TsFileReader::query(const std::string& table_name, Filter* time_filter = new TimeBetween(start_time, end_time, false); ensure_table_query_executor(batch_size); - ret = table_query_executor_->query(to_lower(table_name), columns_names, - time_filter, tag_filter, nullptr, offset, - limit, result_set); + ret = table_query_executor_->query( + to_lower(table_name), columns_names, time_filter, tag_filter, + field_filter_guard.release(), offset, limit, result_set); return ret; } @@ -459,6 +471,17 @@ int TsFileReader::queryByRow(const std::string& table_name, const std::vector& column_names, int offset, int limit, ResultSet*& result_set, Filter* tag_filter, int batch_size) { + return queryByRow(table_name, column_names, offset, limit, result_set, + tag_filter, /*field_filter=*/nullptr, batch_size); +} + +int TsFileReader::queryByRow(const std::string& table_name, + const std::vector& column_names, + int offset, int limit, ResultSet*& result_set, + Filter* tag_filter, Filter* field_filter, + int batch_size) { + // See query(...): the field filter belongs to the executor once invoked. + std::unique_ptr field_filter_guard(field_filter); if (tsfile_executor_ == nullptr) { return E_INVALID_ARG; } @@ -475,8 +498,8 @@ int TsFileReader::queryByRow(const std::string& table_name, ensure_table_query_executor(batch_size); ret = table_query_executor_->query(to_lower(table_name), column_names, /*time_filter=*/nullptr, tag_filter, - /*field_filter=*/nullptr, offset, limit, - result_set); + field_filter_guard.release(), offset, + limit, result_set); return ret; } diff --git a/cpp/src/reader/tsfile_reader.h b/cpp/src/reader/tsfile_reader.h index 6f2c7d340..a6ac916b5 100644 --- a/cpp/src/reader/tsfile_reader.h +++ b/cpp/src/reader/tsfile_reader.h @@ -134,6 +134,22 @@ class TsFileReader { int64_t end_time, int offset, int limit, ResultSet*& result_set, Filter* tag_filter = nullptr, int batch_size = 0); + /** + * @brief Table query with both TAG and FIELD filter pushdown. + * + * FIELD predicates are bound against the table schema and evaluated by + * the table query executor (aligned and non-aligned devices). + * + * @param tag_filter Borrowed; must outlive the result set. + * @param field_filter Ownership is transferred. The reader deletes it on + * every path that does not hand it to the executor; on success the + * result set owns and eventually deletes it. + */ + int query(const std::string& table_name, + const std::vector& columns_names, int64_t start_time, + int64_t end_time, int offset, int limit, ResultSet*& result_set, + Filter* tag_filter, Filter* field_filter, int batch_size = 0); + /** * @brief Query tree-model time series by row with offset and limit. * @@ -201,6 +217,13 @@ class TsFileReader { int limit, ResultSet*& result_set, Filter* tag_filter = nullptr, int batch_size = 0); + // Same as the overload above, plus a FIELD filter whose ownership is + // transferred exactly as in query(..., tag_filter, field_filter, ...). + int queryByRow(const std::string& table_name, + const std::vector& column_names, int offset, + int limit, ResultSet*& result_set, Filter* tag_filter, + Filter* field_filter, int batch_size = 0); + int query_table_on_tree(const std::vector& measurement_names, int64_t star_time, int64_t end_time, ResultSet*& result_set); diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 765a2fdfc..9988bf1e5 100644 --- a/cpp/test/cwrapper/cwrapper_extended_test.cc +++ b/cpp/test/cwrapper/cwrapper_extended_test.cc @@ -529,6 +529,211 @@ TEST(CWrapperExtendedTest, TagFilterCombinations) { std::remove(path.c_str()); } +TEST(CWrapperExtendedTest, FieldFilterSelectsRowsAndComposes) { + const std::string path = unique_path("cwrapper_ext_field"); + write_table_file(path); + + ERRNO err = RET_OK; + TsFileReader reader = tsfile_reader_new(path.c_str(), &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, reader); + CStrArray columns(kTableColumns); + + // INT32 >= 2 leaves rows 2,3,4 of each device. + FieldFilterValue int_value{}; + int_value.type = FIELD_FILTER_VALUE_INT64; + int_value.int64_value = 2; + FieldFilterHandle int_ge_two = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_GTEQ, + &int_value, &int_ge_two)); + ASSERT_NE(nullptr, int_ge_two); + + ResultSet filtered = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, int_ge_two, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, filtered); + std::vector rows = collect_row_identities(filtered, &err); + ASSERT_EQ(6u, rows.size()); + for (const auto& row : rows) { + EXPECT_GE(row.value, 2); + } + free_tsfile_result_set(&filtered); + + // The query copies the FIELD filter, so the same handle can serve another + // query and stays owned by the caller. + filtered = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, int_ge_two, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, filtered); + EXPECT_EQ(6, count_result_rows(filtered, &err)); + free_tsfile_result_set(&filtered); + + FieldFilterValue int_eq_two{}; + int_eq_two.type = FIELD_FILTER_VALUE_INT64; + int_eq_two.int64_value = 2; + FieldFilterHandle int_two = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &int_eq_two, &int_two)); + ASSERT_NE(nullptr, int_two); + filtered = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, int_two, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, filtered); + rows = collect_row_identities(filtered, &err); + ASSERT_EQ(2u, rows.size()); + for (const auto& row : rows) { + EXPECT_EQ(2, row.value); + } + free_tsfile_result_set(&filtered); + + // DOUBLE is NULL on each device's last row: IS NOT NULL keeps 4 rows per + // device, and a comparison never matches the NULL cells. + FieldFilterHandle double_not_null = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "DOUBLE", + FIELD_FILTER_IS_NOT_NULL, nullptr, &double_not_null)); + ASSERT_NE(nullptr, double_not_null); + filtered = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, double_not_null, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, filtered); + EXPECT_EQ(8, count_result_rows(filtered, &err)); + free_tsfile_result_set(&filtered); + + // AND composition with a BOOLEAN predicate: INT32 >= 2 and even rows. + FieldFilterValue bool_value{}; + bool_value.type = FIELD_FILTER_VALUE_BOOL; + bool_value.bool_value = true; + FieldFilterHandle flag_true = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "BOOLEAN", FIELD_FILTER_EQ, + &bool_value, &flag_true)); + ASSERT_NE(nullptr, flag_true); + FieldFilterHandle combined = tsfile_field_filter_and(int_ge_two, flag_true); + ASSERT_NE(nullptr, combined); + filtered = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, combined, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, filtered); + rows = collect_row_identities(filtered, &err); + ASSERT_EQ(4u, rows.size()); + for (const auto& row : rows) { + EXPECT_GE(row.value, 2); + EXPECT_EQ(0, row.value % 2); + } + free_tsfile_result_set(&filtered); + + // The by-row entry point applies OFFSET/LIMIT to accepted rows. + FieldFilterValue int_ge_one{}; + int_ge_one.type = FIELD_FILTER_VALUE_INT64; + int_ge_one.int64_value = 1; + FieldFilterHandle int_ge_one_filter = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_GTEQ, + &int_ge_one, &int_ge_one_filter)); + ASSERT_NE(nullptr, int_ge_one_filter); + ResultSet paged = tsfile_reader_query_table_by_row_with_filters( + reader, kTableName, columns.data(), static_cast(columns.size()), 1, + 2, nullptr, int_ge_one_filter, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, paged); + rows = collect_row_identities(paged, &err); + ASSERT_EQ(2u, rows.size()); + for (const auto& row : rows) { + EXPECT_GE(row.value, 1); + } + free_tsfile_result_set(&paged); + + tsfile_field_filter_free(int_ge_one_filter); + tsfile_field_filter_free(int_two); + tsfile_field_filter_free(double_not_null); + // Composition borrows its inputs and owns copies, so every input handle + // and the composed handle are freed here. + tsfile_field_filter_free(combined); + tsfile_field_filter_free(flag_true); + tsfile_field_filter_free(int_ge_two); + + tsfile_reader_close(reader); + std::remove(path.c_str()); +} + +TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { + const std::string path = unique_path("cwrapper_ext_field_err"); + write_table_file(path); + + ERRNO err = RET_OK; + TsFileReader reader = tsfile_reader_new(path.c_str(), &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, reader); + + FieldFilterValue int_value{}; + int_value.type = FIELD_FILTER_VALUE_INT64; + int_value.int64_value = 1; + FieldFilterValue string_value{}; + string_value.type = FIELD_FILTER_VALUE_STRING; + string_value.string_value = "not-an-int"; + string_value.string_length = + static_cast(std::strlen(string_value.string_value)); + + FieldFilterHandle handle = nullptr; + // A string literal cannot bind to an INT32 column. + EXPECT_EQ(RET_TYPE_NOT_MATCH, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", + FIELD_FILTER_EQ, &string_value, &handle)); + EXPECT_EQ(nullptr, handle); + + // A TAG column is not a FIELD predicate target. + EXPECT_EQ(RET_INVALID_ARG, tsfile_field_filter_create_checked( + reader, kTableName, "TAG", FIELD_FILTER_EQ, + &string_value, &handle)); + EXPECT_EQ(nullptr, handle); + + EXPECT_EQ(RET_COLUMN_NOT_EXIST, tsfile_field_filter_create_checked( + reader, kTableName, "MISSING", + FIELD_FILTER_EQ, &int_value, &handle)); + EXPECT_EQ(RET_TABLE_NOT_EXIST, tsfile_field_filter_create_checked( + reader, "missing_table", "INT32", + FIELD_FILTER_EQ, &int_value, &handle)); + + // Argument validation. + EXPECT_EQ(RET_INVALID_ARG, tsfile_field_filter_create_checked( + nullptr, kTableName, "INT32", + FIELD_FILTER_EQ, &int_value, &handle)); + EXPECT_EQ(RET_INVALID_ARG, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + nullptr, &handle)); + EXPECT_EQ(RET_INVALID_ARG, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &int_value, nullptr)); + EXPECT_EQ(nullptr, tsfile_field_filter_and(nullptr, nullptr)); + EXPECT_EQ(nullptr, tsfile_field_filter_not(nullptr)); + + // A deliberately empty time range still yields an empty result set. + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_GTEQ, + &int_value, &handle)); + ASSERT_NE(nullptr, handle); + CStrArray columns(kTableColumns); + ResultSet empty = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 100, 0, 0, -1, + nullptr, handle, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, empty); + EXPECT_EQ(0, count_result_rows(empty, &err)); + free_tsfile_result_set(&empty); + tsfile_field_filter_free(handle); + + tsfile_reader_close(reader); + std::remove(path.c_str()); +} + TEST(CWrapperExtendedTest, TreeRecordHelpersAndTableOnTree) { const std::string path = unique_path("cwrapper_ext_tree"); write_tree_file(path); diff --git a/python/tests/test_field_filter.py b/python/tests/test_field_filter.py new file mode 100644 index 000000000..3a34d088d --- /dev/null +++ b/python/tests/test_field_filter.py @@ -0,0 +1,144 @@ +# 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. +# + +"""Unit tests for the pure-Python FieldFilter DSL (no native calls).""" + +import pytest + +from tsfile import ( + FieldFilter, + field_eq, + field_neq, + field_lt, + field_lteq, + field_gt, + field_gteq, + field_is_null, + field_is_not_null, + field_between, + field_not_between, +) +from tsfile.field_filter import ( + AndFieldFilter, + BetweenFieldFilter, + ComparisonFieldFilter, + NotFieldFilter, + OrFieldFilter, +) + + +def test_factories_build_comparison_filters(): + cases = [ + (field_eq("value", 1.5), ComparisonFieldFilter.EQ), + (field_neq("value", 1.5), ComparisonFieldFilter.NEQ), + (field_lt("value", 1.5), ComparisonFieldFilter.LT), + (field_lteq("value", 1.5), ComparisonFieldFilter.LTEQ), + (field_gt("value", 1.5), ComparisonFieldFilter.GT), + (field_gteq("value", 1.5), ComparisonFieldFilter.GTEQ), + (field_is_null("value"), ComparisonFieldFilter.IS_NULL), + (field_is_not_null("value"), ComparisonFieldFilter.IS_NOT_NULL), + ] + for field_filter, op in cases: + assert isinstance(field_filter, ComparisonFieldFilter) + assert isinstance(field_filter, FieldFilter) + assert field_filter.column_name == "value" + assert field_filter.op == op + + +def test_repr_matches_tag_filter_style(): + assert repr(field_eq("value", 3.0)) == "FieldFilter(value == 3.0)" + assert repr(field_is_null("value")) == "FieldFilter(value IS NULL)" + assert repr(field_between("value", 1, 2)) == ("FieldFilter(value BETWEEN 1 AND 2)") + assert repr(field_not_between("value", 1, 2)) == ( + "FieldFilter(value NOT BETWEEN 1 AND 2)" + ) + combined = field_eq("a", 1) & field_gt("b", 2.0) + assert repr(combined) == "(FieldFilter(a == 1) AND FieldFilter(b > 2.0))" + assert repr(~field_eq("a", 1)) == "NOT(FieldFilter(a == 1))" + + +def test_logical_composition(): + left = field_eq("a", 1) + right = field_gt("b", 2.0) + assert isinstance(left & right, AndFieldFilter) + assert isinstance(left | right, OrFieldFilter) + assert isinstance(~left, NotFieldFilter) + assert (left & right).left is left + assert (left | right).right is right + assert (~left).filter is left + + +def test_between_bounds_are_normalized(): + between = field_between("value", 1, 2.5) + assert isinstance(between, BetweenFieldFilter) + assert between.lower == 1 + assert between.lower_type == ComparisonFieldFilter.INT64 + assert between.upper == 2.5 + assert between.upper_type == ComparisonFieldFilter.DOUBLE + assert between.is_not is False + assert field_not_between("value", 1, 2).is_not is True + + +def test_literal_types_follow_python_value_types(): + assert field_eq("c", True).value_type == ComparisonFieldFilter.BOOL + # bool is a subclass of int but must not be treated as INT64. + assert field_eq("c", False).value_type == ComparisonFieldFilter.BOOL + assert field_eq("c", 7).value_type == ComparisonFieldFilter.INT64 + assert field_eq("c", 7.5).value_type == ComparisonFieldFilter.DOUBLE + assert field_eq("c", "x").value_type == ComparisonFieldFilter.STRING + + +def test_numpy_scalars_are_accepted(): + np = pytest.importorskip("numpy") + int_filter = field_eq("c", np.int64(7)) + assert int_filter.value == 7 + assert int_filter.value_type == ComparisonFieldFilter.INT64 + float_filter = field_eq("c", np.float64(7.5)) + assert float_filter.value == 7.5 + assert float_filter.value_type == ComparisonFieldFilter.DOUBLE + bool_filter = field_eq("c", np.bool_(True)) + assert bool_filter.value is True + assert bool_filter.value_type == ComparisonFieldFilter.BOOL + + +def test_none_value_is_rejected_with_null_hint(): + with pytest.raises(ValueError, match="field_is_null"): + field_eq("value", None) + with pytest.raises(ValueError, match="BETWEEN upper bound"): + field_between("value", 1.0, None) + + +def test_unsupported_value_types_are_rejected(): + with pytest.raises(TypeError): + field_eq("value", [1, 2]) + with pytest.raises(TypeError): + field_eq("value", object()) + + +def test_int_outside_int64_is_rejected(): + with pytest.raises(OverflowError): + field_eq("value", 2**63) + with pytest.raises(OverflowError): + field_eq("value", -(2**63) - 1) + + +def test_between_bounds_must_be_compatible(): + with pytest.raises(TypeError): + field_between("value", "low", 1.0) + with pytest.raises(TypeError): + field_between("value", True, False) diff --git a/python/tests/test_field_filter_query.py b/python/tests/test_field_filter_query.py new file mode 100644 index 000000000..fe0a91869 --- /dev/null +++ b/python/tests/test_field_filter_query.py @@ -0,0 +1,452 @@ +# 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. +# + +"""End-to-end tests for FIELD predicate pushdown in table queries.""" + +import os + +import pyarrow as pa +import pytest + +from tsfile import ( + ColumnSchema, + TableSchema, + TSDataType, + ColumnCategory, + TsFileTableWriter, + TsFileReader, + Tablet, + field_between, + field_eq, + field_gt, + field_gteq, + field_is_not_null, + field_is_null, + field_lt, + field_lteq, + field_neq, + field_not_between, + tag_eq, +) +from tsfile.exceptions import ( + ColumnNotExistError, + InvalidArgumentError, + TypeMismatchError, +) + +TSFILE_PATH = "test_field_filter_query.tsfile" + +TABLE_NAME = "sensors" +COLUMNS = [ + ColumnSchema("region", TSDataType.STRING, ColumnCategory.TAG), + ColumnSchema("device", TSDataType.STRING, ColumnCategory.TAG), + ColumnSchema("value", TSDataType.DOUBLE, ColumnCategory.FIELD), + ColumnSchema("count", TSDataType.INT64, ColumnCategory.FIELD), + ColumnSchema("flag", TSDataType.BOOLEAN, ColumnCategory.FIELD), + ColumnSchema("name", TSDataType.STRING, ColumnCategory.FIELD), + ColumnSchema("sparse", TSDataType.DOUBLE, ColumnCategory.FIELD), +] +SCHEMA = TableSchema(TABLE_NAME, COLUMNS) +COLUMN_NAMES = ["region", "device", "value", "count", "flag", "name", "sparse"] +COLUMN_TYPES = [ + TSDataType.STRING, + TSDataType.STRING, + TSDataType.DOUBLE, + TSDataType.INT64, + TSDataType.BOOLEAN, + TSDataType.STRING, + TSDataType.DOUBLE, +] + +# Test data (timestamps are global and unique across devices): +# region | device | timestamps | value | count | flag | sparse +# north | dev_a | 0..4 | ts | ts*10 | ts % 2 == 0 | ts if even +# north | dev_b | 5..9 | ts | ts*10 | ts % 2 == 0 | ts if even +# south | dev_c | 10..14 | ts | ts*10 | ts % 2 == 0 | ts if even +# east | dev_d | 15..19 | ts | ts*10 | ts % 2 == 0 | ts if even +DEVICES = [ + ("north", "dev_a", 0, 5), + ("north", "dev_b", 5, 10), + ("south", "dev_c", 10, 15), + ("east", "dev_d", 15, 20), +] + + +@pytest.fixture(scope="module", autouse=True) +def create_tsfile(): + if os.path.exists(TSFILE_PATH): + os.remove(TSFILE_PATH) + + with TsFileTableWriter(TSFILE_PATH, SCHEMA) as writer: + for region, device, start, end in DEVICES: + count = end - start + tablet = Tablet(COLUMN_NAMES, COLUMN_TYPES, count) + for i in range(count): + ts = start + i + tablet.add_timestamp(i, ts) + tablet.add_value_by_name("region", i, region) + tablet.add_value_by_name("device", i, device) + tablet.add_value_by_name("value", i, float(ts)) + tablet.add_value_by_name("count", i, ts * 10) + tablet.add_value_by_name("flag", i, ts % 2 == 0) + tablet.add_value_by_name("name", i, f"n{ts}") + # Leave odd timestamps NULL so IS NULL / NOT predicate + # semantics are observable. + if ts % 2 == 0: + tablet.add_value_by_name("sparse", i, float(ts)) + writer.write_table(tablet) + + yield + + if os.path.exists(TSFILE_PATH): + os.remove(TSFILE_PATH) + + +def _scalar_rows(result): + rows = [] + while result.next(): + rows.append( + ( + result.get_value_by_name("region"), + result.get_value_by_name("device"), + result.get_value_by_name("value"), + result.get_value_by_name("count"), + result.get_value_by_name("flag"), + result.get_value_by_name("name"), + result.get_value_by_name("sparse"), + ) + ) + return rows + + +def _arrow_rows(result): + tables = [] + while True: + batch = result.read_arrow_batch() + if batch is None: + break + tables.append(batch) + if not tables: + return [] + combined = pa.concat_tables(tables) + rows = [] + for i in range(combined.num_rows): + rows.append(tuple(combined.column(name)[i].as_py() for name in COLUMN_NAMES)) + return rows + + +def _query(reader, field_filter, columns=None, **kwargs): + with reader.query_table( + TABLE_NAME, + columns or COLUMN_NAMES, + field_filter=field_filter, + **kwargs, + ) as result: + return _scalar_rows(result) + + +def _times(reader, field_filter, **kwargs): + rows = _query(reader, field_filter, **kwargs) + return sorted(row[2] for row in rows) + + +# =========================================================================== +# Scalar (row-by-row) queries +# =========================================================================== +class TestFieldFilterScalar: + + def test_eq(self): + with TsFileReader(TSFILE_PATH) as reader: + rows = _query(reader, field_eq("value", 7.0)) + assert len(rows) == 1 + assert rows[0][2] == 7.0 + assert rows[0][3] == 70 + + def test_neq(self): + with TsFileReader(TSFILE_PATH) as reader: + rows = _query(reader, field_neq("value", 7.0)) + assert len(rows) == 19 + assert all(row[2] != 7.0 for row in rows) + + def test_ordered_comparisons(self): + with TsFileReader(TSFILE_PATH) as reader: + assert _times(reader, field_lt("value", 3.0)) == [0.0, 1.0, 2.0] + assert _times(reader, field_lteq("value", 3.0)) == [ + 0.0, + 1.0, + 2.0, + 3.0, + ] + assert _times(reader, field_gt("value", 16.0)) == [17.0, 18.0, 19.0] + assert _times(reader, field_gteq("value", 16.0)) == [ + 16.0, + 17.0, + 18.0, + 19.0, + ] + + def test_int_literal_binds_to_int64_and_double_columns(self): + with TsFileReader(TSFILE_PATH) as reader: + rows = _query(reader, field_eq("count", 50)) + assert len(rows) == 1 + assert rows[0][2] == 5.0 + # An int literal also bind to a DOUBLE column. + assert _times(reader, field_eq("value", 7)) == [7.0] + + def test_bool_and_string_columns(self): + with TsFileReader(TSFILE_PATH) as reader: + assert len(_query(reader, field_eq("flag", True))) == 10 + rows = _query(reader, field_eq("name", "n13")) + assert len(rows) == 1 + assert rows[0][0] == "south" + + def test_between(self): + with TsFileReader(TSFILE_PATH) as reader: + assert _times(reader, field_between("value", 5.0, 9.0)) == [ + 5.0, + 6.0, + 7.0, + 8.0, + 9.0, + ] + + def test_not_between(self): + with TsFileReader(TSFILE_PATH) as reader: + times = _times(reader, field_not_between("value", 5.0, 9.0)) + assert len(times) == 15 + assert not any(5.0 <= value <= 9.0 for value in times) + + def test_between_with_mixed_numeric_bounds(self): + with TsFileReader(TSFILE_PATH) as reader: + assert _times(reader, field_between("value", 5, 5.5)) == [5.0] + + def test_is_null_and_is_not_null(self): + with TsFileReader(TSFILE_PATH) as reader: + not_null = _query(reader, field_is_not_null("sparse")) + assert len(not_null) == 10 + assert all(row[6] is not None for row in not_null) + is_null = _query(reader, field_is_null("sparse")) + assert len(is_null) == 10 + assert all(row[6] is None for row in is_null) + + def test_comparison_never_matches_null(self): + with TsFileReader(TSFILE_PATH) as reader: + rows = _query(reader, field_gt("sparse", -1.0)) + assert len(rows) == 10 + assert all(row[6] is not None for row in rows) + + def test_negated_comparison_excludes_null(self): + # NOT(=) becomes != and NULL cells satisfy neither form. + with TsFileReader(TSFILE_PATH) as reader: + rows = _query(reader, ~field_eq("sparse", 10.0)) + assert len(rows) == 9 + assert all(row[6] is not None for row in rows) + + def test_no_match(self): + with TsFileReader(TSFILE_PATH) as reader: + assert _query(reader, field_eq("value", 1000.0)) == [] + assert _query(reader, field_between("value", 100.0, 200.0)) == [] + + def test_logical_composition(self): + with TsFileReader(TSFILE_PATH) as reader: + both = field_gteq("value", 2.0) & field_lteq("value", 3.0) + assert _times(reader, both) == [2.0, 3.0] + either = field_eq("value", 0.0) | field_eq("value", 19.0) + assert _times(reader, either) == [0.0, 19.0] + negated = ~(field_lt("value", 18.0)) + assert _times(reader, negated) == [18.0, 19.0] + + def test_time_range_combines_with_field_filter(self): + with TsFileReader(TSFILE_PATH) as reader: + rows = _query( + reader, + field_gteq("value", 0.0), + start_time=3, + end_time=6, + ) + assert sorted(row[2] for row in rows) == [3.0, 4.0, 5.0, 6.0] + + def test_tag_and_field_filters_combine(self): + with TsFileReader(TSFILE_PATH) as reader: + rows = _query( + reader, + field_gt("value", 7.0), + tag_filter=tag_eq("region", "north"), + ) + assert sorted(row[2] for row in rows) == [8.0, 9.0] + + def test_filter_column_need_not_be_projected(self): + with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table( + TABLE_NAME, + ["region", "value"], + field_filter=field_eq("count", 50), + ) as result: + rows = [] + while result.next(): + rows.append( + ( + result.get_value_by_name("region"), + result.get_value_by_name("value"), + ) + ) + assert rows == [("north", 5.0)] + + def test_filter_object_is_reusable(self): + field_filter = field_gteq("value", 18.0) + with TsFileReader(TSFILE_PATH) as reader: + assert _times(reader, field_filter) == [18.0, 19.0] + assert _times(reader, field_filter) == [18.0, 19.0] + + +# =========================================================================== +# Arrow batch (TsBlock) queries +# =========================================================================== +class TestFieldFilterArrow: + + def test_between(self): + with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table( + TABLE_NAME, + COLUMN_NAMES, + field_filter=field_between("value", 5.0, 9.0), + batch_size=2, + ) as result: + rows = _arrow_rows(result) + assert sorted(row[2] for row in rows) == [ + 5.0, + 6.0, + 7.0, + 8.0, + 9.0, + ] + + def test_eq_with_small_batches(self): + with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table( + TABLE_NAME, + COLUMN_NAMES, + field_filter=field_eq("name", "n13"), + batch_size=1, + ) as result: + rows = _arrow_rows(result) + assert len(rows) == 1 + assert rows[0][0] == "south" + + def test_no_match(self): + with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table( + TABLE_NAME, + COLUMN_NAMES, + field_filter=field_eq("value", 1000.0), + batch_size=4, + ) as result: + assert _arrow_rows(result) == [] + + def test_scalar_and_arrow_agree(self): + field_filter = field_is_not_null("sparse") & field_lteq("value", 12.0) + with TsFileReader(TSFILE_PATH) as reader: + scalar = _query(reader, field_filter) + with reader.query_table( + TABLE_NAME, + COLUMN_NAMES, + field_filter=field_filter, + batch_size=3, + ) as result: + arrow = _arrow_rows(result) + assert len(scalar) == len(arrow) == 7 + assert sorted(row[2] for row in scalar) == sorted(row[2] for row in arrow) + + +# =========================================================================== +# By-row queries +# =========================================================================== +class TestFieldFilterByRow: + + def test_offset_limit_count_accepted_rows(self): + with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table_by_row( + TABLE_NAME, + COLUMN_NAMES, + offset=2, + limit=2, + tag_filter=tag_eq("device", "dev_a"), + field_filter=field_gt("value", 0.0), + ) as result: + rows = _scalar_rows(result) + # dev_a matches timestamps 1..4; OFFSET 2 / LIMIT 2 keeps 3 and 4. + assert [row[2] for row in rows] == [3.0, 4.0] + + def test_with_tag_filter(self): + with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table_by_row( + TABLE_NAME, + COLUMN_NAMES, + tag_filter=tag_eq("device", "dev_c"), + field_filter=field_lt("value", 12.0), + ) as result: + rows = _scalar_rows(result) + assert sorted(row[2] for row in rows) == [10.0, 11.0] + + +# =========================================================================== +# Validation errors +# =========================================================================== +class TestFieldFilterErrors: + + def test_unknown_column(self): + with TsFileReader(TSFILE_PATH) as reader: + with pytest.raises(ColumnNotExistError): + reader.query_table( + TABLE_NAME, COLUMN_NAMES, field_filter=field_eq("missing", 1) + ) + + def test_tag_column_is_rejected(self): + with TsFileReader(TSFILE_PATH) as reader: + with pytest.raises(InvalidArgumentError): + reader.query_table( + TABLE_NAME, + COLUMN_NAMES, + field_filter=field_eq("region", "north"), + ) + + def test_string_literal_on_numeric_column(self): + with TsFileReader(TSFILE_PATH) as reader: + with pytest.raises(TypeMismatchError): + reader.query_table( + TABLE_NAME, COLUMN_NAMES, field_filter=field_eq("value", "x") + ) + + def test_numeric_literal_on_string_column(self): + with TsFileReader(TSFILE_PATH) as reader: + with pytest.raises(TypeMismatchError): + reader.query_table( + TABLE_NAME, COLUMN_NAMES, field_filter=field_eq("name", 1) + ) + + def test_bool_literal_on_numeric_column(self): + with TsFileReader(TSFILE_PATH) as reader: + with pytest.raises(TypeMismatchError): + reader.query_table( + TABLE_NAME, COLUMN_NAMES, field_filter=field_eq("value", True) + ) + + def test_unknown_filter_object(self): + with TsFileReader(TSFILE_PATH) as reader: + with pytest.raises(TypeError): + reader.query_table(TABLE_NAME, COLUMN_NAMES, field_filter=object()) diff --git a/python/tsfile/__init__.py b/python/tsfile/__init__.py index fec2d2e85..508193fe6 100644 --- a/python/tsfile/__init__.py +++ b/python/tsfile/__init__.py @@ -86,6 +86,19 @@ def _preload_dll(path): tag_between, tag_not_between, ) +from .field_filter import ( + FieldFilter, + field_eq, + field_neq, + field_lt, + field_lteq, + field_gt, + field_gteq, + field_is_null, + field_is_not_null, + field_between, + field_not_between, +) from .tsfile_writer import TsFileWriterPy as TsFileWriter from .tsfile_py_cpp import ( get_file_read_backend, diff --git a/python/tsfile/field_filter.py b/python/tsfile/field_filter.py new file mode 100644 index 000000000..0f91a46ec --- /dev/null +++ b/python/tsfile/field_filter.py @@ -0,0 +1,255 @@ +# 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. +# + +"""FIELD-column value filters for table-model queries. + +A ``FieldFilter`` selects table rows by the values of FIELD columns. Pass it as +``field_filter=`` to ``TsFileReader.query_table`` or +``query_table_by_row``; the predicate is pushed down into the native table +query executor. Comparison filters never match NULL cells -- use +:func:`field_is_null` / :func:`field_is_not_null` for NULL checks. + +Values may be ``bool``, ``int`` (64-bit range), ``float`` or ``str``. Numeric +literals adapt to the column's declared numeric type; a string literal needs a +string-like FIELD column and vice versa. The native layer raises +``TypeMismatchError`` for incompatible combinations. +""" + +from numbers import Integral, Real + +INT64_MIN = -(2**63) +INT64_MAX = 2**63 - 1 + +# Literal type tags matching FieldFilterValueType in the C wrapper. +BOOL = 0 +INT64 = 1 +DOUBLE = 2 +STRING = 3 + +_NUMERIC_VALUE_TYPES = (INT64, DOUBLE) + + +def _normalize_literal(value, column_name: str, role: str = "comparison value"): + """Convert a Python value into ``(value, value_type)`` for the native layer. + + numpy scalars are accepted through their ``item()`` conversion. ``None`` + is rejected because a comparison with NULL is never true; use the IS NULL + predicates instead. + """ + if hasattr(value, "item") and not isinstance(value, (str, bytes)): + value = value.item() + if isinstance(value, bool): + return value, BOOL + if isinstance(value, Integral): + value = int(value) + if value < INT64_MIN or value > INT64_MAX: + raise OverflowError( + f"{role} for FIELD column {column_name!r} is outside the " + f"64-bit integer range" + ) + return value, INT64 + if isinstance(value, Real): + return float(value), DOUBLE + if isinstance(value, str): + return value, STRING + if value is None: + raise ValueError( + f"{role} for FIELD column {column_name!r} cannot be None; " + f"use field_is_null() or field_is_not_null()" + ) + raise TypeError( + f"Unsupported {role} type for FIELD column {column_name!r}: " + f"{type(value).__name__}; expected bool, int, float or str" + ) + + +class FieldFilter: + """Base class for FIELD filters used in table queries.""" + + def __and__(self, other): + return AndFieldFilter(self, other) + + def __or__(self, other): + return OrFieldFilter(self, other) + + def __invert__(self): + return NotFieldFilter(self) + + +class ComparisonFieldFilter(FieldFilter): + """A FIELD filter comparing a column to a value with a given operator.""" + + # Operator constants matching FieldFilterOp in C + EQ = 0 + NEQ = 1 + LT = 2 + LTEQ = 3 + GT = 4 + GTEQ = 5 + IS_NULL = 6 + IS_NOT_NULL = 7 + + # Literal type tags matching FieldFilterValueType in C + BOOL = BOOL + INT64 = INT64 + DOUBLE = DOUBLE + STRING = STRING + + # Operators that take no comparison value. + _NO_VALUE_OPS = (IS_NULL, IS_NOT_NULL) + + def __init__(self, column_name: str, value, op: int): + self.column_name = column_name + self.op = op + if op in self._NO_VALUE_OPS: + self.value = None + self.value_type = None + else: + self.value, self.value_type = _normalize_literal(value, column_name) + + def __repr__(self): + op_names = { + 0: "==", + 1: "!=", + 2: "<", + 3: "<=", + 4: ">", + 5: ">=", + 6: "IS NULL", + 7: "IS NOT NULL", + } + if self.op in self._NO_VALUE_OPS: + return f"FieldFilter({self.column_name} {op_names.get(self.op, '?')})" + return ( + f"FieldFilter({self.column_name} {op_names.get(self.op, '?')} " + f"{self.value!r})" + ) + + +class BetweenFieldFilter(FieldFilter): + """A FIELD filter for range queries.""" + + def __init__(self, column_name: str, lower, upper, is_not: bool = False): + self.column_name = column_name + self.lower, lower_type = _normalize_literal( + lower, column_name, "BETWEEN lower bound" + ) + self.upper, upper_type = _normalize_literal( + upper, column_name, "BETWEEN upper bound" + ) + self.lower_type = lower_type + self.upper_type = upper_type + both_numeric = ( + lower_type in _NUMERIC_VALUE_TYPES and upper_type in _NUMERIC_VALUE_TYPES + ) + if not both_numeric and not (lower_type == upper_type == STRING): + raise TypeError( + f"BETWEEN bounds for FIELD column {column_name!r} must both be " + f"numeric or both be strings" + ) + self.is_not = is_not + + def __repr__(self): + op = "NOT BETWEEN" if self.is_not else "BETWEEN" + return ( + f"FieldFilter({self.column_name} {op} {self.lower!r} " + f"AND {self.upper!r})" + ) + + +class AndFieldFilter(FieldFilter): + """Logical AND of two FIELD filters.""" + + def __init__(self, left: FieldFilter, right: FieldFilter): + self.left = left + self.right = right + + def __repr__(self): + return f"({self.left} AND {self.right})" + + +class OrFieldFilter(FieldFilter): + """Logical OR of two FIELD filters.""" + + def __init__(self, left: FieldFilter, right: FieldFilter): + self.left = left + self.right = right + + def __repr__(self): + return f"({self.left} OR {self.right})" + + +class NotFieldFilter(FieldFilter): + """Logical NOT of a FIELD filter. NULL cells never satisfy the negation.""" + + def __init__(self, filter: FieldFilter): + self.filter = filter + + def __repr__(self): + return f"NOT({self.filter})" + + +# Convenience factory functions +def field_eq(column_name: str, value) -> FieldFilter: + """Create a FIELD equality filter: column == value.""" + return ComparisonFieldFilter(column_name, value, ComparisonFieldFilter.EQ) + + +def field_neq(column_name: str, value) -> FieldFilter: + """Create a FIELD inequality filter: column != value.""" + return ComparisonFieldFilter(column_name, value, ComparisonFieldFilter.NEQ) + + +def field_lt(column_name: str, value) -> FieldFilter: + """Create a FIELD less-than filter: column < value.""" + return ComparisonFieldFilter(column_name, value, ComparisonFieldFilter.LT) + + +def field_lteq(column_name: str, value) -> FieldFilter: + """Create a FIELD less-than-or-equal filter: column <= value.""" + return ComparisonFieldFilter(column_name, value, ComparisonFieldFilter.LTEQ) + + +def field_gt(column_name: str, value) -> FieldFilter: + """Create a FIELD greater-than filter: column > value.""" + return ComparisonFieldFilter(column_name, value, ComparisonFieldFilter.GT) + + +def field_gteq(column_name: str, value) -> FieldFilter: + """Create a FIELD greater-than-or-equal filter: column >= value.""" + return ComparisonFieldFilter(column_name, value, ComparisonFieldFilter.GTEQ) + + +def field_is_null(column_name: str) -> FieldFilter: + """Create a FIELD IS NULL filter: the cell has no value.""" + return ComparisonFieldFilter(column_name, None, ComparisonFieldFilter.IS_NULL) + + +def field_is_not_null(column_name: str) -> FieldFilter: + """Create a FIELD IS NOT NULL filter: the cell has a value.""" + return ComparisonFieldFilter(column_name, None, ComparisonFieldFilter.IS_NOT_NULL) + + +def field_between(column_name: str, lower, upper) -> FieldFilter: + """Create a FIELD BETWEEN filter: lower <= column <= upper.""" + return BetweenFieldFilter(column_name, lower, upper, is_not=False) + + +def field_not_between(column_name: str, lower, upper) -> FieldFilter: + """Create a FIELD NOT BETWEEN filter. NULL cells never match.""" + return BetweenFieldFilter(column_name, lower, upper, is_not=True) diff --git a/python/tsfile/tsfile_cpp.pxd b/python/tsfile/tsfile_cpp.pxd index 12e72075c..118ea771a 100644 --- a/python/tsfile/tsfile_cpp.pxd +++ b/python/tsfile/tsfile_cpp.pxd @@ -240,6 +240,7 @@ cdef extern from "cwrapper/tsfile_cwrapper.h": int32_t tsfile_get_thread_count() ctypedef void * TagFilterHandle + ctypedef void * FieldFilterHandle # reader:new and close TsFileReader tsfile_reader_new(const char * pathname, ErrorCode * err_code); @@ -469,6 +470,59 @@ cdef extern from "cwrapper/tsfile_cwrapper.h": int batch_size, ErrorCode* err_code) + # FIELD filter types and functions + + ctypedef enum FieldFilterOp: + FIELD_FILTER_EQ = 0, + FIELD_FILTER_NEQ = 1, + FIELD_FILTER_LT = 2, + FIELD_FILTER_LTEQ = 3, + FIELD_FILTER_GT = 4, + FIELD_FILTER_GTEQ = 5, + FIELD_FILTER_IS_NULL = 6, + FIELD_FILTER_IS_NOT_NULL = 7, + + ctypedef enum FieldFilterValueType: + FIELD_FILTER_VALUE_BOOL = 0, + FIELD_FILTER_VALUE_INT64 = 1, + FIELD_FILTER_VALUE_DOUBLE = 2, + FIELD_FILTER_VALUE_STRING = 3, + + ctypedef struct FieldFilterValue: + FieldFilterValueType type + bint bool_value + int64_t int64_value + double double_value + const char* string_value + uint32_t string_length + + ErrorCode tsfile_field_filter_create_checked( + TsFileReader reader, const char* table_name, const char* column_name, + FieldFilterOp op, const FieldFilterValue* value, + FieldFilterHandle* out_filter) + + FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, + FieldFilterHandle right) + + FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, + FieldFilterHandle right) + + FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter) + + void tsfile_field_filter_free(FieldFilterHandle filter) + + ResultSet tsfile_query_table_with_filters( + TsFileReader reader, const char* table_name, char** columns, + uint32_t column_num, int64_t start_time, int64_t end_time, + int offset, int limit, TagFilterHandle tag_filter, + FieldFilterHandle field_filter, int batch_size, ErrorCode* err_code) + + ResultSet tsfile_reader_query_table_by_row_with_filters( + TsFileReader reader, const char* table_name, char** column_names, + int column_names_len, int offset, int limit, + TagFilterHandle tag_filter, FieldFilterHandle field_filter, + int batch_size, ErrorCode* err_code) + # resultSet : get data from resultSet bint tsfile_result_set_next(ResultSet result_set, ErrorCode * err_code) nogil; bint tsfile_result_set_is_null_by_index(ResultSet result_set, uint32_t column_index); diff --git a/python/tsfile/tsfile_py_cpp.pxd b/python/tsfile/tsfile_py_cpp.pxd index f5845953d..a6cf5fe72 100644 --- a/python/tsfile/tsfile_py_cpp.pxd +++ b/python/tsfile/tsfile_py_cpp.pxd @@ -88,6 +88,15 @@ cdef public api ResultSet tsfile_reader_query_table_with_tag_filter_c(TsFileRead int64_t end_time, void* tag_filter, int batch_size) +cdef public api ResultSet tsfile_query_table_with_filters_c( + TsFileReader reader, object table_name, object column_list, + int64_t start_time, int64_t end_time, int offset, int limit, + void* tag_filter, void* field_filter, int batch_size) + +cdef public api ResultSet tsfile_reader_query_table_by_row_with_filters_c( + TsFileReader reader, object table_name, object column_list, int offset, + int limit, void* tag_filter, void* field_filter, int batch_size) + cdef public api object get_table_schema(TsFileReader reader, object table_name) cdef public api object get_all_table_schema(TsFileReader reader) cdef public api object get_all_timeseries_schema(TsFileReader reader) diff --git a/python/tsfile/tsfile_py_cpp.pyx b/python/tsfile/tsfile_py_cpp.pyx index e6c7f3108..7336f9050 100644 --- a/python/tsfile/tsfile_py_cpp.pyx +++ b/python/tsfile/tsfile_py_cpp.pyx @@ -1375,6 +1375,69 @@ cdef ResultSet tsfile_reader_query_table_with_tag_filter_c(TsFileReader reader, free( columns) columns = NULL +cdef ResultSet tsfile_query_table_with_filters_c( + TsFileReader reader, object table_name, object column_list, + int64_t start_time, int64_t end_time, int offset, int limit, + void* tag_filter, void* field_filter, int batch_size): + cdef ResultSet result + cdef int column_num = len(column_list) + cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) + cdef const char * table_name_c = table_name_bytes + cdef char** columns = malloc(sizeof(char *) * column_num) + cdef int i + cdef ErrorCode code = 0 + if columns == NULL: + raise MemoryError("Failed to allocate memory for columns") + try: + for i in range(column_num): + columns[i] = strdup(( column_list[i]).encode('utf-8')) + if columns[i] == NULL: + raise MemoryError("Failed to allocate memory for column name") + result = tsfile_query_table_with_filters( + reader, table_name_c, columns, column_num, start_time, end_time, + offset, limit, tag_filter, field_filter, batch_size, &code) + check_error(code) + return result + finally: + if columns != NULL: + for i in range(column_num): + if columns[i] != NULL: + free( columns[i]) + columns[i] = NULL + free( columns) + columns = NULL + +cdef ResultSet tsfile_reader_query_table_by_row_with_filters_c( + TsFileReader reader, object table_name, object column_list, int offset, + int limit, void* tag_filter, void* field_filter, int batch_size): + cdef ResultSet result + cdef int column_num = len(column_list) + cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) + cdef const char * table_name_c = table_name_bytes + cdef char** columns = malloc(sizeof(char *) * column_num) + cdef int i + cdef ErrorCode code = 0 + if columns == NULL: + raise MemoryError("Failed to allocate memory for table by-row query columns") + try: + for i in range(column_num): + columns[i] = strdup(( column_list[i]).encode('utf-8')) + if columns[i] == NULL: + raise MemoryError("Failed to allocate memory for column name") + result = tsfile_reader_query_table_by_row_with_filters( + reader, table_name_c, columns, column_num, offset, limit, + tag_filter, field_filter, batch_size, &code) + check_error(code) + return result + finally: + if columns != NULL: + for i in range(column_num): + if columns[i] != NULL: + free( columns[i]) + columns[i] = NULL + free( columns) + columns = NULL + cdef object get_table_schema(TsFileReader reader, object table_name): cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) cdef const char * table_name_c = table_name_bytes diff --git a/python/tsfile/tsfile_reader.pyx b/python/tsfile/tsfile_reader.pyx index 0b8750089..01204aa8a 100644 --- a/python/tsfile/tsfile_reader.pyx +++ b/python/tsfile/tsfile_reader.pyx @@ -35,6 +35,7 @@ from tsfile.schema import TSDataType as TSDataTypePy from tsfile.schema import DeviceID, DeviceTimeseriesMetadataGroup from tsfile.exceptions import TsFileCorruptedError from tsfile.tag_filter import ComparisonTagFilter, BetweenTagFilter, AndTagFilter, OrTagFilter, NotTagFilter, cache_key +from tsfile.field_filter import ComparisonFieldFilter, BetweenFieldFilter, AndFieldFilter, OrFieldFilter, NotFieldFilter from .date_utils import parse_int_to_date from .tsfile_cpp cimport * from .tsfile_py_cpp cimport * @@ -66,6 +67,36 @@ _CACHE_FALLBACK_CODES = frozenset((4, 27, 40, 44, 45, 49, 50)) # path; keep those queries on the regular path. _PREPARED_CACHE_MAX_COLUMNS = 16 +cdef FieldFilterHandle _make_field_comparison( + TsFileReader reader, bytes table_bytes, bytes column_bytes, int op, + object value, object value_type): + """Build one C field comparison handle from a normalized literal.""" + cdef FieldFilterValue literal + cdef bytes value_bytes + cdef FieldFilterHandle handle = NULL + cdef ErrorCode code = 0 + memset(&literal, 0, sizeof(FieldFilterValue)) + if value_type is not None: + literal.type = value_type + if value_type == ComparisonFieldFilter.BOOL: + literal.bool_value = 1 if value else 0 + elif value_type == ComparisonFieldFilter.INT64: + literal.int64_value = value + elif value_type == ComparisonFieldFilter.DOUBLE: + literal.double_value = value + elif value_type == ComparisonFieldFilter.STRING: + value_bytes = value.encode('utf-8') + literal.string_value = value_bytes + literal.string_length = len(value_bytes) + else: + raise TypeError(f"Unknown field filter value type: {value_type!r}") + code = tsfile_field_filter_create_checked( + reader, table_bytes, column_bytes, + op, &literal, &handle) + check_error(code) + return handle + + cdef class ResultSetPy: """ Get data from a query result. When reader run a query, a query handler will return. @@ -82,6 +113,10 @@ cdef class ResultSetPy: # Tag filter handle owned by this result set (freed on close). cdef TagFilterHandle _tag_filter_handle + # Field filter handle owned by this result set (freed on close). The native + # query receives a copy, so the handle can be released with the result. + cdef FieldFilterHandle _field_filter_handle + # ResultSet is valid or not, if the reader is closed, valid will be False. cdef object valid # The reader @@ -95,6 +130,7 @@ cdef class ResultSetPy: self.tsfile_reader = weakref.ref(tsfile_reader) self.is_tree = is_tree self._tag_filter_handle = NULL + self._field_filter_handle = NULL cdef init_c(self, ResultSet result, object device_name): """ @@ -334,6 +370,10 @@ cdef class ResultSetPy: tsfile_tag_filter_free(self._tag_filter_handle) self._tag_filter_handle = NULL + if self._field_filter_handle != NULL: + tsfile_field_filter_free(self._field_filter_handle) + self._field_filter_handle = NULL + if self.tsfile_reader is not None: reader = self.tsfile_reader() if reader is not None: @@ -421,7 +461,8 @@ cdef class TsFileReaderPy: def query_table(self, table_name : str, column_names : List[str], start_time : int = INT64_MIN, end_time : int = INT64_MAX, - tag_filter = None, batch_size : int = 0) -> ResultSetPy: + tag_filter = None, batch_size : int = 0, + field_filter = None) -> ResultSetPy: """ Execute a time range query on specified table and columns. @@ -436,14 +477,18 @@ cdef class TsFileReaderPy: :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 field_filter: Optional FieldFilter to filter by FIELD column + values. The predicate is pushed down natively and disables the + prepared-series cache for this query. :return: query result handler. """ cdef ResultSet result cdef TagFilterHandle c_tag_filter = NULL + cdef FieldFilterHandle c_field_filter = NULL cdef ResultSetPy pyresult if (self._prepared_query_cache_size > 0 and batch_size > 0 and 0 < len(column_names) < _PREPARED_CACHE_MAX_COLUMNS - and tag_filter is not None): + and tag_filter is not None and field_filter is None): key = self._prepared_query_key(table_name, column_names, tag_filter) if key is not None: prepared = self._prepared_query_for(key, tag_filter) @@ -472,7 +517,17 @@ cdef class TsFileReaderPy: if tag_filter is not None: c_tag_filter = self._build_c_tag_filter(table_name.lower(), tag_filter) pyresult._tag_filter_handle = c_tag_filter - if batch_size <= 0: + if field_filter is not None: + c_field_filter = self._build_c_field_filter( + table_name.lower(), field_filter) + pyresult._field_filter_handle = c_field_filter + if field_filter is not None: + result = tsfile_query_table_with_filters_c( + self.reader, table_name.lower(), + [column_name.lower() for column_name in column_names], + start_time, end_time, 0, -1, c_tag_filter, c_field_filter, + batch_size) + elif batch_size <= 0: result = tsfile_reader_query_table_with_tag_filter_c( self.reader, table_name.lower(), [column_name.lower() for column_name in column_names], @@ -654,6 +709,90 @@ cdef class TsFileReaderPy: tsfile_tag_filter_free(inner) else: raise TypeError(f"Unknown tag filter type: {type(tag_filter)}") + + cdef FieldFilterHandle _build_c_field_filter(self, str table_name, object field_filter): + """Recursively build a C FieldFilterHandle from a Python FieldFilter tree. + + The native composition helpers borrow their inputs and return a new + filter owning deep copies, so every intermediate handle built here is + released in the ``finally`` block and only the returned handle is + transferred to the caller. + """ + cdef FieldFilterHandle handle = NULL + cdef FieldFilterHandle left = NULL + cdef FieldFilterHandle right = NULL + cdef FieldFilterHandle inner = NULL + cdef FieldFilterHandle out = NULL + cdef bytes table_bytes + cdef bytes col_bytes + + table_bytes = table_name.encode('utf-8') + if isinstance(field_filter, ComparisonFieldFilter): + col_bytes = field_filter.column_name.encode('utf-8') + return _make_field_comparison( + self.reader, table_bytes, col_bytes, field_filter.op, + field_filter.value, field_filter.value_type) + elif isinstance(field_filter, BetweenFieldFilter): + col_bytes = field_filter.column_name.encode('utf-8') + try: + left = _make_field_comparison( + self.reader, table_bytes, col_bytes, + ComparisonFieldFilter.GTEQ, + field_filter.lower, field_filter.lower_type) + right = _make_field_comparison( + self.reader, table_bytes, col_bytes, + ComparisonFieldFilter.LTEQ, + field_filter.upper, field_filter.upper_type) + handle = tsfile_field_filter_and(left, right) + if handle == NULL: + raise MemoryError("Unable to allocate BETWEEN field filter") + if field_filter.is_not: + out = tsfile_field_filter_not(handle) + if out == NULL: + raise MemoryError( + "Unable to allocate NOT BETWEEN field filter") + else: + out = handle + handle = NULL + return out + finally: + tsfile_field_filter_free(left) + tsfile_field_filter_free(right) + tsfile_field_filter_free(handle) + elif isinstance(field_filter, AndFieldFilter): + try: + left = self._build_c_field_filter(table_name, field_filter.left) + right = self._build_c_field_filter(table_name, field_filter.right) + out = tsfile_field_filter_and(left, right) + if out == NULL: + raise MemoryError("Unable to allocate compound field filter") + return out + finally: + tsfile_field_filter_free(left) + tsfile_field_filter_free(right) + elif isinstance(field_filter, OrFieldFilter): + try: + left = self._build_c_field_filter(table_name, field_filter.left) + right = self._build_c_field_filter(table_name, field_filter.right) + out = tsfile_field_filter_or(left, right) + if out == NULL: + raise MemoryError("Unable to allocate compound field filter") + return out + finally: + tsfile_field_filter_free(left) + tsfile_field_filter_free(right) + elif isinstance(field_filter, NotFieldFilter): + try: + inner = self._build_c_field_filter(table_name, field_filter.filter) + out = tsfile_field_filter_not(inner) + if out == NULL: + raise MemoryError("Unable to allocate compound field filter") + return out + finally: + tsfile_field_filter_free(inner) + else: + raise TypeError(f"Unknown field filter type: {type(field_filter)}") + def query_table_on_tree(self, column_names : List[str], start_time : int = INT64_MIN, end_time : int = INT64_MAX) -> ResultSetPy: """ @@ -688,20 +827,36 @@ cdef class TsFileReaderPy: def query_table_by_row(self, table_name : str, column_names : List[str], offset : int = 0, limit : int = -1, - tag_filter = None, batch_size : int = 0 + tag_filter = None, batch_size : int = 0, + field_filter = None ) -> ResultSetPy: """ Execute table-model query by row with offset/limit. + + :param tag_filter: Optional TagFilter to filter by TAG column values. + :param field_filter: Optional FieldFilter to filter by FIELD column + values, pushed down natively. OFFSET/LIMIT count accepted rows. """ cdef ResultSet result cdef TagFilterHandle c_tag_filter = NULL + cdef FieldFilterHandle c_field_filter = NULL pyresult = ResultSetPy(self) if tag_filter is not None: c_tag_filter = self._build_c_tag_filter(table_name.lower(), tag_filter) pyresult._tag_filter_handle = c_tag_filter - result = tsfile_reader_query_table_by_row_c(self.reader, table_name.lower(), - [column_name.lower() for column_name in column_names], - offset, limit, c_tag_filter, batch_size) + if field_filter is not None: + c_field_filter = self._build_c_field_filter( + table_name.lower(), field_filter) + pyresult._field_filter_handle = c_field_filter + if field_filter is not None: + result = tsfile_reader_query_table_by_row_with_filters_c( + self.reader, table_name.lower(), + [column_name.lower() for column_name in column_names], + offset, limit, c_tag_filter, c_field_filter, batch_size) + else: + result = tsfile_reader_query_table_by_row_c(self.reader, table_name.lower(), + [column_name.lower() for column_name in column_names], + offset, limit, c_tag_filter, batch_size) pyresult.init_c(result, table_name) self.activate_result_set_list.add(pyresult) return pyresult diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 4bd8d4378..7a27edebe 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -70,14 +70,46 @@ arguments. TAG values are strings; do not apply a TAG builder to FIELD columns. Do not translate operator names mechanically across bindings: Java additionally exposes LIKE, while current C++/Python expose explicit null predicates. +## Table FIELD Filters + +FIELD predicates select rows by FIELD-column values and compose with TAG +predicates. They are pushed down into the table query executor: aligned devices +use batch/page evaluation, non-aligned devices evaluate merged rows. A +comparison never matches NULL cells; use the explicit IS NULL / IS NOT NULL +predicates for that. NOT is pushed down into the leaves, so a negated +comparison also excludes NULL cells. + +- Python factories: `field_eq`, `field_neq`, `field_lt`, `field_lteq`, + `field_gt`, `field_gteq`, `field_is_null`, `field_is_not_null`, + `field_between`, and `field_not_between`. Compose with `&`, `|`, and `~`, then + pass `field_filter=` to `query_table` or `query_table_by_row`. Values may be + `bool`, `int` (64-bit range), `float`, or `str`; numeric literals adapt to the + column's numeric type, while string literals require a string-like column and + raise `TypeMismatchError` otherwise. `None` is rejected -- use the IS NULL + predicates. A `field_filter` disables the prepared-series cache for that + query. +- C wrapper: build handles with `tsfile_field_filter_create_checked`, + compose with `tsfile_field_filter_and` / `_or` / `_not`, and release them with + `tsfile_field_filter_free`. Pass TAG and FIELD handles to + `tsfile_query_table_with_filters` or + `tsfile_reader_query_table_by_row_with_filters`; the query copies the FIELD + filter, so the caller keeps ownership of the handle. +- C++: build `storage::AlignedFieldFilter` trees with `compare`, `is_null`, + `is_not_null`, `and_filter`, `or_filter`, and `not_filter` from + `cpp/src/reader/filter/aligned_field_filter.h`, and pass the filter to the + `TsFileReader::query` / `queryByRow` overloads that take a field filter; + those overloads take ownership of it. + ## Source Anchors - Java: `java/tsfile/src/main/java/org/apache/tsfile/read/filter/factory/TagFilterBuilder.java`, `java/tsfile/src/main/java/org/apache/tsfile/read/v4/ITsFileReader.java`, and `java/examples/src/main/java/org/apache/tsfile/v4/TagFilterExample.java` -- Python: `python/tsfile/tag_filter.py`, `python/tsfile/tsfile_reader.pyx`, and - `python/tests/test_tag_filter*.py` +- Python: `python/tsfile/tag_filter.py`, `python/tsfile/field_filter.py`, + `python/tsfile/tsfile_reader.pyx`, and `python/tests/test_tag_filter*.py` plus + `python/tests/test_field_filter*.py` - C/C++: `cpp/src/reader/filter/tag_filter.h`, + `cpp/src/reader/filter/aligned_field_filter.h`, `cpp/src/reader/tsfile_reader.h`, and `cpp/src/cwrapper/tsfile_cwrapper.h` - Properties: the current writer/reader interfaces plus `python/tests/test_tsfile_properties.py` and diff --git a/skills/tsfile/references/python.md b/skills/tsfile/references/python.md index a7446d4d1..dd8498d12 100644 --- a/skills/tsfile/references/python.md +++ b/skills/tsfile/references/python.md @@ -71,6 +71,11 @@ with TsFileReader("data.tsfile") as reader: frame = result.read_data_frame(max_row_num=10) ``` +`query_table` and `query_table_by_row` also accept a `field_filter=` built from +the `field_eq` / `field_gt` / `field_between` / `field_is_null` family, and +`tag_filter=` for TAG predicates; both push down natively. See +`properties-filters.md` for FIELD predicate semantics and NULL handling. + ## Guidance - Writers accept `allow_non_decreasing_timestamps=False`; this is process-wide. From 603c8734fd0d5b83b198210ba985dd9e2db16133 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Mon, 30 Nov 2026 19:09:43 +0800 Subject: [PATCH 02/10] fix(cwrapper): align FIELD filter batch_size semantics and extend tests Address the review findings on 4e47594a: - Accept batch_size < 0 as row-by-row mode in tsfile_query_table_with_filters and tsfile_reader_query_table_by_row_with_filters. This matches query_table without a FIELD filter and the documented promise that batch_size <= 0 selects row-by-row mode. - Document start_time/end_time/offset/limit/batch_size on the new C query entry points. - Drop the unreachable null check around AlignedFieldFilter::clone(); allocation failure propagates as an exception and maps to E_OOM. - Tests: negative batch_size parity, INT32 and FLOAT column literals, NOT of AND/OR compounds (C++ and Python), FLOAT narrowing in the C API. --- cpp/src/cwrapper/tsfile_cwrapper.cc | 23 ++++--- cpp/src/cwrapper/tsfile_cwrapper.h | 11 ++++ cpp/test/cwrapper/cwrapper_extended_test.cc | 43 ++++++++++++- python/tests/test_field_filter_query.py | 67 +++++++++++++++++++-- 4 files changed, 126 insertions(+), 18 deletions(-) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index aa670581f..4b2289e91 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -3076,12 +3076,9 @@ storage::Filter* clone_field_filter(FieldFilterHandle field_filter, *err_code = common::E_INVALID_ARG; return nullptr; } - storage::AlignedFieldFilter::Ptr copy = native->clone(); - if (copy == nullptr) { - *err_code = common::E_OOM; - return nullptr; - } - return copy.release(); + // clone() reports allocation failure by throwing, which the caller turns + // into E_OOM. + return native->clone().release(); } } // namespace @@ -3221,7 +3218,7 @@ ResultSet tsfile_query_table_with_filters( } *err_code = common::E_INVALID_ARG; if (reader == nullptr || table_name == nullptr || columns == nullptr || - column_num == 0 || offset < 0 || batch_size < 0) { + column_num == 0 || offset < 0) { return nullptr; } try { @@ -3235,6 +3232,9 @@ ResultSet tsfile_query_table_with_filters( } storage::ResultSet* result_set = nullptr; const int normalized_limit = limit < 0 ? -1 : limit; + // batch_size <= 0 selects row-by-row mode, matching query_table's + // behavior without a FIELD filter; clamp negatives so both paths agree. + const int normalized_batch_size = batch_size < 0 ? 0 : batch_size; storage::Filter* field_copy = nullptr; if (field_filter != nullptr) { field_copy = clone_field_filter(field_filter, err_code); @@ -3245,7 +3245,8 @@ ResultSet tsfile_query_table_with_filters( *err_code = static_cast(reader)->query( table_name, column_names, start_time, end_time, offset, normalized_limit, result_set, - static_cast(tag_filter), field_copy, batch_size); + static_cast(tag_filter), field_copy, + normalized_batch_size); if (*err_code != common::E_OK) { return nullptr; } @@ -3268,7 +3269,7 @@ ResultSet tsfile_reader_query_table_by_row_with_filters( } *err_code = common::E_INVALID_ARG; if (reader == nullptr || table_name == nullptr || column_names == nullptr || - column_names_len <= 0 || offset < 0 || batch_size < 0) { + column_names_len <= 0 || offset < 0) { return nullptr; } try { @@ -3281,6 +3282,7 @@ ResultSet tsfile_reader_query_table_by_row_with_filters( columns.emplace_back(column_names[i]); } storage::ResultSet* result_set = nullptr; + const int normalized_batch_size = batch_size < 0 ? 0 : batch_size; storage::Filter* field_copy = nullptr; if (field_filter != nullptr) { field_copy = clone_field_filter(field_filter, err_code); @@ -3290,7 +3292,8 @@ ResultSet tsfile_reader_query_table_by_row_with_filters( } *err_code = static_cast(reader)->queryByRow( table_name, columns, offset, limit, result_set, - static_cast(tag_filter), field_copy, batch_size); + static_cast(tag_filter), field_copy, + normalized_batch_size); if (*err_code != common::E_OK) { return nullptr; } diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index c31e57508..0cf61f95c 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -992,12 +992,18 @@ ResultSet tsfile_reader_query_table(TsFileReader reader, const char* table_name, * devices evaluate merged rows. The FIELD filter never matches NULL values; * use FIELD_FILTER_IS_NULL / FIELD_FILTER_IS_NOT_NULL for that. * + * @param start_time [in] Inclusive lower time bound. + * @param end_time [in] Inclusive upper time bound. + * @param offset [in] Number of leading result rows to skip (>= 0). + * @param limit [in] Maximum rows to return; < 0 means unlimited. * @param tag_filter [in] Optional TAG filter, borrowed for the duration of the * query and the returned result set. Free it with * tsfile_tag_filter_free() after the result set is closed. * @param field_filter [in] Optional FIELD filter. The handle is borrowed: the * wrapper copies it, so the caller keeps ownership and must free it * with tsfile_field_filter_free(). + * @param batch_size [in] > 0 returns TsBlock batches of that size; <= 0 + * (including negative values) selects row-by-row mode. * @return ResultSet handle on success; NULL on failure with *err_code set. */ ResultSet tsfile_query_table_with_filters( @@ -1009,6 +1015,11 @@ ResultSet tsfile_query_table_with_filters( /** * @brief Row-limit table query with TAG and FIELD filters. * + * @param offset [in] Number of leading accepted rows to skip (>= 0). + * @param limit [in] Maximum accepted rows to return; < 0 means unlimited. + * @param batch_size [in] > 0 returns TsBlock batches; <= 0 (including + * negative values) selects row-by-row mode. + * * Ownership matches tsfile_query_table_with_filters(). */ ResultSet tsfile_reader_query_table_by_row_with_filters( diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 9988bf1e5..0f9718576 100644 --- a/cpp/test/cwrapper/cwrapper_extended_test.cc +++ b/cpp/test/cwrapper/cwrapper_extended_test.cc @@ -562,10 +562,11 @@ TEST(CWrapperExtendedTest, FieldFilterSelectsRowsAndComposes) { free_tsfile_result_set(&filtered); // The query copies the FIELD filter, so the same handle can serve another - // query and stays owned by the caller. + // query and stays owned by the caller. A negative batch size must select + // row-by-row mode, matching queries without a FIELD filter. filtered = tsfile_query_table_with_filters( reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, - nullptr, int_ge_two, 0, &err); + nullptr, int_ge_two, -1, &err); ASSERT_EQ(RET_OK, err); ASSERT_NE(nullptr, filtered); EXPECT_EQ(6, count_result_rows(filtered, &err)); @@ -591,6 +592,42 @@ TEST(CWrapperExtendedTest, FieldFilterSelectsRowsAndComposes) { } free_tsfile_result_set(&filtered); + // NOT(INT32 == 2) keeps the remaining 8 rows. + FieldFilterHandle int_not_two = tsfile_field_filter_not(int_two); + ASSERT_NE(nullptr, int_not_two); + filtered = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, int_not_two, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, filtered); + rows = collect_row_identities(filtered, &err); + ASSERT_EQ(8u, rows.size()); + for (const auto& row : rows) { + EXPECT_NE(2, row.value); + } + free_tsfile_result_set(&filtered); + + // A DOUBLE literal binds to the FLOAT column (0.5 offset per row). + FieldFilterValue float_value{}; + float_value.type = FIELD_FILTER_VALUE_DOUBLE; + float_value.double_value = 3.5; + FieldFilterHandle float_eq = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "FLOAT", FIELD_FILTER_EQ, + &float_value, &float_eq)); + ASSERT_NE(nullptr, float_eq); + filtered = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, float_eq, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, filtered); + rows = collect_row_identities(filtered, &err); + ASSERT_EQ(2u, rows.size()); + for (const auto& row : rows) { + EXPECT_EQ(3, row.value); + } + free_tsfile_result_set(&filtered); + // DOUBLE is NULL on each device's last row: IS NOT NULL keeps 4 rows per // device, and a comparison never matches the NULL cells. FieldFilterHandle double_not_null = nullptr; @@ -654,6 +691,8 @@ TEST(CWrapperExtendedTest, FieldFilterSelectsRowsAndComposes) { tsfile_field_filter_free(int_ge_one_filter); tsfile_field_filter_free(int_two); tsfile_field_filter_free(double_not_null); + tsfile_field_filter_free(float_eq); + tsfile_field_filter_free(int_not_two); // Composition borrows its inputs and owns copies, so every input handle // and the composed handle are freed here. tsfile_field_filter_free(combined); diff --git a/python/tests/test_field_filter_query.py b/python/tests/test_field_filter_query.py index fe0a91869..2ba317168 100644 --- a/python/tests/test_field_filter_query.py +++ b/python/tests/test_field_filter_query.py @@ -60,9 +60,21 @@ ColumnSchema("flag", TSDataType.BOOLEAN, ColumnCategory.FIELD), ColumnSchema("name", TSDataType.STRING, ColumnCategory.FIELD), ColumnSchema("sparse", TSDataType.DOUBLE, ColumnCategory.FIELD), + ColumnSchema("count32", TSDataType.INT32, ColumnCategory.FIELD), + ColumnSchema("ratio", TSDataType.FLOAT, ColumnCategory.FIELD), ] SCHEMA = TableSchema(TABLE_NAME, COLUMNS) -COLUMN_NAMES = ["region", "device", "value", "count", "flag", "name", "sparse"] +COLUMN_NAMES = [ + "region", + "device", + "value", + "count", + "flag", + "name", + "sparse", + "count32", + "ratio", +] COLUMN_TYPES = [ TSDataType.STRING, TSDataType.STRING, @@ -71,14 +83,16 @@ TSDataType.BOOLEAN, TSDataType.STRING, TSDataType.DOUBLE, + TSDataType.INT32, + TSDataType.FLOAT, ] # Test data (timestamps are global and unique across devices): -# region | device | timestamps | value | count | flag | sparse -# north | dev_a | 0..4 | ts | ts*10 | ts % 2 == 0 | ts if even -# north | dev_b | 5..9 | ts | ts*10 | ts % 2 == 0 | ts if even -# south | dev_c | 10..14 | ts | ts*10 | ts % 2 == 0 | ts if even -# east | dev_d | 15..19 | ts | ts*10 | ts % 2 == 0 | ts if even +# region | device | timestamps | value | count | flag | sparse | count32 | ratio +# north | dev_a | 0..4 | ts | ts*10 | ts % 2 == 0 | ts if even | ts | ts+0.5 +# north | dev_b | 5..9 | ts | ts*10 | ts % 2 == 0 | ts if even | ts | ts+0.5 +# south | dev_c | 10..14 | ts | ts*10 | ts % 2 == 0 | ts if even | ts | ts+0.5 +# east | dev_d | 15..19 | ts | ts*10 | ts % 2 == 0 | ts if even | ts | ts+0.5 DEVICES = [ ("north", "dev_a", 0, 5), ("north", "dev_b", 5, 10), @@ -109,6 +123,8 @@ def create_tsfile(): # semantics are observable. if ts % 2 == 0: tablet.add_value_by_name("sparse", i, float(ts)) + tablet.add_value_by_name("count32", i, ts) + tablet.add_value_by_name("ratio", i, ts + 0.5) writer.write_table(tablet) yield @@ -129,6 +145,8 @@ def _scalar_rows(result): result.get_value_by_name("flag"), result.get_value_by_name("name"), result.get_value_by_name("sparse"), + result.get_value_by_name("count32"), + result.get_value_by_name("ratio"), ) ) return rows @@ -271,6 +289,43 @@ def test_logical_composition(self): negated = ~(field_lt("value", 18.0)) assert _times(reader, negated) == [18.0, 19.0] + def test_not_of_compound_filters(self): + with TsFileReader(TSFILE_PATH) as reader: + # NOT(A AND B) drops the two matching rows. + not_and = ~(field_gteq("value", 2.0) & field_lteq("value", 3.0)) + rows = _query(reader, not_and) + assert len(rows) == 18 + assert {2.0, 3.0}.isdisjoint(row[2] for row in rows) + # NOT(A OR B) drops both matching rows. + not_or = ~(field_eq("value", 0.0) | field_eq("value", 19.0)) + rows = _query(reader, not_or) + assert len(rows) == 18 + assert {0.0, 19.0}.isdisjoint(row[2] for row in rows) + + def test_int32_column_literal(self): + with TsFileReader(TSFILE_PATH) as reader: + rows = _query(reader, field_eq("count32", 7)) + assert len(rows) == 1 + assert rows[0][7] == 7 + assert _times(reader, field_lt("count32", 2)) == [0.0, 1.0] + + def test_float_column_literal(self): + with TsFileReader(TSFILE_PATH) as reader: + rows = _query(reader, field_eq("ratio", 7.5)) + assert len(rows) == 1 + assert rows[0][8] == pytest.approx(7.5) + assert _times(reader, field_lt("ratio", 2.0)) == [0.0, 1.0] + + def test_negative_batch_size_uses_row_mode(self): + # The Python API promises batch_size <= 0 = row-by-row mode; a FIELD + # filter must not turn a negative batch size into an error. + field_filter = field_gteq("value", 15.0) + with TsFileReader(TSFILE_PATH) as reader: + default_rows = _query(reader, field_filter) + negative_rows = _query(reader, field_filter, batch_size=-1) + assert len(default_rows) == len(negative_rows) == 5 + assert [row[2] for row in default_rows] == [row[2] for row in negative_rows] + def test_time_range_combines_with_field_filter(self): with TsFileReader(TSFILE_PATH) as reader: rows = _query( From ce03bf2d45a07082b526e075f3ce416e6fb97ad9 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Tue, 1 Dec 2026 15:29:35 +0800 Subject: [PATCH 03/10] fix(python): reject lossy FIELD literals and harden filter ownership - Reject numeric literals whose Java-style narrowing would change the predicate on integral columns (fractional, NaN/inf, out-of-range) with E_TYPE_NOT_MATCH / TypeMismatchError instead of silently narrowing. - Validate creation literals on a throwaway clone so reusable handles keep the caller literal and bind against the query-time schema. - Align FIELD and/or/not ownership with the TAG API: inputs are consumed; wrong-typed or too-deep inputs are rejected and consumed. - Cap filter trees at 512 levels in the C API, query wrapper and Cython builder to stop unbounded recursion. - Make TableQueryExecutor adopt time/field filters with RAII so a throwing allocation cannot leak them; hoist table-name lowering out of the release window. - Zero-initialize Cython column-name arrays and free handles through the virtual Filter destructor. - Validate empty projections and negative offsets uniformly in query_table / query_table_by_row. - Add regression tests (Python and C wrapper) and update the header, DSL and skill docs. --- cpp/src/cwrapper/tsfile_cwrapper.cc | 183 ++++++++++++++++-- cpp/src/cwrapper/tsfile_cwrapper.h | 44 +++-- cpp/src/reader/filter/aligned_field_filter.h | 4 + cpp/src/reader/table_query_executor.cc | 51 +++-- cpp/src/reader/tsfile_reader.cc | 18 +- cpp/test/cwrapper/cwrapper_extended_test.cc | 105 +++++++++- python/tests/test_field_filter_query.py | 77 ++++++++ python/tsfile/field_filter.py | 8 +- python/tsfile/tsfile_py_cpp.pyx | 10 + python/tsfile/tsfile_reader.pyx | 57 ++++-- .../tsfile/references/properties-filters.md | 15 +- 11 files changed, 477 insertions(+), 95 deletions(-) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index 4b2289e91..2a2c98b4d 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -31,6 +31,8 @@ #include #endif +#include +#include #include #include #include @@ -3065,6 +3067,88 @@ bool to_field_literal(const FieldFilterValue& value, } } +// Validates that a numeric literal is exactly representable in the declared +// column type. AlignedFieldFilter::bind() narrows constants with Java's +// Number.intValue/longValue rules (low-bit wrap, truncation toward zero, +// NaN -> 0), which would silently change the predicate the caller wrote, so +// those literals are rejected up front instead. +ERRNO validate_exact_literal(const FieldFilterValue& value, + common::TSDataType column_type) { + const bool integral_column = + column_type == common::INT32 || column_type == common::INT64 || + column_type == common::DATE || column_type == common::TIMESTAMP; + if (!integral_column) { + return common::E_OK; + } + if (value.type == FIELD_FILTER_VALUE_INT64) { + if ((column_type == common::INT32 || column_type == common::DATE) && + (value.int64_value < + static_cast(std::numeric_limits::min()) || + value.int64_value > + static_cast(std::numeric_limits::max()))) { + return common::E_TYPE_NOT_MATCH; + } + return common::E_OK; + } + if (value.type == FIELD_FILTER_VALUE_DOUBLE) { + const double literal = value.double_value; + if (!std::isfinite(literal) || std::trunc(literal) != literal) { + return common::E_TYPE_NOT_MATCH; + } + if (column_type == common::INT32 || column_type == common::DATE) { + if (literal < + static_cast(std::numeric_limits::min()) || + literal > + static_cast(std::numeric_limits::max())) { + return common::E_TYPE_NOT_MATCH; + } + return common::E_OK; + } + // INT64/TIMESTAMP: [-2^63, 2^63) are the doubles that map exactly. + constexpr double kInt64Min = -9223372036854775808.0; // -2^63 + constexpr double kInt64MaxExclusive = 9223372036854775808.0; // 2^63 + if (literal < kInt64Min || literal >= kInt64MaxExclusive) { + return common::E_TYPE_NOT_MATCH; + } + } + return common::E_OK; +} + +// Maximum depth of a FIELD filter tree accepted by this API. The native +// clone()/bind() implementations recurse once per level, so deeper trees are +// rejected instead of being able to overflow the C stack. +constexpr int kMaxFieldFilterDepth = 512; + +int field_filter_depth(const storage::AlignedFieldFilter* filter) { + struct Entry { + const storage::AlignedFieldFilter* node; + int depth; + }; + std::vector stack; + stack.push_back(Entry{filter, 1}); + int max_depth = 0; + while (!stack.empty()) { + Entry entry = stack.back(); + stack.pop_back(); + if (entry.node == nullptr) { + continue; + } + if (entry.depth > max_depth) { + max_depth = entry.depth; + } + if (max_depth > kMaxFieldFilterDepth) { + return max_depth; + } + if (entry.node->left() != nullptr) { + stack.push_back(Entry{entry.node->left(), entry.depth + 1}); + } + if (entry.node->right() != nullptr) { + stack.push_back(Entry{entry.node->right(), entry.depth + 1}); + } + } + return max_depth; +} + // Copies a FIELD filter handle into a filter owned by the query call. The // table query executor (and the result set) owns the filter it receives, so // the caller's handle cannot be handed over directly. @@ -3072,7 +3156,8 @@ storage::Filter* clone_field_filter(FieldFilterHandle field_filter, ERRNO* err_code) { auto* native = dynamic_cast( static_cast(field_filter)); - if (native == nullptr) { + if (native == nullptr || + field_filter_depth(native) > kMaxFieldFilterDepth) { *err_code = common::E_INVALID_ARG; return nullptr; } @@ -3135,10 +3220,36 @@ ERRNO tsfile_field_filter_create_checked(TsFileReader reader, if (filter == nullptr) { return common::E_OOM; } - // Resolve the column and bind the literal against its declared type so - // bad column names, non-FIELD columns and type mismatches surface here - // instead of during iteration. - ret = filter->bind(*schema); + // Reject numeric literals that Java-style narrowing would alter before + // they can reach the filter (see validate_exact_literal). Binding also + // resolves the column, so a missing or non-FIELD column still produces + // the precise error from bind() below. + if (needs_value) { + std::string lookup_name(column_name); + for (char& ch : lookup_name) { + ch = static_cast( + std::tolower(static_cast(ch))); + } + const common::ColumnSchema column_schema = + schema->get_column_schema(lookup_name); + if (column_schema.is_valid() && column_schema.column_category_ == + common::ColumnCategory::FIELD) { + ret = validate_exact_literal(*value, column_schema.data_type_); + if (ret != common::E_OK) { + return ret; + } + } + } + // Validate on a throwaway copy so the reusable handle keeps the + // caller's literal. The query-time clone is bound against the schema + // of the table actually queried, so a handle reused with a different + // schema still compares the original value instead of the creating + // schema's narrowed constant. + FieldFilter::Ptr probe = filter->clone(); + if (probe == nullptr) { + return common::E_OOM; + } + ret = probe->bind(*schema); if (ret == common::E_NOT_SUPPORT) { return common::E_TYPE_NOT_MATCH; } @@ -3159,13 +3270,27 @@ FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, if (left == nullptr || right == nullptr) { return nullptr; } - // Borrow both inputs: the returned node owns deep copies, so the caller's - // handles stay valid and can be freed independently. + using FieldFilter = storage::AlignedFieldFilter; + auto* left_node = + dynamic_cast(static_cast(left)); + auto* right_node = + dynamic_cast(static_cast(right)); + if (left_node == nullptr || right_node == nullptr || + field_filter_depth(left_node) >= kMaxFieldFilterDepth || + field_filter_depth(right_node) >= kMaxFieldFilterDepth) { + // The inputs are consumed either way. Both handle families are Filter + // subclasses, so free through the virtual destructor. + delete static_cast(left); + delete static_cast(right); + return nullptr; + } + // Takes ownership of both inputs on every path, matching the TAG filter + // composition API: the returned node adopts them directly, so the caller + // must not free the inputs afterwards (even when this returns NULL). try { return static_cast( - storage::AlignedFieldFilter::and_filter( - static_cast(left)->clone(), - static_cast(right)->clone()) + FieldFilter::and_filter(FieldFilter::Ptr(left_node), + FieldFilter::Ptr(right_node)) .release()); } catch (...) { return nullptr; @@ -3177,11 +3302,25 @@ FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, if (left == nullptr || right == nullptr) { return nullptr; } + using FieldFilter = storage::AlignedFieldFilter; + auto* left_node = + dynamic_cast(static_cast(left)); + auto* right_node = + dynamic_cast(static_cast(right)); + if (left_node == nullptr || right_node == nullptr || + field_filter_depth(left_node) >= kMaxFieldFilterDepth || + field_filter_depth(right_node) >= kMaxFieldFilterDepth) { + // The inputs are consumed either way; see tsfile_field_filter_and(). + delete static_cast(left); + delete static_cast(right); + return nullptr; + } + // Takes ownership of both inputs on every path; see + // tsfile_field_filter_and(). try { return static_cast( - storage::AlignedFieldFilter::or_filter( - static_cast(left)->clone(), - static_cast(right)->clone()) + FieldFilter::or_filter(FieldFilter::Ptr(left_node), + FieldFilter::Ptr(right_node)) .release()); } catch (...) { return nullptr; @@ -3192,11 +3331,19 @@ FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter) { if (filter == nullptr) { return nullptr; } + using FieldFilter = storage::AlignedFieldFilter; + auto* node = + dynamic_cast(static_cast(filter)); + if (node == nullptr || field_filter_depth(node) >= kMaxFieldFilterDepth) { + // The input is consumed either way; see tsfile_field_filter_and(). + delete static_cast(filter); + return nullptr; + } + // Takes ownership of the input on every path; see + // tsfile_field_filter_and(). try { return static_cast( - storage::AlignedFieldFilter::not_filter( - static_cast(filter)->clone()) - .release()); + FieldFilter::not_filter(FieldFilter::Ptr(node)).release()); } catch (...) { return nullptr; } @@ -3204,7 +3351,9 @@ FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter) { void tsfile_field_filter_free(FieldFilterHandle filter) { if (filter != nullptr) { - delete static_cast(filter); + // ~Filter is virtual, so this is also safe for a handle from the other + // family (TAG) that was passed by mistake. + delete static_cast(filter); } } diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index 0cf61f95c..37709573b 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -989,7 +989,7 @@ ResultSet tsfile_reader_query_table(TsFileReader reader, const char* table_name, * * Both filters are optional. FIELD predicates are pushed down into the table * query executor: aligned devices use batch/page evaluation, non-aligned - * devices evaluate merged rows. The FIELD filter never matches NULL values; + * devices evaluate merged rows. FIELD comparisons never match NULL values; * use FIELD_FILTER_IS_NULL / FIELD_FILTER_IS_NOT_NULL for that. * * @param start_time [in] Inclusive lower time bound. @@ -1422,10 +1422,15 @@ ResultSet tsfile_query_table_with_tag_filter( // FIELD_FILTER_IS_NOT_NULL for NULL checks. // // Ownership: every create/compose function returns an owning handle. Free it -// with tsfile_field_filter_free(). The and/or/not functions borrow their -// inputs and return a new filter owning deep copies, so every input handle -// stays owned by the caller. Query functions borrow the handle and copy it -// before execution, so a handle may be reused and must be freed by the caller. +// with tsfile_field_filter_free(). The and/or/not functions take ownership of +// their inputs, like the TAG filter API above: the caller must not free the +// inputs afterwards, whether or not the call succeeds. Query functions borrow +// the handle and copy it before execution, so a handle may be reused and must +// be freed by the caller. +// +// Only FIELD handles are accepted by the compose functions: a handle from the +// TAG family (or any other non-FIELD filter) is rejected and consumed, and +// trees deeper than 512 levels are rejected the same way. /** * @brief FIELD filter comparison operators. @@ -1454,9 +1459,13 @@ typedef enum { /** * @brief Comparison literal for tsfile_field_filter_create_checked(). * - * Only the member selected by @c type is read. @c string_value is borrowed - * for the duration of the call. INT64 and DOUBLE literals bind to any numeric - * FIELD type using Java's number-narrowing rules. + * Only the member selected by @c type is read; for FIELD_FILTER_VALUE_STRING, + * @c string_value and @c string_length (the byte length of the payload, no + * terminator; 0 means the empty string) are used. @c string_value is borrowed + * for the duration of the call. INT64 and DOUBLE literals must be exactly + * representable in the column's declared numeric type; the creation call + * rejects lossy values (fractional, NaN/inf or out-of-range constants on + * integral columns) with E_TYPE_NOT_MATCH instead of narrowing them. */ typedef struct { FieldFilterValueType type; @@ -1480,7 +1489,8 @@ typedef struct { * @return E_OK on success, E_INVALID_ARG for a bad handle/name/operator or a * non-FIELD column, E_COLUMN_NOT_EXIST for an unknown column, * E_TYPE_NOT_MATCH when the literal type cannot bind to the column - * type, E_TABLE_NOT_EXIST for an unknown table. + * type or a numeric literal is not exactly representable in it, + * E_TABLE_NOT_EXIST for an unknown table. */ ERRNO tsfile_field_filter_create_checked(TsFileReader reader, const char* table_name, @@ -1492,8 +1502,9 @@ ERRNO tsfile_field_filter_create_checked(TsFileReader reader, /** * @brief Logical AND of two FIELD filters. * - * Borrows both inputs and returns a new filter that owns deep copies, so the - * caller keeps and must still free both handles. Returns NULL on failure. + * Takes ownership of both inputs; the caller must not free them afterwards. + * Returns a new filter that owns them directly. Returns NULL on failure + * (the inputs are consumed either way). */ FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, FieldFilterHandle right); @@ -1501,8 +1512,9 @@ FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, /** * @brief Logical OR of two FIELD filters. * - * Borrows both inputs and returns a new filter that owns deep copies, so the - * caller keeps and must still free both handles. Returns NULL on failure. + * Takes ownership of both inputs; the caller must not free them afterwards. + * Returns a new filter that owns them directly. Returns NULL on failure + * (the inputs are consumed either way). */ FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, FieldFilterHandle right); @@ -1510,9 +1522,9 @@ FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, /** * @brief Logical NOT of a FIELD filter. * - * Borrows the input and returns a new filter that owns a deep copy, so the - * caller keeps and must still free the handle. Returns NULL on failure. NULL - * rows never satisfy a negated predicate. + * Takes ownership of the input; the caller must not free it afterwards. + * Returns a new filter that owns it directly. Returns NULL on failure (the + * input is consumed either way). NULL rows never satisfy a negated predicate. */ FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter); diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 76aa96030..eb9db5ee7 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -97,6 +97,10 @@ class AlignedFieldFilter : public Filter { CompareOp compare_op() const { return compare_op_; } const std::string& column() const { return column_; } const Literal& literal() const { return literal_; } + // Composite operands (null for leaves); used for iterative traversal, e.g. + // depth checks before recursing into clone()/bind(). + const AlignedFieldFilter* left() const { return left_.get(); } + const AlignedFieldFilter* right() const { return right_.get(); } std::vector referenced_columns() const; diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 8ecc1256d..15f6982f0 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -26,12 +26,14 @@ int TableQueryExecutor::query(const std::string& table_name, const std::vector& columns, Filter* time_filter, Filter* tag_filter, Filter* field_filter, ResultSet*& ret_qds) { + // Adopt both filters immediately so every error return and any exception + // frees them unless they are handed to the block reader below. + std::unique_ptr time_filter_guard(time_filter); + std::unique_ptr field_filter_guard(field_filter); int ret = common::E_OK; TsFileMeta* file_metadata = nullptr; ret_qds = nullptr; if (RET_FAIL(tsfile_io_reader_->get_tsfile_meta(file_metadata))) { - delete time_filter; - delete field_filter; return ret; } common::PageArena pa; @@ -44,8 +46,6 @@ int TableQueryExecutor::query(const std::string& table_name, // not exist". if (RET_FAIL(file_metadata->get_table_schema(table_name, table_schema))) { ret_qds = nullptr; - delete time_filter; - delete field_filter; return ret; } file_metadata->get_table_metaindex_node(table_name, table_root); @@ -64,20 +64,16 @@ int TableQueryExecutor::query(const std::string& table_name, for (size_t i = 0; i < lower_case_column_names.size(); ++i) { auto ind = table_schema->find_column_index(lower_case_column_names[i]); if (ind < 0) { - delete time_filter; - delete field_filter; return common::E_COLUMN_NOT_EXIST; } data_types.push_back(table_schema->get_data_types()[ind]); } if (auto* aligned_filter = - dynamic_cast(field_filter)) { + dynamic_cast(field_filter_guard.get())) { ret = aligned_filter->is_valid() ? column_mapping->add_filter_columns( *aligned_filter, *table_schema) : common::E_INVALID_ARG; if (ret != common::E_OK) { - delete time_filter; - delete field_filter; return ret; } } @@ -93,12 +89,15 @@ int TableQueryExecutor::query(const std::string& table_name, tsblock_reader = std::unique_ptr( new DeviceOrderedTsBlockReader( std::move(device_task_iterator), meta_data_querier_, - block_size_, tsfile_io_reader_, time_filter, field_filter)); + block_size_, tsfile_io_reader_, time_filter_guard.get(), + field_filter_guard.get())); + // Ownership moves to the reader only after it is constructed, so a + // throwing allocation above cannot leak the filters. + time_filter_guard.release(); + field_filter_guard.release(); break; case TableQueryOrdering::TIME: default: - delete time_filter; - delete field_filter; ret_qds = nullptr; return common::E_UNSUPPORTED_ORDER; } @@ -114,12 +113,14 @@ int TableQueryExecutor::query(const std::string& table_name, Filter* time_filter, Filter* tag_filter, Filter* field_filter, int offset, int limit, ResultSet*& ret_qds) { + // Adopt both filters immediately so every error return and any exception + // frees them unless they are handed to the block reader below. + std::unique_ptr time_filter_guard(time_filter); + std::unique_ptr field_filter_guard(field_filter); int ret = common::E_OK; TsFileMeta* file_metadata = nullptr; ret_qds = nullptr; if (RET_FAIL(tsfile_io_reader_->get_tsfile_meta(file_metadata))) { - delete time_filter; - delete field_filter; return ret; } common::PageArena pa; @@ -128,8 +129,6 @@ int TableQueryExecutor::query(const std::string& table_name, std::shared_ptr table_schema; if (RET_FAIL(file_metadata->get_table_schema(table_name, table_schema))) { ret_qds = nullptr; - delete time_filter; - delete field_filter; return ret; } file_metadata->get_table_metaindex_node(table_name, table_root); @@ -148,20 +147,16 @@ int TableQueryExecutor::query(const std::string& table_name, for (size_t i = 0; i < lower_case_column_names.size(); ++i) { auto ind = table_schema->find_column_index(lower_case_column_names[i]); if (ind < 0) { - delete time_filter; - delete field_filter; return common::E_COLUMN_NOT_EXIST; } data_types.push_back(table_schema->get_data_types()[ind]); } if (auto* aligned_filter = - dynamic_cast(field_filter)) { + dynamic_cast(field_filter_guard.get())) { ret = aligned_filter->is_valid() ? column_mapping->add_filter_columns( *aligned_filter, *table_schema) : common::E_INVALID_ARG; if (ret != common::E_OK) { - delete time_filter; - delete field_filter; return ret; } } @@ -175,15 +170,17 @@ int TableQueryExecutor::query(const std::string& table_name, 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)); + new DeviceOrderedTsBlockReader( + std::move(device_task_iterator), meta_data_querier_, + block_size_, tsfile_io_reader_, time_filter_guard.get(), + field_filter_guard.get(), offset, limit)); + // Ownership moves to the reader only after it is constructed, so a + // throwing allocation above cannot leak the filters. + time_filter_guard.release(); + field_filter_guard.release(); break; case TableQueryOrdering::TIME: default: - delete time_filter; - delete field_filter; ret_qds = nullptr; return common::E_UNSUPPORTED_ORDER; } diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index 147c24ebd..33c3a864b 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -283,9 +283,13 @@ int TsFileReader::query(const std::string& table_name, Filter* time_filter = new TimeBetween(start_time, end_time, false); ensure_table_query_executor(batch_size); + // Compute the lower-case name before handing the filter over: no + // allocating expression may remain between release() and the call. + const std::string lower_table_name = to_lower(table_name); + Filter* field_filter_raw = field_filter_guard.release(); ret = table_query_executor_->query( - to_lower(table_name), columns_names, time_filter, tag_filter, - field_filter_guard.release(), offset, limit, result_set); + lower_table_name, columns_names, time_filter, tag_filter, + field_filter_raw, offset, limit, result_set); return ret; } @@ -496,10 +500,14 @@ int TsFileReader::queryByRow(const std::string& table_name, } ensure_table_query_executor(batch_size); - ret = table_query_executor_->query(to_lower(table_name), column_names, + // Compute the lower-case name before handing the filter over: no + // allocating expression may remain between release() and the call. + const std::string lower_table_name = to_lower(table_name); + Filter* field_filter_raw = field_filter_guard.release(); + ret = table_query_executor_->query(lower_table_name, column_names, /*time_filter=*/nullptr, tag_filter, - field_filter_guard.release(), offset, - limit, result_set); + field_filter_raw, offset, limit, + result_set); return ret; } diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 0f9718576..47cc75a56 100644 --- a/cpp/test/cwrapper/cwrapper_extended_test.cc +++ b/cpp/test/cwrapper/cwrapper_extended_test.cc @@ -26,9 +26,11 @@ #endif #include +#include #include #include #include +#include #include #include @@ -683,21 +685,46 @@ TEST(CWrapperExtendedTest, FieldFilterSelectsRowsAndComposes) { ASSERT_NE(nullptr, paged); rows = collect_row_identities(paged, &err); ASSERT_EQ(2u, rows.size()); - for (const auto& row : rows) { - EXPECT_GE(row.value, 1); - } + // OFFSET counts accepted rows: INT32 1,2,3,4 per device, skip 1 -> 2,3. + EXPECT_EQ(2, rows[0].value); + EXPECT_EQ(3, rows[1].value); free_tsfile_result_set(&paged); + // OR composition through the same entry (row mode; batch-mode pushdown is + // covered by the Python Arrow tests). + FieldFilterValue int_eq_two_again{}; + int_eq_two_again.type = FIELD_FILTER_VALUE_INT64; + int_eq_two_again.int64_value = 2; + FieldFilterHandle or_left = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &int_eq_two_again, &or_left)); + FieldFilterValue int_eq_four{}; + int_eq_four.type = FIELD_FILTER_VALUE_INT64; + int_eq_four.int64_value = 4; + FieldFilterHandle or_right = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &int_eq_four, &or_right)); + FieldFilterHandle either = tsfile_field_filter_or(or_left, or_right); + ASSERT_NE(nullptr, either); + ResultSet or_filtered = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, either, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, or_filtered); + EXPECT_EQ(4, count_result_rows(or_filtered, &err)); + free_tsfile_result_set(&or_filtered); + tsfile_field_filter_free(either); + tsfile_field_filter_free(int_ge_one_filter); - tsfile_field_filter_free(int_two); tsfile_field_filter_free(double_not_null); tsfile_field_filter_free(float_eq); tsfile_field_filter_free(int_not_two); - // Composition borrows its inputs and owns copies, so every input handle - // and the composed handle are freed here. + // Composition takes ownership of its inputs: int_two was consumed by + // tsfile_field_filter_not, and int_ge_two / flag_true by + // tsfile_field_filter_and, so only the composed handle is freed here. tsfile_field_filter_free(combined); - tsfile_field_filter_free(flag_true); - tsfile_field_filter_free(int_ge_two); tsfile_reader_close(reader); std::remove(path.c_str()); @@ -754,6 +781,53 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { EXPECT_EQ(nullptr, tsfile_field_filter_and(nullptr, nullptr)); EXPECT_EQ(nullptr, tsfile_field_filter_not(nullptr)); + // Malformed inputs are rejected. + EXPECT_EQ(RET_INVALID_ARG, + tsfile_field_filter_create_checked(reader, kTableName, "INT32", + static_cast(99), + &int_value, &handle)); + EXPECT_EQ(nullptr, handle); + FieldFilterValue null_string{}; + null_string.type = FIELD_FILTER_VALUE_STRING; + null_string.string_value = nullptr; + EXPECT_EQ(RET_INVALID_ARG, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &null_string, &handle)); + EXPECT_EQ(nullptr, handle); + + // Lossy literals on integral columns are rejected instead of narrowed. + FieldFilterValue fractional{}; + fractional.type = FIELD_FILTER_VALUE_DOUBLE; + fractional.double_value = 1.5; + EXPECT_EQ(RET_TYPE_NOT_MATCH, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", + FIELD_FILTER_EQ, &fractional, &handle)); + EXPECT_EQ(nullptr, handle); + FieldFilterValue nan_value{}; + nan_value.type = FIELD_FILTER_VALUE_DOUBLE; + nan_value.double_value = std::numeric_limits::quiet_NaN(); + EXPECT_EQ(RET_TYPE_NOT_MATCH, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", + FIELD_FILTER_EQ, &nan_value, &handle)); + EXPECT_EQ(nullptr, handle); + FieldFilterValue wrapped{}; + wrapped.type = FIELD_FILTER_VALUE_INT64; + wrapped.int64_value = (int64_t{1} << 32) + 1; // would wrap to 1 in INT32 + EXPECT_EQ(RET_TYPE_NOT_MATCH, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", + FIELD_FILTER_EQ, &wrapped, &handle)); + EXPECT_EQ(nullptr, handle); + // An integral DOUBLE is exactly representable and stays accepted. + FieldFilterValue integral_double{}; + integral_double.type = FIELD_FILTER_VALUE_DOUBLE; + integral_double.double_value = 2.0; + EXPECT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &integral_double, &handle)); + ASSERT_NE(nullptr, handle); + tsfile_field_filter_free(handle); + handle = nullptr; + // A deliberately empty time range still yields an empty result set. ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( reader, kTableName, "INT32", FIELD_FILTER_GTEQ, @@ -769,6 +843,21 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { free_tsfile_result_set(&empty); tsfile_field_filter_free(handle); + // Query-level argument validation on the new entry points. + EXPECT_EQ(nullptr, tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), + 0, 100, -1, -1, nullptr, nullptr, 0, &err)); + EXPECT_EQ(RET_INVALID_ARG, err); + EXPECT_EQ(nullptr, tsfile_query_table_with_filters( + reader, kTableName, columns.data(), 0, 0, 100, 0, -1, + nullptr, nullptr, 0, &err)); + EXPECT_EQ(RET_INVALID_ARG, err); + EXPECT_EQ(nullptr, tsfile_reader_query_table_by_row_with_filters( + reader, kTableName, columns.data(), + static_cast(columns.size()), -1, -1, nullptr, + nullptr, 0, &err)); + EXPECT_EQ(RET_INVALID_ARG, err); + tsfile_reader_close(reader); std::remove(path.c_str()); } diff --git a/python/tests/test_field_filter_query.py b/python/tests/test_field_filter_query.py index 2ba317168..1a9ccd91f 100644 --- a/python/tests/test_field_filter_query.py +++ b/python/tests/test_field_filter_query.py @@ -505,3 +505,80 @@ def test_unknown_filter_object(self): with TsFileReader(TSFILE_PATH) as reader: with pytest.raises(TypeError): reader.query_table(TABLE_NAME, COLUMN_NAMES, field_filter=object()) + + def test_lossy_literals_on_integral_column_are_rejected(self): + # Java-style narrowing would silently turn these into other constants + # (1.5 -> 1, NaN -> 0, 2**32 -> 0), so they must be rejected instead. + with TsFileReader(TSFILE_PATH) as reader: + for bad_filter in ( + field_eq("count32", 1.5), + field_lt("count32", 2.5), + field_between("count32", 1.5, 2.5), + field_eq("count32", float("nan")), + field_eq("count32", float("inf")), + field_eq("count32", 2**32), + ): + with pytest.raises(TypeMismatchError): + reader.query_table( + TABLE_NAME, COLUMN_NAMES, field_filter=bad_filter + ) + + def test_integral_double_is_accepted_on_integral_column(self): + with TsFileReader(TSFILE_PATH) as reader: + assert _times(reader, field_eq("count32", 2.0)) == [2.0] + assert _times(reader, field_between("count32", 2.0, 3.0)) == [2.0, 3.0] + + def test_deep_filter_tree_is_rejected(self): + # A loop-built chain must not overflow the C stack in the builder or in + # the native clone()/bind() recursion. + deep = field_eq("value", 1.0) + for _ in range(600): + deep = deep & field_eq("value", 1.0) + with TsFileReader(TSFILE_PATH) as reader: + with pytest.raises(ValueError, match="maximum depth"): + reader.query_table(TABLE_NAME, COLUMN_NAMES, field_filter=deep) + + def test_validation_independent_of_field_filter(self): + with TsFileReader(TSFILE_PATH) as reader: + for field_filter in (None, field_gt("value", 0.0)): + with pytest.raises(InvalidArgumentError): + reader.query_table_by_row( + TABLE_NAME, COLUMN_NAMES, offset=-1, field_filter=field_filter + ) + with pytest.raises(InvalidArgumentError): + reader.query_table(TABLE_NAME, [], field_filter=field_filter) + + +class TestFieldFilterCoverage: + """Paths the original tests did not reach (cache bypass, NULL negation).""" + + def test_cache_bypass_with_tag_and_field_filter(self): + # A single-device tag filter plus batch mode would use the prepared + # series cache; the field filter must force the regular path instead. + with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table( + TABLE_NAME, + ["value"], + tag_filter=tag_eq("device", "dev_c"), + field_filter=field_eq("value", 13.0), + batch_size=2, + ) as result: + values = [] + while True: + batch = result.read_arrow_batch() + if batch is None: + break + values.extend(batch.column("value").to_pylist()) + assert values == [13.0] + + def test_negation_never_matches_null(self): + with TsFileReader(TSFILE_PATH) as reader: + rows = _query(reader, field_not_between("sparse", 5.0, 9.0)) + assert len(rows) == 8 + assert all(row[6] is not None for row in rows) + rows = _query(reader, ~field_lt("sparse", 8.0)) + assert len(rows) == 6 + assert all(row[6] is not None for row in rows) + rows = _query(reader, ~field_is_null("sparse")) + assert len(rows) == 10 + assert all(row[6] is not None for row in rows) diff --git a/python/tsfile/field_filter.py b/python/tsfile/field_filter.py index 0f91a46ec..6615fc614 100644 --- a/python/tsfile/field_filter.py +++ b/python/tsfile/field_filter.py @@ -25,9 +25,11 @@ :func:`field_is_null` / :func:`field_is_not_null` for NULL checks. Values may be ``bool``, ``int`` (64-bit range), ``float`` or ``str``. Numeric -literals adapt to the column's declared numeric type; a string literal needs a -string-like FIELD column and vice versa. The native layer raises -``TypeMismatchError`` for incompatible combinations. +literals are compared in the column's declared numeric type; a string literal +needs a string-like FIELD column and vice versa. Literals the column type +cannot represent exactly -- a fractional, NaN/inf or out-of-range value on an +integral column -- raise ``TypeMismatchError`` instead of being silently +narrowed, so the predicate always compares the value that was written. """ from numbers import Integral, Real diff --git a/python/tsfile/tsfile_py_cpp.pyx b/python/tsfile/tsfile_py_cpp.pyx index 7336f9050..1155c9626 100644 --- a/python/tsfile/tsfile_py_cpp.pyx +++ b/python/tsfile/tsfile_py_cpp.pyx @@ -1159,6 +1159,7 @@ cdef ResultSet tsfile_reader_query_table_c(TsFileReader reader, object table_nam cdef ErrorCode code = 0 if columns == NULL: raise MemoryError("Failed to allocate memory for columns") + memset(columns, 0, sizeof(char *) * column_num) try: for i in range(column_num): columns[i] = strdup(( column_list[i]).encode('utf-8')) @@ -1184,6 +1185,7 @@ cdef ResultSet tsfile_reader_query_table_on_tree_c(TsFileReader reader, object c cdef ErrorCode code = 0 if columns == NULL: raise MemoryError("Failed to allocate memory for columns") + memset(columns, 0, sizeof(char *) * column_num) try: for i in range(column_num): columns[i] = strdup(( column_list[i]).encode('utf-8')) @@ -1215,6 +1217,8 @@ cdef ResultSet tsfile_reader_query_tree_by_row_c(TsFileReader reader, if device_ids_c == NULL or measurement_names_c == NULL: raise MemoryError("Failed to allocate memory for tree by-row query arrays") + memset(device_ids_c, 0, sizeof(char *) * device_num) + memset(measurement_names_c, 0, sizeof(char *) * measurement_num) try: for i in range(device_num): @@ -1264,6 +1268,7 @@ cdef ResultSet tsfile_reader_query_table_by_row_c(TsFileReader reader, if columns == NULL: raise MemoryError("Failed to allocate memory for table by-row query columns") + memset(columns, 0, sizeof(char *) * column_num) try: for i in range(column_num): columns[i] = strdup(( column_list[i]).encode('utf-8')) @@ -1296,6 +1301,7 @@ cdef ResultSet tsfile_reader_query_table_batch_c(TsFileReader reader, object tab cdef ErrorCode code = 0 if columns == NULL: raise MemoryError("Failed to allocate memory for columns") + memset(columns, 0, sizeof(char *) * column_num) try: for i in range(column_num): columns[i] = strdup(( column_list[i]).encode('utf-8')) @@ -1327,6 +1333,7 @@ cdef ResultSet tsfile_reader_query_paths_c(TsFileReader reader, object device_na cdef ErrorCode code = 0 if sensor_list_c == NULL: raise MemoryError("Failed to allocate memory for paths") + memset(sensor_list_c, 0, sizeof(char *) * path_num) try: for i in range(path_num): sensor_list_c[i] = strdup(( sensor_list[i]).encode('utf-8')) @@ -1358,6 +1365,7 @@ cdef ResultSet tsfile_reader_query_table_with_tag_filter_c(TsFileReader reader, cdef ErrorCode code = 0 if columns == NULL: raise MemoryError("Failed to allocate memory for columns") + memset(columns, 0, sizeof(char *) * column_num) try: for i in range(column_num): columns[i] = strdup(( column_list[i]).encode('utf-8')) @@ -1388,6 +1396,7 @@ cdef ResultSet tsfile_query_table_with_filters_c( cdef ErrorCode code = 0 if columns == NULL: raise MemoryError("Failed to allocate memory for columns") + memset(columns, 0, sizeof(char *) * column_num) try: for i in range(column_num): columns[i] = strdup(( column_list[i]).encode('utf-8')) @@ -1419,6 +1428,7 @@ cdef ResultSet tsfile_reader_query_table_by_row_with_filters_c( cdef ErrorCode code = 0 if columns == NULL: raise MemoryError("Failed to allocate memory for table by-row query columns") + memset(columns, 0, sizeof(char *) * column_num) try: for i in range(column_num): columns[i] = strdup(( column_list[i]).encode('utf-8')) diff --git a/python/tsfile/tsfile_reader.pyx b/python/tsfile/tsfile_reader.pyx index 01204aa8a..b5bd05373 100644 --- a/python/tsfile/tsfile_reader.pyx +++ b/python/tsfile/tsfile_reader.pyx @@ -33,7 +33,7 @@ from libc.stdint cimport INT64_MIN, INT64_MAX, uint32_t, uintptr_t from tsfile.schema import TSDataType as TSDataTypePy from tsfile.schema import DeviceID, DeviceTimeseriesMetadataGroup -from tsfile.exceptions import TsFileCorruptedError +from tsfile.exceptions import InvalidArgumentError, TsFileCorruptedError from tsfile.tag_filter import ComparisonTagFilter, BetweenTagFilter, AndTagFilter, OrTagFilter, NotTagFilter, cache_key from tsfile.field_filter import ComparisonFieldFilter, BetweenFieldFilter, AndFieldFilter, OrFieldFilter, NotFieldFilter from .date_utils import parse_int_to_date @@ -67,6 +67,11 @@ _CACHE_FALLBACK_CODES = frozenset((4, 27, 40, 44, 45, 49, 50)) # path; keep those queries on the regular path. _PREPARED_CACHE_MAX_COLUMNS = 16 +# The native clone()/bind() implementations recurse once per filter-tree level +# and the builder here recurses too, so depth is capped instead of being able +# to overflow the C stack. +_MAX_FIELD_FILTER_DEPTH = 512 + cdef FieldFilterHandle _make_field_comparison( TsFileReader reader, bytes table_bytes, bytes column_bytes, int op, object value, object value_type): @@ -486,6 +491,9 @@ cdef class TsFileReaderPy: cdef TagFilterHandle c_tag_filter = NULL cdef FieldFilterHandle c_field_filter = NULL cdef ResultSetPy pyresult + if not column_names: + raise InvalidArgumentError( + context="column_names must not be empty") if (self._prepared_query_cache_size > 0 and batch_size > 0 and 0 < len(column_names) < _PREPARED_CACHE_MAX_COLUMNS and tag_filter is not None and field_filter is None): @@ -519,7 +527,7 @@ cdef class TsFileReaderPy: pyresult._tag_filter_handle = c_tag_filter if field_filter is not None: c_field_filter = self._build_c_field_filter( - table_name.lower(), field_filter) + table_name.lower(), field_filter, 0) pyresult._field_filter_handle = c_field_filter if field_filter is not None: result = tsfile_query_table_with_filters_c( @@ -710,13 +718,12 @@ cdef class TsFileReaderPy: else: raise TypeError(f"Unknown tag filter type: {type(tag_filter)}") - cdef FieldFilterHandle _build_c_field_filter(self, str table_name, object field_filter): + cdef FieldFilterHandle _build_c_field_filter(self, str table_name, object field_filter, int depth): """Recursively build a C FieldFilterHandle from a Python FieldFilter tree. - The native composition helpers borrow their inputs and return a new - filter owning deep copies, so every intermediate handle built here is - released in the ``finally`` block and only the returned handle is - transferred to the caller. + The native composition helpers take ownership of their inputs, so every + intermediate handle is handed over and cleared here; only the returned + handle is transferred to the caller. """ cdef FieldFilterHandle handle = NULL cdef FieldFilterHandle left = NULL @@ -726,6 +733,11 @@ cdef class TsFileReaderPy: cdef bytes table_bytes cdef bytes col_bytes + if depth >= _MAX_FIELD_FILTER_DEPTH: + raise ValueError( + f"FIELD filter tree exceeds the maximum depth of " + f"{_MAX_FIELD_FILTER_DEPTH}") + table_bytes = table_name.encode('utf-8') if isinstance(field_filter, ComparisonFieldFilter): col_bytes = field_filter.column_name.encode('utf-8') @@ -744,10 +756,13 @@ cdef class TsFileReaderPy: ComparisonFieldFilter.LTEQ, field_filter.upper, field_filter.upper_type) handle = tsfile_field_filter_and(left, right) + left = NULL + right = NULL if handle == NULL: raise MemoryError("Unable to allocate BETWEEN field filter") if field_filter.is_not: out = tsfile_field_filter_not(handle) + handle = NULL if out == NULL: raise MemoryError( "Unable to allocate NOT BETWEEN field filter") @@ -761,9 +776,13 @@ cdef class TsFileReaderPy: tsfile_field_filter_free(handle) elif isinstance(field_filter, AndFieldFilter): try: - left = self._build_c_field_filter(table_name, field_filter.left) - right = self._build_c_field_filter(table_name, field_filter.right) + left = self._build_c_field_filter( + table_name, field_filter.left, depth + 1) + right = self._build_c_field_filter( + table_name, field_filter.right, depth + 1) out = tsfile_field_filter_and(left, right) + left = NULL + right = NULL if out == NULL: raise MemoryError("Unable to allocate compound field filter") return out @@ -772,9 +791,13 @@ cdef class TsFileReaderPy: tsfile_field_filter_free(right) elif isinstance(field_filter, OrFieldFilter): try: - left = self._build_c_field_filter(table_name, field_filter.left) - right = self._build_c_field_filter(table_name, field_filter.right) + left = self._build_c_field_filter( + table_name, field_filter.left, depth + 1) + right = self._build_c_field_filter( + table_name, field_filter.right, depth + 1) out = tsfile_field_filter_or(left, right) + left = NULL + right = NULL if out == NULL: raise MemoryError("Unable to allocate compound field filter") return out @@ -783,8 +806,10 @@ cdef class TsFileReaderPy: tsfile_field_filter_free(right) elif isinstance(field_filter, NotFieldFilter): try: - inner = self._build_c_field_filter(table_name, field_filter.filter) + inner = self._build_c_field_filter( + table_name, field_filter.filter, depth + 1) out = tsfile_field_filter_not(inner) + inner = NULL if out == NULL: raise MemoryError("Unable to allocate compound field filter") return out @@ -841,12 +866,18 @@ cdef class TsFileReaderPy: cdef TagFilterHandle c_tag_filter = NULL cdef FieldFilterHandle c_field_filter = NULL pyresult = ResultSetPy(self) + if not column_names: + raise InvalidArgumentError( + context="column_names must not be empty") + if offset < 0: + raise InvalidArgumentError( + context=f"offset must be >= 0, got {offset}") if tag_filter is not None: c_tag_filter = self._build_c_tag_filter(table_name.lower(), tag_filter) pyresult._tag_filter_handle = c_tag_filter if field_filter is not None: c_field_filter = self._build_c_field_filter( - table_name.lower(), field_filter) + table_name.lower(), field_filter, 0) pyresult._field_filter_handle = c_field_filter if field_filter is not None: result = tsfile_reader_query_table_by_row_with_filters_c( diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 7a27edebe..2be0d74ef 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -83,13 +83,16 @@ comparison also excludes NULL cells. `field_gt`, `field_gteq`, `field_is_null`, `field_is_not_null`, `field_between`, and `field_not_between`. Compose with `&`, `|`, and `~`, then pass `field_filter=` to `query_table` or `query_table_by_row`. Values may be - `bool`, `int` (64-bit range), `float`, or `str`; numeric literals adapt to the - column's numeric type, while string literals require a string-like column and - raise `TypeMismatchError` otherwise. `None` is rejected -- use the IS NULL - predicates. A `field_filter` disables the prepared-series cache for that - query. + `bool`, `int` (64-bit range), `float`, or `str`; numeric literals are compared + in the column's numeric type, and literals the column type cannot represent + exactly (fractional, NaN/inf or out-of-range values on integral columns) raise + `TypeMismatchError` instead of being narrowed. String literals require a + string-like column and raise `TypeMismatchError` otherwise. `None` is + rejected -- use the IS NULL predicates. A `field_filter` disables the + prepared-series cache for that query. - C wrapper: build handles with `tsfile_field_filter_create_checked`, - compose with `tsfile_field_filter_and` / `_or` / `_not`, and release them with + compose with `tsfile_field_filter_and` / `_or` / `_not` (each takes ownership + of its inputs, like the TAG filter API), and release the result with `tsfile_field_filter_free`. Pass TAG and FIELD handles to `tsfile_query_table_with_filters` or `tsfile_reader_query_table_by_row_with_filters`; the query copies the FIELD From 0b41fb0219f03b23fb7f34f90677355716196763 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Tue, 1 Dec 2026 16:04:14 +0800 Subject: [PATCH 04/10] fix(python): harden FIELD filter composition and validate literals at query time - Reject an aliased operand pair (same handle twice) and consume the non-NULL operand on a NULL-sibling call, matching the documented consumption contract. - Validate literal exactness against the queried schema in the table query executor, so a handle reused with a different schema is rejected instead of being silently narrowed. - Keep negation valid for a maximum-depth tree (negation preserves height) and charge BETWEEN's synthetic native level in the Cython builder so the boundary raises ValueError instead of MemoryError. - Guard the TimeBetween filter with RAII and materialise the table name before cloning, closing the remaining exception windows. - Use len() for the empty-projection check so numpy arrays and pandas Index work; document the new validation, depth and ownership rules. - Add regression tests: aliasing, NULL sibling, 512/513 depth boundary, INT32/INT64 literal boundaries, cross-device OFFSET, cache-bypass proof, Arrow OR composition, and the by-row validation paths. --- cpp/src/cwrapper/tsfile_cwrapper.cc | 156 +++++++----------- cpp/src/cwrapper/tsfile_cwrapper.h | 28 ++-- cpp/src/reader/filter/aligned_field_filter.cc | 79 +++++++++ cpp/src/reader/filter/aligned_field_filter.h | 8 + cpp/src/reader/table_query_executor.cc | 12 ++ cpp/src/reader/tsfile_reader.cc | 8 +- cpp/test/cwrapper/cwrapper_extended_test.cc | 137 +++++++++++++++ python/tests/test_field_filter_query.py | 67 +++++++- python/tsfile/field_filter.py | 9 +- python/tsfile/tsfile_reader.pyx | 16 +- .../tsfile/references/properties-filters.md | 9 +- 11 files changed, 406 insertions(+), 123 deletions(-) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index 2a2c98b4d..3a1800086 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -3067,53 +3067,6 @@ bool to_field_literal(const FieldFilterValue& value, } } -// Validates that a numeric literal is exactly representable in the declared -// column type. AlignedFieldFilter::bind() narrows constants with Java's -// Number.intValue/longValue rules (low-bit wrap, truncation toward zero, -// NaN -> 0), which would silently change the predicate the caller wrote, so -// those literals are rejected up front instead. -ERRNO validate_exact_literal(const FieldFilterValue& value, - common::TSDataType column_type) { - const bool integral_column = - column_type == common::INT32 || column_type == common::INT64 || - column_type == common::DATE || column_type == common::TIMESTAMP; - if (!integral_column) { - return common::E_OK; - } - if (value.type == FIELD_FILTER_VALUE_INT64) { - if ((column_type == common::INT32 || column_type == common::DATE) && - (value.int64_value < - static_cast(std::numeric_limits::min()) || - value.int64_value > - static_cast(std::numeric_limits::max()))) { - return common::E_TYPE_NOT_MATCH; - } - return common::E_OK; - } - if (value.type == FIELD_FILTER_VALUE_DOUBLE) { - const double literal = value.double_value; - if (!std::isfinite(literal) || std::trunc(literal) != literal) { - return common::E_TYPE_NOT_MATCH; - } - if (column_type == common::INT32 || column_type == common::DATE) { - if (literal < - static_cast(std::numeric_limits::min()) || - literal > - static_cast(std::numeric_limits::max())) { - return common::E_TYPE_NOT_MATCH; - } - return common::E_OK; - } - // INT64/TIMESTAMP: [-2^63, 2^63) are the doubles that map exactly. - constexpr double kInt64Min = -9223372036854775808.0; // -2^63 - constexpr double kInt64MaxExclusive = 9223372036854775808.0; // 2^63 - if (literal < kInt64Min || literal >= kInt64MaxExclusive) { - return common::E_TYPE_NOT_MATCH; - } - } - return common::E_OK; -} - // Maximum depth of a FIELD filter tree accepted by this API. The native // clone()/bind() implementations recurse once per level, so deeper trees are // rejected instead of being able to overflow the C stack. @@ -3220,31 +3173,17 @@ ERRNO tsfile_field_filter_create_checked(TsFileReader reader, if (filter == nullptr) { return common::E_OOM; } - // Reject numeric literals that Java-style narrowing would alter before - // they can reach the filter (see validate_exact_literal). Binding also - // resolves the column, so a missing or non-FIELD column still produces - // the precise error from bind() below. - if (needs_value) { - std::string lookup_name(column_name); - for (char& ch : lookup_name) { - ch = static_cast( - std::tolower(static_cast(ch))); - } - const common::ColumnSchema column_schema = - schema->get_column_schema(lookup_name); - if (column_schema.is_valid() && column_schema.column_category_ == - common::ColumnCategory::FIELD) { - ret = validate_exact_literal(*value, column_schema.data_type_); - if (ret != common::E_OK) { - return ret; - } - } + // Reject numeric literals that Java-style narrowing would alter on the + // creating table; the query re-checks them against the queried schema. + // Missing or non-FIELD columns are skipped here so bind() below can + // report the precise error. + ret = filter->check_exact_literals(*schema); + if (ret != common::E_OK) { + return ret; } // Validate on a throwaway copy so the reusable handle keeps the - // caller's literal. The query-time clone is bound against the schema - // of the table actually queried, so a handle reused with a different - // schema still compares the original value instead of the creating - // schema's narrowed constant. + // caller's literal; the query-time clone is checked and bound against + // the schema of the table actually queried. FieldFilter::Ptr probe = filter->clone(); if (probe == nullptr) { return common::E_OOM; @@ -3268,6 +3207,16 @@ ERRNO tsfile_field_filter_create_checked(TsFileReader reader, FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, FieldFilterHandle right) { if (left == nullptr || right == nullptr) { + // A NULL sibling still consumes the other input: delete on a null + // pointer is a no-op for the missing side. + delete static_cast(left); + delete static_cast(right); + return nullptr; + } + if (left == right) { + // Operands must be distinct; an aliased pair is rejected and the one + // handle is consumed exactly once. + delete static_cast(left); return nullptr; } using FieldFilter = storage::AlignedFieldFilter; @@ -3275,22 +3224,25 @@ FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, dynamic_cast(static_cast(left)); auto* right_node = dynamic_cast(static_cast(right)); - if (left_node == nullptr || right_node == nullptr || - field_filter_depth(left_node) >= kMaxFieldFilterDepth || - field_filter_depth(right_node) >= kMaxFieldFilterDepth) { - // The inputs are consumed either way. Both handle families are Filter - // subclasses, so free through the virtual destructor. + if (left_node == nullptr || right_node == nullptr) { + // Both handle families are Filter subclasses, so free through the + // virtual destructor. delete static_cast(left); delete static_cast(right); return nullptr; } - // Takes ownership of both inputs on every path, matching the TAG filter - // composition API: the returned node adopts them directly, so the caller - // must not free the inputs afterwards (even when this returns NULL). + // Takes ownership of both inputs on every path: the returned node adopts + // them directly, so the caller must not free the inputs afterwards (even + // when this returns NULL). try { + FieldFilter::Ptr left_ptr(left_node); + FieldFilter::Ptr right_ptr(right_node); + if (field_filter_depth(left_node) >= kMaxFieldFilterDepth || + field_filter_depth(right_node) >= kMaxFieldFilterDepth) { + return nullptr; + } return static_cast( - FieldFilter::and_filter(FieldFilter::Ptr(left_node), - FieldFilter::Ptr(right_node)) + FieldFilter::and_filter(std::move(left_ptr), std::move(right_ptr)) .release()); } catch (...) { return nullptr; @@ -3300,6 +3252,12 @@ FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, FieldFilterHandle right) { if (left == nullptr || right == nullptr) { + delete static_cast(left); + delete static_cast(right); + return nullptr; + } + if (left == right) { + delete static_cast(left); return nullptr; } using FieldFilter = storage::AlignedFieldFilter; @@ -3307,10 +3265,7 @@ FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, dynamic_cast(static_cast(left)); auto* right_node = dynamic_cast(static_cast(right)); - if (left_node == nullptr || right_node == nullptr || - field_filter_depth(left_node) >= kMaxFieldFilterDepth || - field_filter_depth(right_node) >= kMaxFieldFilterDepth) { - // The inputs are consumed either way; see tsfile_field_filter_and(). + if (left_node == nullptr || right_node == nullptr) { delete static_cast(left); delete static_cast(right); return nullptr; @@ -3318,9 +3273,14 @@ FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, // Takes ownership of both inputs on every path; see // tsfile_field_filter_and(). try { + FieldFilter::Ptr left_ptr(left_node); + FieldFilter::Ptr right_ptr(right_node); + if (field_filter_depth(left_node) >= kMaxFieldFilterDepth || + field_filter_depth(right_node) >= kMaxFieldFilterDepth) { + return nullptr; + } return static_cast( - FieldFilter::or_filter(FieldFilter::Ptr(left_node), - FieldFilter::Ptr(right_node)) + FieldFilter::or_filter(std::move(left_ptr), std::move(right_ptr)) .release()); } catch (...) { return nullptr; @@ -3334,16 +3294,21 @@ FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter) { using FieldFilter = storage::AlignedFieldFilter; auto* node = dynamic_cast(static_cast(filter)); - if (node == nullptr || field_filter_depth(node) >= kMaxFieldFilterDepth) { - // The input is consumed either way; see tsfile_field_filter_and(). + if (node == nullptr) { delete static_cast(filter); return nullptr; } // Takes ownership of the input on every path; see // tsfile_field_filter_and(). try { + FieldFilter::Ptr node_ptr(node); + // Negation preserves the tree height, so a tree at the maximum size + // remains valid. + if (field_filter_depth(node) > kMaxFieldFilterDepth) { + return nullptr; + } return static_cast( - FieldFilter::not_filter(FieldFilter::Ptr(node)).release()); + FieldFilter::not_filter(std::move(node_ptr)).release()); } catch (...) { return nullptr; } @@ -3384,6 +3349,9 @@ ResultSet tsfile_query_table_with_filters( // batch_size <= 0 selects row-by-row mode, matching query_table's // behavior without a FIELD filter; clamp negatives so both paths agree. const int normalized_batch_size = batch_size < 0 ? 0 : batch_size; + // Materialise the table name before taking ownership of the clone so a + // throwing string construction cannot leak it. + const std::string table(table_name); storage::Filter* field_copy = nullptr; if (field_filter != nullptr) { field_copy = clone_field_filter(field_filter, err_code); @@ -3392,9 +3360,8 @@ ResultSet tsfile_query_table_with_filters( } } *err_code = static_cast(reader)->query( - table_name, column_names, start_time, end_time, offset, - normalized_limit, result_set, - static_cast(tag_filter), field_copy, + table, column_names, start_time, end_time, offset, normalized_limit, + result_set, static_cast(tag_filter), field_copy, normalized_batch_size); if (*err_code != common::E_OK) { return nullptr; @@ -3432,6 +3399,9 @@ ResultSet tsfile_reader_query_table_by_row_with_filters( } storage::ResultSet* result_set = nullptr; const int normalized_batch_size = batch_size < 0 ? 0 : batch_size; + // Materialise the table name before taking ownership of the clone so a + // throwing string construction cannot leak it. + const std::string table(table_name); storage::Filter* field_copy = nullptr; if (field_filter != nullptr) { field_copy = clone_field_filter(field_filter, err_code); @@ -3440,7 +3410,7 @@ ResultSet tsfile_reader_query_table_by_row_with_filters( } } *err_code = static_cast(reader)->queryByRow( - table_name, columns, offset, limit, result_set, + table, columns, offset, limit, result_set, static_cast(tag_filter), field_copy, normalized_batch_size); if (*err_code != common::E_OK) { diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index 37709573b..0d85221d9 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -1422,15 +1422,19 @@ ResultSet tsfile_query_table_with_tag_filter( // FIELD_FILTER_IS_NOT_NULL for NULL checks. // // Ownership: every create/compose function returns an owning handle. Free it -// with tsfile_field_filter_free(). The and/or/not functions take ownership of -// their inputs, like the TAG filter API above: the caller must not free the -// inputs afterwards, whether or not the call succeeds. Query functions borrow -// the handle and copy it before execution, so a handle may be reused and must -// be freed by the caller. +// with tsfile_field_filter_free(). The and/or/not functions CONSUME their +// inputs on every path: non-NULL inputs are freed even when the call fails +// (wrong handle family, too-deep operand, allocation failure), and an aliased +// pair (the same handle passed twice) is rejected and freed once. This differs +// from the TAG API above, which keeps the inputs when composition fails. +// Inputs must be distinct handles and must not be reused after the call. +// Query functions borrow the handle and copy it before execution, so a handle +// may be reused and must be freed by the caller. // // Only FIELD handles are accepted by the compose functions: a handle from the -// TAG family (or any other non-FIELD filter) is rejected and consumed, and -// trees deeper than 512 levels are rejected the same way. +// TAG family (or any other non-FIELD filter) is rejected and consumed. +// Operands at or beyond 512 levels are rejected the same way (a composed tree +// may reach 512 levels; NOT preserves the input height). /** * @brief FIELD filter comparison operators. @@ -1462,10 +1466,12 @@ typedef enum { * Only the member selected by @c type is read; for FIELD_FILTER_VALUE_STRING, * @c string_value and @c string_length (the byte length of the payload, no * terminator; 0 means the empty string) are used. @c string_value is borrowed - * for the duration of the call. INT64 and DOUBLE literals must be exactly - * representable in the column's declared numeric type; the creation call - * rejects lossy values (fractional, NaN/inf or out-of-range constants on - * integral columns) with E_TYPE_NOT_MATCH instead of narrowing them. + * for the duration of the call. On integral FIELD columns (INT32, INT64, DATE, + * TIMESTAMP), INT64 and DOUBLE literals must be exactly representable in the + * column's declared type: the creation call, and every query that binds the + * handle, rejects lossy values (fractional, NaN/inf or out-of-range constants) + * with E_TYPE_NOT_MATCH instead of narrowing them. On FLOAT/DOUBLE columns the + * literal adapts to the column type. */ typedef struct { FieldFilterValueType type; diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index d1dfc8f0b..012a0557c 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -229,6 +229,59 @@ std::string normalize_column_name(const std::string& column) { return normalized; } +bool is_integral_column_type(common::TSDataType type) { + return type == common::INT32 || type == common::INT64 || + type == common::DATE || type == common::TIMESTAMP; +} + +// True when Java-style narrowing of a floating-point constant into the +// integral column type is value-preserving (no truncation, NaN/inf or +// saturation). +bool floating_fits_integral(double value, common::TSDataType column_type) { + if (!std::isfinite(value) || std::trunc(value) != value) { + return false; + } + if (column_type == common::INT32 || column_type == common::DATE) { + return value >= + static_cast(std::numeric_limits::min()) && + value <= + static_cast(std::numeric_limits::max()); + } + // INT64/TIMESTAMP: [-2^63, 2^63) are the doubles that map exactly. + constexpr double kInt64Min = -9223372036854775808.0; // -2^63 + constexpr double kInt64MaxExclusive = 9223372036854775808.0; // 2^63 + return value >= kInt64Min && value < kInt64MaxExclusive; +} + +int check_exact_literal(const AlignedFieldFilter::Literal& literal, + common::TSDataType column_type) { + if (!is_integral_column_type(column_type)) { + return common::E_OK; + } + if (literal.type == common::INT64) { + if ((column_type == common::INT32 || column_type == common::DATE) && + (literal.int64_value < + static_cast(std::numeric_limits::min()) || + literal.int64_value > + static_cast(std::numeric_limits::max()))) { + return common::E_TYPE_NOT_MATCH; + } + return common::E_OK; + } + if (literal.type == common::DOUBLE) { + return floating_fits_integral(literal.double_value, column_type) + ? common::E_OK + : common::E_TYPE_NOT_MATCH; + } + if (literal.type == common::FLOAT) { + return floating_fits_integral(static_cast(literal.float_value), + column_type) + ? common::E_OK + : common::E_TYPE_NOT_MATCH; + } + return common::E_OK; +} + } // namespace AlignedFieldFilter::Literal AlignedFieldFilter::Literal::boolean(bool value) { @@ -445,6 +498,32 @@ int AlignedFieldFilter::bind(TableSchema& schema) { return common::E_OK; } +int AlignedFieldFilter::check_exact_literals(TableSchema& schema) const { + // Iterative walk: this check runs on every query, and must not add another + // recursion level to the tree traversals. + std::vector stack{this}; + while (!stack.empty()) { + const AlignedFieldFilter* node = stack.back(); + stack.pop_back(); + if (node == nullptr) continue; + if (node->kind_ == Kind::AND || node->kind_ == Kind::OR) { + if (node->right_) stack.push_back(node->right_.get()); + if (node->left_) stack.push_back(node->left_.get()); + continue; + } + if (node->kind_ != Kind::COMPARISON) continue; + const common::ColumnSchema column = + schema.get_column_schema(node->column_); + if (!column.is_valid() || + column.column_category_ != common::ColumnCategory::FIELD) { + continue; + } + const int ret = check_exact_literal(node->literal_, column.data_type_); + if (ret != common::E_OK) return ret; + } + return common::E_OK; +} + bool AlignedFieldFilter::may_match( const std::map& statistics, int64_t row_count) const { diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index eb9db5ee7..6b3f4aa43 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -116,6 +116,14 @@ class AlignedFieldFilter : public Filter { // or all-NULL inputs. int bind(TableSchema& schema); + // Verifies that every comparison literal is exactly representable in the + // column's declared type of the given schema. Only integral columns + // (INT32, INT64, DATE, TIMESTAMP) can lose information to the Java-style + // narrowing in bind(), so only those are rejected; FLOAT and DOUBLE + // columns keep bind_literal's rounding semantics. Missing or non-FIELD + // columns are skipped: bind() reports the precise error for them. + int check_exact_literals(TableSchema& schema) const; + // Conservatively decides whether any row in a page can satisfy the filter. // Missing or unsupported statistics always return true. bool may_match(const std::map& statistics, diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 15f6982f0..51f21086c 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -70,6 +70,12 @@ int TableQueryExecutor::query(const std::string& table_name, } if (auto* aligned_filter = dynamic_cast(field_filter_guard.get())) { + // The filter may have been created against another schema; reject + // literals that the queried schema would silently narrow. + ret = aligned_filter->check_exact_literals(*table_schema); + if (ret != common::E_OK) { + return ret; + } ret = aligned_filter->is_valid() ? column_mapping->add_filter_columns( *aligned_filter, *table_schema) : common::E_INVALID_ARG; @@ -153,6 +159,12 @@ int TableQueryExecutor::query(const std::string& table_name, } if (auto* aligned_filter = dynamic_cast(field_filter_guard.get())) { + // The filter may have been created against another schema; reject + // literals that the queried schema would silently narrow. + ret = aligned_filter->check_exact_literals(*table_schema); + if (ret != common::E_OK) { + return ret; + } ret = aligned_filter->is_valid() ? column_mapping->add_filter_columns( *aligned_filter, *table_schema) : common::E_INVALID_ARG; diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index 33c3a864b..4ee91b46f 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -281,14 +281,16 @@ int TsFileReader::query(const std::string& table_name, limit = -1; } - Filter* time_filter = new TimeBetween(start_time, end_time, false); + std::unique_ptr time_filter_guard( + new TimeBetween(start_time, end_time, false)); ensure_table_query_executor(batch_size); - // Compute the lower-case name before handing the filter over: no + // Compute the lower-case name before handing the filters over: no // allocating expression may remain between release() and the call. const std::string lower_table_name = to_lower(table_name); Filter* field_filter_raw = field_filter_guard.release(); + Filter* time_filter_raw = time_filter_guard.release(); ret = table_query_executor_->query( - lower_table_name, columns_names, time_filter, tag_filter, + lower_table_name, columns_names, time_filter_raw, tag_filter, field_filter_raw, offset, limit, result_set); return ret; } diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 47cc75a56..609498a02 100644 --- a/cpp/test/cwrapper/cwrapper_extended_test.cc +++ b/cpp/test/cwrapper/cwrapper_extended_test.cc @@ -690,6 +690,20 @@ TEST(CWrapperExtendedTest, FieldFilterSelectsRowsAndComposes) { EXPECT_EQ(3, rows[1].value); free_tsfile_result_set(&paged); + // OFFSET carries across devices: skipping 5 accepted rows lands on the + // second device (a per-device reset would return 8 rows here). + ResultSet crossed = tsfile_reader_query_table_by_row_with_filters( + reader, kTableName, columns.data(), static_cast(columns.size()), 5, + -1, nullptr, int_ge_one_filter, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, crossed); + rows = collect_row_identities(crossed, &err); + ASSERT_EQ(3u, rows.size()); + for (size_t i = 0; i < rows.size(); ++i) { + EXPECT_EQ(static_cast(2 + i), rows[i].value); + } + free_tsfile_result_set(&crossed); + // OR composition through the same entry (row mode; batch-mode pushdown is // covered by the Python Arrow tests). FieldFilterValue int_eq_two_again{}; @@ -795,6 +809,64 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { &null_string, &handle)); EXPECT_EQ(nullptr, handle); + // A NULL sibling consumes the other handle; an aliased pair is rejected + // and freed once (ASan verifies both). + FieldFilterHandle null_sibling = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &int_value, &null_sibling)); + ASSERT_NE(nullptr, null_sibling); + EXPECT_EQ(nullptr, tsfile_field_filter_and(null_sibling, nullptr)); + FieldFilterHandle aliased = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &int_value, &aliased)); + ASSERT_NE(nullptr, aliased); + EXPECT_EQ(nullptr, tsfile_field_filter_or(aliased, aliased)); + + // Integral boundaries: exact edges pass, one step beyond is rejected. + FieldFilterValue int32_max{}; + int32_max.type = FIELD_FILTER_VALUE_DOUBLE; + int32_max.double_value = 2147483647.0; + EXPECT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &int32_max, &handle)); + EXPECT_NE(nullptr, handle); + tsfile_field_filter_free(handle); + handle = nullptr; + FieldFilterValue int32_over{}; + int32_over.type = FIELD_FILTER_VALUE_DOUBLE; + int32_over.double_value = 2147483648.0; + EXPECT_EQ(RET_TYPE_NOT_MATCH, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", + FIELD_FILTER_EQ, &int32_over, &handle)); + EXPECT_EQ(nullptr, handle); + // INT64 column: fractional literals are rejected, exact edges accepted. + FieldFilterValue int64_fractional{}; + int64_fractional.type = FIELD_FILTER_VALUE_DOUBLE; + int64_fractional.double_value = 2.5; + EXPECT_EQ(RET_TYPE_NOT_MATCH, + tsfile_field_filter_create_checked(reader, kTableName, "INT64", + FIELD_FILTER_EQ, + &int64_fractional, &handle)); + EXPECT_EQ(nullptr, handle); + FieldFilterValue int64_edge{}; + int64_edge.type = FIELD_FILTER_VALUE_DOUBLE; + int64_edge.double_value = -9223372036854775808.0; + EXPECT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT64", FIELD_FILTER_GTEQ, + &int64_edge, &handle)); + EXPECT_NE(nullptr, handle); + tsfile_field_filter_free(handle); + handle = nullptr; + FieldFilterValue int64_over{}; + int64_over.type = FIELD_FILTER_VALUE_DOUBLE; + int64_over.double_value = 9223372036854775808.0; + EXPECT_EQ(RET_TYPE_NOT_MATCH, tsfile_field_filter_create_checked( + reader, kTableName, "INT64", + FIELD_FILTER_EQ, &int64_over, &handle)); + EXPECT_EQ(nullptr, handle); + // Lossy literals on integral columns are rejected instead of narrowed. FieldFilterValue fractional{}; fractional.type = FIELD_FILTER_VALUE_DOUBLE; @@ -857,6 +929,71 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { static_cast(columns.size()), -1, -1, nullptr, nullptr, 0, &err)); EXPECT_EQ(RET_INVALID_ARG, err); + EXPECT_EQ(nullptr, tsfile_reader_query_table_by_row_with_filters( + reader, kTableName, columns.data(), 0, 0, -1, + nullptr, nullptr, 0, &err)); + EXPECT_EQ(RET_INVALID_ARG, err); + + tsfile_reader_close(reader); + std::remove(path.c_str()); +} + +TEST(CWrapperExtendedTest, FieldFilterDepthLimit) { + const std::string path = unique_path("cwrapper_ext_depth"); + write_table_file(path); + + ERRNO err = RET_OK; + TsFileReader reader = tsfile_reader_new(path.c_str(), &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, reader); + CStrArray columns(kTableColumns); + + FieldFilterValue zero{}; + zero.type = FIELD_FILTER_VALUE_INT64; + zero.int64_value = 0; + + auto build_chain = [&](int leaves) { + FieldFilterHandle chain = nullptr; + for (int i = 0; i < leaves; ++i) { + FieldFilterHandle leaf = nullptr; + EXPECT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", + FIELD_FILTER_GTEQ, &zero, &leaf)); + chain = + chain == nullptr ? leaf : tsfile_field_filter_and(chain, leaf); + EXPECT_NE(nullptr, chain); + } + return chain; + }; + + // A 512-level tree is accepted, queryable, and negatable. + FieldFilterHandle chain = build_chain(512); + ASSERT_NE(nullptr, chain); + ResultSet deep = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, chain, 0, &err); + ASSERT_EQ(RET_OK, err); + ASSERT_NE(nullptr, deep); + EXPECT_EQ(10, count_result_rows(deep, &err)); + free_tsfile_result_set(&deep); + FieldFilterHandle negated = tsfile_field_filter_not(chain); + ASSERT_NE(nullptr, negated); + tsfile_field_filter_free(negated); + + // One more composition exceeds the limit; both inputs are consumed. + chain = build_chain(512); + ASSERT_NE(nullptr, chain); + FieldFilterHandle extra_leaf = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_GTEQ, &zero, + &extra_leaf)); + ASSERT_NE(nullptr, extra_leaf); + EXPECT_EQ(nullptr, tsfile_field_filter_and(chain, extra_leaf)); + + // An aliased pair is rejected and freed once (ASan-verified). + chain = build_chain(1); + ASSERT_NE(nullptr, chain); + EXPECT_EQ(nullptr, tsfile_field_filter_and(chain, chain)); tsfile_reader_close(reader); std::remove(path.c_str()); diff --git a/python/tests/test_field_filter_query.py b/python/tests/test_field_filter_query.py index 1a9ccd91f..09fbc352e 100644 --- a/python/tests/test_field_filter_query.py +++ b/python/tests/test_field_filter_query.py @@ -427,6 +427,17 @@ def test_scalar_and_arrow_agree(self): assert len(scalar) == len(arrow) == 7 assert sorted(row[2] for row in scalar) == sorted(row[2] for row in arrow) + def test_or_composition(self): + with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table( + TABLE_NAME, + COLUMN_NAMES, + field_filter=field_eq("value", 0.0) | field_eq("value", 19.0), + batch_size=2, + ) as result: + rows = _arrow_rows(result) + assert sorted(row[2] for row in rows) == [0.0, 19.0] + # =========================================================================== # By-row queries @@ -530,13 +541,39 @@ def test_integral_double_is_accepted_on_integral_column(self): def test_deep_filter_tree_is_rejected(self): # A loop-built chain must not overflow the C stack in the builder or in - # the native clone()/bind() recursion. - deep = field_eq("value", 1.0) - for _ in range(600): - deep = deep & field_eq("value", 1.0) + # the native clone()/bind() recursion. 512 leaves is the exact limit. + def chain(leaves): + f = field_gteq("value", 0.0) + for _ in range(leaves - 1): + f = f & field_gteq("value", 0.0) + return f + with TsFileReader(TSFILE_PATH) as reader: + assert len(_query(reader, chain(512))) == 20 with pytest.raises(ValueError, match="maximum depth"): - reader.query_table(TABLE_NAME, COLUMN_NAMES, field_filter=deep) + _query(reader, chain(513)) + # BETWEEN expands to a native AND, one level deeper than the + # builder's count; at the boundary it must still raise ValueError. + between = field_between("value", 0.0, 100.0) + for _ in range(511): + between = between & field_gteq("value", 0.0) + with pytest.raises(ValueError, match="maximum depth"): + _query(reader, between) + + def test_int64_literal_boundaries(self): + with TsFileReader(TSFILE_PATH) as reader: + with pytest.raises(TypeMismatchError): + reader.query_table( + TABLE_NAME, COLUMN_NAMES, field_filter=field_eq("count", 2.5) + ) + with pytest.raises(TypeMismatchError): + reader.query_table( + TABLE_NAME, + COLUMN_NAMES, + field_filter=field_eq("count", float(2**63)), + ) + assert _times(reader, field_eq("count", float(-(2**63)))) == [] + assert _times(reader, field_eq("count", 50.0)) == [5.0] def test_validation_independent_of_field_filter(self): with TsFileReader(TSFILE_PATH) as reader: @@ -545,6 +582,8 @@ def test_validation_independent_of_field_filter(self): reader.query_table_by_row( TABLE_NAME, COLUMN_NAMES, offset=-1, field_filter=field_filter ) + with pytest.raises(InvalidArgumentError): + reader.query_table_by_row(TABLE_NAME, [], field_filter=field_filter) with pytest.raises(InvalidArgumentError): reader.query_table(TABLE_NAME, [], field_filter=field_filter) @@ -553,9 +592,23 @@ class TestFieldFilterCoverage: """Paths the original tests did not reach (cache bypass, NULL negation).""" def test_cache_bypass_with_tag_and_field_filter(self): - # A single-device tag filter plus batch mode would use the prepared - # series cache; the field filter must force the regular path instead. + # Warm the prepared-series cache with the same tag filter, then verify + # that adding a field filter still forces the regular path. with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table( + TABLE_NAME, + ["value"], + tag_filter=tag_eq("device", "dev_c"), + batch_size=2, + ) as result: + values = [] + while True: + batch = result.read_arrow_batch() + if batch is None: + break + values.extend(batch.column("value").to_pylist()) + assert sorted(values) == [10.0, 11.0, 12.0, 13.0, 14.0] + assert reader.prepared_query_cache_size() > 0 with reader.query_table( TABLE_NAME, ["value"], diff --git a/python/tsfile/field_filter.py b/python/tsfile/field_filter.py index 6615fc614..2cf66af75 100644 --- a/python/tsfile/field_filter.py +++ b/python/tsfile/field_filter.py @@ -26,10 +26,11 @@ Values may be ``bool``, ``int`` (64-bit range), ``float`` or ``str``. Numeric literals are compared in the column's declared numeric type; a string literal -needs a string-like FIELD column and vice versa. Literals the column type -cannot represent exactly -- a fractional, NaN/inf or out-of-range value on an -integral column -- raise ``TypeMismatchError`` instead of being silently -narrowed, so the predicate always compares the value that was written. +needs a string-like FIELD column and vice versa. On integral columns +(INT32/INT64/DATE/TIMESTAMP), literals the column type cannot represent +exactly -- a fractional, NaN/inf or out-of-range value -- raise +``TypeMismatchError`` instead of being silently narrowed. On FLOAT/DOUBLE +columns the literal is converted to the column type. """ from numbers import Integral, Real diff --git a/python/tsfile/tsfile_reader.pyx b/python/tsfile/tsfile_reader.pyx index b5bd05373..2ebe450ee 100644 --- a/python/tsfile/tsfile_reader.pyx +++ b/python/tsfile/tsfile_reader.pyx @@ -485,13 +485,15 @@ cdef class TsFileReaderPy: :param field_filter: Optional FieldFilter to filter by FIELD column values. The predicate is pushed down natively and disables the prepared-series cache for this query. + :raises InvalidArgumentError: if column_names is empty. :return: query result handler. """ cdef ResultSet result cdef TagFilterHandle c_tag_filter = NULL cdef FieldFilterHandle c_field_filter = NULL cdef ResultSetPy pyresult - if not column_names: + # len() rather than truthiness so numpy arrays / pandas Index work. + if len(column_names) == 0: raise InvalidArgumentError( context="column_names must not be empty") if (self._prepared_query_cache_size > 0 and batch_size > 0 @@ -745,6 +747,12 @@ cdef class TsFileReaderPy: self.reader, table_bytes, col_bytes, field_filter.op, field_filter.value, field_filter.value_type) elif isinstance(field_filter, BetweenFieldFilter): + # BETWEEN expands to a native AND of two comparisons, one level + # deeper than this node, so charge the extra level here. + if depth + 1 >= _MAX_FIELD_FILTER_DEPTH: + raise ValueError( + f"FIELD filter tree exceeds the maximum depth of " + f"{_MAX_FIELD_FILTER_DEPTH}") col_bytes = field_filter.column_name.encode('utf-8') try: left = _make_field_comparison( @@ -858,15 +866,19 @@ cdef class TsFileReaderPy: """ Execute table-model query by row with offset/limit. + :param offset: Number of leading accepted rows to skip (>= 0). :param tag_filter: Optional TagFilter to filter by TAG column values. :param field_filter: Optional FieldFilter to filter by FIELD column values, pushed down natively. OFFSET/LIMIT count accepted rows. + :raises InvalidArgumentError: if column_names is empty or offset is + negative. """ cdef ResultSet result cdef TagFilterHandle c_tag_filter = NULL cdef FieldFilterHandle c_field_filter = NULL pyresult = ResultSetPy(self) - if not column_names: + # len() rather than truthiness so numpy arrays / pandas Index work. + if len(column_names) == 0: raise InvalidArgumentError( context="column_names must not be empty") if offset < 0: diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 2be0d74ef..994c69e1a 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -91,9 +91,12 @@ comparison also excludes NULL cells. rejected -- use the IS NULL predicates. A `field_filter` disables the prepared-series cache for that query. - C wrapper: build handles with `tsfile_field_filter_create_checked`, - compose with `tsfile_field_filter_and` / `_or` / `_not` (each takes ownership - of its inputs, like the TAG filter API), and release the result with - `tsfile_field_filter_free`. Pass TAG and FIELD handles to + compose with `tsfile_field_filter_and` / `_or` / `_not` (each consumes its + non-NULL inputs whether or not it succeeds -- unlike the TAG API, which keeps + them on failure -- and requires distinct handles), and release the result + with `tsfile_field_filter_free`. Operands at or beyond 512 levels are + rejected and consumed; the Python builder raises `ValueError` at the same + limit. Pass TAG and FIELD handles to `tsfile_query_table_with_filters` or `tsfile_reader_query_table_by_row_with_filters`; the query copies the FIELD filter, so the caller keeps ownership of the handle. From 0903185b8e0166afbf946290ca553a1e2841b200 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Tue, 1 Dec 2026 17:36:05 +0800 Subject: [PATCH 05/10] fix(python): align FIELD filter depth with native height and tighten validation - Unwrap consecutive NOT filters iteratively with parity reduction, so the Python builder counts native tree height (negation preserves it) and a maximum-depth tree stays negatable; BETWEEN keeps its extra native level. - check_exact_literals now treats TIMESTAMP/DATE source literals like INT64/INT32 and reports E_COLUMN_NOT_EXIST / E_INVALID_ARG for missing or non-FIELD columns; the executor validates structure before literals. - TableQueryExecutor::query_on_tree adopts its time filter with RAII and returns on unsupported ordering instead of falling through with a null reader. - Accept arbitrary column-name sequences (numpy arrays, pandas Index, generators) by dropping the Cython list annotation and materialising once; free both tree-by-row arrays when one allocation fails. - Document the 512-level ValueError, query-time column validation, bool and string literal binding, string_value requirements, error-code lists and the per-function depth rules; add unit and e2e tests for exactness, wrong-family handles, depth boundaries, negation and sequence inputs. --- cpp/src/cwrapper/tsfile_cwrapper.cc | 2 - cpp/src/cwrapper/tsfile_cwrapper.h | 36 ++++--- cpp/src/reader/filter/aligned_field_filter.cc | 10 +- cpp/src/reader/filter/aligned_field_filter.h | 9 +- cpp/src/reader/table_query_executor.cc | 28 ++++-- cpp/test/cwrapper/cwrapper_extended_test.cc | 96 ++++++++++++++----- .../filter/aligned_field_filter_test.cc | 55 +++++++++++ python/tests/test_field_filter_query.py | 20 ++++ python/tsfile/field_filter.py | 18 ++-- python/tsfile/tsfile_py_cpp.pyx | 2 + python/tsfile/tsfile_reader.pyx | 30 +++++- .../tsfile/references/properties-filters.md | 9 +- 12 files changed, 241 insertions(+), 74 deletions(-) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index 3a1800086..349f74ed1 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -31,8 +31,6 @@ #include #endif -#include -#include #include #include #include diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index 0d85221d9..b52dcf8c4 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -1015,10 +1015,13 @@ ResultSet tsfile_query_table_with_filters( /** * @brief Row-limit table query with TAG and FIELD filters. * + * Both filters are optional and may be NULL. + * * @param offset [in] Number of leading accepted rows to skip (>= 0). * @param limit [in] Maximum accepted rows to return; < 0 means unlimited. * @param batch_size [in] > 0 returns TsBlock batches; <= 0 (including * negative values) selects row-by-row mode. + * @param err_code [in] Required; must not be NULL. * * Ownership matches tsfile_query_table_with_filters(). */ @@ -1432,9 +1435,10 @@ ResultSet tsfile_query_table_with_tag_filter( // may be reused and must be freed by the caller. // // Only FIELD handles are accepted by the compose functions: a handle from the -// TAG family (or any other non-FIELD filter) is rejected and consumed. -// Operands at or beyond 512 levels are rejected the same way (a composed tree -// may reach 512 levels; NOT preserves the input height). +// TAG family (or any other non-FIELD filter) is rejected and consumed. and/or +// reject an operand at 512 levels (the result would be 513 deep); NOT accepts +// a tree of 512 levels because negation preserves its height. A composed tree +// may therefore reach 512 levels. /** * @brief FIELD filter comparison operators. @@ -1464,14 +1468,18 @@ typedef enum { * @brief Comparison literal for tsfile_field_filter_create_checked(). * * Only the member selected by @c type is read; for FIELD_FILTER_VALUE_STRING, - * @c string_value and @c string_length (the byte length of the payload, no - * terminator; 0 means the empty string) are used. @c string_value is borrowed + * @c string_value (which must not be NULL; use a valid pointer with + * @c string_length 0 for the empty string) and @c string_length (the byte + * length of the payload, no terminator) are used. @c string_value is borrowed * for the duration of the call. On integral FIELD columns (INT32, INT64, DATE, - * TIMESTAMP), INT64 and DOUBLE literals must be exactly representable in the + * TIMESTAMP), INT64/DOUBLE literals must be exactly representable in the * column's declared type: the creation call, and every query that binds the * handle, rejects lossy values (fractional, NaN/inf or out-of-range constants) - * with E_TYPE_NOT_MATCH instead of narrowing them. On FLOAT/DOUBLE columns the - * literal adapts to the column type. + * with E_TYPE_NOT_MATCH instead of narrowing them. On FLOAT/DOUBLE columns an + * INT64 or DOUBLE literal is converted to the column type; a BOOL literal + * requires a BOOLEAN column and a STRING literal a string-like column. Other + * binding mismatches on a reused handle surface from the query with bind()'s + * code (for example E_NOT_SUPPORT). */ typedef struct { FieldFilterValueType type; @@ -1492,11 +1500,13 @@ typedef struct { * @param value [in] Comparison literal. Ignored and may be NULL for * FIELD_FILTER_IS_NULL / FIELD_FILTER_IS_NOT_NULL. * @param out_filter [out] Required; set to NULL on failure. - * @return E_OK on success, E_INVALID_ARG for a bad handle/name/operator or a - * non-FIELD column, E_COLUMN_NOT_EXIST for an unknown column, - * E_TYPE_NOT_MATCH when the literal type cannot bind to the column - * type or a numeric literal is not exactly representable in it, - * E_TABLE_NOT_EXIST for an unknown table. + * @return E_OK on success, E_INVALID_ARG for a bad handle/name/operator, a + * non-FIELD column, or a NULL value for a value-carrying operator, + * E_COLUMN_NOT_EXIST for an unknown column, E_TYPE_NOT_MATCH when the + * literal type cannot bind to the column type or a numeric literal is + * not exactly representable in it, E_TABLE_NOT_EXIST for an unknown + * table, E_OOM on allocation failure, and E_FILE_READ_ERR (or an + * underlying metadata-read error) when the file cannot be read. */ ERRNO tsfile_field_filter_create_checked(TsFileReader reader, const char* table_name, diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index 012a0557c..d48dff049 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -258,7 +258,7 @@ int check_exact_literal(const AlignedFieldFilter::Literal& literal, if (!is_integral_column_type(column_type)) { return common::E_OK; } - if (literal.type == common::INT64) { + if (literal.type == common::INT64 || literal.type == common::TIMESTAMP) { if ((column_type == common::INT32 || column_type == common::DATE) && (literal.int64_value < static_cast(std::numeric_limits::min()) || @@ -514,9 +514,11 @@ int AlignedFieldFilter::check_exact_literals(TableSchema& schema) const { if (node->kind_ != Kind::COMPARISON) continue; const common::ColumnSchema column = schema.get_column_schema(node->column_); - if (!column.is_valid() || - column.column_category_ != common::ColumnCategory::FIELD) { - continue; + if (!column.is_valid()) { + return common::E_COLUMN_NOT_EXIST; + } + if (column.column_category_ != common::ColumnCategory::FIELD) { + return common::E_INVALID_ARG; } const int ret = check_exact_literal(node->literal_, column.data_type_); if (ret != common::E_OK) return ret; diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 6b3f4aa43..4b75da94b 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -113,15 +113,18 @@ class AlignedFieldFilter : public Filter { // and convert numeric constants to the declared column type using Java's // Number.intValue/longValue/floatValue/doubleValue rules. Comparisons and // statistics pruning then use the same normalized constant, even on empty - // or all-NULL inputs. + // or all-NULL inputs. Table queries additionally call + // check_exact_literals() first and reject constants that this narrowing + // would alter on integral columns; bind() itself keeps the Java rules. int bind(TableSchema& schema); // Verifies that every comparison literal is exactly representable in the // column's declared type of the given schema. Only integral columns // (INT32, INT64, DATE, TIMESTAMP) can lose information to the Java-style // narrowing in bind(), so only those are rejected; FLOAT and DOUBLE - // columns keep bind_literal's rounding semantics. Missing or non-FIELD - // columns are skipped: bind() reports the precise error for them. + // columns keep bind_literal's rounding semantics. Missing columns return + // E_COLUMN_NOT_EXIST and non-FIELD columns E_INVALID_ARG, matching what + // bind() reports for them. int check_exact_literals(TableSchema& schema) const; // Conservatively decides whether any row in a page can satisfy the filter. diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 51f21086c..65a2bae5c 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -70,15 +70,17 @@ int TableQueryExecutor::query(const std::string& table_name, } if (auto* aligned_filter = dynamic_cast(field_filter_guard.get())) { + if (!aligned_filter->is_valid()) { + return common::E_INVALID_ARG; + } // The filter may have been created against another schema; reject // literals that the queried schema would silently narrow. ret = aligned_filter->check_exact_literals(*table_schema); if (ret != common::E_OK) { return ret; } - ret = aligned_filter->is_valid() ? column_mapping->add_filter_columns( - *aligned_filter, *table_schema) - : common::E_INVALID_ARG; + ret = + column_mapping->add_filter_columns(*aligned_filter, *table_schema); if (ret != common::E_OK) { return ret; } @@ -159,15 +161,17 @@ int TableQueryExecutor::query(const std::string& table_name, } if (auto* aligned_filter = dynamic_cast(field_filter_guard.get())) { + if (!aligned_filter->is_valid()) { + return common::E_INVALID_ARG; + } // The filter may have been created against another schema; reject // literals that the queried schema would silently narrow. ret = aligned_filter->check_exact_literals(*table_schema); if (ret != common::E_OK) { return ret; } - ret = aligned_filter->is_valid() ? column_mapping->add_filter_columns( - *aligned_filter, *table_schema) - : common::E_INVALID_ARG; + ret = + column_mapping->add_filter_columns(*aligned_filter, *table_schema); if (ret != common::E_OK) { return ret; } @@ -208,13 +212,15 @@ int TableQueryExecutor::query_on_tree( const std::vector& tag_columns, const std::vector& field_columns, Filter* time_filter, ResultSet*& ret_qds) { + // Adopt the time filter immediately so every error return and any + // exception frees it unless it is handed to the block reader below. + std::unique_ptr time_filter_guard(time_filter); common::PageArena pa; pa.init(512, common::MOD_TSFILE_READER); int ret = common::E_OK; ret_qds = nullptr; TsFileMeta* file_meta = nullptr; if (RET_FAIL(tsfile_io_reader_->get_tsfile_meta(file_meta))) { - delete time_filter; return ret; } std::unordered_set table_inodes; @@ -222,7 +228,6 @@ int TableQueryExecutor::query_on_tree( MetaIndexNode* table_inode = nullptr; if (RET_FAIL(file_meta->get_table_metaindex_node( device->get_table_name(), table_inode))) { - delete time_filter; return ret; } table_inodes.insert(table_inode); @@ -304,11 +309,14 @@ int TableQueryExecutor::query_on_tree( tsblock_reader = std::unique_ptr( new DeviceOrderedTsBlockReader( std::move(device_task_iterator), meta_data_querier_, - block_size_, tsfile_io_reader_, time_filter, nullptr)); + block_size_, tsfile_io_reader_, time_filter_guard.get(), + nullptr)); + // Ownership moves to the reader only after it is constructed. + time_filter_guard.release(); break; case TableQueryOrdering::TIME: default: - ret = common::E_UNSUPPORTED_ORDER; + return common::E_UNSUPPORTED_ORDER; } assert(tsblock_reader != nullptr); ret_qds = new TableResultSet(std::move(tsblock_reader), diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 609498a02..8639c6eef 100644 --- a/cpp/test/cwrapper/cwrapper_extended_test.cc +++ b/cpp/test/cwrapper/cwrapper_extended_test.cc @@ -691,7 +691,8 @@ TEST(CWrapperExtendedTest, FieldFilterSelectsRowsAndComposes) { free_tsfile_result_set(&paged); // OFFSET carries across devices: skipping 5 accepted rows lands on the - // second device (a per-device reset would return 8 rows here). + // second device. A per-device reset would return 0 rows here, and + // ignoring OFFSET entirely would return all 8. ResultSet crossed = tsfile_reader_query_table_by_row_with_filters( reader, kTableName, columns.data(), static_cast(columns.size()), 5, -1, nullptr, int_ge_one_filter, 0, &err); @@ -824,6 +825,25 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { ASSERT_NE(nullptr, aliased); EXPECT_EQ(nullptr, tsfile_field_filter_or(aliased, aliased)); + // A handle from the TAG family is rejected and consumed. + TagFilterHandle tag_a = + tsfile_tag_filter_eq(reader, kTableName, "TAG", "devA"); + ASSERT_NE(nullptr, tag_a); + FieldFilterHandle field_for_family = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &int_value, &field_for_family)); + ASSERT_NE(nullptr, field_for_family); + EXPECT_EQ(nullptr, tsfile_field_filter_and(tag_a, field_for_family)); + TagFilterHandle tag_b = + tsfile_tag_filter_eq(reader, kTableName, "TAG", "devB"); + ASSERT_NE(nullptr, tag_b); + EXPECT_EQ(nullptr, tsfile_field_filter_not(tag_b)); + TagFilterHandle tag_c = + tsfile_tag_filter_eq(reader, kTableName, "TAG", "devA"); + ASSERT_NE(nullptr, tag_c); + tsfile_field_filter_free(tag_c); // safe through the virtual destructor + // Integral boundaries: exact edges pass, one step beyond is rejected. FieldFilterValue int32_max{}; int32_max.type = FIELD_FILTER_VALUE_DOUBLE; @@ -948,9 +968,9 @@ TEST(CWrapperExtendedTest, FieldFilterDepthLimit) { ASSERT_NE(nullptr, reader); CStrArray columns(kTableColumns); - FieldFilterValue zero{}; - zero.type = FIELD_FILTER_VALUE_INT64; - zero.int64_value = 0; + FieldFilterValue threshold{}; + threshold.type = FIELD_FILTER_VALUE_INT64; + threshold.int64_value = 3; // selects rows 3 and 4 of each device auto build_chain = [&](int leaves) { FieldFilterHandle chain = nullptr; @@ -958,7 +978,7 @@ TEST(CWrapperExtendedTest, FieldFilterDepthLimit) { FieldFilterHandle leaf = nullptr; EXPECT_EQ(RET_OK, tsfile_field_filter_create_checked( reader, kTableName, "INT32", - FIELD_FILTER_GTEQ, &zero, &leaf)); + FIELD_FILTER_GTEQ, &threshold, &leaf)); chain = chain == nullptr ? leaf : tsfile_field_filter_and(chain, leaf); EXPECT_NE(nullptr, chain); @@ -966,34 +986,58 @@ TEST(CWrapperExtendedTest, FieldFilterDepthLimit) { return chain; }; - // A 512-level tree is accepted, queryable, and negatable. + // A 512-level tree is accepted and queryable; the selective predicate + // makes the row count depend on the filter actually being evaluated. FieldFilterHandle chain = build_chain(512); - ASSERT_NE(nullptr, chain); - ResultSet deep = tsfile_query_table_with_filters( - reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, - nullptr, chain, 0, &err); - ASSERT_EQ(RET_OK, err); - ASSERT_NE(nullptr, deep); - EXPECT_EQ(10, count_result_rows(deep, &err)); - free_tsfile_result_set(&deep); - FieldFilterHandle negated = tsfile_field_filter_not(chain); - ASSERT_NE(nullptr, negated); - tsfile_field_filter_free(negated); + EXPECT_NE(nullptr, chain); + if (chain != nullptr) { + ResultSet deep = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, -1, + nullptr, chain, 0, &err); + EXPECT_EQ(RET_OK, err); + if (deep != nullptr) { + EXPECT_EQ(4, count_result_rows(deep, &err)); + free_tsfile_result_set(&deep); + } + + // Negation preserves height, so a 512-level tree stays negatable and + // the negated tree is still evaluated. + FieldFilterHandle negated = tsfile_field_filter_not(chain); + EXPECT_NE(nullptr, negated); + if (negated != nullptr) { + ResultSet inverted = tsfile_query_table_with_filters( + reader, kTableName, columns.data(), columns.size(), 0, 100, 0, + -1, nullptr, negated, 0, &err); + EXPECT_EQ(RET_OK, err); + if (inverted != nullptr) { + EXPECT_EQ(6, count_result_rows(inverted, &err)); + free_tsfile_result_set(&inverted); + } + tsfile_field_filter_free(negated); + } + } // One more composition exceeds the limit; both inputs are consumed. chain = build_chain(512); - ASSERT_NE(nullptr, chain); - FieldFilterHandle extra_leaf = nullptr; - ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( - reader, kTableName, "INT32", FIELD_FILTER_GTEQ, &zero, - &extra_leaf)); - ASSERT_NE(nullptr, extra_leaf); - EXPECT_EQ(nullptr, tsfile_field_filter_and(chain, extra_leaf)); + EXPECT_NE(nullptr, chain); + if (chain != nullptr) { + FieldFilterHandle extra_leaf = nullptr; + EXPECT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_GTEQ, + &threshold, &extra_leaf)); + if (extra_leaf != nullptr) { + EXPECT_EQ(nullptr, tsfile_field_filter_and(chain, extra_leaf)); + } else { + tsfile_field_filter_free(chain); + } + } // An aliased pair is rejected and freed once (ASan-verified). chain = build_chain(1); - ASSERT_NE(nullptr, chain); - EXPECT_EQ(nullptr, tsfile_field_filter_and(chain, chain)); + EXPECT_NE(nullptr, chain); + if (chain != nullptr) { + EXPECT_EQ(nullptr, tsfile_field_filter_and(chain, chain)); + } tsfile_reader_close(reader); std::remove(path.c_str()); diff --git a/cpp/test/reader/filter/aligned_field_filter_test.cc b/cpp/test/reader/filter/aligned_field_filter_test.cc index cb5a20040..460e6e4b5 100644 --- a/cpp/test/reader/filter/aligned_field_filter_test.cc +++ b/cpp/test/reader/filter/aligned_field_filter_test.cc @@ -473,5 +473,60 @@ TEST(AlignedFieldFilterTest, NegatedFloatingStatisticsPreserveSafeShortcuts) { } } +TEST(AlignedFieldFilterTest, ExactLiteralsAreValidatedAgainstSchema) { + using namespace common; + using A = AlignedFieldFilter; + TableSchema schema( + "t", {{"i", INT32, UNCOMPRESSED, PLAIN, ColumnCategory::FIELD}, + {"l", INT64, UNCOMPRESSED, PLAIN, ColumnCategory::FIELD}, + {"tag", STRING, UNCOMPRESSED, PLAIN, ColumnCategory::TAG}}); + + // Lossy constants are rejected on integral columns. + EXPECT_EQ(A::compare("i", A::CompareOp::EQ, A::Literal::float64(1.5)) + ->check_exact_literals(schema), + E_TYPE_NOT_MATCH); + EXPECT_EQ(A::compare("i", A::CompareOp::EQ, A::Literal::int64(1LL << 40)) + ->check_exact_literals(schema), + E_TYPE_NOT_MATCH); + // A TIMESTAMP-typed source literal is a 64-bit constant as well. + A::Literal timestamp_literal; + timestamp_literal.type = TIMESTAMP; + timestamp_literal.int64_value = 1LL << 40; + EXPECT_EQ(A::compare("i", A::CompareOp::EQ, timestamp_literal) + ->check_exact_literals(schema), + E_TYPE_NOT_MATCH); + + // Exactly representable constants pass, including the boundaries and + // widening across integral columns. + EXPECT_EQ(A::compare("i", A::CompareOp::EQ, A::Literal::float64(2.0)) + ->check_exact_literals(schema), + E_OK); + EXPECT_EQ( + A::compare("i", A::CompareOp::EQ, A::Literal::float64(2147483647.0)) + ->check_exact_literals(schema), + E_OK); + EXPECT_EQ(A::compare("l", A::CompareOp::EQ, + A::Literal::float64(-9223372036854775808.0)) + ->check_exact_literals(schema), + E_OK); + EXPECT_EQ(A::compare("i", A::CompareOp::EQ, A::Literal::int64(5)) + ->check_exact_literals(schema), + E_OK); + + // Missing and non-FIELD columns report the same codes as bind(). + EXPECT_EQ(A::compare("missing", A::CompareOp::EQ, A::Literal::int64(1)) + ->check_exact_literals(schema), + E_COLUMN_NOT_EXIST); + EXPECT_EQ(A::compare("tag", A::CompareOp::EQ, A::Literal::string("x")) + ->check_exact_literals(schema), + E_INVALID_ARG); + + // Composite trees validate every comparison leaf. + auto tree = A::and_filter( + A::compare("i", A::CompareOp::GE, A::Literal::float64(1.0)), + A::compare("l", A::CompareOp::LT, A::Literal::float64(2.5))); + EXPECT_EQ(tree->check_exact_literals(schema), E_TYPE_NOT_MATCH); +} + } // namespace } // namespace storage diff --git a/python/tests/test_field_filter_query.py b/python/tests/test_field_filter_query.py index 09fbc352e..1cd4daa24 100644 --- a/python/tests/test_field_filter_query.py +++ b/python/tests/test_field_filter_query.py @@ -550,6 +550,10 @@ def chain(leaves): with TsFileReader(TSFILE_PATH) as reader: assert len(_query(reader, chain(512))) == 20 + # NOT preserves the native height, so a maximum-depth tree is + # still negatable (and an even number of NOTs cancels out). + assert _query(reader, ~chain(512)) == [] + assert len(_query(reader, ~~chain(512))) == 20 with pytest.raises(ValueError, match="maximum depth"): _query(reader, chain(513)) # BETWEEN expands to a native AND, one level deeper than the @@ -609,6 +613,12 @@ def test_cache_bypass_with_tag_and_field_filter(self): values.extend(batch.column("value").to_pylist()) assert sorted(values) == [10.0, 11.0, 12.0, 13.0, 14.0] assert reader.prepared_query_cache_size() > 0 + # Prove the prepared form really exists for this fixture: a + # negative cache entry would also bump the size counter. + prepared = reader.prepare_table_series( + TABLE_NAME, "value", tag_eq("device", "dev_c") + ) + prepared.close() with reader.query_table( TABLE_NAME, ["value"], @@ -635,3 +645,13 @@ def test_negation_never_matches_null(self): rows = _query(reader, ~field_is_null("sparse")) assert len(rows) == 10 assert all(row[6] is not None for row in rows) + + def test_column_names_accept_sequences(self): + np = pytest.importorskip("numpy") + with TsFileReader(TSFILE_PATH) as reader: + for columns in (np.array(["value"]), (c for c in ["value"])): + with reader.query_table(TABLE_NAME, columns) as result: + rows = 0 + while result.next(): + rows += 1 + assert rows == 20 diff --git a/python/tsfile/field_filter.py b/python/tsfile/field_filter.py index 2cf66af75..c572303b8 100644 --- a/python/tsfile/field_filter.py +++ b/python/tsfile/field_filter.py @@ -24,13 +24,17 @@ query executor. Comparison filters never match NULL cells -- use :func:`field_is_null` / :func:`field_is_not_null` for NULL checks. -Values may be ``bool``, ``int`` (64-bit range), ``float`` or ``str``. Numeric -literals are compared in the column's declared numeric type; a string literal -needs a string-like FIELD column and vice versa. On integral columns -(INT32/INT64/DATE/TIMESTAMP), literals the column type cannot represent -exactly -- a fractional, NaN/inf or out-of-range value -- raise -``TypeMismatchError`` instead of being silently narrowed. On FLOAT/DOUBLE -columns the literal is converted to the column type. +Values may be ``bool``, ``int`` (64-bit range), ``float`` or ``str``. A bool +literal binds only to a BOOLEAN column; a string literal needs a string-like +FIELD column. INT64 and DOUBLE literals are compared in the column's declared +numeric type: on integral columns (INT32/INT64/DATE/TIMESTAMP), literals the +column type cannot represent exactly -- a fractional, NaN/inf or out-of-range +value -- raise ``TypeMismatchError`` instead of being silently narrowed; on +FLOAT/DOUBLE columns the literal is converted to the column type. Column-aware +validation (types and exactness) happens when the filter is used in +``query_table`` / ``query_table_by_row``, not when the filter object is built. +Filter trees may be at most 512 levels deep; deeper trees raise ``ValueError`` +at query time. """ from numbers import Integral, Real diff --git a/python/tsfile/tsfile_py_cpp.pyx b/python/tsfile/tsfile_py_cpp.pyx index 1155c9626..841bc3215 100644 --- a/python/tsfile/tsfile_py_cpp.pyx +++ b/python/tsfile/tsfile_py_cpp.pyx @@ -1216,6 +1216,8 @@ cdef ResultSet tsfile_reader_query_tree_by_row_c(TsFileReader reader, cdef ErrorCode code = 0 if device_ids_c == NULL or measurement_names_c == NULL: + free(device_ids_c) + free(measurement_names_c) raise MemoryError("Failed to allocate memory for tree by-row query arrays") memset(device_ids_c, 0, sizeof(char *) * device_num) memset(measurement_names_c, 0, sizeof(char *) * measurement_num) diff --git a/python/tsfile/tsfile_reader.pyx b/python/tsfile/tsfile_reader.pyx index 2ebe450ee..8acf46f21 100644 --- a/python/tsfile/tsfile_reader.pyx +++ b/python/tsfile/tsfile_reader.pyx @@ -464,7 +464,7 @@ cdef class TsFileReaderPy: source, &error_code) check_error(error_code) - def query_table(self, table_name : str, column_names : List[str], + def query_table(self, table_name : str, column_names, start_time : int = INT64_MIN, end_time : int = INT64_MAX, tag_filter = None, batch_size : int = 0, field_filter = None) -> ResultSetPy: @@ -486,13 +486,16 @@ cdef class TsFileReaderPy: values. The predicate is pushed down natively and disables the prepared-series cache for this query. :raises InvalidArgumentError: if column_names is empty. + :raises ValueError: if field_filter exceeds the 512-level limit. :return: query result handler. """ cdef ResultSet result cdef TagFilterHandle c_tag_filter = NULL cdef FieldFilterHandle c_field_filter = NULL cdef ResultSetPy pyresult - # len() rather than truthiness so numpy arrays / pandas Index work. + # len() rather than truthiness so numpy arrays / pandas Index work; + # materialise once so unsized iterables (generators) keep working. + column_names = list(column_names) if len(column_names) == 0: raise InvalidArgumentError( context="column_names must not be empty") @@ -732,6 +735,8 @@ cdef class TsFileReaderPy: cdef FieldFilterHandle right = NULL cdef FieldFilterHandle inner = NULL cdef FieldFilterHandle out = NULL + cdef object inner_filter = None + cdef int inverted = 0 cdef bytes table_bytes cdef bytes col_bytes @@ -813,9 +818,21 @@ cdef class TsFileReaderPy: tsfile_field_filter_free(left) tsfile_field_filter_free(right) elif isinstance(field_filter, NotFieldFilter): + # Native negation is pushed into the leaves and preserves the tree + # height, so unwrap consecutive NOTs iteratively: no builder + # recursion, no depth charge, and an even count cancels out. + inverted = 0 + inner_filter = field_filter + while isinstance(inner_filter, NotFieldFilter): + inverted ^= 1 + inner_filter = inner_filter.filter try: inner = self._build_c_field_filter( - table_name, field_filter.filter, depth + 1) + table_name, inner_filter, depth) + if not inverted: + out = inner + inner = NULL + return out out = tsfile_field_filter_not(inner) inner = NULL if out == NULL: @@ -858,7 +875,7 @@ cdef class TsFileReaderPy: self.activate_result_set_list.add(pyresult) return pyresult - def query_table_by_row(self, table_name : str, column_names : List[str], + def query_table_by_row(self, table_name : str, column_names, offset : int = 0, limit : int = -1, tag_filter = None, batch_size : int = 0, field_filter = None @@ -872,12 +889,15 @@ cdef class TsFileReaderPy: values, pushed down natively. OFFSET/LIMIT count accepted rows. :raises InvalidArgumentError: if column_names is empty or offset is negative. + :raises ValueError: if field_filter exceeds the 512-level limit. """ cdef ResultSet result cdef TagFilterHandle c_tag_filter = NULL cdef FieldFilterHandle c_field_filter = NULL pyresult = ResultSetPy(self) - # len() rather than truthiness so numpy arrays / pandas Index work. + # len() rather than truthiness so numpy arrays / pandas Index work; + # materialise once so unsized iterables (generators) keep working. + column_names = list(column_names) if len(column_names) == 0: raise InvalidArgumentError( context="column_names must not be empty") diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 994c69e1a..d73d3c257 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -94,10 +94,11 @@ comparison also excludes NULL cells. compose with `tsfile_field_filter_and` / `_or` / `_not` (each consumes its non-NULL inputs whether or not it succeeds -- unlike the TAG API, which keeps them on failure -- and requires distinct handles), and release the result - with `tsfile_field_filter_free`. Operands at or beyond 512 levels are - rejected and consumed; the Python builder raises `ValueError` at the same - limit. Pass TAG and FIELD handles to - `tsfile_query_table_with_filters` or + with `tsfile_field_filter_free`. `and`/`or` reject an operand at 512 levels + (the result would be 513 deep); `not` accepts a 512-level tree because + negation preserves its height. The Python builder applies the same height + limit and raises `ValueError` for deeper trees. Pass TAG and FIELD handles + to `tsfile_query_table_with_filters` or `tsfile_reader_query_table_by_row_with_filters`; the query copies the FIELD filter, so the caller keeps ownership of the handle. - C++: build `storage::AlignedFieldFilter` trees with `compare`, `is_null`, From 0acbb361f64256a863db75d5e5495d9c827ece2b Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Tue, 1 Dec 2026 18:02:58 +0800 Subject: [PATCH 06/10] fix(python): enforce filter height at the C++ boundary and polish docs/tests - Add AlignedFieldFilter::height() and reject caller-built FIELD trees taller than 512 in TableQueryExecutor::query, so the C++ API cannot overflow the recursive clone()/bind() traversals. - Guard the NOT unwrap against cyclic filter objects by tracking visited nodes and raising ValueError instead of looping forever. - Accept arbitrary column-name sequences in query_table_on_tree, query_tree_by_row and query_timeseries as well (materialise once). - Keep the tree-model time filter guarded until the executor adopts it. - Correct the NULL wording for NOT(IS NOT NULL), the TAG-filter lifetime note, err_code direction, the Python height wording and the check_exact_literals comment scope. - Strengthen tests: selective depth predicate and BETWEEN acceptance boundary, captured composition results, or/family and right-operand depth cases, TIMESTAMP/FLOAT literal acceptance, by-row sequence inputs. --- cpp/src/cwrapper/tsfile_cwrapper.cc | 5 +- cpp/src/cwrapper/tsfile_cwrapper.h | 5 +- cpp/src/reader/filter/aligned_field_filter.cc | 23 ++++++++ cpp/src/reader/filter/aligned_field_filter.h | 12 +++- cpp/src/reader/table_query_executor.cc | 16 ++++++ cpp/src/reader/tsfile_reader.cc | 6 +- cpp/test/cwrapper/cwrapper_extended_test.cc | 56 +++++++++++++++++-- .../filter/aligned_field_filter_test.cc | 28 ++++++++++ python/tests/test_field_filter_query.py | 38 ++++++++----- python/tsfile/field_filter.py | 11 +++- python/tsfile/tsfile_reader.pyx | 20 +++++-- .../tsfile/references/properties-filters.md | 4 +- 12 files changed, 187 insertions(+), 37 deletions(-) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index 349f74ed1..c282815fe 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -3173,8 +3173,9 @@ ERRNO tsfile_field_filter_create_checked(TsFileReader reader, } // Reject numeric literals that Java-style narrowing would alter on the // creating table; the query re-checks them against the queried schema. - // Missing or non-FIELD columns are skipped here so bind() below can - // report the precise error. + // Missing and non-FIELD columns are rejected here with the same codes + // bind() would return; the probe bind below additionally validates the + // literal type. ret = filter->check_exact_literals(*schema); if (ret != common::E_OK) { return ret; diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index b52dcf8c4..206f8346b 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -1021,7 +1021,7 @@ ResultSet tsfile_query_table_with_filters( * @param limit [in] Maximum accepted rows to return; < 0 means unlimited. * @param batch_size [in] > 0 returns TsBlock batches; <= 0 (including * negative values) selects row-by-row mode. - * @param err_code [in] Required; must not be NULL. + * @param err_code [out] Required; must not be NULL. * * Ownership matches tsfile_query_table_with_filters(). */ @@ -1540,7 +1540,8 @@ FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, * * Takes ownership of the input; the caller must not free it afterwards. * Returns a new filter that owns it directly. Returns NULL on failure (the - * input is consumed either way). NULL rows never satisfy a negated predicate. + * input is consumed either way). A negated comparison never matches NULL + * rows; NOT(IS NOT NULL) becomes IS NULL and does match them. */ FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter); diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index d48dff049..cbbaefabe 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -526,6 +526,29 @@ int AlignedFieldFilter::check_exact_literals(TableSchema& schema) const { return common::E_OK; } +int AlignedFieldFilter::height() const { + struct Entry { + const AlignedFieldFilter* node; + int height; + }; + std::vector stack; + stack.push_back(Entry{this, 1}); + int max_height = 0; + while (!stack.empty()) { + Entry entry = stack.back(); + stack.pop_back(); + if (entry.node == nullptr) continue; + if (entry.height > max_height) max_height = entry.height; + if (entry.node->right_ != nullptr) { + stack.push_back(Entry{entry.node->right_.get(), entry.height + 1}); + } + if (entry.node->left_ != nullptr) { + stack.push_back(Entry{entry.node->left_.get(), entry.height + 1}); + } + } + return max_height; +} + bool AlignedFieldFilter::may_match( const std::map& statistics, int64_t row_count) const { diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 4b75da94b..20effd5d5 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -122,11 +122,17 @@ class AlignedFieldFilter : public Filter { // column's declared type of the given schema. Only integral columns // (INT32, INT64, DATE, TIMESTAMP) can lose information to the Java-style // narrowing in bind(), so only those are rejected; FLOAT and DOUBLE - // columns keep bind_literal's rounding semantics. Missing columns return - // E_COLUMN_NOT_EXIST and non-FIELD columns E_INVALID_ARG, matching what - // bind() reports for them. + // columns keep bind_literal's rounding semantics. For comparison nodes, + // missing columns return E_COLUMN_NOT_EXIST and non-FIELD columns + // E_INVALID_ARG, matching bind(); IS NULL / IS NOT NULL nodes carry no + // literal here and are validated by bind(). int check_exact_literals(TableSchema& schema) const; + // Tree height (a leaf is 1), computed iteratively. Query paths use this + // to reject caller-built trees deep enough to overflow the recursive + // clone()/bind()/is_valid()/may_match()/all_match() traversals. + int height() const; + // Conservatively decides whether any row in a page can satisfy the filter. // Missing or unsupported statistics always return true. bool may_match(const std::map& statistics, diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 65a2bae5c..356c7f652 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -22,6 +22,12 @@ #include "utils/db_utils.h" namespace storage { + +// FIELD filter trees deeper than this are rejected by every entry point +// (C wrapper, Cython builder and this executor): the recursive clone()/bind()/ +// is_valid() traversals would otherwise overflow the stack. +constexpr int kMaxFieldFilterHeight = 512; + int TableQueryExecutor::query(const std::string& table_name, const std::vector& columns, Filter* time_filter, Filter* tag_filter, @@ -70,6 +76,11 @@ int TableQueryExecutor::query(const std::string& table_name, } if (auto* aligned_filter = dynamic_cast(field_filter_guard.get())) { + // Matches the C wrapper limit: deeper caller-built trees would + // overflow the recursive clone()/bind()/is_valid() traversals. + if (aligned_filter->height() > kMaxFieldFilterHeight) { + return common::E_INVALID_ARG; + } if (!aligned_filter->is_valid()) { return common::E_INVALID_ARG; } @@ -161,6 +172,11 @@ int TableQueryExecutor::query(const std::string& table_name, } if (auto* aligned_filter = dynamic_cast(field_filter_guard.get())) { + // Matches the C wrapper limit: deeper caller-built trees would + // overflow the recursive clone()/bind()/is_valid() traversals. + if (aligned_filter->height() > kMaxFieldFilterHeight) { + return common::E_INVALID_ARG; + } if (!aligned_filter->is_valid()) { return common::E_INVALID_ARG; } diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index 4ee91b46f..fb56f1c9f 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -593,8 +593,12 @@ int TsFileReader::query_table_on_tree( for (int i = 0; i < device_max_len; i++) { columns_names[i] = "col_" + std::to_string(i); } - Filter* time_filter = new TimeBetween(star_time, end_time, false); ensure_table_query_executor(-1); + // The executor adopts the time filter on entry; keep it guarded until the + // call so no allocation above can leak it. + std::unique_ptr time_filter_guard( + new TimeBetween(star_time, end_time, false)); + Filter* time_filter = time_filter_guard.release(); ret = table_query_executor_->query_on_tree( satisfied_device_ids, columns_names, measurement_names_to_query, time_filter, result_set); diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 8639c6eef..6978bb912 100644 --- a/cpp/test/cwrapper/cwrapper_extended_test.cc +++ b/cpp/test/cwrapper/cwrapper_extended_test.cc @@ -817,13 +817,18 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { reader, kTableName, "INT32", FIELD_FILTER_EQ, &int_value, &null_sibling)); ASSERT_NE(nullptr, null_sibling); - EXPECT_EQ(nullptr, tsfile_field_filter_and(null_sibling, nullptr)); + FieldFilterHandle null_result = + tsfile_field_filter_and(null_sibling, nullptr); + EXPECT_EQ(nullptr, null_result); + tsfile_field_filter_free(null_result); FieldFilterHandle aliased = nullptr; ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( reader, kTableName, "INT32", FIELD_FILTER_EQ, &int_value, &aliased)); ASSERT_NE(nullptr, aliased); - EXPECT_EQ(nullptr, tsfile_field_filter_or(aliased, aliased)); + FieldFilterHandle alias_result = tsfile_field_filter_or(aliased, aliased); + EXPECT_EQ(nullptr, alias_result); + tsfile_field_filter_free(alias_result); // A handle from the TAG family is rejected and consumed. TagFilterHandle tag_a = @@ -834,11 +839,27 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { reader, kTableName, "INT32", FIELD_FILTER_EQ, &int_value, &field_for_family)); ASSERT_NE(nullptr, field_for_family); - EXPECT_EQ(nullptr, tsfile_field_filter_and(tag_a, field_for_family)); + FieldFilterHandle wrong_family = + tsfile_field_filter_and(tag_a, field_for_family); + EXPECT_EQ(nullptr, wrong_family); + tsfile_field_filter_free(wrong_family); TagFilterHandle tag_b = tsfile_tag_filter_eq(reader, kTableName, "TAG", "devB"); ASSERT_NE(nullptr, tag_b); - EXPECT_EQ(nullptr, tsfile_field_filter_not(tag_b)); + FieldFilterHandle wrong_not = tsfile_field_filter_not(tag_b); + EXPECT_EQ(nullptr, wrong_not); + tsfile_field_filter_free(wrong_not); + TagFilterHandle tag_d = + tsfile_tag_filter_eq(reader, kTableName, "TAG", "devA"); + ASSERT_NE(nullptr, tag_d); + FieldFilterHandle field_for_or = nullptr; + ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_EQ, + &int_value, &field_for_or)); + ASSERT_NE(nullptr, field_for_or); + FieldFilterHandle wrong_or = tsfile_field_filter_or(tag_d, field_for_or); + EXPECT_EQ(nullptr, wrong_or); + tsfile_field_filter_free(wrong_or); TagFilterHandle tag_c = tsfile_tag_filter_eq(reader, kTableName, "TAG", "devA"); ASSERT_NE(nullptr, tag_c); @@ -1026,7 +1047,28 @@ TEST(CWrapperExtendedTest, FieldFilterDepthLimit) { reader, kTableName, "INT32", FIELD_FILTER_GTEQ, &threshold, &extra_leaf)); if (extra_leaf != nullptr) { - EXPECT_EQ(nullptr, tsfile_field_filter_and(chain, extra_leaf)); + FieldFilterHandle over_limit = + tsfile_field_filter_and(chain, extra_leaf); + EXPECT_EQ(nullptr, over_limit); + tsfile_field_filter_free(over_limit); + } else { + tsfile_field_filter_free(chain); + } + } + + // The right operand of a composition is depth-checked as well. + chain = build_chain(512); + EXPECT_NE(nullptr, chain); + if (chain != nullptr) { + FieldFilterHandle left_leaf = nullptr; + EXPECT_EQ(RET_OK, tsfile_field_filter_create_checked( + reader, kTableName, "INT32", FIELD_FILTER_GTEQ, + &threshold, &left_leaf)); + if (left_leaf != nullptr) { + FieldFilterHandle right_deep = + tsfile_field_filter_or(left_leaf, chain); + EXPECT_EQ(nullptr, right_deep); + tsfile_field_filter_free(right_deep); } else { tsfile_field_filter_free(chain); } @@ -1036,7 +1078,9 @@ TEST(CWrapperExtendedTest, FieldFilterDepthLimit) { chain = build_chain(1); EXPECT_NE(nullptr, chain); if (chain != nullptr) { - EXPECT_EQ(nullptr, tsfile_field_filter_and(chain, chain)); + FieldFilterHandle alias_result = tsfile_field_filter_and(chain, chain); + EXPECT_EQ(nullptr, alias_result); + tsfile_field_filter_free(alias_result); } tsfile_reader_close(reader); diff --git a/cpp/test/reader/filter/aligned_field_filter_test.cc b/cpp/test/reader/filter/aligned_field_filter_test.cc index 460e6e4b5..db35a6dbc 100644 --- a/cpp/test/reader/filter/aligned_field_filter_test.cc +++ b/cpp/test/reader/filter/aligned_field_filter_test.cc @@ -495,6 +495,18 @@ TEST(AlignedFieldFilterTest, ExactLiteralsAreValidatedAgainstSchema) { EXPECT_EQ(A::compare("i", A::CompareOp::EQ, timestamp_literal) ->check_exact_literals(schema), E_TYPE_NOT_MATCH); + // In range, the same literal type is accepted. + timestamp_literal.int64_value = 5; + EXPECT_EQ(A::compare("i", A::CompareOp::EQ, timestamp_literal) + ->check_exact_literals(schema), + E_OK); + // FLOAT-typed source literals follow the same integral rules. + EXPECT_EQ(A::compare("i", A::CompareOp::EQ, A::Literal::float32(1.5F)) + ->check_exact_literals(schema), + E_TYPE_NOT_MATCH); + EXPECT_EQ(A::compare("i", A::CompareOp::EQ, A::Literal::float32(2.0F)) + ->check_exact_literals(schema), + E_OK); // Exactly representable constants pass, including the boundaries and // widening across integral columns. @@ -528,5 +540,21 @@ TEST(AlignedFieldFilterTest, ExactLiteralsAreValidatedAgainstSchema) { EXPECT_EQ(tree->check_exact_literals(schema), E_TYPE_NOT_MATCH); } +TEST(AlignedFieldFilterTest, HeightCountsTreeLevels) { + using namespace common; + using A = AlignedFieldFilter; + auto make_leaf = [] { + return A::compare("v", A::CompareOp::EQ, A::Literal::int64(1)); + }; + EXPECT_EQ(make_leaf()->height(), 1); + auto pair = A::and_filter(make_leaf(), make_leaf()); + EXPECT_EQ(pair->height(), 2); + A::Ptr chain = make_leaf(); + for (int i = 1; i < 600; ++i) { + chain = A::and_filter(std::move(chain), make_leaf()); + } + EXPECT_EQ(chain->height(), 600); +} + } // namespace } // namespace storage diff --git a/python/tests/test_field_filter_query.py b/python/tests/test_field_filter_query.py index 1cd4daa24..f0ddf1fe5 100644 --- a/python/tests/test_field_filter_query.py +++ b/python/tests/test_field_filter_query.py @@ -542,27 +542,31 @@ def test_integral_double_is_accepted_on_integral_column(self): def test_deep_filter_tree_is_rejected(self): # A loop-built chain must not overflow the C stack in the builder or in # the native clone()/bind() recursion. 512 leaves is the exact limit. + # The threshold is selective so a dropped or mis-negated filter shows + # up in the row counts. def chain(leaves): - f = field_gteq("value", 0.0) + f = field_gteq("value", 10.0) for _ in range(leaves - 1): - f = f & field_gteq("value", 0.0) + f = f & field_gteq("value", 10.0) return f with TsFileReader(TSFILE_PATH) as reader: - assert len(_query(reader, chain(512))) == 20 + assert len(_query(reader, chain(512))) == 10 # NOT preserves the native height, so a maximum-depth tree is # still negatable (and an even number of NOTs cancels out). - assert _query(reader, ~chain(512)) == [] - assert len(_query(reader, ~~chain(512))) == 20 + assert _times(reader, ~chain(512)) == [float(i) for i in range(10)] + assert len(_query(reader, ~~chain(512))) == 10 with pytest.raises(ValueError, match="maximum depth"): _query(reader, chain(513)) # BETWEEN expands to a native AND, one level deeper than the - # builder's count; at the boundary it must still raise ValueError. + # builder's count: depth 510 is still valid (native height 512), + # and one more AND exceeds the limit. between = field_between("value", 0.0, 100.0) - for _ in range(511): + for _ in range(510): between = between & field_gteq("value", 0.0) + assert len(_query(reader, between)) == 20 with pytest.raises(ValueError, match="maximum depth"): - _query(reader, between) + _query(reader, between & field_gteq("value", 0.0)) def test_int64_literal_boundaries(self): with TsFileReader(TSFILE_PATH) as reader: @@ -649,9 +653,15 @@ def test_negation_never_matches_null(self): def test_column_names_accept_sequences(self): np = pytest.importorskip("numpy") with TsFileReader(TSFILE_PATH) as reader: - for columns in (np.array(["value"]), (c for c in ["value"])): - with reader.query_table(TABLE_NAME, columns) as result: - rows = 0 - while result.next(): - rows += 1 - assert rows == 20 + for make_columns in ( + lambda: np.array(["value"]), + lambda: (c for c in ["value"]), + ): + for query in (reader.query_table, reader.query_table_by_row): + with query(TABLE_NAME, make_columns()) as result: + rows = 0 + while result.next(): + rows += 1 + assert rows == 20 + with pytest.raises(InvalidArgumentError): + reader.query_table(TABLE_NAME, iter(())) diff --git a/python/tsfile/field_filter.py b/python/tsfile/field_filter.py index c572303b8..a1ea0c301 100644 --- a/python/tsfile/field_filter.py +++ b/python/tsfile/field_filter.py @@ -33,8 +33,9 @@ FLOAT/DOUBLE columns the literal is converted to the column type. Column-aware validation (types and exactness) happens when the filter is used in ``query_table`` / ``query_table_by_row``, not when the filter object is built. -Filter trees may be at most 512 levels deep; deeper trees raise ``ValueError`` -at query time. +Filter trees may be at most 512 levels of AND/OR/BETWEEN height; NOT does not +add a level because negation preserves height. Deeper trees raise +``ValueError`` at query time. """ from numbers import Integral, Real @@ -202,7 +203,11 @@ def __repr__(self): class NotFieldFilter(FieldFilter): - """Logical NOT of a FIELD filter. NULL cells never satisfy the negation.""" + """Logical NOT of a FIELD filter. + + A negated comparison never matches NULL cells; NOT(IS NOT NULL) becomes + IS NULL and does match them. + """ def __init__(self, filter: FieldFilter): self.filter = filter diff --git a/python/tsfile/tsfile_reader.pyx b/python/tsfile/tsfile_reader.pyx index 8acf46f21..723be4c66 100644 --- a/python/tsfile/tsfile_reader.pyx +++ b/python/tsfile/tsfile_reader.pyx @@ -486,7 +486,7 @@ cdef class TsFileReaderPy: values. The predicate is pushed down natively and disables the prepared-series cache for this query. :raises InvalidArgumentError: if column_names is empty. - :raises ValueError: if field_filter exceeds the 512-level limit. + :raises ValueError: if field_filter exceeds the 512-level height limit. :return: query result handler. """ cdef ResultSet result @@ -823,7 +823,12 @@ cdef class TsFileReaderPy: # recursion, no depth charge, and an even count cancels out. inverted = 0 inner_filter = field_filter + seen_filters = set() while isinstance(inner_filter, NotFieldFilter): + if id(inner_filter) in seen_filters: + raise ValueError( + "FIELD filter tree contains a NOT cycle") + seen_filters.add(id(inner_filter)) inverted ^= 1 inner_filter = inner_filter.filter try: @@ -843,7 +848,7 @@ cdef class TsFileReaderPy: else: raise TypeError(f"Unknown field filter type: {type(field_filter)}") - def query_table_on_tree(self, column_names : List[str], + def query_table_on_tree(self, column_names, start_time : int = INT64_MIN, end_time : int = INT64_MAX) -> ResultSetPy: """ Execute a time range query on specified columns on tree structure. @@ -851,17 +856,20 @@ cdef class TsFileReaderPy: """ cdef ResultSet result; ## No need to convert column names to lowercase, as measurement names in the tree model are case-sensitive. + column_names = list(column_names) result = tsfile_reader_query_table_on_tree_c(self.reader, column_names, start_time, end_time) pyresult = ResultSetPy(self, True) pyresult.init_c(result, "root") self.activate_result_set_list.add(pyresult) return pyresult - def query_tree_by_row(self, device_ids : List[str], measurement_names : List[str], + def query_tree_by_row(self, device_ids, measurement_names, offset : int = 0, limit : int = -1) -> ResultSetPy: """ Execute tree-model query by row with offset/limit. """ + device_ids = list(device_ids) + measurement_names = list(measurement_names) if len(device_ids) == 0: raise ValueError("device_ids must not be empty") if len(measurement_names) == 0: @@ -889,7 +897,8 @@ cdef class TsFileReaderPy: values, pushed down natively. OFFSET/LIMIT count accepted rows. :raises InvalidArgumentError: if column_names is empty or offset is negative. - :raises ValueError: if field_filter exceeds the 512-level limit. + :raises ValueError: if field_filter exceeds the 512-level height + limit. """ cdef ResultSet result cdef TagFilterHandle c_tag_filter = NULL @@ -924,12 +933,13 @@ cdef class TsFileReaderPy: self.activate_result_set_list.add(pyresult) return pyresult - def query_timeseries(self, device_name : str, sensor_list : List[str], start_time : int = 0, + def query_timeseries(self, device_name : str, sensor_list, start_time : int = 0, end_time : int = 0) -> ResultSetPy: """ Execute a time range query on a specify device. """ cdef ResultSet result; + sensor_list = list(sensor_list) result = tsfile_reader_query_paths_c(self.reader, device_name, sensor_list, start_time, end_time) pyresult = ResultSetPy(self, True) pyresult.init_c(result, device_name) diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index d73d3c257..a470bb926 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -100,7 +100,9 @@ comparison also excludes NULL cells. limit and raises `ValueError` for deeper trees. Pass TAG and FIELD handles to `tsfile_query_table_with_filters` or `tsfile_reader_query_table_by_row_with_filters`; the query copies the FIELD - filter, so the caller keeps ownership of the handle. + filter, so the caller keeps ownership of the handle and may free it as soon + as the call returns. The TAG handle is not copied: it must stay alive until + the result set is closed. - C++: build `storage::AlignedFieldFilter` trees with `compare`, `is_null`, `is_not_null`, `and_filter`, `or_filter`, and `not_filter` from `cpp/src/reader/filter/aligned_field_filter.h`, and pass the filter to the From c53b54094f0d8268a33421baaaa802b742c251d1 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 00:07:48 +0800 Subject: [PATCH 07/10] Share table query wrappers and align FIELD filter ownership --- cpp/src/cwrapper/tsfile_cwrapper.cc | 377 +++++------------- cpp/src/cwrapper/tsfile_cwrapper.h | 45 +-- cpp/src/reader/filter/aligned_field_filter.cc | 68 ++-- cpp/src/reader/filter/aligned_field_filter.h | 12 +- cpp/src/reader/table_query_executor.cc | 102 +---- cpp/src/reader/table_query_executor.h | 4 + cpp/src/reader/tsfile_reader.cc | 18 +- cpp/test/cwrapper/cwrapper_extended_test.cc | 37 +- python/tests/test_field_filter_query.py | 44 +- python/tsfile/tsfile_py_cpp.pyx | 200 ++-------- python/tsfile/tsfile_reader.pyx | 90 ++--- .../tsfile/references/properties-filters.md | 11 +- 12 files changed, 291 insertions(+), 717 deletions(-) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index c282815fe..0f7b1fc7b 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -843,15 +843,9 @@ ResultSet tsfile_query_table(TsFileReader reader, const char* table_name, char** columns, uint32_t column_num, Timestamp start_time, Timestamp end_time, ERRNO* err_code) { - auto* r = static_cast(reader); - storage::ResultSet* table_result_set = nullptr; - std::vector column_names; - for (uint32_t i = 0; i < column_num; i++) { - column_names.emplace_back(columns[i]); - } - *err_code = r->query(table_name, column_names, start_time, end_time, - table_result_set); - return table_result_set; + return tsfile_query_table_with_filters(reader, table_name, columns, + column_num, start_time, end_time, 0, + -1, nullptr, nullptr, 0, err_code); } ResultSet tsfile_query_table_on_tree(TsFileReader reader, char** columns, @@ -934,22 +928,9 @@ ResultSet tsfile_reader_query_table_by_row( TsFileReader reader, const char* table_name, char** column_names, int column_names_len, int offset, int limit, TagFilterHandle tag_filter, int batch_size, ERRNO* err_code) { - auto* r = static_cast(reader); - storage::ResultSet* result_set = nullptr; - - std::vector columns; - if (column_names_len > 0) { - columns.reserve(static_cast(column_names_len)); - } - for (int i = 0; i < column_names_len; i++) { - const char* name = column_names[i]; - columns.emplace_back(name == nullptr ? "" : std::string(name)); - } - - *err_code = r->queryByRow( - table_name == nullptr ? "" : table_name, columns, offset, limit, - result_set, static_cast(tag_filter), batch_size); - return result_set; + return tsfile_reader_query_table_by_row_with_filters( + reader, table_name, column_names, column_names_len, offset, limit, + tag_filter, nullptr, batch_size, err_code); } ResultSet tsfile_reader_query_table(TsFileReader reader, const char* table_name, @@ -959,36 +940,14 @@ ResultSet tsfile_reader_query_table(TsFileReader reader, const char* table_name, int offset, int limit, TagFilterHandle tag_filter, int batch_size, ERRNO* err_code) { - if (err_code == nullptr) { - return nullptr; - } - *err_code = common::E_INVALID_ARG; - if (reader == nullptr || table_name == nullptr || column_names == nullptr || - column_names_len == 0 || offset < 0 || batch_size < 0) { - return nullptr; - } - try { - std::vector columns; - columns.reserve(column_names_len); - for (uint32_t i = 0; i < column_names_len; ++i) { - if (column_names[i] == nullptr) { - return nullptr; - } - columns.emplace_back(column_names[i]); - } - storage::ResultSet* result_set = nullptr; - const int normalized_limit = limit < 0 ? -1 : limit; - *err_code = static_cast(reader)->query( - table_name, columns, start_time, end_time, offset, normalized_limit, - result_set, static_cast(tag_filter), batch_size); - return result_set; - } catch (const std::bad_alloc&) { - *err_code = common::E_OOM; - return nullptr; - } catch (...) { - *err_code = common::E_FILE_READ_ERR; + // This checked API requires a projection and a nonnegative batch size. + if (column_names_len == 0 || batch_size < 0) { + if (err_code) *err_code = common::E_INVALID_ARG; return nullptr; } + return tsfile_query_table_with_filters( + reader, table_name, column_names, column_names_len, start_time, + end_time, offset, limit, tag_filter, nullptr, batch_size, err_code); } ResultSet tsfile_query_table_batch(TsFileReader reader, const char* table_name, @@ -996,16 +955,9 @@ ResultSet tsfile_query_table_batch(TsFileReader reader, const char* table_name, Timestamp start_time, Timestamp end_time, TagFilterHandle tag_filter, int batch_size, ERRNO* err_code) { - auto* r = static_cast(reader); - storage::ResultSet* table_result_set = nullptr; - std::vector column_names; - for (uint32_t i = 0; i < column_num; i++) { - column_names.emplace_back(columns[i]); - } - *err_code = r->query(table_name, column_names, start_time, end_time, - table_result_set, - static_cast(tag_filter), batch_size); - return table_result_set; + return tsfile_query_table_with_filters( + reader, table_name, columns, column_num, start_time, end_time, 0, -1, + tag_filter, nullptr, batch_size, err_code); } bool tsfile_result_set_next(ResultSet result_set, ERRNO* err_code) { @@ -2999,16 +2951,9 @@ ResultSet tsfile_query_table_with_tag_filter( TsFileReader reader, const char* table_name, char** columns, uint32_t column_num, Timestamp start_time, Timestamp end_time, TagFilterHandle tag_filter, int batch_size, ERRNO* err_code) { - auto* r = static_cast(reader); - storage::ResultSet* table_result_set = nullptr; - std::vector column_names; - for (uint32_t i = 0; i < column_num; i++) { - column_names.emplace_back(columns[i]); - } - *err_code = r->query(table_name, column_names, start_time, end_time, - table_result_set, - static_cast(tag_filter), batch_size); - return table_result_set; + return tsfile_query_table_with_filters( + reader, table_name, columns, column_num, start_time, end_time, 0, -1, + tag_filter, nullptr, batch_size, err_code); } // ============== Field Filter API Implementation ============== @@ -3065,39 +3010,26 @@ bool to_field_literal(const FieldFilterValue& value, } } -// Maximum depth of a FIELD filter tree accepted by this API. The native -// clone()/bind() implementations recurse once per level, so deeper trees are -// rejected instead of being able to overflow the C stack. -constexpr int kMaxFieldFilterDepth = 512; +using FieldFilter = storage::AlignedFieldFilter; -int field_filter_depth(const storage::AlignedFieldFilter* filter) { - struct Entry { - const storage::AlignedFieldFilter* node; - int depth; - }; - std::vector stack; - stack.push_back(Entry{filter, 1}); - int max_depth = 0; - while (!stack.empty()) { - Entry entry = stack.back(); - stack.pop_back(); - if (entry.node == nullptr) { - continue; - } - if (entry.depth > max_depth) { - max_depth = entry.depth; - } - if (max_depth > kMaxFieldFilterDepth) { - return max_depth; - } - if (entry.node->left() != nullptr) { - stack.push_back(Entry{entry.node->left(), entry.depth + 1}); - } - if (entry.node->right() != nullptr) { - stack.push_back(Entry{entry.node->right(), entry.depth + 1}); - } +FieldFilter* as_field_filter(FieldFilterHandle handle) { + return dynamic_cast(static_cast(handle)); +} + +FieldFilterHandle combine_field_filters(FieldFilterHandle left, + FieldFilterHandle right, + bool conjunction) { + auto* lhs = as_field_filter(left); + auto* rhs = as_field_filter(right); + if (!lhs || !rhs || lhs == rhs) return nullptr; + try { + if (lhs->height() >= FieldFilter::MAX_HEIGHT || + rhs->height() >= FieldFilter::MAX_HEIGHT) + return nullptr; + return FieldFilter::adopt_binary(conjunction, lhs, rhs).release(); + } catch (...) { + return nullptr; } - return max_depth; } // Copies a FIELD filter handle into a filter owned by the query call. The @@ -3105,10 +3037,8 @@ int field_filter_depth(const storage::AlignedFieldFilter* filter) { // the caller's handle cannot be handed over directly. storage::Filter* clone_field_filter(FieldFilterHandle field_filter, ERRNO* err_code) { - auto* native = dynamic_cast( - static_cast(field_filter)); - if (native == nullptr || - field_filter_depth(native) > kMaxFieldFilterDepth) { + auto* native = as_field_filter(field_filter); + if (native == nullptr || native->height() > FieldFilter::MAX_HEIGHT) { *err_code = common::E_INVALID_ARG; return nullptr; } @@ -3205,109 +3135,21 @@ ERRNO tsfile_field_filter_create_checked(TsFileReader reader, FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, FieldFilterHandle right) { - if (left == nullptr || right == nullptr) { - // A NULL sibling still consumes the other input: delete on a null - // pointer is a no-op for the missing side. - delete static_cast(left); - delete static_cast(right); - return nullptr; - } - if (left == right) { - // Operands must be distinct; an aliased pair is rejected and the one - // handle is consumed exactly once. - delete static_cast(left); - return nullptr; - } - using FieldFilter = storage::AlignedFieldFilter; - auto* left_node = - dynamic_cast(static_cast(left)); - auto* right_node = - dynamic_cast(static_cast(right)); - if (left_node == nullptr || right_node == nullptr) { - // Both handle families are Filter subclasses, so free through the - // virtual destructor. - delete static_cast(left); - delete static_cast(right); - return nullptr; - } - // Takes ownership of both inputs on every path: the returned node adopts - // them directly, so the caller must not free the inputs afterwards (even - // when this returns NULL). - try { - FieldFilter::Ptr left_ptr(left_node); - FieldFilter::Ptr right_ptr(right_node); - if (field_filter_depth(left_node) >= kMaxFieldFilterDepth || - field_filter_depth(right_node) >= kMaxFieldFilterDepth) { - return nullptr; - } - return static_cast( - FieldFilter::and_filter(std::move(left_ptr), std::move(right_ptr)) - .release()); - } catch (...) { - return nullptr; - } + return combine_field_filters(left, right, true); } FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, FieldFilterHandle right) { - if (left == nullptr || right == nullptr) { - delete static_cast(left); - delete static_cast(right); - return nullptr; - } - if (left == right) { - delete static_cast(left); - return nullptr; - } - using FieldFilter = storage::AlignedFieldFilter; - auto* left_node = - dynamic_cast(static_cast(left)); - auto* right_node = - dynamic_cast(static_cast(right)); - if (left_node == nullptr || right_node == nullptr) { - delete static_cast(left); - delete static_cast(right); - return nullptr; - } - // Takes ownership of both inputs on every path; see - // tsfile_field_filter_and(). - try { - FieldFilter::Ptr left_ptr(left_node); - FieldFilter::Ptr right_ptr(right_node); - if (field_filter_depth(left_node) >= kMaxFieldFilterDepth || - field_filter_depth(right_node) >= kMaxFieldFilterDepth) { - return nullptr; - } - return static_cast( - FieldFilter::or_filter(std::move(left_ptr), std::move(right_ptr)) - .release()); - } catch (...) { - return nullptr; - } + return combine_field_filters(left, right, false); } FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter) { - if (filter == nullptr) { - return nullptr; - } - using FieldFilter = storage::AlignedFieldFilter; - auto* node = - dynamic_cast(static_cast(filter)); - if (node == nullptr) { - delete static_cast(filter); - return nullptr; - } - // Takes ownership of the input on every path; see - // tsfile_field_filter_and(). + auto* node = as_field_filter(filter); + if (!node) return nullptr; try { - FieldFilter::Ptr node_ptr(node); - // Negation preserves the tree height, so a tree at the maximum size - // remains valid. - if (field_filter_depth(node) > kMaxFieldFilterDepth) { - return nullptr; - } - return static_cast( - FieldFilter::not_filter(std::move(node_ptr)).release()); + if (node->height() > FieldFilter::MAX_HEIGHT) return nullptr; + // Negation of a non-null tree rewrites it in place without allocation. + return FieldFilter::not_filter(FieldFilter::Ptr(node)).release(); } catch (...) { return nullptr; } @@ -3321,108 +3163,75 @@ void tsfile_field_filter_free(FieldFilterHandle filter) { } } -ResultSet tsfile_query_table_with_filters( - TsFileReader reader, const char* table_name, char** columns, - uint32_t column_num, Timestamp start_time, Timestamp end_time, int offset, - int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, - int batch_size, ERRNO* err_code) { - if (err_code == nullptr) { - return nullptr; - } +namespace { + +ResultSet query_table_with_filters(TsFileReader reader, const char* table_name, + char** columns, uint32_t column_num, + const Timestamp* time_range, int offset, + int limit, TagFilterHandle tag_filter, + FieldFilterHandle field_filter, + int batch_size, ERRNO* err_code) { + if (!err_code) return nullptr; *err_code = common::E_INVALID_ARG; - if (reader == nullptr || table_name == nullptr || columns == nullptr || - column_num == 0 || offset < 0) { + if (!reader || !table_name || (column_num && !columns) || offset < 0) return nullptr; - } try { - std::vector column_names; - column_names.reserve(column_num); + std::vector names; + names.reserve(column_num); for (uint32_t i = 0; i < column_num; ++i) { - if (columns[i] == nullptr) { - return nullptr; - } - column_names.emplace_back(columns[i]); + if (!columns[i]) return nullptr; + names.emplace_back(columns[i]); } - storage::ResultSet* result_set = nullptr; - const int normalized_limit = limit < 0 ? -1 : limit; - // batch_size <= 0 selects row-by-row mode, matching query_table's - // behavior without a FIELD filter; clamp negatives so both paths agree. - const int normalized_batch_size = batch_size < 0 ? 0 : batch_size; - // Materialise the table name before taking ownership of the clone so a - // throwing string construction cannot leak it. const std::string table(table_name); - storage::Filter* field_copy = nullptr; - if (field_filter != nullptr) { - field_copy = clone_field_filter(field_filter, err_code); - if (field_copy == nullptr) { - return nullptr; - } + storage::Filter* copy = nullptr; + if (field_filter) { + copy = clone_field_filter(field_filter, err_code); + if (!copy) return nullptr; } - *err_code = static_cast(reader)->query( - table, column_names, start_time, end_time, offset, normalized_limit, - result_set, static_cast(tag_filter), field_copy, - normalized_batch_size); - if (*err_code != common::E_OK) { - return nullptr; + auto* r = static_cast(reader); + auto* tag = static_cast(tag_filter); + storage::ResultSet* result = nullptr; + if (time_range) { + *err_code = r->query(table, names, time_range[0], time_range[1], + offset, limit, result, tag, copy, batch_size); + } else { + *err_code = r->queryByRow(table, names, offset, limit, result, tag, + copy, batch_size); } - return result_set; + return *err_code == common::E_OK ? result : nullptr; } catch (const std::bad_alloc&) { *err_code = common::E_OOM; - return nullptr; } catch (...) { *err_code = common::E_FILE_READ_ERR; - return nullptr; } + return nullptr; +} + +} // namespace + +ResultSet tsfile_query_table_with_filters( + TsFileReader reader, const char* table_name, char** columns, + uint32_t column_num, Timestamp start_time, Timestamp end_time, int offset, + int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, + int batch_size, ERRNO* err_code) { + const Timestamp range[] = {start_time, end_time}; + return query_table_with_filters(reader, table_name, columns, column_num, + range, offset, limit, tag_filter, + field_filter, batch_size, err_code); } ResultSet tsfile_reader_query_table_by_row_with_filters( TsFileReader reader, const char* table_name, char** column_names, int column_names_len, int offset, int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, int batch_size, ERRNO* err_code) { - if (err_code == nullptr) { - return nullptr; - } - *err_code = common::E_INVALID_ARG; - if (reader == nullptr || table_name == nullptr || column_names == nullptr || - column_names_len <= 0 || offset < 0) { - return nullptr; - } - try { - std::vector columns; - columns.reserve(static_cast(column_names_len)); - for (int i = 0; i < column_names_len; ++i) { - if (column_names[i] == nullptr) { - return nullptr; - } - columns.emplace_back(column_names[i]); - } - storage::ResultSet* result_set = nullptr; - const int normalized_batch_size = batch_size < 0 ? 0 : batch_size; - // Materialise the table name before taking ownership of the clone so a - // throwing string construction cannot leak it. - const std::string table(table_name); - storage::Filter* field_copy = nullptr; - if (field_filter != nullptr) { - field_copy = clone_field_filter(field_filter, err_code); - if (field_copy == nullptr) { - return nullptr; - } - } - *err_code = static_cast(reader)->queryByRow( - table, columns, offset, limit, result_set, - static_cast(tag_filter), field_copy, - normalized_batch_size); - if (*err_code != common::E_OK) { - return nullptr; - } - return result_set; - } catch (const std::bad_alloc&) { - *err_code = common::E_OOM; - return nullptr; - } catch (...) { - *err_code = common::E_FILE_READ_ERR; + if (column_names_len < 0) { + if (err_code) *err_code = common::E_INVALID_ARG; return nullptr; } + return query_table_with_filters(reader, table_name, column_names, + static_cast(column_names_len), + nullptr, offset, limit, tag_filter, + field_filter, batch_size, err_code); } #ifdef __cplusplus diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index 206f8346b..cf571180d 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -987,10 +987,11 @@ ResultSet tsfile_reader_query_table(TsFileReader reader, const char* table_name, /** * @brief Query table data with TAG and FIELD filters. * - * Both filters are optional. FIELD predicates are pushed down into the table - * query executor: aligned devices use batch/page evaluation, non-aligned - * devices evaluate merged rows. FIELD comparisons never match NULL values; - * use FIELD_FILTER_IS_NULL / FIELD_FILTER_IS_NOT_NULL for that. + * An empty projection returns only timestamps. Both filters are optional. FIELD + * predicates are pushed down into the table query executor: aligned devices use + * batch/page evaluation, non-aligned devices evaluate merged rows. FIELD + * comparisons never match NULL values; use FIELD_FILTER_IS_NULL / + * FIELD_FILTER_IS_NOT_NULL for that. * * @param start_time [in] Inclusive lower time bound. * @param end_time [in] Inclusive upper time bound. @@ -1424,21 +1425,12 @@ ResultSet tsfile_query_table_with_tag_filter( // comparison never matches NULL; use FIELD_FILTER_IS_NULL / // FIELD_FILTER_IS_NOT_NULL for NULL checks. // -// Ownership: every create/compose function returns an owning handle. Free it -// with tsfile_field_filter_free(). The and/or/not functions CONSUME their -// inputs on every path: non-NULL inputs are freed even when the call fails -// (wrong handle family, too-deep operand, allocation failure), and an aliased -// pair (the same handle passed twice) is rejected and freed once. This differs -// from the TAG API above, which keeps the inputs when composition fails. -// Inputs must be distinct handles and must not be reused after the call. -// Query functions borrow the handle and copy it before execution, so a handle -// may be reused and must be freed by the caller. -// -// Only FIELD handles are accepted by the compose functions: a handle from the -// TAG family (or any other non-FIELD filter) is rejected and consumed. and/or -// reject an operand at 512 levels (the result would be 513 deep); NOT accepts -// a tree of 512 levels because negation preserves its height. A composed tree -// may therefore reach 512 levels. +// Each successful create/compose returns an owning handle. As with TAG, +// and/or/not take ownership of their inputs only on success. On failure the +// caller retains every input. Binary operands must be distinct FIELD handles. +// Query functions borrow the FIELD handle and copy it before execution. +// and/or reject trees whose combined height would exceed 512 levels. NOT +// preserves height. /** * @brief FIELD filter comparison operators. @@ -1518,9 +1510,8 @@ ERRNO tsfile_field_filter_create_checked(TsFileReader reader, /** * @brief Logical AND of two FIELD filters. * - * Takes ownership of both inputs; the caller must not free them afterwards. - * Returns a new filter that owns them directly. Returns NULL on failure - * (the inputs are consumed either way). + * Takes ownership of both inputs on success. Returns NULL on failure; + * the caller still owns the inputs. */ FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, FieldFilterHandle right); @@ -1528,9 +1519,8 @@ FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, /** * @brief Logical OR of two FIELD filters. * - * Takes ownership of both inputs; the caller must not free them afterwards. - * Returns a new filter that owns them directly. Returns NULL on failure - * (the inputs are consumed either way). + * Takes ownership of both inputs on success. Returns NULL on failure; + * the caller still owns the inputs. */ FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, FieldFilterHandle right); @@ -1538,9 +1528,8 @@ FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, /** * @brief Logical NOT of a FIELD filter. * - * Takes ownership of the input; the caller must not free it afterwards. - * Returns a new filter that owns it directly. Returns NULL on failure (the - * input is consumed either way). A negated comparison never matches NULL + * Takes ownership of the input on success. Returns NULL on failure; + * the caller still owns the input. A negated comparison never matches NULL * rows; NOT(IS NOT NULL) becomes IS NULL and does match them. */ FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter); diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index cbbaefabe..6ef41892d 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -369,51 +369,49 @@ AlignedFieldFilter::Ptr AlignedFieldFilter::or_filter(Ptr left, Ptr right) { new AlignedFieldFilter(Kind::OR, std::move(left), std::move(right))); } -AlignedFieldFilter::Ptr AlignedFieldFilter::not_filter(Ptr child) { - return negate(std::move(child)); +AlignedFieldFilter::Ptr AlignedFieldFilter::adopt_binary( + bool conjunction, AlignedFieldFilter* left, AlignedFieldFilter* right) { + Ptr parent(new AlignedFieldFilter(conjunction ? Kind::AND : Kind::OR, + nullptr, nullptr)); + parent->left_.reset(left); + parent->right_.reset(right); + return parent; } -AlignedFieldFilter::Ptr AlignedFieldFilter::negate(Ptr node) { - if (node == nullptr) { - // Preserve the invalid operand so query validation cannot mistake - // this predicate for the optional "no FIELD filter" argument. +AlignedFieldFilter::Ptr AlignedFieldFilter::not_filter(Ptr child) { + if (!child) { return Ptr(new AlignedFieldFilter(Kind::NOT, nullptr, nullptr)); } - switch (node->kind_) { - case Kind::COMPARISON: { - // The literal type does not identify the column type: an integer - // constant can bind to a floating-point column. Preserve ordered - // negation until binding so NOT (NaN < 5) remains true, while NULL - // remains unknown. Equality can still flip its operator directly. - const bool ordered = node->compare_op_ == CompareOp::LT || - node->compare_op_ == CompareOp::LE || - node->compare_op_ == CompareOp::GT || - node->compare_op_ == CompareOp::GE; - if (ordered) { - return Ptr(new AlignedFieldFilter( - Kind::COMPARISON, node->column_, node->compare_op_, - node->literal_, !node->negated_)); + child->negate(); + return child; +} + +void AlignedFieldFilter::negate() noexcept { + switch (kind_) { + case Kind::COMPARISON: + // Ordered comparisons need explicit negation until binding, as + // flipping the operator changes the result for floating-point NaNs. + if (compare_op_ == CompareOp::EQ || compare_op_ == CompareOp::NE) { + compare_op_ = negate_comparison(compare_op_); + } else { + negated_ = !negated_; } - return Ptr(new AlignedFieldFilter( - Kind::COMPARISON, node->column_, - negate_comparison(node->compare_op_), node->literal_)); - } + break; case Kind::IS_NULL: - return is_not_null(node->column_); + kind_ = Kind::IS_NOT_NULL; + break; case Kind::IS_NOT_NULL: - return is_null(node->column_); - case Kind::NOT: - // Only invalid markers remain after NOT pushdown. Repeated - // negation must preserve them instead of erasing an invalid tree. - return node; + kind_ = Kind::IS_NULL; + break; case Kind::AND: - return or_filter(negate(std::move(node->left_)), - negate(std::move(node->right_))); case Kind::OR: - return and_filter(negate(std::move(node->left_)), - negate(std::move(node->right_))); + kind_ = kind_ == Kind::AND ? Kind::OR : Kind::AND; + if (left_) left_->negate(); + if (right_) right_->negate(); + break; + case Kind::NOT: + break; // Invalid operand marker. } - return node; } AlignedFieldFilter::Ptr AlignedFieldFilter::clone() const { diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 20effd5d5..8f86440b8 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -87,6 +87,10 @@ class AlignedFieldFilter : public Filter { static Ptr or_filter(Ptr left, Ptr right); static Ptr not_filter(Ptr child); + // The C handle API transfers ownership only after the parent is allocated. + static Ptr adopt_binary(bool conjunction, AlignedFieldFilter* left, + AlignedFieldFilter* right); + // Deep copy, including the bound literal and negation state. The table // query executor takes ownership of the filter it runs, so a caller that // keeps its own filter (for example a C binding handle reused across @@ -97,11 +101,6 @@ class AlignedFieldFilter : public Filter { CompareOp compare_op() const { return compare_op_; } const std::string& column() const { return column_; } const Literal& literal() const { return literal_; } - // Composite operands (null for leaves); used for iterative traversal, e.g. - // depth checks before recursing into clone()/bind(). - const AlignedFieldFilter* left() const { return left_.get(); } - const AlignedFieldFilter* right() const { return right_.get(); } - std::vector referenced_columns() const; // False when a composite node is missing one of its operands. Callers use @@ -131,6 +130,7 @@ class AlignedFieldFilter : public Filter { // Tree height (a leaf is 1), computed iteratively. Query paths use this // to reject caller-built trees deep enough to overflow the recursive // clone()/bind()/is_valid()/may_match()/all_match() traversals. + static constexpr int MAX_HEIGHT = 512; int height() const; // Conservatively decides whether any row in a page can satisfy the filter. @@ -154,7 +154,7 @@ class AlignedFieldFilter : public Filter { AlignedFieldFilter(Kind kind, Ptr left, Ptr right); // Push NOT down to the leaves so negation keeps SQL three-valued NULL // semantics; a single SelectionMask bit cannot represent NULL vs FALSE. - static Ptr negate(Ptr node); + void negate() noexcept; int evaluate_leaf(common::TsBlock& block, const std::map& column_index, diff --git a/cpp/src/reader/table_query_executor.cc b/cpp/src/reader/table_query_executor.cc index 356c7f652..632ac1011 100644 --- a/cpp/src/reader/table_query_executor.cc +++ b/cpp/src/reader/table_query_executor.cc @@ -23,108 +23,12 @@ namespace storage { -// FIELD filter trees deeper than this are rejected by every entry point -// (C wrapper, Cython builder and this executor): the recursive clone()/bind()/ -// is_valid() traversals would otherwise overflow the stack. -constexpr int kMaxFieldFilterHeight = 512; - int TableQueryExecutor::query(const std::string& table_name, const std::vector& columns, Filter* time_filter, Filter* tag_filter, Filter* field_filter, ResultSet*& ret_qds) { - // Adopt both filters immediately so every error return and any exception - // frees them unless they are handed to the block reader below. - std::unique_ptr time_filter_guard(time_filter); - std::unique_ptr field_filter_guard(field_filter); - int ret = common::E_OK; - TsFileMeta* file_metadata = nullptr; - ret_qds = nullptr; - if (RET_FAIL(tsfile_io_reader_->get_tsfile_meta(file_metadata))) { - return ret; - } - common::PageArena pa; - pa.init(512, common::MOD_TSFILE_READER); - MetaIndexNode* table_root = nullptr; - std::shared_ptr table_schema; - // A schema-only table has no device-level index. Resolve the schema - // first, then leave table_root null so DeviceMetaIterator yields an empty - // result set with the correct columns instead of reporting "table does - // not exist". - if (RET_FAIL(file_metadata->get_table_schema(table_name, table_schema))) { - ret_qds = nullptr; - return ret; - } - file_metadata->get_table_metaindex_node(table_name, table_root); - std::vector lower_case_column_names(columns); - for (auto& column : lower_case_column_names) { - to_lowercase_inplace(column); - } - std::shared_ptr column_mapping = - std::make_shared(); - for (size_t i = 0; i < lower_case_column_names.size(); ++i) { - column_mapping->add(lower_case_column_names[i], static_cast(i), - *table_schema); - } - std::vector data_types; - data_types.reserve(lower_case_column_names.size()); - for (size_t i = 0; i < lower_case_column_names.size(); ++i) { - auto ind = table_schema->find_column_index(lower_case_column_names[i]); - if (ind < 0) { - return common::E_COLUMN_NOT_EXIST; - } - data_types.push_back(table_schema->get_data_types()[ind]); - } - if (auto* aligned_filter = - dynamic_cast(field_filter_guard.get())) { - // Matches the C wrapper limit: deeper caller-built trees would - // overflow the recursive clone()/bind()/is_valid() traversals. - if (aligned_filter->height() > kMaxFieldFilterHeight) { - return common::E_INVALID_ARG; - } - if (!aligned_filter->is_valid()) { - return common::E_INVALID_ARG; - } - // The filter may have been created against another schema; reject - // literals that the queried schema would silently narrow. - ret = aligned_filter->check_exact_literals(*table_schema); - if (ret != common::E_OK) { - return ret; - } - ret = - column_mapping->add_filter_columns(*aligned_filter, *table_schema); - if (ret != common::E_OK) { - return ret; - } - } - - auto device_task_iterator = - std::unique_ptr(new DeviceTaskIterator( - 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_guard.get(), - field_filter_guard.get())); - // Ownership moves to the reader only after it is constructed, so a - // throwing allocation above cannot leak the filters. - time_filter_guard.release(); - field_filter_guard.release(); - break; - case TableQueryOrdering::TIME: - default: - 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_); - return ret; + return query(table_name, columns, time_filter, tag_filter, field_filter, 0, + -1, ret_qds); } int TableQueryExecutor::query(const std::string& table_name, @@ -174,7 +78,7 @@ int TableQueryExecutor::query(const std::string& table_name, dynamic_cast(field_filter_guard.get())) { // Matches the C wrapper limit: deeper caller-built trees would // overflow the recursive clone()/bind()/is_valid() traversals. - if (aligned_filter->height() > kMaxFieldFilterHeight) { + if (aligned_filter->height() > AlignedFieldFilter::MAX_HEIGHT) { return common::E_INVALID_ARG; } if (!aligned_filter->is_valid()) { diff --git a/cpp/src/reader/table_query_executor.h b/cpp/src/reader/table_query_executor.h index e968c3601..0b2fcb8d7 100644 --- a/cpp/src/reader/table_query_executor.h +++ b/cpp/src/reader/table_query_executor.h @@ -53,6 +53,10 @@ class TableQueryExecutor { tsfile_io_reader_->init(read_file); meta_data_querier_ = new MetadataQuerier(tsfile_io_reader_); table_query_ordering_ = TableQueryOrdering::DEVICE; + set_batch_size(batch_size); + } + // Readers copy the block size and return mode when a query is created. + void set_batch_size(int batch_size) { if (batch_size <= 0) { block_size_ = 1024; return_mode_ = RETURN_ROW; diff --git a/cpp/src/reader/tsfile_reader.cc b/cpp/src/reader/tsfile_reader.cc index fb56f1c9f..ed539dcc9 100644 --- a/cpp/src/reader/tsfile_reader.cc +++ b/cpp/src/reader/tsfile_reader.cc @@ -166,18 +166,14 @@ int TsFileReader::open_source(std::unique_ptr read_file, unsigned char TsFileReader::get_file_version() const { return file_version_; } int TsFileReader::ensure_table_query_executor(int batch_size) { - if (table_query_executor_ != nullptr && - table_query_executor_batch_size_ == batch_size) { - return E_OK; + if (batch_size < 0) batch_size = 0; + if (table_query_executor_ == nullptr) { + table_query_executor_ = + new TableQueryExecutor(read_file_.get(), batch_size); + } else if (table_query_executor_batch_size_ != batch_size) { + // Active result sets borrow this executor's metadata and I/O readers. + table_query_executor_->set_batch_size(batch_size); } - - if (table_query_executor_ != nullptr) { - delete table_query_executor_; - table_query_executor_ = nullptr; - } - - table_query_executor_ = - new TableQueryExecutor(read_file_.get(), batch_size); table_query_executor_batch_size_ = batch_size; return E_OK; } diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 6978bb912..3f61b18f2 100644 --- a/cpp/test/cwrapper/cwrapper_extended_test.cc +++ b/cpp/test/cwrapper/cwrapper_extended_test.cc @@ -810,8 +810,7 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { &null_string, &handle)); EXPECT_EQ(nullptr, handle); - // A NULL sibling consumes the other handle; an aliased pair is rejected - // and freed once (ASan verifies both). + // Rejected compositions leave every distinct input with the caller. FieldFilterHandle null_sibling = nullptr; ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( reader, kTableName, "INT32", FIELD_FILTER_EQ, @@ -820,7 +819,7 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { FieldFilterHandle null_result = tsfile_field_filter_and(null_sibling, nullptr); EXPECT_EQ(nullptr, null_result); - tsfile_field_filter_free(null_result); + tsfile_field_filter_free(null_sibling); FieldFilterHandle aliased = nullptr; ASSERT_EQ(RET_OK, tsfile_field_filter_create_checked( reader, kTableName, "INT32", FIELD_FILTER_EQ, @@ -828,9 +827,9 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { ASSERT_NE(nullptr, aliased); FieldFilterHandle alias_result = tsfile_field_filter_or(aliased, aliased); EXPECT_EQ(nullptr, alias_result); - tsfile_field_filter_free(alias_result); + tsfile_field_filter_free(aliased); - // A handle from the TAG family is rejected and consumed. + // A handle from the TAG family remains owned by its caller. TagFilterHandle tag_a = tsfile_tag_filter_eq(reader, kTableName, "TAG", "devA"); ASSERT_NE(nullptr, tag_a); @@ -842,13 +841,14 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { FieldFilterHandle wrong_family = tsfile_field_filter_and(tag_a, field_for_family); EXPECT_EQ(nullptr, wrong_family); - tsfile_field_filter_free(wrong_family); + tsfile_tag_filter_free(tag_a); + tsfile_field_filter_free(field_for_family); TagFilterHandle tag_b = tsfile_tag_filter_eq(reader, kTableName, "TAG", "devB"); ASSERT_NE(nullptr, tag_b); FieldFilterHandle wrong_not = tsfile_field_filter_not(tag_b); EXPECT_EQ(nullptr, wrong_not); - tsfile_field_filter_free(wrong_not); + tsfile_tag_filter_free(tag_b); TagFilterHandle tag_d = tsfile_tag_filter_eq(reader, kTableName, "TAG", "devA"); ASSERT_NE(nullptr, tag_d); @@ -859,7 +859,8 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { ASSERT_NE(nullptr, field_for_or); FieldFilterHandle wrong_or = tsfile_field_filter_or(tag_d, field_for_or); EXPECT_EQ(nullptr, wrong_or); - tsfile_field_filter_free(wrong_or); + tsfile_tag_filter_free(tag_d); + tsfile_field_filter_free(field_for_or); TagFilterHandle tag_c = tsfile_tag_filter_eq(reader, kTableName, "TAG", "devA"); ASSERT_NE(nullptr, tag_c); @@ -962,7 +963,7 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { 0, 100, -1, -1, nullptr, nullptr, 0, &err)); EXPECT_EQ(RET_INVALID_ARG, err); EXPECT_EQ(nullptr, tsfile_query_table_with_filters( - reader, kTableName, columns.data(), 0, 0, 100, 0, -1, + reader, kTableName, nullptr, 1, 0, 100, 0, -1, nullptr, nullptr, 0, &err)); EXPECT_EQ(RET_INVALID_ARG, err); EXPECT_EQ(nullptr, tsfile_reader_query_table_by_row_with_filters( @@ -971,7 +972,7 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { nullptr, 0, &err)); EXPECT_EQ(RET_INVALID_ARG, err); EXPECT_EQ(nullptr, tsfile_reader_query_table_by_row_with_filters( - reader, kTableName, columns.data(), 0, 0, -1, + reader, kTableName, columns.data(), -1, 0, -1, nullptr, nullptr, 0, &err)); EXPECT_EQ(RET_INVALID_ARG, err); @@ -1038,7 +1039,7 @@ TEST(CWrapperExtendedTest, FieldFilterDepthLimit) { } } - // One more composition exceeds the limit; both inputs are consumed. + // One more composition exceeds the limit; both inputs remain usable. chain = build_chain(512); EXPECT_NE(nullptr, chain); if (chain != nullptr) { @@ -1050,10 +1051,9 @@ TEST(CWrapperExtendedTest, FieldFilterDepthLimit) { FieldFilterHandle over_limit = tsfile_field_filter_and(chain, extra_leaf); EXPECT_EQ(nullptr, over_limit); - tsfile_field_filter_free(over_limit); - } else { - tsfile_field_filter_free(chain); + tsfile_field_filter_free(extra_leaf); } + tsfile_field_filter_free(chain); } // The right operand of a composition is depth-checked as well. @@ -1068,19 +1068,18 @@ TEST(CWrapperExtendedTest, FieldFilterDepthLimit) { FieldFilterHandle right_deep = tsfile_field_filter_or(left_leaf, chain); EXPECT_EQ(nullptr, right_deep); - tsfile_field_filter_free(right_deep); - } else { - tsfile_field_filter_free(chain); + tsfile_field_filter_free(left_leaf); } + tsfile_field_filter_free(chain); } - // An aliased pair is rejected and freed once (ASan-verified). + // An aliased pair is rejected; the caller still owns one handle. chain = build_chain(1); EXPECT_NE(nullptr, chain); if (chain != nullptr) { FieldFilterHandle alias_result = tsfile_field_filter_and(chain, chain); EXPECT_EQ(nullptr, alias_result); - tsfile_field_filter_free(alias_result); + tsfile_field_filter_free(chain); } tsfile_reader_close(reader); diff --git a/python/tests/test_field_filter_query.py b/python/tests/test_field_filter_query.py index f0ddf1fe5..3ad164810 100644 --- a/python/tests/test_field_filter_query.py +++ b/python/tests/test_field_filter_query.py @@ -590,10 +590,44 @@ def test_validation_independent_of_field_filter(self): reader.query_table_by_row( TABLE_NAME, COLUMN_NAMES, offset=-1, field_filter=field_filter ) - with pytest.raises(InvalidArgumentError): - reader.query_table_by_row(TABLE_NAME, [], field_filter=field_filter) - with pytest.raises(InvalidArgumentError): - reader.query_table(TABLE_NAME, [], field_filter=field_filter) + + @pytest.mark.parametrize("by_row", [False, True]) + @pytest.mark.parametrize("batch_size", [-1, 0, 3]) + def test_time_only_projection(self, by_row, batch_size): + with TsFileReader(TSFILE_PATH) as reader: + query = reader.query_table_by_row if by_row else reader.query_table + for predicate, expected in [ + (None, range(20)), + (field_gt("value", 16), range(17, 20)), + ]: + with query( + TABLE_NAME, iter(()), field_filter=predicate, batch_size=batch_size + ) as result: + times = [] + if batch_size > 0: + while (batch := result.read_arrow_batch()) is not None: + assert batch.num_columns == 1 + times.extend(batch.column(0).to_pylist()) + else: + while result.next(): + times.append(result.get_value_by_index(1)) + assert sorted(times) == list(expected) + + def test_active_results_keep_their_batch_mode(self): + with TsFileReader(TSFILE_PATH) as reader: + with reader.query_table(TABLE_NAME, ["value"], batch_size=-1) as rows: + with reader.query_table_by_row( + TABLE_NAME, + ["value"], + batch_size=2, + field_filter=field_gt("value", 16), + ) as batches: + assert rows.next() + assert sum(1 for _ in iter(rows.next, False)) == 19 + values = [] + while (batch := batches.read_arrow_batch()) is not None: + values.extend(batch.column("value").to_pylist()) + assert sorted(values) == [17, 18, 19] class TestFieldFilterCoverage: @@ -663,5 +697,3 @@ def test_column_names_accept_sequences(self): while result.next(): rows += 1 assert rows == 20 - with pytest.raises(InvalidArgumentError): - reader.query_table(TABLE_NAME, iter(())) diff --git a/python/tsfile/tsfile_py_cpp.pyx b/python/tsfile/tsfile_py_cpp.pyx index 841bc3215..5b0832f48 100644 --- a/python/tsfile/tsfile_py_cpp.pyx +++ b/python/tsfile/tsfile_py_cpp.pyx @@ -1150,31 +1150,9 @@ cdef bint tsfile_result_set_is_null_by_name_c(ResultSet result_set, object name) cdef ResultSet tsfile_reader_query_table_c(TsFileReader reader, object table_name, object column_list, int64_t start_time, int64_t end_time): - cdef ResultSet result - cdef int column_num = len(column_list) - cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) - cdef const char * table_name_c = table_name_bytes - cdef char** columns = malloc(sizeof(char *) * column_num) - cdef int i - cdef ErrorCode code = 0 - if columns == NULL: - raise MemoryError("Failed to allocate memory for columns") - memset(columns, 0, sizeof(char *) * column_num) - try: - for i in range(column_num): - columns[i] = strdup(( column_list[i]).encode('utf-8')) - if columns[i] == NULL: - raise MemoryError("Failed to allocate memory for column name") - result = tsfile_query_table(reader, table_name_c, columns, column_num, start_time, end_time, &code) - check_error(code) - return result - finally: - if columns != NULL: - for i in range(column_num): - free( columns[i]) - columns[i] = NULL - free( columns) - columns = NULL + return tsfile_query_table_with_filters_c(reader, table_name, column_list, + start_time, end_time, 0, -1, NULL, NULL, 0) + cdef ResultSet tsfile_reader_query_table_on_tree_c(TsFileReader reader, object column_list, int64_t start_time, int64_t end_time): @@ -1260,68 +1238,16 @@ cdef ResultSet tsfile_reader_query_table_by_row_c(TsFileReader reader, int offset, int limit, void* tag_filter, int batch_size): - cdef ResultSet result - cdef int column_num = len(column_list) - cdef char** columns = malloc(sizeof(char *) * column_num) - cdef int i - cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) - cdef const char * table_name_c = table_name_bytes - cdef ErrorCode code = 0 + return tsfile_reader_query_table_by_row_with_filters_c(reader, table_name, + column_list, offset, limit, tag_filter, NULL, batch_size) - if columns == NULL: - raise MemoryError("Failed to allocate memory for table by-row query columns") - memset(columns, 0, sizeof(char *) * column_num) - try: - for i in range(column_num): - columns[i] = strdup(( column_list[i]).encode('utf-8')) - if columns[i] == NULL: - raise MemoryError("Failed to allocate memory for column name") - - result = tsfile_reader_query_table_by_row(reader, - table_name_c, columns, column_num, - offset, limit, tag_filter, batch_size, &code) - check_error(code) - return result - finally: - if columns != NULL: - for i in range(column_num): - if columns[i] != NULL: - free( columns[i]) - columns[i] = NULL - free( columns) - columns = NULL cdef ResultSet tsfile_reader_query_table_batch_c(TsFileReader reader, object table_name, object column_list, int64_t start_time, int64_t end_time, void* tag_filter, int batch_size): - cdef ResultSet result - cdef int column_num = len(column_list) - cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) - cdef const char * table_name_c = table_name_bytes - cdef char** columns = malloc(sizeof(char *) * column_num) - cdef int i - cdef ErrorCode code = 0 - if columns == NULL: - raise MemoryError("Failed to allocate memory for columns") - memset(columns, 0, sizeof(char *) * column_num) - try: - for i in range(column_num): - columns[i] = strdup(( column_list[i]).encode('utf-8')) - if columns[i] == NULL: - raise MemoryError("Failed to allocate memory for column name") - result = tsfile_query_table_batch(reader, table_name_c, columns, - column_num, start_time, end_time, - tag_filter, batch_size, &code) - check_error(code) - return result - finally: - if columns != NULL: - for i in range(column_num): - if columns[i] != NULL: - free( columns[i]) - columns[i] = NULL - free( columns) - columns = NULL + return tsfile_query_table_with_filters_c(reader, table_name, column_list, + start_time, end_time, 0, -1, tag_filter, NULL, batch_size) + cdef ResultSet tsfile_reader_query_paths_c(TsFileReader reader, object device_name, object sensor_list, int64_t start_time, @@ -1358,97 +1284,55 @@ cdef ResultSet tsfile_reader_query_table_with_tag_filter_c(TsFileReader reader, object column_list, int64_t start_time, int64_t end_time, void* tag_filter, int batch_size): + return tsfile_query_table_with_filters_c(reader, table_name, column_list, + start_time, end_time, 0, -1, tag_filter, NULL, batch_size) + + +cdef ResultSet _query_table(TsFileReader reader, object table_name, object column_list, + bint by_row, int64_t start_time, int64_t end_time, + int offset, int limit, void* tag_filter, void* field_filter, + int batch_size): cdef ResultSet result - cdef int column_num = len(column_list) - cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) - cdef const char * table_name_c = table_name_bytes - cdef char** columns = malloc(sizeof(char *) * column_num) - cdef int i + cdef int count = len(column_list) + cdef bytes table = table_name.encode('utf-8') + cdef list names = [name.encode('utf-8') for name in column_list] + cdef char** columns = NULL cdef ErrorCode code = 0 - if columns == NULL: - raise MemoryError("Failed to allocate memory for columns") - memset(columns, 0, sizeof(char *) * column_num) + cdef int i + if count: + columns = malloc(sizeof(char*) * count) + if columns == NULL: + raise MemoryError("Failed to allocate table query columns") try: - for i in range(column_num): - columns[i] = strdup(( column_list[i]).encode('utf-8')) - if columns[i] == NULL: - raise MemoryError("Failed to allocate memory for column name") - result = tsfile_query_table_with_tag_filter(reader, table_name_c, columns, column_num, - start_time, end_time, tag_filter, batch_size, &code) + for i in range(count): + columns[i] = names[i] + if by_row: + result = tsfile_reader_query_table_by_row_with_filters( + reader, table, columns, count, offset, limit, tag_filter, + field_filter, batch_size, &code) + else: + result = tsfile_query_table_with_filters( + reader, table, columns, count, start_time, end_time, offset, + limit, tag_filter, field_filter, batch_size, &code) check_error(code) return result finally: - if columns != NULL: - for i in range(column_num): - free( columns[i]) - columns[i] = NULL - free( columns) - columns = NULL + free(columns) cdef ResultSet tsfile_query_table_with_filters_c( TsFileReader reader, object table_name, object column_list, int64_t start_time, int64_t end_time, int offset, int limit, void* tag_filter, void* field_filter, int batch_size): - cdef ResultSet result - cdef int column_num = len(column_list) - cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) - cdef const char * table_name_c = table_name_bytes - cdef char** columns = malloc(sizeof(char *) * column_num) - cdef int i - cdef ErrorCode code = 0 - if columns == NULL: - raise MemoryError("Failed to allocate memory for columns") - memset(columns, 0, sizeof(char *) * column_num) - try: - for i in range(column_num): - columns[i] = strdup(( column_list[i]).encode('utf-8')) - if columns[i] == NULL: - raise MemoryError("Failed to allocate memory for column name") - result = tsfile_query_table_with_filters( - reader, table_name_c, columns, column_num, start_time, end_time, - offset, limit, tag_filter, field_filter, batch_size, &code) - check_error(code) - return result - finally: - if columns != NULL: - for i in range(column_num): - if columns[i] != NULL: - free( columns[i]) - columns[i] = NULL - free( columns) - columns = NULL + return _query_table(reader, table_name, column_list, False, start_time, end_time, + offset, limit, tag_filter, field_filter, batch_size) + cdef ResultSet tsfile_reader_query_table_by_row_with_filters_c( TsFileReader reader, object table_name, object column_list, int offset, int limit, void* tag_filter, void* field_filter, int batch_size): - cdef ResultSet result - cdef int column_num = len(column_list) - cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) - cdef const char * table_name_c = table_name_bytes - cdef char** columns = malloc(sizeof(char *) * column_num) - cdef int i - cdef ErrorCode code = 0 - if columns == NULL: - raise MemoryError("Failed to allocate memory for table by-row query columns") - memset(columns, 0, sizeof(char *) * column_num) - try: - for i in range(column_num): - columns[i] = strdup(( column_list[i]).encode('utf-8')) - if columns[i] == NULL: - raise MemoryError("Failed to allocate memory for column name") - result = tsfile_reader_query_table_by_row_with_filters( - reader, table_name_c, columns, column_num, offset, limit, - tag_filter, field_filter, batch_size, &code) - check_error(code) - return result - finally: - if columns != NULL: - for i in range(column_num): - if columns[i] != NULL: - free( columns[i]) - columns[i] = NULL - free( columns) - columns = NULL + return _query_table(reader, table_name, column_list, True, 0, 0, + offset, limit, tag_filter, field_filter, batch_size) + cdef object get_table_schema(TsFileReader reader, object table_name): cdef bytes table_name_bytes = PyUnicode_AsUTF8String(table_name) diff --git a/python/tsfile/tsfile_reader.pyx b/python/tsfile/tsfile_reader.pyx index 723be4c66..410162d21 100644 --- a/python/tsfile/tsfile_reader.pyx +++ b/python/tsfile/tsfile_reader.pyx @@ -70,7 +70,9 @@ _PREPARED_CACHE_MAX_COLUMNS = 16 # The native clone()/bind() implementations recurse once per filter-tree level # and the builder here recurses too, so depth is capped instead of being able # to overflow the C stack. -_MAX_FIELD_FILTER_DEPTH = 512 +cdef extern from "reader/filter/aligned_field_filter.h": + enum: + _MAX_FIELD_FILTER_DEPTH "storage::AlignedFieldFilter::MAX_HEIGHT" cdef FieldFilterHandle _make_field_comparison( TsFileReader reader, bytes table_bytes, bytes column_bytes, int op, @@ -118,10 +120,6 @@ cdef class ResultSetPy: # Tag filter handle owned by this result set (freed on close). cdef TagFilterHandle _tag_filter_handle - # Field filter handle owned by this result set (freed on close). The native - # query receives a copy, so the handle can be released with the result. - cdef FieldFilterHandle _field_filter_handle - # ResultSet is valid or not, if the reader is closed, valid will be False. cdef object valid # The reader @@ -135,7 +133,6 @@ cdef class ResultSetPy: self.tsfile_reader = weakref.ref(tsfile_reader) self.is_tree = is_tree self._tag_filter_handle = NULL - self._field_filter_handle = NULL cdef init_c(self, ResultSet result, object device_name): """ @@ -375,10 +372,6 @@ cdef class ResultSetPy: tsfile_tag_filter_free(self._tag_filter_handle) self._tag_filter_handle = NULL - if self._field_filter_handle != NULL: - tsfile_field_filter_free(self._field_filter_handle) - self._field_filter_handle = NULL - if self.tsfile_reader is not None: reader = self.tsfile_reader() if reader is not None: @@ -485,7 +478,7 @@ cdef class TsFileReaderPy: :param field_filter: Optional FieldFilter to filter by FIELD column values. The predicate is pushed down natively and disables the prepared-series cache for this query. - :raises InvalidArgumentError: if column_names is empty. + :param column_names: Projected columns. An empty sequence selects only time. :raises ValueError: if field_filter exceeds the 512-level height limit. :return: query result handler. """ @@ -493,12 +486,7 @@ cdef class TsFileReaderPy: cdef TagFilterHandle c_tag_filter = NULL cdef FieldFilterHandle c_field_filter = NULL cdef ResultSetPy pyresult - # len() rather than truthiness so numpy arrays / pandas Index work; - # materialise once so unsized iterables (generators) keep working. column_names = list(column_names) - if len(column_names) == 0: - raise InvalidArgumentError( - context="column_names must not be empty") if (self._prepared_query_cache_size > 0 and batch_size > 0 and 0 < len(column_names) < _PREPARED_CACHE_MAX_COLUMNS and tag_filter is not None and field_filter is None): @@ -533,23 +521,13 @@ cdef class TsFileReaderPy: if field_filter is not None: c_field_filter = self._build_c_field_filter( table_name.lower(), field_filter, 0) - pyresult._field_filter_handle = c_field_filter - if field_filter is not None: + try: result = tsfile_query_table_with_filters_c( self.reader, table_name.lower(), - [column_name.lower() for column_name in column_names], - start_time, end_time, 0, -1, c_tag_filter, c_field_filter, - batch_size) - elif batch_size <= 0: - result = tsfile_reader_query_table_with_tag_filter_c( - self.reader, table_name.lower(), - [column_name.lower() for column_name in column_names], - start_time, end_time, c_tag_filter, batch_size) - else: - result = tsfile_reader_query_table_batch_c( - self.reader, table_name.lower(), - [column_name.lower() for column_name in column_names], - start_time, end_time, c_tag_filter, batch_size) + [column.lower() for column in column_names], + start_time, end_time, 0, -1, c_tag_filter, c_field_filter, batch_size) + finally: + tsfile_field_filter_free(c_field_filter) pyresult.init_c(result, table_name) self.activate_result_set_list.add(pyresult) return pyresult @@ -769,16 +747,16 @@ cdef class TsFileReaderPy: ComparisonFieldFilter.LTEQ, field_filter.upper, field_filter.upper_type) handle = tsfile_field_filter_and(left, right) - left = NULL - right = NULL if handle == NULL: raise MemoryError("Unable to allocate BETWEEN field filter") + left = NULL + right = NULL if field_filter.is_not: out = tsfile_field_filter_not(handle) - handle = NULL if out == NULL: raise MemoryError( "Unable to allocate NOT BETWEEN field filter") + handle = NULL else: out = handle handle = NULL @@ -787,32 +765,20 @@ cdef class TsFileReaderPy: tsfile_field_filter_free(left) tsfile_field_filter_free(right) tsfile_field_filter_free(handle) - elif isinstance(field_filter, AndFieldFilter): + elif isinstance(field_filter, (AndFieldFilter, OrFieldFilter)): try: left = self._build_c_field_filter( table_name, field_filter.left, depth + 1) right = self._build_c_field_filter( table_name, field_filter.right, depth + 1) - out = tsfile_field_filter_and(left, right) - left = NULL - right = NULL + if isinstance(field_filter, AndFieldFilter): + out = tsfile_field_filter_and(left, right) + else: + out = tsfile_field_filter_or(left, right) if out == NULL: raise MemoryError("Unable to allocate compound field filter") - return out - finally: - tsfile_field_filter_free(left) - tsfile_field_filter_free(right) - elif isinstance(field_filter, OrFieldFilter): - try: - left = self._build_c_field_filter( - table_name, field_filter.left, depth + 1) - right = self._build_c_field_filter( - table_name, field_filter.right, depth + 1) - out = tsfile_field_filter_or(left, right) left = NULL right = NULL - if out == NULL: - raise MemoryError("Unable to allocate compound field filter") return out finally: tsfile_field_filter_free(left) @@ -839,9 +805,9 @@ cdef class TsFileReaderPy: inner = NULL return out out = tsfile_field_filter_not(inner) - inner = NULL if out == NULL: raise MemoryError("Unable to allocate compound field filter") + inner = NULL return out finally: tsfile_field_filter_free(inner) @@ -895,8 +861,8 @@ cdef class TsFileReaderPy: :param tag_filter: Optional TagFilter to filter by TAG column values. :param field_filter: Optional FieldFilter to filter by FIELD column values, pushed down natively. OFFSET/LIMIT count accepted rows. - :raises InvalidArgumentError: if column_names is empty or offset is - negative. + :param column_names: Projected columns. An empty sequence selects only time. + :raises InvalidArgumentError: if offset is negative. :raises ValueError: if field_filter exceeds the 512-level height limit. """ @@ -904,12 +870,7 @@ cdef class TsFileReaderPy: cdef TagFilterHandle c_tag_filter = NULL cdef FieldFilterHandle c_field_filter = NULL pyresult = ResultSetPy(self) - # len() rather than truthiness so numpy arrays / pandas Index work; - # materialise once so unsized iterables (generators) keep working. column_names = list(column_names) - if len(column_names) == 0: - raise InvalidArgumentError( - context="column_names must not be empty") if offset < 0: raise InvalidArgumentError( context=f"offset must be >= 0, got {offset}") @@ -919,16 +880,13 @@ cdef class TsFileReaderPy: if field_filter is not None: c_field_filter = self._build_c_field_filter( table_name.lower(), field_filter, 0) - pyresult._field_filter_handle = c_field_filter - if field_filter is not None: + try: result = tsfile_reader_query_table_by_row_with_filters_c( self.reader, table_name.lower(), - [column_name.lower() for column_name in column_names], + [column.lower() for column in column_names], offset, limit, c_tag_filter, c_field_filter, batch_size) - else: - result = tsfile_reader_query_table_by_row_c(self.reader, table_name.lower(), - [column_name.lower() for column_name in column_names], - offset, limit, c_tag_filter, batch_size) + finally: + tsfile_field_filter_free(c_field_filter) pyresult.init_c(result, table_name) self.activate_result_set_list.add(pyresult) return pyresult diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index a470bb926..0c28aae7b 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -89,12 +89,13 @@ comparison also excludes NULL cells. `TypeMismatchError` instead of being narrowed. String literals require a string-like column and raise `TypeMismatchError` otherwise. `None` is rejected -- use the IS NULL predicates. A `field_filter` disables the - prepared-series cache for that query. + prepared-series cache for that query. An empty projection returns only + timestamps, including when a FIELD predicate is supplied. - C wrapper: build handles with `tsfile_field_filter_create_checked`, - compose with `tsfile_field_filter_and` / `_or` / `_not` (each consumes its - non-NULL inputs whether or not it succeeds -- unlike the TAG API, which keeps - them on failure -- and requires distinct handles), and release the result - with `tsfile_field_filter_free`. `and`/`or` reject an operand at 512 levels + compose with `tsfile_field_filter_and` / `_or` / `_not` and release the result + with `tsfile_field_filter_free`. As with TAG, a successful composition takes + ownership of its inputs. On failure the caller retains each handle. Binary + operands must be distinct. `and`/`or` reject an operand at 512 levels (the result would be 513 deep); `not` accepts a 512-level tree because negation preserves its height. The Python builder applies the same height limit and raises `ValueError` for deeper trees. Pass TAG and FIELD handles From cef5344ab7ee3f76181b9d98edcfc5475bfd1034 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 11:18:11 +0800 Subject: [PATCH 08/10] Move TAG and FIELD filter C wrappers into a separate source file --- cpp/src/cwrapper/CMakeLists.txt | 2 +- cpp/src/cwrapper/tsfile_cwrapper.cc | 488 ------------------- cpp/src/cwrapper/tsfile_cwrapper_filter.cc | 519 +++++++++++++++++++++ 3 files changed, 520 insertions(+), 489 deletions(-) create mode 100644 cpp/src/cwrapper/tsfile_cwrapper_filter.cc diff --git a/cpp/src/cwrapper/CMakeLists.txt b/cpp/src/cwrapper/CMakeLists.txt index d62250bf0..59ce8599a 100644 --- a/cpp/src/cwrapper/CMakeLists.txt +++ b/cpp/src/cwrapper/CMakeLists.txt @@ -18,7 +18,7 @@ under the License. ]] message("Running in cwrapper directory") set(CMAKE_POSITION_INDEPENDENT_CODE ON) -set(CWRAPPER_SRC_LIST tsfile_cwrapper.cc arrow_c.cc) +set(CWRAPPER_SRC_LIST tsfile_cwrapper.cc tsfile_cwrapper_filter.cc arrow_c.cc) add_library(cwrapper_obj OBJECT ${CWRAPPER_SRC_LIST}) # install header files diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index 0f7b1fc7b..4ec5c1f26 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -43,8 +43,6 @@ #include "common/statistic.h" #include "common/tablet.h" #include "common/tsfile_common.h" -#include "reader/filter/aligned_field_filter.h" -#include "reader/filter/tag_filter.h" #include "reader/result_set.h" #include "reader/table_result_set.h" #include "reader/tsfile_reader.h" @@ -2748,492 +2746,6 @@ ResultSet _tsfile_reader_query_device(TsFileReader reader, return qds; } -// ============== Tag Filter API Implementation ============== - -#define DEFINE_TAG_FILTER_FACTORY(name, op) \ - TagFilterHandle tsfile_tag_filter_##name( \ - TsFileReader reader, const char* table_name, const char* column_name, \ - const char* value) { \ - ERRNO error_code = common::E_OK; \ - return tsfile_tag_filter_create(reader, table_name, column_name, \ - value, TAG_FILTER_##op, &error_code); \ - } - -DEFINE_TAG_FILTER_FACTORY(eq, EQ) -DEFINE_TAG_FILTER_FACTORY(neq, NEQ) -DEFINE_TAG_FILTER_FACTORY(lt, LT) -DEFINE_TAG_FILTER_FACTORY(lteq, LTEQ) -DEFINE_TAG_FILTER_FACTORY(gt, GT) -DEFINE_TAG_FILTER_FACTORY(gteq, GTEQ) - -#undef DEFINE_TAG_FILTER_FACTORY - -ERRNO tsfile_tag_filter_create_checked(TsFileReader reader, - const char* table_name, - const char* column_name, - const char* value, TagFilterOp op, - TagFilterHandle* out_filter) { - if (out_filter != nullptr) { - *out_filter = nullptr; - } - if (reader == nullptr || table_name == nullptr || column_name == nullptr || - out_filter == nullptr || - (value == nullptr && op != TAG_FILTER_IS_NULL && - op != TAG_FILTER_IS_NOT_NULL)) { - return common::E_INVALID_ARG; - } - try { - auto* r = static_cast(reader); - std::shared_ptr schema; - const int ret = r->get_table_schema(table_name, schema); - if (ret != common::E_OK) { - return ret; - } - storage::TagFilterBuilder builder(schema.get()); - storage::Filter* filter = nullptr; - switch (op) { - case TAG_FILTER_EQ: - filter = builder.eq(column_name, value); - break; - case TAG_FILTER_NEQ: - filter = builder.neq(column_name, value); - break; - case TAG_FILTER_LT: - filter = builder.lt(column_name, value); - break; - case TAG_FILTER_LTEQ: - filter = builder.lteq(column_name, value); - break; - case TAG_FILTER_GT: - filter = builder.gt(column_name, value); - break; - case TAG_FILTER_GTEQ: - filter = builder.gteq(column_name, value); - break; - case TAG_FILTER_REGEXP: - filter = builder.reg_exp(column_name, value); - break; - case TAG_FILTER_NOT_REGEXP: - filter = builder.not_reg_exp(column_name, value); - break; - case TAG_FILTER_IS_NULL: - filter = builder.is_null(column_name); - break; - case TAG_FILTER_IS_NOT_NULL: - filter = builder.is_not_null(column_name); - break; - default: - return common::E_INVALID_ARG; - } - if (filter == nullptr) { - return common::E_COLUMN_NOT_EXIST; - } - *out_filter = static_cast(filter); - return common::E_OK; - } catch (const std::bad_alloc&) { - return common::E_OOM; - } catch (...) { - return common::E_FILE_READ_ERR; - } -} - -TagFilterHandle tsfile_tag_filter_create(TsFileReader reader, - const char* table_name, - const char* column_name, - const char* value, TagFilterOp op, - ERRNO* err_code) { - if (err_code == nullptr) { - return nullptr; - } - TagFilterHandle filter = nullptr; - *err_code = tsfile_tag_filter_create_checked( - reader, table_name, column_name, value, op, &filter); - if (*err_code == common::E_TABLE_NOT_EXIST) { - *err_code = common::E_INVALID_ARG; - } - return *err_code == common::E_OK ? filter : nullptr; -} - -ERRNO tsfile_tag_filter_between_checked(TsFileReader reader, - const char* table_name, - const char* column_name, - const char* lower, const char* upper, - bool is_not, - TagFilterHandle* out_filter) { - if (out_filter != nullptr) { - *out_filter = nullptr; - } - if (reader == nullptr || table_name == nullptr || column_name == nullptr || - lower == nullptr || upper == nullptr || out_filter == nullptr) { - return common::E_INVALID_ARG; - } - try { - auto* r = static_cast(reader); - std::shared_ptr schema; - const int ret = r->get_table_schema(table_name, schema); - if (ret != common::E_OK) { - return ret; - } - storage::TagFilterBuilder builder(schema.get()); - storage::Filter* filter = - is_not ? builder.not_between_and(column_name, lower, upper) - : builder.between_and(column_name, lower, upper); - if (filter == nullptr) { - return common::E_COLUMN_NOT_EXIST; - } - *out_filter = static_cast(filter); - return common::E_OK; - } catch (const std::bad_alloc&) { - return common::E_OOM; - } catch (...) { - return common::E_FILE_READ_ERR; - } -} - -TagFilterHandle tsfile_tag_filter_between(TsFileReader reader, - const char* table_name, - const char* column_name, - const char* lower, const char* upper, - bool is_not, ERRNO* err_code) { - if (err_code == nullptr) { - return nullptr; - } - TagFilterHandle filter = nullptr; - *err_code = tsfile_tag_filter_between_checked( - reader, table_name, column_name, lower, upper, is_not, &filter); - if (*err_code == common::E_TABLE_NOT_EXIST) { - *err_code = common::E_INVALID_ARG; - } - return *err_code == common::E_OK ? filter : nullptr; -} - -TagFilterHandle tsfile_tag_filter_and(TagFilterHandle left, - TagFilterHandle right) { - if (!left || !right) return nullptr; - try { - return storage::TagFilterBuilder::and_filter( - static_cast(left), - static_cast(right)); - } catch (...) { - return nullptr; - } -} - -TagFilterHandle tsfile_tag_filter_or(TagFilterHandle left, - TagFilterHandle right) { - if (!left || !right) return nullptr; - try { - return storage::TagFilterBuilder::or_filter( - static_cast(left), - static_cast(right)); - } catch (...) { - return nullptr; - } -} - -TagFilterHandle tsfile_tag_filter_not(TagFilterHandle filter) { - if (!filter) return nullptr; - try { - return storage::TagFilterBuilder::not_filter( - static_cast(filter)); - } catch (...) { - return nullptr; - } -} - -void tsfile_tag_filter_free(TagFilterHandle filter) { - if (filter) { - delete static_cast(filter); - } -} - -ResultSet tsfile_query_table_with_tag_filter( - TsFileReader reader, const char* table_name, char** columns, - uint32_t column_num, Timestamp start_time, Timestamp end_time, - TagFilterHandle tag_filter, int batch_size, ERRNO* err_code) { - return tsfile_query_table_with_filters( - reader, table_name, columns, column_num, start_time, end_time, 0, -1, - tag_filter, nullptr, batch_size, err_code); -} - -// ============== Field Filter API Implementation ============== - -namespace { - -storage::AlignedFieldFilter::CompareOp to_field_compare_op(FieldFilterOp op, - bool* valid) { - using CompareOp = storage::AlignedFieldFilter::CompareOp; - *valid = true; - switch (op) { - case FIELD_FILTER_EQ: - return CompareOp::EQ; - case FIELD_FILTER_NEQ: - return CompareOp::NE; - case FIELD_FILTER_LT: - return CompareOp::LT; - case FIELD_FILTER_LTEQ: - return CompareOp::LE; - case FIELD_FILTER_GT: - return CompareOp::GT; - case FIELD_FILTER_GTEQ: - return CompareOp::GE; - default: - *valid = false; - return CompareOp::EQ; - } -} - -// Builds the native literal for a comparison. Returns false for an unknown -// literal type or a NULL string payload. -bool to_field_literal(const FieldFilterValue& value, - storage::AlignedFieldFilter::Literal* literal) { - using Literal = storage::AlignedFieldFilter::Literal; - switch (value.type) { - case FIELD_FILTER_VALUE_BOOL: - *literal = Literal::boolean(value.bool_value); - return true; - case FIELD_FILTER_VALUE_INT64: - *literal = Literal::int64(value.int64_value); - return true; - case FIELD_FILTER_VALUE_DOUBLE: - *literal = Literal::float64(value.double_value); - return true; - case FIELD_FILTER_VALUE_STRING: - if (value.string_value == nullptr) { - return false; - } - *literal = Literal::string( - std::string(value.string_value, value.string_length)); - return true; - default: - return false; - } -} - -using FieldFilter = storage::AlignedFieldFilter; - -FieldFilter* as_field_filter(FieldFilterHandle handle) { - return dynamic_cast(static_cast(handle)); -} - -FieldFilterHandle combine_field_filters(FieldFilterHandle left, - FieldFilterHandle right, - bool conjunction) { - auto* lhs = as_field_filter(left); - auto* rhs = as_field_filter(right); - if (!lhs || !rhs || lhs == rhs) return nullptr; - try { - if (lhs->height() >= FieldFilter::MAX_HEIGHT || - rhs->height() >= FieldFilter::MAX_HEIGHT) - return nullptr; - return FieldFilter::adopt_binary(conjunction, lhs, rhs).release(); - } catch (...) { - return nullptr; - } -} - -// Copies a FIELD filter handle into a filter owned by the query call. The -// table query executor (and the result set) owns the filter it receives, so -// the caller's handle cannot be handed over directly. -storage::Filter* clone_field_filter(FieldFilterHandle field_filter, - ERRNO* err_code) { - auto* native = as_field_filter(field_filter); - if (native == nullptr || native->height() > FieldFilter::MAX_HEIGHT) { - *err_code = common::E_INVALID_ARG; - return nullptr; - } - // clone() reports allocation failure by throwing, which the caller turns - // into E_OOM. - return native->clone().release(); -} - -} // namespace - -ERRNO tsfile_field_filter_create_checked(TsFileReader reader, - const char* table_name, - const char* column_name, - FieldFilterOp op, - const FieldFilterValue* value, - FieldFilterHandle* out_filter) { - if (out_filter != nullptr) { - *out_filter = nullptr; - } - if (reader == nullptr || table_name == nullptr || column_name == nullptr || - out_filter == nullptr) { - return common::E_INVALID_ARG; - } - const bool needs_value = - op != FIELD_FILTER_IS_NULL && op != FIELD_FILTER_IS_NOT_NULL; - if (needs_value && value == nullptr) { - return common::E_INVALID_ARG; - } - using FieldFilter = storage::AlignedFieldFilter; - try { - auto* r = static_cast(reader); - std::shared_ptr schema; - int ret = r->get_table_schema(table_name, schema); - if (ret != common::E_OK) { - return ret; - } - if (schema == nullptr) { - return common::E_TABLE_NOT_EXIST; - } - - FieldFilter::Ptr filter; - if (op == FIELD_FILTER_IS_NULL) { - filter = FieldFilter::is_null(column_name); - } else if (op == FIELD_FILTER_IS_NOT_NULL) { - filter = FieldFilter::is_not_null(column_name); - } else { - bool valid_op = true; - const FieldFilter::CompareOp compare_op = - to_field_compare_op(op, &valid_op); - if (!valid_op) { - return common::E_INVALID_ARG; - } - FieldFilter::Literal literal; - if (!to_field_literal(*value, &literal)) { - return common::E_INVALID_ARG; - } - filter = FieldFilter::compare(column_name, compare_op, - std::move(literal)); - } - if (filter == nullptr) { - return common::E_OOM; - } - // Reject numeric literals that Java-style narrowing would alter on the - // creating table; the query re-checks them against the queried schema. - // Missing and non-FIELD columns are rejected here with the same codes - // bind() would return; the probe bind below additionally validates the - // literal type. - ret = filter->check_exact_literals(*schema); - if (ret != common::E_OK) { - return ret; - } - // Validate on a throwaway copy so the reusable handle keeps the - // caller's literal; the query-time clone is checked and bound against - // the schema of the table actually queried. - FieldFilter::Ptr probe = filter->clone(); - if (probe == nullptr) { - return common::E_OOM; - } - ret = probe->bind(*schema); - if (ret == common::E_NOT_SUPPORT) { - return common::E_TYPE_NOT_MATCH; - } - if (ret != common::E_OK) { - return ret; - } - *out_filter = static_cast(filter.release()); - return common::E_OK; - } catch (const std::bad_alloc&) { - return common::E_OOM; - } catch (...) { - return common::E_FILE_READ_ERR; - } -} - -FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, - FieldFilterHandle right) { - return combine_field_filters(left, right, true); -} - -FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, - FieldFilterHandle right) { - return combine_field_filters(left, right, false); -} - -FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter) { - auto* node = as_field_filter(filter); - if (!node) return nullptr; - try { - if (node->height() > FieldFilter::MAX_HEIGHT) return nullptr; - // Negation of a non-null tree rewrites it in place without allocation. - return FieldFilter::not_filter(FieldFilter::Ptr(node)).release(); - } catch (...) { - return nullptr; - } -} - -void tsfile_field_filter_free(FieldFilterHandle filter) { - if (filter != nullptr) { - // ~Filter is virtual, so this is also safe for a handle from the other - // family (TAG) that was passed by mistake. - delete static_cast(filter); - } -} - -namespace { - -ResultSet query_table_with_filters(TsFileReader reader, const char* table_name, - char** columns, uint32_t column_num, - const Timestamp* time_range, int offset, - int limit, TagFilterHandle tag_filter, - FieldFilterHandle field_filter, - int batch_size, ERRNO* err_code) { - if (!err_code) return nullptr; - *err_code = common::E_INVALID_ARG; - if (!reader || !table_name || (column_num && !columns) || offset < 0) - return nullptr; - try { - std::vector names; - names.reserve(column_num); - for (uint32_t i = 0; i < column_num; ++i) { - if (!columns[i]) return nullptr; - names.emplace_back(columns[i]); - } - const std::string table(table_name); - storage::Filter* copy = nullptr; - if (field_filter) { - copy = clone_field_filter(field_filter, err_code); - if (!copy) return nullptr; - } - auto* r = static_cast(reader); - auto* tag = static_cast(tag_filter); - storage::ResultSet* result = nullptr; - if (time_range) { - *err_code = r->query(table, names, time_range[0], time_range[1], - offset, limit, result, tag, copy, batch_size); - } else { - *err_code = r->queryByRow(table, names, offset, limit, result, tag, - copy, batch_size); - } - return *err_code == common::E_OK ? result : nullptr; - } catch (const std::bad_alloc&) { - *err_code = common::E_OOM; - } catch (...) { - *err_code = common::E_FILE_READ_ERR; - } - return nullptr; -} - -} // namespace - -ResultSet tsfile_query_table_with_filters( - TsFileReader reader, const char* table_name, char** columns, - uint32_t column_num, Timestamp start_time, Timestamp end_time, int offset, - int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, - int batch_size, ERRNO* err_code) { - const Timestamp range[] = {start_time, end_time}; - return query_table_with_filters(reader, table_name, columns, column_num, - range, offset, limit, tag_filter, - field_filter, batch_size, err_code); -} - -ResultSet tsfile_reader_query_table_by_row_with_filters( - TsFileReader reader, const char* table_name, char** column_names, - int column_names_len, int offset, int limit, TagFilterHandle tag_filter, - FieldFilterHandle field_filter, int batch_size, ERRNO* err_code) { - if (column_names_len < 0) { - if (err_code) *err_code = common::E_INVALID_ARG; - return nullptr; - } - return query_table_with_filters(reader, table_name, column_names, - static_cast(column_names_len), - nullptr, offset, limit, tag_filter, - field_filter, batch_size, err_code); -} - #ifdef __cplusplus } #endif diff --git a/cpp/src/cwrapper/tsfile_cwrapper_filter.cc b/cpp/src/cwrapper/tsfile_cwrapper_filter.cc new file mode 100644 index 000000000..d451e50fa --- /dev/null +++ b/cpp/src/cwrapper/tsfile_cwrapper_filter.cc @@ -0,0 +1,519 @@ +/* + * 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 "cwrapper/tsfile_cwrapper.h" +#include "reader/filter/aligned_field_filter.h" +#include "reader/filter/tag_filter.h" +#include "reader/tsfile_reader.h" + +extern "C" { + +// ============== Tag Filter API Implementation ============== + +#define DEFINE_TAG_FILTER_FACTORY(name, op) \ + TagFilterHandle tsfile_tag_filter_##name( \ + TsFileReader reader, const char* table_name, const char* column_name, \ + const char* value) { \ + ERRNO error_code = common::E_OK; \ + return tsfile_tag_filter_create(reader, table_name, column_name, \ + value, TAG_FILTER_##op, &error_code); \ + } + +DEFINE_TAG_FILTER_FACTORY(eq, EQ) +DEFINE_TAG_FILTER_FACTORY(neq, NEQ) +DEFINE_TAG_FILTER_FACTORY(lt, LT) +DEFINE_TAG_FILTER_FACTORY(lteq, LTEQ) +DEFINE_TAG_FILTER_FACTORY(gt, GT) +DEFINE_TAG_FILTER_FACTORY(gteq, GTEQ) + +#undef DEFINE_TAG_FILTER_FACTORY + +ERRNO tsfile_tag_filter_create_checked(TsFileReader reader, + const char* table_name, + const char* column_name, + const char* value, TagFilterOp op, + TagFilterHandle* out_filter) { + if (out_filter != nullptr) { + *out_filter = nullptr; + } + if (reader == nullptr || table_name == nullptr || column_name == nullptr || + out_filter == nullptr || + (value == nullptr && op != TAG_FILTER_IS_NULL && + op != TAG_FILTER_IS_NOT_NULL)) { + return common::E_INVALID_ARG; + } + try { + auto* r = static_cast(reader); + std::shared_ptr schema; + const int ret = r->get_table_schema(table_name, schema); + if (ret != common::E_OK) { + return ret; + } + storage::TagFilterBuilder builder(schema.get()); + storage::Filter* filter = nullptr; + switch (op) { + case TAG_FILTER_EQ: + filter = builder.eq(column_name, value); + break; + case TAG_FILTER_NEQ: + filter = builder.neq(column_name, value); + break; + case TAG_FILTER_LT: + filter = builder.lt(column_name, value); + break; + case TAG_FILTER_LTEQ: + filter = builder.lteq(column_name, value); + break; + case TAG_FILTER_GT: + filter = builder.gt(column_name, value); + break; + case TAG_FILTER_GTEQ: + filter = builder.gteq(column_name, value); + break; + case TAG_FILTER_REGEXP: + filter = builder.reg_exp(column_name, value); + break; + case TAG_FILTER_NOT_REGEXP: + filter = builder.not_reg_exp(column_name, value); + break; + case TAG_FILTER_IS_NULL: + filter = builder.is_null(column_name); + break; + case TAG_FILTER_IS_NOT_NULL: + filter = builder.is_not_null(column_name); + break; + default: + return common::E_INVALID_ARG; + } + if (filter == nullptr) { + return common::E_COLUMN_NOT_EXIST; + } + *out_filter = static_cast(filter); + return common::E_OK; + } catch (const std::bad_alloc&) { + return common::E_OOM; + } catch (...) { + return common::E_FILE_READ_ERR; + } +} + +TagFilterHandle tsfile_tag_filter_create(TsFileReader reader, + const char* table_name, + const char* column_name, + const char* value, TagFilterOp op, + ERRNO* err_code) { + if (err_code == nullptr) { + return nullptr; + } + TagFilterHandle filter = nullptr; + *err_code = tsfile_tag_filter_create_checked( + reader, table_name, column_name, value, op, &filter); + if (*err_code == common::E_TABLE_NOT_EXIST) { + *err_code = common::E_INVALID_ARG; + } + return *err_code == common::E_OK ? filter : nullptr; +} + +ERRNO tsfile_tag_filter_between_checked(TsFileReader reader, + const char* table_name, + const char* column_name, + const char* lower, const char* upper, + bool is_not, + TagFilterHandle* out_filter) { + if (out_filter != nullptr) { + *out_filter = nullptr; + } + if (reader == nullptr || table_name == nullptr || column_name == nullptr || + lower == nullptr || upper == nullptr || out_filter == nullptr) { + return common::E_INVALID_ARG; + } + try { + auto* r = static_cast(reader); + std::shared_ptr schema; + const int ret = r->get_table_schema(table_name, schema); + if (ret != common::E_OK) { + return ret; + } + storage::TagFilterBuilder builder(schema.get()); + storage::Filter* filter = + is_not ? builder.not_between_and(column_name, lower, upper) + : builder.between_and(column_name, lower, upper); + if (filter == nullptr) { + return common::E_COLUMN_NOT_EXIST; + } + *out_filter = static_cast(filter); + return common::E_OK; + } catch (const std::bad_alloc&) { + return common::E_OOM; + } catch (...) { + return common::E_FILE_READ_ERR; + } +} + +TagFilterHandle tsfile_tag_filter_between(TsFileReader reader, + const char* table_name, + const char* column_name, + const char* lower, const char* upper, + bool is_not, ERRNO* err_code) { + if (err_code == nullptr) { + return nullptr; + } + TagFilterHandle filter = nullptr; + *err_code = tsfile_tag_filter_between_checked( + reader, table_name, column_name, lower, upper, is_not, &filter); + if (*err_code == common::E_TABLE_NOT_EXIST) { + *err_code = common::E_INVALID_ARG; + } + return *err_code == common::E_OK ? filter : nullptr; +} + +TagFilterHandle tsfile_tag_filter_and(TagFilterHandle left, + TagFilterHandle right) { + if (!left || !right) return nullptr; + try { + return storage::TagFilterBuilder::and_filter( + static_cast(left), + static_cast(right)); + } catch (...) { + return nullptr; + } +} + +TagFilterHandle tsfile_tag_filter_or(TagFilterHandle left, + TagFilterHandle right) { + if (!left || !right) return nullptr; + try { + return storage::TagFilterBuilder::or_filter( + static_cast(left), + static_cast(right)); + } catch (...) { + return nullptr; + } +} + +TagFilterHandle tsfile_tag_filter_not(TagFilterHandle filter) { + if (!filter) return nullptr; + try { + return storage::TagFilterBuilder::not_filter( + static_cast(filter)); + } catch (...) { + return nullptr; + } +} + +void tsfile_tag_filter_free(TagFilterHandle filter) { + if (filter) { + delete static_cast(filter); + } +} + +ResultSet tsfile_query_table_with_tag_filter( + TsFileReader reader, const char* table_name, char** columns, + uint32_t column_num, Timestamp start_time, Timestamp end_time, + TagFilterHandle tag_filter, int batch_size, ERRNO* err_code) { + return tsfile_query_table_with_filters( + reader, table_name, columns, column_num, start_time, end_time, 0, -1, + tag_filter, nullptr, batch_size, err_code); +} + +// ============== Field Filter API Implementation ============== + +namespace { + +storage::AlignedFieldFilter::CompareOp to_field_compare_op(FieldFilterOp op, + bool* valid) { + using CompareOp = storage::AlignedFieldFilter::CompareOp; + *valid = true; + switch (op) { + case FIELD_FILTER_EQ: + return CompareOp::EQ; + case FIELD_FILTER_NEQ: + return CompareOp::NE; + case FIELD_FILTER_LT: + return CompareOp::LT; + case FIELD_FILTER_LTEQ: + return CompareOp::LE; + case FIELD_FILTER_GT: + return CompareOp::GT; + case FIELD_FILTER_GTEQ: + return CompareOp::GE; + default: + *valid = false; + return CompareOp::EQ; + } +} + +// Builds the native literal for a comparison. Returns false for an unknown +// literal type or a NULL string payload. +bool to_field_literal(const FieldFilterValue& value, + storage::AlignedFieldFilter::Literal* literal) { + using Literal = storage::AlignedFieldFilter::Literal; + switch (value.type) { + case FIELD_FILTER_VALUE_BOOL: + *literal = Literal::boolean(value.bool_value); + return true; + case FIELD_FILTER_VALUE_INT64: + *literal = Literal::int64(value.int64_value); + return true; + case FIELD_FILTER_VALUE_DOUBLE: + *literal = Literal::float64(value.double_value); + return true; + case FIELD_FILTER_VALUE_STRING: + if (value.string_value == nullptr) { + return false; + } + *literal = Literal::string( + std::string(value.string_value, value.string_length)); + return true; + default: + return false; + } +} + +using FieldFilter = storage::AlignedFieldFilter; + +FieldFilter* as_field_filter(FieldFilterHandle handle) { + return dynamic_cast(static_cast(handle)); +} + +FieldFilterHandle combine_field_filters(FieldFilterHandle left, + FieldFilterHandle right, + bool conjunction) { + auto* lhs = as_field_filter(left); + auto* rhs = as_field_filter(right); + if (!lhs || !rhs || lhs == rhs) return nullptr; + try { + if (lhs->height() >= FieldFilter::MAX_HEIGHT || + rhs->height() >= FieldFilter::MAX_HEIGHT) + return nullptr; + return FieldFilter::adopt_binary(conjunction, lhs, rhs).release(); + } catch (...) { + return nullptr; + } +} + +// Copies a FIELD filter handle into a filter owned by the query call. The +// table query executor (and the result set) owns the filter it receives, so +// the caller's handle cannot be handed over directly. +storage::Filter* clone_field_filter(FieldFilterHandle field_filter, + ERRNO* err_code) { + auto* native = as_field_filter(field_filter); + if (native == nullptr || native->height() > FieldFilter::MAX_HEIGHT) { + *err_code = common::E_INVALID_ARG; + return nullptr; + } + // clone() reports allocation failure by throwing, which the caller turns + // into E_OOM. + return native->clone().release(); +} + +} // namespace + +ERRNO tsfile_field_filter_create_checked(TsFileReader reader, + const char* table_name, + const char* column_name, + FieldFilterOp op, + const FieldFilterValue* value, + FieldFilterHandle* out_filter) { + if (out_filter != nullptr) { + *out_filter = nullptr; + } + if (reader == nullptr || table_name == nullptr || column_name == nullptr || + out_filter == nullptr) { + return common::E_INVALID_ARG; + } + const bool needs_value = + op != FIELD_FILTER_IS_NULL && op != FIELD_FILTER_IS_NOT_NULL; + if (needs_value && value == nullptr) { + return common::E_INVALID_ARG; + } + using FieldFilter = storage::AlignedFieldFilter; + try { + auto* r = static_cast(reader); + std::shared_ptr schema; + int ret = r->get_table_schema(table_name, schema); + if (ret != common::E_OK) { + return ret; + } + if (schema == nullptr) { + return common::E_TABLE_NOT_EXIST; + } + + FieldFilter::Ptr filter; + if (op == FIELD_FILTER_IS_NULL) { + filter = FieldFilter::is_null(column_name); + } else if (op == FIELD_FILTER_IS_NOT_NULL) { + filter = FieldFilter::is_not_null(column_name); + } else { + bool valid_op = true; + const FieldFilter::CompareOp compare_op = + to_field_compare_op(op, &valid_op); + if (!valid_op) { + return common::E_INVALID_ARG; + } + FieldFilter::Literal literal; + if (!to_field_literal(*value, &literal)) { + return common::E_INVALID_ARG; + } + filter = FieldFilter::compare(column_name, compare_op, + std::move(literal)); + } + if (filter == nullptr) { + return common::E_OOM; + } + // Reject numeric literals that Java-style narrowing would alter on the + // creating table; the query re-checks them against the queried schema. + // Missing and non-FIELD columns are rejected here with the same codes + // bind() would return; the probe bind below additionally validates the + // literal type. + ret = filter->check_exact_literals(*schema); + if (ret != common::E_OK) { + return ret; + } + // Validate on a throwaway copy so the reusable handle keeps the + // caller's literal; the query-time clone is checked and bound against + // the schema of the table actually queried. + FieldFilter::Ptr probe = filter->clone(); + if (probe == nullptr) { + return common::E_OOM; + } + ret = probe->bind(*schema); + if (ret == common::E_NOT_SUPPORT) { + return common::E_TYPE_NOT_MATCH; + } + if (ret != common::E_OK) { + return ret; + } + *out_filter = static_cast(filter.release()); + return common::E_OK; + } catch (const std::bad_alloc&) { + return common::E_OOM; + } catch (...) { + return common::E_FILE_READ_ERR; + } +} + +FieldFilterHandle tsfile_field_filter_and(FieldFilterHandle left, + FieldFilterHandle right) { + return combine_field_filters(left, right, true); +} + +FieldFilterHandle tsfile_field_filter_or(FieldFilterHandle left, + FieldFilterHandle right) { + return combine_field_filters(left, right, false); +} + +FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter) { + auto* node = as_field_filter(filter); + if (!node) return nullptr; + try { + if (node->height() > FieldFilter::MAX_HEIGHT) return nullptr; + // Negation of a non-null tree rewrites it in place without allocation. + return FieldFilter::not_filter(FieldFilter::Ptr(node)).release(); + } catch (...) { + return nullptr; + } +} + +void tsfile_field_filter_free(FieldFilterHandle filter) { + if (filter != nullptr) { + // ~Filter is virtual, so this is also safe for a handle from the other + // family (TAG) that was passed by mistake. + delete static_cast(filter); + } +} + +namespace { + +ResultSet query_table_with_filters(TsFileReader reader, const char* table_name, + char** columns, uint32_t column_num, + const Timestamp* time_range, int offset, + int limit, TagFilterHandle tag_filter, + FieldFilterHandle field_filter, + int batch_size, ERRNO* err_code) { + if (!err_code) return nullptr; + *err_code = common::E_INVALID_ARG; + if (!reader || !table_name || (column_num && !columns) || offset < 0) + return nullptr; + try { + std::vector names; + names.reserve(column_num); + for (uint32_t i = 0; i < column_num; ++i) { + if (!columns[i]) return nullptr; + names.emplace_back(columns[i]); + } + const std::string table(table_name); + storage::Filter* copy = nullptr; + if (field_filter) { + copy = clone_field_filter(field_filter, err_code); + if (!copy) return nullptr; + } + auto* r = static_cast(reader); + auto* tag = static_cast(tag_filter); + storage::ResultSet* result = nullptr; + if (time_range) { + *err_code = r->query(table, names, time_range[0], time_range[1], + offset, limit, result, tag, copy, batch_size); + } else { + *err_code = r->queryByRow(table, names, offset, limit, result, tag, + copy, batch_size); + } + return *err_code == common::E_OK ? result : nullptr; + } catch (const std::bad_alloc&) { + *err_code = common::E_OOM; + } catch (...) { + *err_code = common::E_FILE_READ_ERR; + } + return nullptr; +} + +} // namespace + +ResultSet tsfile_query_table_with_filters( + TsFileReader reader, const char* table_name, char** columns, + uint32_t column_num, Timestamp start_time, Timestamp end_time, int offset, + int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, + int batch_size, ERRNO* err_code) { + const Timestamp range[] = {start_time, end_time}; + return query_table_with_filters(reader, table_name, columns, column_num, + range, offset, limit, tag_filter, + field_filter, batch_size, err_code); +} + +ResultSet tsfile_reader_query_table_by_row_with_filters( + TsFileReader reader, const char* table_name, char** column_names, + int column_names_len, int offset, int limit, TagFilterHandle tag_filter, + FieldFilterHandle field_filter, int batch_size, ERRNO* err_code) { + if (column_names_len < 0) { + if (err_code) *err_code = common::E_INVALID_ARG; + return nullptr; + } + return query_table_with_filters(reader, table_name, column_names, + static_cast(column_names_len), + nullptr, offset, limit, tag_filter, + field_filter, batch_size, err_code); +} + +} // extern "C" From 8f0e37f516c460b50d2cdb8a98ecea088aa4a057 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 11:44:05 +0800 Subject: [PATCH 09/10] Use consistent column parameters for filtered table queries --- cpp/src/cwrapper/tsfile_cwrapper.cc | 9 ++++++-- cpp/src/cwrapper/tsfile_cwrapper.h | 10 +++++++-- cpp/src/cwrapper/tsfile_cwrapper_filter.cc | 11 +++------- cpp/test/cwrapper/cwrapper_extended_test.cc | 21 +++++++++++-------- python/tsfile/tsfile_cpp.pxd | 4 ++-- python/tsfile/tsfile_py_cpp.pyx | 17 ++++++++------- .../tsfile/references/properties-filters.md | 5 +++-- 7 files changed, 45 insertions(+), 32 deletions(-) diff --git a/cpp/src/cwrapper/tsfile_cwrapper.cc b/cpp/src/cwrapper/tsfile_cwrapper.cc index 4ec5c1f26..7986bdec2 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper.cc @@ -926,9 +926,14 @@ ResultSet tsfile_reader_query_table_by_row( TsFileReader reader, const char* table_name, char** column_names, int column_names_len, int offset, int limit, TagFilterHandle tag_filter, int batch_size, ERRNO* err_code) { + if (column_names_len < 0) { + if (err_code) *err_code = common::E_INVALID_ARG; + return nullptr; + } return tsfile_reader_query_table_by_row_with_filters( - reader, table_name, column_names, column_names_len, offset, limit, - tag_filter, nullptr, batch_size, err_code); + reader, table_name, column_names, + static_cast(column_names_len), offset, limit, tag_filter, + nullptr, batch_size, err_code); } ResultSet tsfile_reader_query_table(TsFileReader reader, const char* table_name, diff --git a/cpp/src/cwrapper/tsfile_cwrapper.h b/cpp/src/cwrapper/tsfile_cwrapper.h index cf571180d..0eaafcb2a 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper.h +++ b/cpp/src/cwrapper/tsfile_cwrapper.h @@ -993,6 +993,9 @@ ResultSet tsfile_reader_query_table(TsFileReader reader, const char* table_name, * comparisons never match NULL values; use FIELD_FILTER_IS_NULL / * FIELD_FILTER_IS_NOT_NULL for that. * + * @param columns [in] Requested column names. May be NULL when column_num is 0. + * @param column_num [in] Number of entries in columns. Use 0 for timestamps + * only. * @param start_time [in] Inclusive lower time bound. * @param end_time [in] Inclusive upper time bound. * @param offset [in] Number of leading result rows to skip (>= 0). @@ -1018,6 +1021,9 @@ ResultSet tsfile_query_table_with_filters( * * Both filters are optional and may be NULL. * + * @param columns [in] Requested column names. May be NULL when column_num is 0. + * @param column_num [in] Number of entries in columns. Use 0 for timestamps + * only. * @param offset [in] Number of leading accepted rows to skip (>= 0). * @param limit [in] Maximum accepted rows to return; < 0 means unlimited. * @param batch_size [in] > 0 returns TsBlock batches; <= 0 (including @@ -1027,8 +1033,8 @@ ResultSet tsfile_query_table_with_filters( * Ownership matches tsfile_query_table_with_filters(). */ ResultSet tsfile_reader_query_table_by_row_with_filters( - TsFileReader reader, const char* table_name, char** column_names, - int column_names_len, int offset, int limit, TagFilterHandle tag_filter, + TsFileReader reader, const char* table_name, char** columns, + uint32_t column_num, int offset, int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, int batch_size, ERRNO* err_code); ResultSet tsfile_query_table_batch(TsFileReader reader, const char* table_name, diff --git a/cpp/src/cwrapper/tsfile_cwrapper_filter.cc b/cpp/src/cwrapper/tsfile_cwrapper_filter.cc index d451e50fa..0b6738a47 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper_filter.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper_filter.cc @@ -503,15 +503,10 @@ ResultSet tsfile_query_table_with_filters( } ResultSet tsfile_reader_query_table_by_row_with_filters( - TsFileReader reader, const char* table_name, char** column_names, - int column_names_len, int offset, int limit, TagFilterHandle tag_filter, + TsFileReader reader, const char* table_name, char** columns, + uint32_t column_num, int offset, int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, int batch_size, ERRNO* err_code) { - if (column_names_len < 0) { - if (err_code) *err_code = common::E_INVALID_ARG; - return nullptr; - } - return query_table_with_filters(reader, table_name, column_names, - static_cast(column_names_len), + return query_table_with_filters(reader, table_name, columns, column_num, nullptr, offset, limit, tag_filter, field_filter, batch_size, err_code); } diff --git a/cpp/test/cwrapper/cwrapper_extended_test.cc b/cpp/test/cwrapper/cwrapper_extended_test.cc index 3f61b18f2..39261f5eb 100644 --- a/cpp/test/cwrapper/cwrapper_extended_test.cc +++ b/cpp/test/cwrapper/cwrapper_extended_test.cc @@ -679,8 +679,8 @@ TEST(CWrapperExtendedTest, FieldFilterSelectsRowsAndComposes) { &int_ge_one, &int_ge_one_filter)); ASSERT_NE(nullptr, int_ge_one_filter); ResultSet paged = tsfile_reader_query_table_by_row_with_filters( - reader, kTableName, columns.data(), static_cast(columns.size()), 1, - 2, nullptr, int_ge_one_filter, 0, &err); + reader, kTableName, columns.data(), columns.size(), 1, 2, nullptr, + int_ge_one_filter, 0, &err); ASSERT_EQ(RET_OK, err); ASSERT_NE(nullptr, paged); rows = collect_row_identities(paged, &err); @@ -694,8 +694,8 @@ TEST(CWrapperExtendedTest, FieldFilterSelectsRowsAndComposes) { // second device. A per-device reset would return 0 rows here, and // ignoring OFFSET entirely would return all 8. ResultSet crossed = tsfile_reader_query_table_by_row_with_filters( - reader, kTableName, columns.data(), static_cast(columns.size()), 5, - -1, nullptr, int_ge_one_filter, 0, &err); + reader, kTableName, columns.data(), columns.size(), 5, -1, nullptr, + int_ge_one_filter, 0, &err); ASSERT_EQ(RET_OK, err); ASSERT_NE(nullptr, crossed); rows = collect_row_identities(crossed, &err); @@ -967,13 +967,16 @@ TEST(CWrapperExtendedTest, FieldFilterValidatesColumnsAndTypes) { nullptr, nullptr, 0, &err)); EXPECT_EQ(RET_INVALID_ARG, err); EXPECT_EQ(nullptr, tsfile_reader_query_table_by_row_with_filters( - reader, kTableName, columns.data(), - static_cast(columns.size()), -1, -1, nullptr, - nullptr, 0, &err)); + reader, kTableName, columns.data(), columns.size(), + -1, -1, nullptr, nullptr, 0, &err)); EXPECT_EQ(RET_INVALID_ARG, err); EXPECT_EQ(nullptr, tsfile_reader_query_table_by_row_with_filters( - reader, kTableName, columns.data(), -1, 0, -1, - nullptr, nullptr, 0, &err)); + reader, kTableName, nullptr, 1, 0, -1, nullptr, + nullptr, 0, &err)); + EXPECT_EQ(RET_INVALID_ARG, err); + EXPECT_EQ(nullptr, tsfile_reader_query_table_by_row(reader, kTableName, + columns.data(), -1, 0, + -1, nullptr, 0, &err)); EXPECT_EQ(RET_INVALID_ARG, err); tsfile_reader_close(reader); diff --git a/python/tsfile/tsfile_cpp.pxd b/python/tsfile/tsfile_cpp.pxd index 118ea771a..a613e660a 100644 --- a/python/tsfile/tsfile_cpp.pxd +++ b/python/tsfile/tsfile_cpp.pxd @@ -518,8 +518,8 @@ cdef extern from "cwrapper/tsfile_cwrapper.h": FieldFilterHandle field_filter, int batch_size, ErrorCode* err_code) ResultSet tsfile_reader_query_table_by_row_with_filters( - TsFileReader reader, const char* table_name, char** column_names, - int column_names_len, int offset, int limit, + TsFileReader reader, const char* table_name, char** columns, + uint32_t column_num, int offset, int limit, TagFilterHandle tag_filter, FieldFilterHandle field_filter, int batch_size, ErrorCode* err_code) diff --git a/python/tsfile/tsfile_py_cpp.pyx b/python/tsfile/tsfile_py_cpp.pyx index 5b0832f48..cf28e94cf 100644 --- a/python/tsfile/tsfile_py_cpp.pyx +++ b/python/tsfile/tsfile_py_cpp.pyx @@ -25,6 +25,7 @@ import os import pandas as pd import numpy as np +from libc.stdint cimport UINT32_MAX from libc.stdlib cimport free from libc.stdlib cimport malloc from libc.string cimport strdup @@ -1293,26 +1294,28 @@ cdef ResultSet _query_table(TsFileReader reader, object table_name, object colum int offset, int limit, void* tag_filter, void* field_filter, int batch_size): cdef ResultSet result - cdef int count = len(column_list) cdef bytes table = table_name.encode('utf-8') cdef list names = [name.encode('utf-8') for name in column_list] cdef char** columns = NULL cdef ErrorCode code = 0 - cdef int i - if count: - columns = malloc(sizeof(char*) * count) + cdef uint32_t i, column_num + if len(names) > UINT32_MAX: + raise OverflowError("Table query column count exceeds uint32_t") + column_num = len(names) + if column_num: + columns = malloc(sizeof(char*) * column_num) if columns == NULL: raise MemoryError("Failed to allocate table query columns") try: - for i in range(count): + for i in range(column_num): columns[i] = names[i] if by_row: result = tsfile_reader_query_table_by_row_with_filters( - reader, table, columns, count, offset, limit, tag_filter, + reader, table, columns, column_num, offset, limit, tag_filter, field_filter, batch_size, &code) else: result = tsfile_query_table_with_filters( - reader, table, columns, count, start_time, end_time, offset, + reader, table, columns, column_num, start_time, end_time, offset, limit, tag_filter, field_filter, batch_size, &code) check_error(code) return result diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index 0c28aae7b..ff0fd0274 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -100,8 +100,9 @@ comparison also excludes NULL cells. negation preserves its height. The Python builder applies the same height limit and raises `ValueError` for deeper trees. Pass TAG and FIELD handles to `tsfile_query_table_with_filters` or - `tsfile_reader_query_table_by_row_with_filters`; the query copies the FIELD - filter, so the caller keeps ownership of the handle and may free it as soon + `tsfile_reader_query_table_by_row_with_filters`. Both take `char** columns` + and `uint32_t column_num`. Pass `NULL, 0` to return only timestamps. The query + copies the FIELD filter, so the caller keeps ownership and may free it as soon as the call returns. The TAG handle is not copied: it must stay alive until the result set is closed. - C++: build `storage::AlignedFieldFilter` trees with `compare`, `is_null`, From 8be8b3d3523c4d4de30911d7ac5f057726d00bfc Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 17:30:21 +0800 Subject: [PATCH 10/10] Share table predicate operators across TAG and FIELD filters --- cpp/src/cwrapper/tsfile_cwrapper_filter.cc | 3 +- cpp/src/reader/device_meta_iterator.cc | 6 +- cpp/src/reader/filter/aligned_field_filter.cc | 457 +++++++----------- cpp/src/reader/filter/aligned_field_filter.h | 54 ++- cpp/src/reader/filter/table_predicate.h | 90 ++++ cpp/src/reader/filter/tag_filter.cc | 203 +++----- cpp/src/reader/filter/tag_filter.h | 38 +- .../filter/aligned_field_filter_test.cc | 21 + cpp/test/reader/filter/tag_filter_test.cc | 39 +- .../tsfile/references/properties-filters.md | 7 +- 10 files changed, 438 insertions(+), 480 deletions(-) create mode 100644 cpp/src/reader/filter/table_predicate.h diff --git a/cpp/src/cwrapper/tsfile_cwrapper_filter.cc b/cpp/src/cwrapper/tsfile_cwrapper_filter.cc index 0b6738a47..5848e1434 100644 --- a/cpp/src/cwrapper/tsfile_cwrapper_filter.cc +++ b/cpp/src/cwrapper/tsfile_cwrapper_filter.cc @@ -430,8 +430,7 @@ FieldFilterHandle tsfile_field_filter_not(FieldFilterHandle filter) { if (!node) return nullptr; try { if (node->height() > FieldFilter::MAX_HEIGHT) return nullptr; - // Negation of a non-null tree rewrites it in place without allocation. - return FieldFilter::not_filter(FieldFilter::Ptr(node)).release(); + return FieldFilter::adopt_not(node).release(); } catch (...) { return nullptr; } diff --git a/cpp/src/reader/device_meta_iterator.cc b/cpp/src/reader/device_meta_iterator.cc index e57111e32..5fb50dafd 100644 --- a/cpp/src/reader/device_meta_iterator.cc +++ b/cpp/src/reader/device_meta_iterator.cc @@ -171,8 +171,10 @@ int DeviceMetaIterator::load_internal_node(MetaIndexNode* meta_index_node) { void DeviceMetaIterator::try_setup_direct_lookup(MetaIndexNode* root_node) { if (id_filter_ == nullptr || root_node == nullptr) return; - const auto* eq = dynamic_cast(id_filter_); - if (eq == nullptr) return; + const auto* eq = dynamic_cast(id_filter_); + if (eq == nullptr || eq->kind() != TablePredicate::Kind::COMPARISON || + eq->compare_op() != TablePredicate::CompareOp::EQ || eq->col_idx_ != 1) + return; if (root_node->children_.empty()) return; diff --git a/cpp/src/reader/filter/aligned_field_filter.cc b/cpp/src/reader/filter/aligned_field_filter.cc index 6ef41892d..b40f31488 100644 --- a/cpp/src/reader/filter/aligned_field_filter.cc +++ b/cpp/src/reader/filter/aligned_field_filter.cc @@ -32,25 +32,6 @@ namespace storage { namespace { -template -bool compare_values(T left, T right, AlignedFieldFilter::CompareOp op) { - switch (op) { - case AlignedFieldFilter::CompareOp::EQ: - return left == right; - case AlignedFieldFilter::CompareOp::NE: - return left != right; - case AlignedFieldFilter::CompareOp::LT: - return left < right; - case AlignedFieldFilter::CompareOp::LE: - return left <= right; - case AlignedFieldFilter::CompareOp::GT: - return left > right; - case AlignedFieldFilter::CompareOp::GE: - return left >= right; - } - return false; -} - AlignedFieldFilter::CompareOp negate_comparison( AlignedFieldFilter::CompareOp op) { using Op = AlignedFieldFilter::CompareOp; @@ -71,26 +52,6 @@ AlignedFieldFilter::CompareOp negate_comparison( return Op::EQ; } -int compare_string(const char* data, uint32_t len, const std::string& literal, - AlignedFieldFilter::CompareOp op) { - const std::string value(data, len); - switch (op) { - case AlignedFieldFilter::CompareOp::EQ: - return value == literal; - case AlignedFieldFilter::CompareOp::NE: - return value != literal; - case AlignedFieldFilter::CompareOp::LT: - return value < literal; - case AlignedFieldFilter::CompareOp::LE: - return value <= literal; - case AlignedFieldFilter::CompareOp::GT: - return value > literal; - case AlignedFieldFilter::CompareOp::GE: - return value >= literal; - } - return false; -} - // NaN values count as non-NULL, but may not change finite min/max values. // Their presence is retained in the sum, including after statistics merge. // A NaN sum can also result from opposite infinities; conservatively falling @@ -328,16 +289,13 @@ AlignedFieldFilter::Literal AlignedFieldFilter::Literal::string( } AlignedFieldFilter::AlignedFieldFilter(Kind kind, std::string column, - CompareOp op, Literal literal, - bool negated) - : kind_(kind), + CompareOp op, Literal literal) + : TablePredicate(kind, op), column_(std::move(column)), - compare_op_(op), - literal_(std::move(literal)), - negated_(negated) {} + literal_(std::move(literal)) {} AlignedFieldFilter::AlignedFieldFilter(Kind kind, Ptr left, Ptr right) - : kind_(kind), left_(std::move(left)), right_(std::move(right)) {} + : TablePredicate(kind, std::move(left), std::move(right)) {} AlignedFieldFilter::Ptr AlignedFieldFilter::compare(std::string column, CompareOp op, @@ -379,57 +337,30 @@ AlignedFieldFilter::Ptr AlignedFieldFilter::adopt_binary( } AlignedFieldFilter::Ptr AlignedFieldFilter::not_filter(Ptr child) { - if (!child) { - return Ptr(new AlignedFieldFilter(Kind::NOT, nullptr, nullptr)); - } - child->negate(); - return child; + Ptr result = adopt_not(child.get()); + child.release(); + return result; } -void AlignedFieldFilter::negate() noexcept { - switch (kind_) { - case Kind::COMPARISON: - // Ordered comparisons need explicit negation until binding, as - // flipping the operator changes the result for floating-point NaNs. - if (compare_op_ == CompareOp::EQ || compare_op_ == CompareOp::NE) { - compare_op_ = negate_comparison(compare_op_); - } else { - negated_ = !negated_; - } - break; - case Kind::IS_NULL: - kind_ = Kind::IS_NOT_NULL; - break; - case Kind::IS_NOT_NULL: - kind_ = Kind::IS_NULL; - break; - case Kind::AND: - case Kind::OR: - kind_ = kind_ == Kind::AND ? Kind::OR : Kind::AND; - if (left_) left_->negate(); - if (right_) right_->negate(); - break; - case Kind::NOT: - break; // Invalid operand marker. +AlignedFieldFilter::Ptr AlignedFieldFilter::adopt_not( + AlignedFieldFilter* child) { + if (child && child->kind() == Kind::NOT) { + // Cancel consecutive NOTs without growing the tree. A missing operand + // stays invalid even when negated again. + if (!child->left_) return Ptr(child); + Ptr wrapper(child); + return Ptr(static_cast(wrapper->left_.release())); } + Ptr parent(new AlignedFieldFilter(Kind::NOT, nullptr, nullptr)); + parent->left_.reset(child); + return parent; } AlignedFieldFilter::Ptr AlignedFieldFilter::clone() const { - switch (kind_) { - case Kind::COMPARISON: - case Kind::IS_NULL: - case Kind::IS_NOT_NULL: - return Ptr(new AlignedFieldFilter(kind_, column_, compare_op_, - literal_, negated_)); - case Kind::AND: - case Kind::OR: - return Ptr( - new AlignedFieldFilter(kind_, left_ ? left_->clone() : nullptr, - right_ ? right_->clone() : nullptr)); - case Kind::NOT: - return Ptr(new AlignedFieldFilter(Kind::NOT, nullptr, nullptr)); - } - return Ptr(new AlignedFieldFilter(Kind::NOT, nullptr, nullptr)); + Ptr copy(new AlignedFieldFilter(kind_, column_, compare_op_, literal_)); + if (left_) copy->left_ = left_field()->clone(); + if (right_) copy->right_ = right_field()->clone(); + return copy; } std::vector AlignedFieldFilter::referenced_columns() const { @@ -448,8 +379,8 @@ std::vector AlignedFieldFilter::referenced_columns() const { } continue; } - if (node->right_) stack.push_back(node->right_.get()); - if (node->left_) stack.push_back(node->left_.get()); + if (node->right_) stack.push_back(node->right_field()); + if (node->left_) stack.push_back(node->left_field()); } return columns; } @@ -461,39 +392,40 @@ bool AlignedFieldFilter::is_valid() const { case Kind::IS_NOT_NULL: return true; case Kind::NOT: - // Valid NOTs are pushed to leaves; only invalid markers remain. + return left_ && left_field()->is_valid(); + case Kind::BETWEEN: + case Kind::NOT_BETWEEN: + case Kind::REGEXP: + case Kind::NOT_REGEXP: + case Kind::CUSTOM: return false; case Kind::AND: case Kind::OR: - return left_ != nullptr && right_ != nullptr && left_->is_valid() && - right_->is_valid(); + return left_ != nullptr && right_ != nullptr && + left_field()->is_valid() && right_field()->is_valid(); } return false; } int AlignedFieldFilter::bind(TableSchema& schema) { - if (kind_ == Kind::NOT) return common::E_INVALID_ARG; + if (kind_ == Kind::NOT) { + return left_ + ? static_cast(left_.get())->bind(schema) + : common::E_INVALID_ARG; + } if (kind_ == Kind::AND || kind_ == Kind::OR) { if (!left_ || !right_) return common::E_INVALID_ARG; - const int ret = left_->bind(schema); + const int ret = + static_cast(left_.get())->bind(schema); if (ret != common::E_OK) return ret; - return right_->bind(schema); + return static_cast(right_.get())->bind(schema); } const common::ColumnSchema column = schema.get_column_schema(column_); if (!column.is_valid()) return common::E_COLUMN_NOT_EXIST; if (column.column_category_ != common::ColumnCategory::FIELD) return common::E_INVALID_ARG; if (kind_ != Kind::COMPARISON) return common::E_OK; - const int ret = bind_literal(literal_, column.data_type_); - if (ret != common::E_OK) return ret; - // Integral, Boolean, and string columns have no NaN values. Canonicalize - // their bound operators once, retaining the existing execution fast path. - if (negated_ && column.data_type_ != common::FLOAT && - column.data_type_ != common::DOUBLE) { - compare_op_ = negate_comparison(compare_op_); - negated_ = false; - } - return common::E_OK; + return bind_literal(literal_, column.data_type_); } int AlignedFieldFilter::check_exact_literals(TableSchema& schema) const { @@ -504,9 +436,10 @@ int AlignedFieldFilter::check_exact_literals(TableSchema& schema) const { const AlignedFieldFilter* node = stack.back(); stack.pop_back(); if (node == nullptr) continue; - if (node->kind_ == Kind::AND || node->kind_ == Kind::OR) { - if (node->right_) stack.push_back(node->right_.get()); - if (node->left_) stack.push_back(node->left_.get()); + if (node->kind_ == Kind::AND || node->kind_ == Kind::OR || + node->kind_ == Kind::NOT) { + if (node->right_) stack.push_back(node->right_field()); + if (node->left_) stack.push_back(node->left_field()); continue; } if (node->kind_ != Kind::COMPARISON) continue; @@ -538,10 +471,12 @@ int AlignedFieldFilter::height() const { if (entry.node == nullptr) continue; if (entry.height > max_height) max_height = entry.height; if (entry.node->right_ != nullptr) { - stack.push_back(Entry{entry.node->right_.get(), entry.height + 1}); + stack.push_back(Entry{entry.node->right_field(), entry.height + 1}); } if (entry.node->left_ != nullptr) { - stack.push_back(Entry{entry.node->left_.get(), entry.height + 1}); + stack.push_back( + Entry{entry.node->left_field(), + entry.height + (entry.node->kind_ != Kind::NOT)}); } } return max_height; @@ -550,36 +485,54 @@ int AlignedFieldFilter::height() const { bool AlignedFieldFilter::may_match( const std::map& statistics, int64_t row_count) const { - if (kind_ == Kind::AND) { - return !left_ || !right_ || - (left_->may_match(statistics, row_count) && - right_->may_match(statistics, row_count)); - } - if (kind_ == Kind::OR) { - return !left_ || !right_ || - (left_->may_match(statistics, row_count) || - right_->may_match(statistics, row_count)); - } + return page_matches(statistics, row_count, false, false); +} + +bool AlignedFieldFilter::all_match( + const std::map& statistics, + int64_t row_count) const { + return page_matches(statistics, row_count, true, false); +} + +bool AlignedFieldFilter::page_matches( + const std::map& statistics, int64_t row_count, + bool require_all, bool negated) const { if (kind_ == Kind::NOT) { - // NOT can be pushed down to leaves in a future planner. Until then, - // never use page statistics to prune a negated predicate. - return true; + return left_ ? left_field()->page_matches(statistics, row_count, + require_all, !negated) + : !require_all; + } + if (kind_ == Kind::AND || kind_ == Kind::OR) { + if (!left_ || !right_) return !require_all; + const bool lhs = left_field()->page_matches(statistics, row_count, + require_all, negated); + if ((kind_ == Kind::AND) != negated) { + return lhs && right_field()->page_matches(statistics, row_count, + require_all, negated); + } + return lhs || right_field()->page_matches(statistics, row_count, + require_all, negated); } + return require_all ? leaf_all_match(statistics, row_count, negated) + : leaf_may_match(statistics, row_count, negated); +} +bool AlignedFieldFilter::leaf_may_match( + const std::map& statistics, int64_t row_count, + bool negated) const { const auto found = statistics.find(column_); if (found == statistics.end() || found->second == nullptr) return true; Statistic* statistic = found->second; - if (kind_ == Kind::IS_NULL) { - return row_count <= 0 || statistic->count_ < row_count; - } - if (kind_ == Kind::IS_NOT_NULL) { - return statistic->count_ > 0; + if (kind_ == Kind::IS_NULL || kind_ == Kind::IS_NOT_NULL) { + const bool selects_null = (kind_ == Kind::IS_NULL) != negated; + return selects_null ? (row_count <= 0 || statistic->count_ < row_count) + : statistic->count_ > 0; } if (statistic->count_ <= 0) return false; if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::INT32) return true; - switch (negated_ ? negate_comparison(compare_op_) : compare_op_) { + switch (negated ? negate_comparison(compare_op_) : compare_op_) { case CompareOp::EQ: return typed->min_value_ <= literal_.int32_value && literal_.int32_value <= typed->max_value_; @@ -599,7 +552,7 @@ bool AlignedFieldFilter::may_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::INT64) return true; - switch (negated_ ? negate_comparison(compare_op_) : compare_op_) { + switch (negated ? negate_comparison(compare_op_) : compare_op_) { case CompareOp::EQ: return typed->min_value_ <= literal_.int64_value && literal_.int64_value <= typed->max_value_; @@ -619,12 +572,13 @@ bool AlignedFieldFilter::may_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::FLOAT || has_nan_statistics(*typed) || - (negated_ && std::isnan(literal_.float_value))) + (negated && compare_op_ != CompareOp::EQ && + compare_op_ != CompareOp::NE && std::isnan(literal_.float_value))) return true; // Complementing an ordered operator is safe only when neither the // page nor the literal can contain NaN. const CompareOp op = - negated_ ? negate_comparison(compare_op_) : compare_op_; + negated ? negate_comparison(compare_op_) : compare_op_; switch (op) { case CompareOp::EQ: return typed->min_value_ <= literal_.float_value && @@ -645,10 +599,11 @@ bool AlignedFieldFilter::may_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::DOUBLE || has_nan_statistics(*typed) || - (negated_ && std::isnan(literal_.double_value))) + (negated && compare_op_ != CompareOp::EQ && + compare_op_ != CompareOp::NE && std::isnan(literal_.double_value))) return true; const CompareOp op = - negated_ ? negate_comparison(compare_op_) : compare_op_; + negated ? negate_comparison(compare_op_) : compare_op_; switch (op) { case CompareOp::EQ: return typed->min_value_ <= literal_.double_value && @@ -670,36 +625,16 @@ bool AlignedFieldFilter::may_match( return true; } -bool AlignedFieldFilter::all_match( - const std::map& statistics, - int64_t row_count) const { - if (row_count <= 0) return false; - if (kind_ == Kind::AND) { - return left_ && right_ && left_->all_match(statistics, row_count) && - right_->all_match(statistics, row_count); - } - if (kind_ == Kind::OR) { - // Both operands are required: a half-built OR must fall through to - // row evaluation, which reports E_INVALID_ARG, instead of matching a - // page through its remaining operand as a full-page pass. - return left_ && right_ && - (left_->all_match(statistics, row_count) || - right_->all_match(statistics, row_count)); - } - if (kind_ == Kind::NOT) { - // Physical plans may keep a NOT node for now. Do not infer a - // page-wide match from its child statistics. - return false; - } - +bool AlignedFieldFilter::leaf_all_match( + const std::map& statistics, int64_t row_count, + bool negated) const { const auto found = statistics.find(column_); if (found == statistics.end() || found->second == nullptr) return false; Statistic* statistic = found->second; - if (kind_ == Kind::IS_NULL) { - return statistic->count_ == 0; - } - if (kind_ == Kind::IS_NOT_NULL) { - return statistic->count_ == row_count; + if (kind_ == Kind::IS_NULL || kind_ == Kind::IS_NOT_NULL) { + const bool selects_null = (kind_ == Kind::IS_NULL) != negated; + return selects_null ? statistic->count_ == 0 + : statistic->count_ == row_count; } // Ordinary comparisons do not match NULL. A page-wide match requires that // every row has a non-NULL value and that the whole min/max range passes. @@ -707,7 +642,7 @@ bool AlignedFieldFilter::all_match( if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::INT32) return false; - switch (negated_ ? negate_comparison(compare_op_) : compare_op_) { + switch (negated ? negate_comparison(compare_op_) : compare_op_) { case CompareOp::EQ: return typed->min_value_ == literal_.int32_value && typed->max_value_ == literal_.int32_value; @@ -726,7 +661,7 @@ bool AlignedFieldFilter::all_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::INT64) return false; - switch (negated_ ? negate_comparison(compare_op_) : compare_op_) { + switch (negated ? negate_comparison(compare_op_) : compare_op_) { case CompareOp::EQ: return typed->min_value_ == literal_.int64_value && typed->max_value_ == literal_.int64_value; @@ -745,10 +680,11 @@ bool AlignedFieldFilter::all_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::FLOAT || has_nan_statistics(*typed) || - (negated_ && std::isnan(literal_.float_value))) + (negated && compare_op_ != CompareOp::EQ && + compare_op_ != CompareOp::NE && std::isnan(literal_.float_value))) return false; const CompareOp op = - negated_ ? negate_comparison(compare_op_) : compare_op_; + negated ? negate_comparison(compare_op_) : compare_op_; switch (op) { case CompareOp::EQ: return typed->min_value_ == literal_.float_value && @@ -768,10 +704,11 @@ bool AlignedFieldFilter::all_match( } if (auto* typed = dynamic_cast(statistic)) { if (literal_.type != common::DOUBLE || has_nan_statistics(*typed) || - (negated_ && std::isnan(literal_.double_value))) + (negated && compare_op_ != CompareOp::EQ && + compare_op_ != CompareOp::NE && std::isnan(literal_.double_value))) return false; const CompareOp op = - negated_ ? negate_comparison(compare_op_) : compare_op_; + negated ? negate_comparison(compare_op_) : compare_op_; switch (op) { case CompareOp::EQ: return typed->min_value_ == literal_.double_value && @@ -800,62 +737,12 @@ int AlignedFieldFilter::evaluate(common::TsBlock& block, column_index[column_names[i]] = i + 1; } - struct Frame { - const AlignedFieldFilter* node; - uint8_t state; - }; - std::vector traversal; - std::vector postorder; - traversal.push_back({this, 0}); - while (!traversal.empty()) { - Frame& frame = traversal.back(); - const AlignedFieldFilter* node = frame.node; - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - postorder.push_back(node); - traversal.pop_back(); - } else if (node->kind_ == Kind::NOT) { - // Inverting a one-bit mask would incorrectly select NULL rows. - // Factory-built NOTs have already been pushed to the leaves. - return common::E_INVALID_ARG; - } else { - if (!node->left_ || !node->right_) return common::E_INVALID_ARG; - if (frame.state == 0) { - frame.state = 1; - traversal.push_back({node->left_.get(), 0}); - } else if (frame.state == 1) { - frame.state = 2; - traversal.push_back({node->right_.get(), 0}); - } else { - postorder.push_back(node); - traversal.pop_back(); - } - } - } - - std::vector masks; - masks.reserve(postorder.size()); - for (const auto* node : postorder) { - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - SelectionMask leaf_mask(block.get_row_count()); - int ret = node->evaluate_leaf(block, column_index, leaf_mask); - if (ret != common::E_OK) return ret; - masks.push_back(std::move(leaf_mask)); - } else { - if (masks.size() < 2) return common::E_INVALID_ARG; - SelectionMask right = std::move(masks.back()); - masks.pop_back(); - if (node->kind_ == Kind::AND) { - masks.back().and_with(right); - } else { - masks.back().or_with(right); - } - } - } - if (masks.size() != 1) return common::E_INVALID_ARG; - mask = std::move(masks.back()); - return common::E_OK; + return evaluate_tree(block.get_row_count(), mask, + [&](const AlignedFieldFilter& leaf, bool negated, + SelectionMask& result) { + return leaf.evaluate_leaf(block, column_index, + negated, result); + }); } int AlignedFieldFilter::evaluate_columns(const std::vector& columns, @@ -866,68 +753,62 @@ int AlignedFieldFilter::evaluate_columns(const std::vector& columns, column_index[columns[i].name] = i; } + return evaluate_tree(row_count, mask, + [&](const AlignedFieldFilter& leaf, bool negated, + SelectionMask& result) -> int { + const auto found = column_index.find(leaf.column_); + if (found == column_index.end()) + return common::E_COLUMN_NOT_EXIST; + return leaf.evaluate_leaf(columns[found->second], + row_count, negated, + result); + }); +} + +// Carry NOT down to the comparison. Complementing a completed one-bit mask +// would also select NULL rows; only non-null comparisons may be inverted. +template +int AlignedFieldFilter::evaluate_tree(uint32_t row_count, SelectionMask& mask, + EvaluateLeaf evaluate_leaf) const { struct Frame { const AlignedFieldFilter* node; - uint8_t state; + bool negated; + bool combine; }; - std::vector traversal{{this, 0}}; - std::vector postorder; - while (!traversal.empty()) { - Frame& frame = traversal.back(); - const AlignedFieldFilter* node = frame.node; - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - postorder.push_back(node); - traversal.pop_back(); - } else if (node->kind_ == Kind::NOT) { - // Inverting a one-bit mask would incorrectly select NULL rows. - // Factory-built NOTs have already been pushed to the leaves. - return common::E_INVALID_ARG; - } else { - if (!node->left_ || !node->right_) return common::E_INVALID_ARG; - if (frame.state == 0) { - frame.state = 1; - traversal.push_back({node->left_.get(), 0}); - } else if (frame.state == 1) { - frame.state = 2; - traversal.push_back({node->right_.get(), 0}); + std::vector pending{{this, false, false}}; + std::vector results; + while (!pending.empty()) { + const Frame frame = pending.back(); + pending.pop_back(); + const auto* node = frame.node; + if (!node) return common::E_INVALID_ARG; + if (frame.combine) { + SelectionMask rhs = std::move(results.back()); + results.pop_back(); + if ((node->kind_ == Kind::AND) != frame.negated) { + results.back().and_with(rhs); } else { - postorder.push_back(node); - traversal.pop_back(); + results.back().or_with(rhs); } - } - } - - std::vector masks; - masks.reserve(postorder.size()); - for (const auto* node : postorder) { - if (node->kind_ == Kind::COMPARISON || node->kind_ == Kind::IS_NULL || - node->kind_ == Kind::IS_NOT_NULL) { - const auto found = column_index.find(node->column_); - if (found == column_index.end()) return common::E_COLUMN_NOT_EXIST; - SelectionMask leaf_mask(row_count); - int ret = node->evaluate_leaf(columns[found->second], row_count, - leaf_mask); - if (ret != common::E_OK) return ret; - masks.push_back(std::move(leaf_mask)); + } else if (node->kind_ == Kind::NOT) { + pending.push_back({node->left_field(), !frame.negated, false}); + } else if (node->kind_ == Kind::AND || node->kind_ == Kind::OR) { + if (!node->left_ || !node->right_) return common::E_INVALID_ARG; + pending.push_back({node, frame.negated, true}); + pending.push_back({node->right_field(), frame.negated, false}); + pending.push_back({node->left_field(), frame.negated, false}); } else { - if (masks.size() < 2) return common::E_INVALID_ARG; - SelectionMask right = std::move(masks.back()); - masks.pop_back(); - if (node->kind_ == Kind::AND) { - masks.back().and_with(right); - } else { - masks.back().or_with(right); - } + results.emplace_back(row_count); + const int ret = evaluate_leaf(*node, frame.negated, results.back()); + if (ret != common::E_OK) return ret; } } - if (masks.size() != 1) return common::E_INVALID_ARG; - mask = std::move(masks.back()); + mask = std::move(results.back()); return common::E_OK; } int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, - uint32_t row_count, + uint32_t row_count, bool negated, SelectionMask& mask) const { if (column.type == common::INVALID_DATATYPE) return common::E_INVALID_ARG; if ((column.notnull_bitmap != nullptr && @@ -975,9 +856,9 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, bool satisfied = false; if (kind_ == Kind::IS_NULL) { - satisfied = is_null; + satisfied = is_null != negated; } else if (kind_ == Kind::IS_NOT_NULL) { - satisfied = !is_null; + satisfied = is_null == negated; } else if (!is_null) { if (column.type == common::BOOLEAN && literal_.type == common::BOOLEAN) { @@ -1013,13 +894,13 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, compare_values(value, literal_.double_value, compare_op_); } else if (is_string_type(column.type) && is_string_type(literal_.type)) { - satisfied = compare_string(data, len, literal_.string_value, - compare_op_); + satisfied = compare_values(std::string(data, len), + literal_.string_value, compare_op_); } else { return common::E_NOT_SUPPORT; } // NULL never satisfies a comparison, negated or not. - if (negated_) satisfied = !satisfied; + if (negated) satisfied = !satisfied; } if (satisfied) mask.set_one(row); } @@ -1028,7 +909,7 @@ int AlignedFieldFilter::evaluate_leaf(const ColumnView& column, int AlignedFieldFilter::evaluate_leaf( common::TsBlock& block, const std::map& column_index, - SelectionMask& mask) const { + bool negated, SelectionMask& mask) const { const auto found = column_index.find(column_); if (found == column_index.end()) return common::E_COLUMN_NOT_EXIST; @@ -1046,9 +927,9 @@ int AlignedFieldFilter::evaluate_leaf( bool satisfied = false; if (kind_ == Kind::IS_NULL) { - satisfied = is_null; + satisfied = is_null != negated; } else if (kind_ == Kind::IS_NOT_NULL) { - satisfied = !is_null; + satisfied = is_null == negated; } else if (!is_null) { if (column_type == common::BOOLEAN && literal_.type == common::BOOLEAN) { @@ -1084,13 +965,13 @@ int AlignedFieldFilter::evaluate_leaf( compare_values(value, literal_.double_value, compare_op_); } else if (is_string_type(column_type) && is_string_type(literal_.type)) { - satisfied = compare_string(data, len, literal_.string_value, - compare_op_); + satisfied = compare_values(std::string(data, len), + literal_.string_value, compare_op_); } else { return common::E_NOT_SUPPORT; } // NULL never satisfies a comparison, negated or not. - if (negated_) satisfied = !satisfied; + if (negated) satisfied = !satisfied; } if (satisfied) mask.set_one(row); iter.next(); diff --git a/cpp/src/reader/filter/aligned_field_filter.h b/cpp/src/reader/filter/aligned_field_filter.h index 8f86440b8..931ac9c61 100644 --- a/cpp/src/reader/filter/aligned_field_filter.h +++ b/cpp/src/reader/filter/aligned_field_filter.h @@ -28,8 +28,8 @@ #include #include "common/tsblock/tsblock.h" -#include "reader/filter/filter.h" #include "reader/filter/selection_mask.h" +#include "reader/filter/table_predicate.h" namespace storage { class TableSchema; @@ -38,12 +38,8 @@ class TableSchema; // pruning when possible; non-aligned sources use the table reader's timestamp // merge and typed row evaluation. Mixed-device files may use both paths. // It deliberately does not implement TableFieldFilter::satisfy_row(). -class AlignedFieldFilter : public Filter { +class AlignedFieldFilter : public TablePredicate { public: - enum class Kind { COMPARISON, IS_NULL, IS_NOT_NULL, AND, OR, NOT }; - - enum class CompareOp { EQ, NE, LT, LE, GT, GE }; - struct ColumnView { std::string name; common::TSDataType type = common::INVALID_DATATYPE; @@ -91,14 +87,15 @@ class AlignedFieldFilter : public Filter { static Ptr adopt_binary(bool conjunction, AlignedFieldFilter* left, AlignedFieldFilter* right); + // Transfer the operand only after a NOT node has been allocated. + static Ptr adopt_not(AlignedFieldFilter* child); + // Deep copy, including the bound literal and negation state. The table // query executor takes ownership of the filter it runs, so a caller that // keeps its own filter (for example a C binding handle reused across // queries) must hand over a clone instead of the original. Ptr clone() const; - Kind kind() const { return kind_; } - CompareOp compare_op() const { return compare_op_; } const std::string& column() const { return column_; } const Literal& literal() const { return literal_; } std::vector referenced_columns() const; @@ -127,8 +124,9 @@ class AlignedFieldFilter : public Filter { // literal here and are validated by bind(). int check_exact_literals(TableSchema& schema) const; - // Tree height (a leaf is 1), computed iteratively. Query paths use this - // to reject caller-built trees deep enough to overflow the recursive + // AND/OR tree height (a leaf is 1, NOT is transparent), computed + // iteratively. Query paths use this to reject caller-built trees deep + // enough to overflow the recursive // clone()/bind()/is_valid()/may_match()/all_match() traversals. static constexpr int MAX_HEIGHT = 512; int height() const; @@ -150,29 +148,33 @@ class AlignedFieldFilter : public Filter { private: AlignedFieldFilter(Kind kind, std::string column, CompareOp op, - Literal literal, bool negated = false); + Literal literal); AlignedFieldFilter(Kind kind, Ptr left, Ptr right); - // Push NOT down to the leaves so negation keeps SQL three-valued NULL - // semantics; a single SelectionMask bit cannot represent NULL vs FALSE. - void negate() noexcept; + const AlignedFieldFilter* left_field() const { + return static_cast(left()); + } + const AlignedFieldFilter* right_field() const { + return static_cast(right()); + } + + bool page_matches(const std::map& statistics, + int64_t row_count, bool require_all, bool negated) const; + bool leaf_may_match(const std::map& statistics, + int64_t row_count, bool negated) const; + bool leaf_all_match(const std::map& statistics, + int64_t row_count, bool negated) const; + + template + int evaluate_tree(uint32_t row_count, SelectionMask& mask, + EvaluateLeaf evaluate_leaf) const; int evaluate_leaf(common::TsBlock& block, const std::map& column_index, - SelectionMask& mask) const; + bool negated, SelectionMask& mask) const; int evaluate_leaf(const ColumnView& column, uint32_t row_count, - SelectionMask& mask) const; - Kind kind_; + bool negated, SelectionMask& mask) const; std::string column_; - CompareOp compare_op_ = CompareOp::EQ; Literal literal_; - // True when this leaf negates an ordered comparison. Preserve it until - // binding identifies the column type. Flipping the operator is not - // equivalent for FLOAT/DOUBLE: NaN makes - // every ordered comparison false, so the negation must be evaluated as - // !(value literal). NULL still never satisfies either form. - bool negated_ = false; - Ptr left_; - Ptr right_; }; } // namespace storage diff --git a/cpp/src/reader/filter/table_predicate.h b/cpp/src/reader/filter/table_predicate.h new file mode 100644 index 000000000..8f627c206 --- /dev/null +++ b/cpp/src/reader/filter/table_predicate.h @@ -0,0 +1,90 @@ +/* + * 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_FILTER_TABLE_PREDICATE_H +#define READER_FILTER_TABLE_PREDICATE_H + +#include +#include + +#include "reader/filter/filter.h" + +namespace storage { + +// An operator tree for table predicates. The two builders supply different +// bound operands: a device-ID segment for TAG and a typed column for FIELD. +class TablePredicate : public Filter { + public: + enum class Kind { + COMPARISON, + IS_NULL, + IS_NOT_NULL, + AND, + OR, + NOT, + BETWEEN, + NOT_BETWEEN, + REGEXP, + NOT_REGEXP, + CUSTOM + }; + enum class CompareOp { EQ, NE, LT, LE, GT, GE }; + + Kind kind() const { return kind_; } + CompareOp compare_op() const { return compare_op_; } + const TablePredicate* left() const { return left_.get(); } + const TablePredicate* right() const { return right_.get(); } + + protected: + explicit TablePredicate(Kind kind, CompareOp op = CompareOp::EQ) + : kind_(kind), compare_op_(op) {} + TablePredicate(Kind kind, std::unique_ptr left, + std::unique_ptr right) + : kind_(kind), + compare_op_(CompareOp::EQ), + left_(std::move(left)), + right_(std::move(right)) {} + + template + static bool compare_values(const T& value, const T& literal, CompareOp op) { + switch (op) { + case CompareOp::EQ: + return value == literal; + case CompareOp::NE: + return value != literal; + case CompareOp::LT: + return value < literal; + case CompareOp::LE: + return value <= literal; + case CompareOp::GT: + return value > literal; + case CompareOp::GE: + return value >= literal; + } + return false; + } + + Kind kind_; + CompareOp compare_op_; + std::unique_ptr left_; + std::unique_ptr right_; +}; + +} // namespace storage +#endif // READER_FILTER_TABLE_PREDICATE_H diff --git a/cpp/src/reader/filter/tag_filter.cc b/cpp/src/reader/filter/tag_filter.cc index 03b8ae785..6c8398b52 100644 --- a/cpp/src/reader/filter/tag_filter.cc +++ b/cpp/src/reader/filter/tag_filter.cc @@ -24,84 +24,79 @@ namespace storage { -// TagFilter base class implementation -TagFilter::TagFilter(int col_idx, std::string tag_value) - : value_(std::move(tag_value)), value2_(""), col_idx_(col_idx) {} +TagFilter::TagFilter(int col_idx, std::string value) + : TagFilter(Kind::CUSTOM, col_idx, std::move(value)) {} + +TagFilter::TagFilter(Kind kind, int col_idx, std::string value, CompareOp op) + : TablePredicate(kind, op), value_(std::move(value)), col_idx_(col_idx) {} + +TagFilter::TagFilter(Kind kind, TagFilter* left, TagFilter* right) + : TablePredicate(kind, std::unique_ptr(left), + std::unique_ptr(right)), + col_idx_(-1) {} TagFilter::~TagFilter() = default; bool TagFilter::satisfyRow(int time, std::vector segments) const { - return satisfyRow(segments); + return satisfyRow(std::move(segments)); } bool TagFilter::satisfyRow(std::vector segments) const { - ASSERT(false); + switch (kind_) { + case Kind::AND: + return left_->satisfyRow(0, segments) && + right_->satisfyRow(0, std::move(segments)); + case Kind::OR: + return left_->satisfyRow(0, segments) || + right_->satisfyRow(0, std::move(segments)); + case Kind::NOT: + return !left_->satisfyRow(0, std::move(segments)); + case Kind::IS_NULL: + return col_idx_ >= segments.size() || !segments[col_idx_]; + case Kind::IS_NOT_NULL: + return col_idx_ < segments.size() && segments[col_idx_]; + case Kind::COMPARISON: + return col_idx_ < segments.size() && segments[col_idx_] && + compare_values(*segments[col_idx_], value_, compare_op_); + case Kind::BETWEEN: + case Kind::NOT_BETWEEN: { + if (col_idx_ >= segments.size() || !segments[col_idx_]) + return false; + const auto& value = *segments[col_idx_]; + const bool between = compare_values(value, value_, CompareOp::GE) && + compare_values(value, value2_, CompareOp::LE); + return kind_ == Kind::BETWEEN ? between : !between; + } + case Kind::REGEXP: + case Kind::NOT_REGEXP: + case Kind::CUSTOM: + ASSERT(false); + return false; + } return false; } -// TagEq implementation -TagEq::TagEq(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagEq::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] == value_; -} +TagEq::TagEq(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::EQ) {} -// TagNeq implementation -TagNeq::TagNeq(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} +TagNeq::TagNeq(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::NE) {} -bool TagNeq::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] != value_; -} +TagLt::TagLt(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::LT) {} -// TagLt implementation -TagLt::TagLt(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} +TagLteq::TagLteq(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::LE) {} -bool TagLt::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] < value_; -} +TagGt::TagGt(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::GT) {} -// TagLteq implementation -TagLteq::TagLteq(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagLteq::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] <= value_; -} - -// TagGt implementation -TagGt::TagGt(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagGt::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] > value_; -} - -// TagGteq implementation -TagGteq::TagGteq(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) {} - -bool TagGteq::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - return *segments[col_idx_] >= value_; -} +TagGteq::TagGteq(int col_idx, std::string value) + : TagFilter(Kind::COMPARISON, col_idx, std::move(value), CompareOp::GE) {} // TagRegExp implementation TagRegExp::TagRegExp(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) { + : TagFilter(Kind::REGEXP, col_idx, std::move(tag_value)) { try { pattern_ = std::regex(value_); is_valid_pattern_ = true; @@ -123,7 +118,7 @@ bool TagRegExp::satisfyRow(std::vector segments) const { // TagNotRegExp implementation TagNotRegExp::TagNotRegExp(int col_idx, std::string tag_value) - : TagFilter(col_idx, std::move(tag_value)) { + : TagFilter(Kind::NOT_REGEXP, col_idx, std::move(tag_value)) { try { pattern_ = std::regex(value_); is_valid_pattern_ = true; @@ -143,84 +138,29 @@ bool TagNotRegExp::satisfyRow(std::vector segments) const { } } -// TagIsNull implementation -TagIsNull::TagIsNull(int col_idx) : TagFilter(col_idx, "") {} - -bool TagIsNull::satisfyRow(std::vector segments) const { - // A tag is null when its segment is an explicit null pointer or when the - // device id omits the (trailing) segment entirely. - return col_idx_ >= segments.size() || segments[col_idx_] == nullptr; -} - -// TagIsNotNull implementation -TagIsNotNull::TagIsNotNull(int col_idx) : TagFilter(col_idx, "") {} - -bool TagIsNotNull::satisfyRow(std::vector segments) const { - return col_idx_ < segments.size() && segments[col_idx_] != nullptr; -} +TagIsNull::TagIsNull(int col_idx) : TagFilter(Kind::IS_NULL, col_idx, "") {} +TagIsNotNull::TagIsNotNull(int col_idx) + : TagFilter(Kind::IS_NOT_NULL, col_idx, "") {} // TagBetween implementation TagBetween::TagBetween(int col_idx, std::string lower_value, std::string upper_value) - : TagFilter(col_idx, std::move(lower_value)) { + : TagFilter(Kind::BETWEEN, col_idx, std::move(lower_value)) { value2_ = std::move(upper_value); } -bool TagBetween::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - const std::string& segment_value = *segments[col_idx_]; - return segment_value >= value_ && segment_value <= value2_; -} - // TagNotBetween implementation TagNotBetween::TagNotBetween(int col_idx, std::string lower_value, std::string upper_value) - : TagFilter(col_idx, std::move(lower_value)) { + : TagFilter(Kind::NOT_BETWEEN, col_idx, std::move(lower_value)) { value2_ = std::move(upper_value); } -bool TagNotBetween::satisfyRow(std::vector segments) const { - if (col_idx_ >= segments.size() || segments[col_idx_] == nullptr) - return false; - const std::string& segment_value = *segments[col_idx_]; - return segment_value < value_ || segment_value > value2_; -} - -// TagAnd implementation TagAnd::TagAnd(TagFilter* left, TagFilter* right) - : TagFilter(-1, ""), left_(left), right_(right) {} - -TagAnd::~TagAnd() { - delete left_; - delete right_; -} - -bool TagAnd::satisfyRow(std::vector segments) const { - return left_->satisfyRow(segments) && right_->satisfyRow(segments); -} - -// TagOr implementation + : TagFilter(Kind::AND, left, right) {} TagOr::TagOr(TagFilter* left, TagFilter* right) - : TagFilter(-1, ""), left_(left), right_(right) {} - -TagOr::~TagOr() { - delete left_; - delete right_; -} - -bool TagOr::satisfyRow(std::vector segments) const { - return left_->satisfyRow(segments) || right_->satisfyRow(segments); -} - -// TagNot implementation -TagNot::TagNot(TagFilter* filter) : TagFilter(-1, ""), filter_(filter) {} - -TagNot::~TagNot() { delete filter_; } - -bool TagNot::satisfyRow(std::vector segments) const { - return !filter_->satisfyRow(segments); -} + : TagFilter(Kind::OR, left, right) {} +TagNot::TagNot(TagFilter* child) : TagFilter(Kind::NOT, child, nullptr) {} // TagFilterBuilder implementation TagFilterBuilder::TagFilterBuilder(TableSchema* schema) @@ -311,17 +251,22 @@ Filter* TagFilterBuilder::not_between_and(const std::string& columnName, } Filter* TagFilterBuilder::and_filter(Filter* left, Filter* right) { - return new TagAnd(dynamic_cast(left), - dynamic_cast(right)); + auto* lhs = dynamic_cast(left); + auto* rhs = dynamic_cast(right); + if (!lhs || !rhs || lhs == rhs) return nullptr; + return new TagAnd(lhs, rhs); } Filter* TagFilterBuilder::or_filter(Filter* left, Filter* right) { - return new TagOr(dynamic_cast(left), - dynamic_cast(right)); + auto* lhs = dynamic_cast(left); + auto* rhs = dynamic_cast(right); + if (!lhs || !rhs || lhs == rhs) return nullptr; + return new TagOr(lhs, rhs); } Filter* TagFilterBuilder::not_filter(Filter* filter) { - return new TagNot(dynamic_cast(filter)); + auto* child = dynamic_cast(filter); + return child ? new TagNot(child) : nullptr; } int TagFilterBuilder::get_tag_column_index(const std::string& columnName) { diff --git a/cpp/src/reader/filter/tag_filter.h b/cpp/src/reader/filter/tag_filter.h index 50c750d44..2e22bb328 100644 --- a/cpp/src/reader/filter/tag_filter.h +++ b/cpp/src/reader/filter/tag_filter.h @@ -20,17 +20,17 @@ #ifndef READER_FILTER_TAG_FILTER_H #define READER_FILTER_TAG_FILTER_H -#include +#include #include #include #include "common/allocator/my_string.h" #include "common/schema.h" -#include "reader/filter/filter.h" +#include "reader/filter/table_predicate.h" struct table_schema; namespace storage { -class TagFilter : public Filter { +class TagFilter : public TablePredicate { public: TagFilter(int col_idx, std::string tag_value); ~TagFilter() override; @@ -42,48 +42,47 @@ class TagFilter : public Filter { std::string value_; std::string value2_; // For range queries int col_idx_; + + protected: + TagFilter(Kind kind, int col_idx, std::string value, + CompareOp op = CompareOp::EQ); + TagFilter(Kind kind, TagFilter* left, TagFilter* right); }; // Equality comparison class TagEq : public TagFilter { public: TagEq(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Inequality comparison class TagNeq : public TagFilter { public: TagNeq(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Less than comparison class TagLt : public TagFilter { public: TagLt(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Less than or equal comparison class TagLteq : public TagFilter { public: TagLteq(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Greater than comparison class TagGt : public TagFilter { public: TagGt(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Greater than or equal comparison class TagGteq : public TagFilter { public: TagGteq(int col_idx, std::string tag_value); - bool satisfyRow(std::vector segments) const override; }; // Regular expression match @@ -111,21 +110,18 @@ class TagNotRegExp : public TagFilter { class TagIsNull : public TagFilter { public: explicit TagIsNull(int col_idx); - bool satisfyRow(std::vector segments) const override; }; // IS NOT NULL: tag column has a concrete value for this device. class TagIsNotNull : public TagFilter { public: explicit TagIsNotNull(int col_idx); - bool satisfyRow(std::vector segments) const override; }; // Range query [value_, value2_] class TagBetween : public TagFilter { public: TagBetween(int col_idx, std::string lower_value, std::string upper_value); - bool satisfyRow(std::vector segments) const override; }; // Not in range @@ -133,42 +129,24 @@ class TagNotBetween : public TagFilter { public: TagNotBetween(int col_idx, std::string lower_value, std::string upper_value); - bool satisfyRow(std::vector segments) const override; }; // Logical AND operation (binary) class TagAnd : public TagFilter { public: TagAnd(TagFilter* left, TagFilter* right); - ~TagAnd() override; - bool satisfyRow(std::vector segments) const override; - - private: - TagFilter* left_; - TagFilter* right_; }; // Logical OR operation (binary) class TagOr : public TagFilter { public: TagOr(TagFilter* left, TagFilter* right); - ~TagOr() override; - bool satisfyRow(std::vector segments) const override; - - private: - TagFilter* left_; - TagFilter* right_; }; // Logical NOT operation class TagNot : public TagFilter { public: explicit TagNot(TagFilter* filter); - ~TagNot() override; - bool satisfyRow(std::vector segments) const override; - - private: - TagFilter* filter_; }; class TagFilterBuilder { diff --git a/cpp/test/reader/filter/aligned_field_filter_test.cc b/cpp/test/reader/filter/aligned_field_filter_test.cc index db35a6dbc..a73dbf8fa 100644 --- a/cpp/test/reader/filter/aligned_field_filter_test.cc +++ b/cpp/test/reader/filter/aligned_field_filter_test.cc @@ -540,6 +540,27 @@ TEST(AlignedFieldFilterTest, ExactLiteralsAreValidatedAgainstSchema) { EXPECT_EQ(tree->check_exact_literals(schema), E_TYPE_NOT_MATCH); } +TEST(AlignedFieldFilterTest, AlternatingNotAtHeightLimitSurvivesCloneAndBind) { + using A = AlignedFieldFilter; + const int height_limit = A::MAX_HEIGHT; + auto expr = A::is_null("v"); + for (int height = 1; height < height_limit; ++height) { + expr = A::not_filter(A::and_filter(std::move(expr), A::is_null("v"))); + } + auto copy = expr->clone(); + EXPECT_EQ(height_limit, copy->height()); + ASSERT_TRUE(copy->is_valid()); + TableSchema schema("t", {{"v", common::INT64, common::UNCOMPRESSED, + common::PLAIN, common::ColumnCategory::FIELD}}); + ASSERT_EQ(common::E_OK, copy->bind(schema)); + A::ColumnView v; + v.name = "v"; + v.type = common::INT64; + SelectionMask mask; + ASSERT_EQ(common::E_OK, copy->evaluate_columns({v}, 1, mask)); + EXPECT_EQ((height_limit % 2) == 1, mask.test(0)); +} + TEST(AlignedFieldFilterTest, HeightCountsTreeLevels) { using namespace common; using A = AlignedFieldFilter; diff --git a/cpp/test/reader/filter/tag_filter_test.cc b/cpp/test/reader/filter/tag_filter_test.cc index 923bb920a..8c9450846 100644 --- a/cpp/test/reader/filter/tag_filter_test.cc +++ b/cpp/test/reader/filter/tag_filter_test.cc @@ -22,6 +22,7 @@ #include #include "common/schema.h" +#include "reader/filter/aligned_field_filter.h" using namespace storage; @@ -497,4 +498,40 @@ TEST_F(TagFilterTest, TagIsNotNullFilter) { delete filter; delete trailing; -} \ No newline at end of file +} +TEST_F(TagFilterTest, SameNotExpressionPreservesTagAndFieldNullSemantics) { + using Field = AlignedFieldFilter; + using Kind = TablePredicate::Kind; + std::unique_ptr tag( + builder_->not_filter(builder_->eq("name", "x"))); + auto field = Field::not_filter(Field::compare("name", Field::CompareOp::EQ, + Field::Literal::string("x"))); + + const auto* tag_expr = dynamic_cast(tag.get()); + ASSERT_NE(nullptr, tag_expr); + for (const TablePredicate* expr : + {tag_expr, static_cast(field.get())}) { + EXPECT_EQ(Kind::NOT, expr->kind()); + ASSERT_NE(nullptr, expr->left()); + EXPECT_EQ(Kind::COMPARISON, expr->left()->kind()); + EXPECT_EQ(TablePredicate::CompareOp::EQ, expr->left()->compare_op()); + } + + EXPECT_TRUE(tag->satisfyRow(0, {})); + EXPECT_TRUE(tag->satisfyRow(0, {nullptr, nullptr})); + Field::ColumnView column; + column.name = "name"; + column.type = common::STRING; + SelectionMask mask; + ASSERT_EQ(common::E_OK, field->evaluate_columns({column}, 1, mask)); + EXPECT_FALSE(mask.test(0)); +} + +TEST_F(TagFilterTest, TagCombinatorsRejectFieldOperandsWithoutTakingOwnership) { + std::unique_ptr tag(builder_->eq("name", "x")); + auto field = AlignedFieldFilter::is_null("name"); + EXPECT_EQ(nullptr, builder_->and_filter(tag.get(), field.get())); + EXPECT_EQ(nullptr, builder_->or_filter(field.get(), tag.get())); + EXPECT_EQ(nullptr, builder_->not_filter(field.get())); + EXPECT_EQ(nullptr, builder_->and_filter(tag.get(), tag.get())); +} diff --git a/skills/tsfile/references/properties-filters.md b/skills/tsfile/references/properties-filters.md index ff0fd0274..03abc061d 100644 --- a/skills/tsfile/references/properties-filters.md +++ b/skills/tsfile/references/properties-filters.md @@ -48,7 +48,9 @@ the property manually does not enable it. Build TAG predicates against a `TableSchema`, apply them only to Table-model queries, and pass field/time restrictions through their separate query -arguments. TAG values are strings; do not apply a TAG builder to FIELD columns. +arguments. In C++, TAG and FIELD share the comparison, null-test, and logical +operators in `reader/filter/table_predicate.h`. TAG evaluates them on device-ID +segments. For a missing TAG, equality is false and its logical NOT is true. TAG values are strings; do not apply a TAG builder to FIELD columns. - Java `TagFilterBuilder`: `eq`, `neq`, `lt`, `lteq`, `gt`, `gteq`, `betweenAnd`, `notBetweenAnd`, `regExp`, `notRegExp`, `like`, `notLike`, plus @@ -76,7 +78,8 @@ FIELD predicates select rows by FIELD-column values and compose with TAG predicates. They are pushed down into the table query executor: aligned devices use batch/page evaluation, non-aligned devices evaluate merged rows. A comparison never matches NULL cells; use the explicit IS NULL / IS NOT NULL -predicates for that. NOT is pushed down into the leaves, so a negated +predicates for that. FIELD evaluation carries NOT through the expression tree +to each comparison and preserves SQL three-valued NULL semantics. A negated comparison also excludes NULL cells. - Python factories: `field_eq`, `field_neq`, `field_lt`, `field_lteq`,