From 12d0f47e663f3d556417df0d9c0077fae7ad99e8 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Thu, 26 Nov 2026 11:08:26 +0800 Subject: [PATCH 1/7] fix(cpp): keep NULL column for series with no data in query range A multi-path query dropped the column of a selected measurement that exists in the file but has no data inside the query time range, shifting the values of the following columns into the wrong positions. This aligns C++ with the Java behavior: keep the column and return NULL for it. alloc_ssi now reports a bloom-filter miss (measurement truly absent) as E_NOT_EXIST instead of E_NO_MORE_DATA, and exposes the series data type for the exists-but-empty-in-range case. QDSWithoutTimeGenerator keeps a NULL column with the correct type for the latter and only drops the column when the measurement does not exist. --- cpp/src/file/tsfile_io_reader.cc | 12 +++- cpp/src/file/tsfile_io_reader.h | 3 +- cpp/src/reader/qds_with_timegenerator.cc | 10 ++-- cpp/src/reader/qds_without_timegenerator.cc | 52 +++++++++++++---- cpp/test/reader/tsfile_reader_test.cc | 64 +++++++++++++++++++++ 5 files changed, 123 insertions(+), 18 deletions(-) diff --git a/cpp/src/file/tsfile_io_reader.cc b/cpp/src/file/tsfile_io_reader.cc index 1c4cac29f..66ee94835 100644 --- a/cpp/src/file/tsfile_io_reader.cc +++ b/cpp/src/file/tsfile_io_reader.cc @@ -89,12 +89,17 @@ void TsFileIOReader::reset() { int TsFileIOReader::alloc_ssi(std::shared_ptr device_id, const std::string& measurement_name, TsFileSeriesScanIterator*& ssi, - common::PageArena& pa, Filter* time_filter) { + common::PageArena& pa, Filter* time_filter, + common::TSDataType* out_series_type) { int ret = E_OK; if (RET_FAIL(load_tsfile_meta_if_necessary())) { } else if (!bloom_filter_contains(device_id->get_device_name(), measurement_name)) { - return E_NO_MORE_DATA; + // The measurement is absent from this file (the bloom filter has no + // false negatives). Report it as not-found rather than E_NO_MORE_DATA + // so callers can tell a missing series apart from one that exists but + // has no data in the query range. + return E_NOT_EXIST; } else { void* ssi_buf = mem_alloc(sizeof(TsFileSeriesScanIterator), MOD_TSFILE_READER); @@ -106,6 +111,9 @@ int TsFileIOReader::alloc_ssi(std::shared_ptr device_id, } else if (time_filter != nullptr && !filter_stasify(ssi->itimeseries_index_, time_filter)) { ret = E_NO_MORE_DATA; + if (out_series_type != nullptr) { + *out_series_type = ssi->get_data_type(); + } } else if (RET_FAIL(ssi->init_chunk_reader())) { } if (ret != E_OK) { diff --git a/cpp/src/file/tsfile_io_reader.h b/cpp/src/file/tsfile_io_reader.h index 22283ebc5..81c945ef9 100644 --- a/cpp/src/file/tsfile_io_reader.h +++ b/cpp/src/file/tsfile_io_reader.h @@ -85,7 +85,8 @@ class TsFileIOReader { int alloc_ssi(std::shared_ptr device_id, const std::string& measurement_name, TsFileSeriesScanIterator*& ssi, common::PageArena& pa, - Filter* time_filter = nullptr); + Filter* time_filter = nullptr, + common::TSDataType* out_series_type = nullptr); int alloc_multi_ssi(std::shared_ptr device_id, const std::vector& measurement_names, diff --git a/cpp/src/reader/qds_with_timegenerator.cc b/cpp/src/reader/qds_with_timegenerator.cc index d5398bbc9..ff0f7e5e7 100644 --- a/cpp/src/reader/qds_with_timegenerator.cc +++ b/cpp/src/reader/qds_with_timegenerator.cc @@ -431,10 +431,12 @@ int QDSWithTimeGenerator::construct_node_tree(Expression* expr, Node*& node) { leaf->sss_.ssi_, pa_, expr->filter_); if (E_OK == ret) { leaf->sss_.init(); - } else if (ret == E_NO_MORE_DATA) { - // The filter pruned every chunk of this series. Keep the leaf so - // parent AND/OR nodes still have a child; its stream reports - // INVALID_NEXT_TIMESTAMP for every lookup. + } else if (ret == E_NO_MORE_DATA || ret == E_MEASUREMENT_NOT_EXIST || + ret == E_DEVICE_NOT_EXIST || ret == E_NOT_EXIST) { + // The filter pruned every chunk of this series, or the series does + // not exist in this file. Keep the leaf so parent AND/OR nodes + // still have a child; its stream reports INVALID_NEXT_TIMESTAMP + // for every lookup. ret = E_OK; } if (ret == E_OK) { diff --git a/cpp/src/reader/qds_without_timegenerator.cc b/cpp/src/reader/qds_without_timegenerator.cc index f9ce7903c..458a55935 100644 --- a/cpp/src/reader/qds_without_timegenerator.cc +++ b/cpp/src/reader/qds_without_timegenerator.cc @@ -120,20 +120,39 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, index_lookup_.insert({"time", 0}); for (size_t i = 0; i < origin_path_count; i++) { TsFileSeriesScanIterator* ssi = nullptr; + common::TSDataType empty_series_type = common::INVALID_DATATYPE; ret = io_reader_->alloc_ssi(paths[i].device_id_, paths[i].measurement_, - ssi, pa_, global_time_filter); + ssi, pa_, global_time_filter, + &empty_series_type); if (ret == E_MEASUREMENT_NOT_EXIST || ret == E_DEVICE_NOT_EXIST || - ret == E_NOT_EXIST || ret == E_NO_MORE_DATA) { + ret == E_NOT_EXIST) { // Java-aligned: silently skip paths whose device or measurement - // doesn't exist in this file. The bloom-filter optimization in - // alloc_ssi reports a missing series as E_NO_MORE_DATA, so treat - // that the same as the not-found codes. + // doesn't exist in this file. + ret = E_OK; + continue; + } + if (ret == E_NO_MORE_DATA) { + // The series exists but has no data in the query time range. Keep + // its column (aligned with Java) so callers see a NULL value for it + // instead of a later column's value. No SSI is allocated, so a + // nullptr placeholder keeps the column indices aligned. + size_t col_idx = ssi_vec_.size(); + index_lookup_.insert({paths[i].measurement_, col_idx + 1}); + if (paths[i].full_path_ != paths[i].measurement_) { + index_lookup_.insert({paths[i].full_path_, col_idx + 1}); + } + ssi_vec_.push_back(nullptr); + valid_paths.push_back(paths[i]); + column_names.push_back(paths[i].full_path_); + ssi_data_types.push_back(empty_series_type); ret = E_OK; continue; } if (ret != E_OK) { for (size_t j = 0; j < ssi_vec_.size(); j++) { - io_reader_->revert_ssi(ssi_vec_[j]); + if (ssi_vec_[j] != nullptr) { + io_reader_->revert_ssi(ssi_vec_[j]); + } } ssi_vec_.clear(); return ret; @@ -154,8 +173,10 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, // Only push offset/limit to SSI for single-path; multi-path applies at // merge. for (size_t i = 0; i < path_count; i++) { - ssi_vec_[i]->set_row_range(is_single_path_ ? remaining_offset_ : 0, - is_single_path_ ? remaining_limit_ : -1); + if (ssi_vec_[i] != nullptr) { + ssi_vec_[i]->set_row_range(is_single_path_ ? remaining_offset_ : 0, + is_single_path_ ? remaining_limit_ : -1); + } } row_record_ = new RowRecord(path_count + 1); tsblocks_.resize(path_count); @@ -163,6 +184,11 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, value_iters_.resize(path_count); for (size_t i = 0; i < path_count; i++) { + if (ssi_vec_[i] == nullptr) { + // Empty-in-range column: keep it NULL with its real data type. + data_types.push_back(ssi_data_types[i]); + continue; + } if (RET_FAIL(load_next_tsblock(i, true))) { return ret; } @@ -178,7 +204,7 @@ int QDSWithoutTimeGenerator::init_internal(TsFileIOReader* io_reader, } // Single-path: SSI may have consumed offset/limit by skipping chunks/pages // during first load_next_tsblock(); sync so QDS does not double-apply. - if (is_single_path_) { + if (is_single_path_ && ssi_vec_[0] != nullptr) { remaining_offset_ = ssi_vec_[0]->get_row_offset(); remaining_limit_ = ssi_vec_[0]->get_row_limit(); } @@ -206,11 +232,15 @@ void QDSWithoutTimeGenerator::close() { ASSERT(ssi_vec_.size() == tsblocks_.size()); for (size_t i = 0; i < ssi_vec_.size(); i++) { - ssi_vec_[i]->revert_tsblock(); + if (ssi_vec_[i] != nullptr) { + ssi_vec_[i]->revert_tsblock(); + } } for (size_t i = 0; i < ssi_vec_.size(); i++) { TsFileSeriesScanIterator* ssi = ssi_vec_[i]; - io_reader_->revert_ssi(ssi); + if (ssi != nullptr) { + io_reader_->revert_ssi(ssi); + } } ssi_vec_.clear(); tsblocks_.clear(); diff --git a/cpp/test/reader/tsfile_reader_test.cc b/cpp/test/reader/tsfile_reader_test.cc index 2058e2646..19a690478 100644 --- a/cpp/test/reader/tsfile_reader_test.cc +++ b/cpp/test/reader/tsfile_reader_test.cc @@ -2302,3 +2302,67 @@ TEST_F(TsFileReaderTest, RepeatedGetTimeseriesMetadataDoesNotLeakArena) { << " across 11 calls — reset on entry is missing"; reader.close(); } + +TEST_F(TsFileReaderTest, MultiPathKeepsNullColumnForSeriesEmptyInRange) { + const std::string device = "root.t"; + ASSERT_EQ(tsfile_writer_->register_timeseries( + device, + MeasurementSchema("v1", TSDataType::INT64, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)), + E_OK); + ASSERT_EQ(tsfile_writer_->register_timeseries( + device, + MeasurementSchema("v2", TSDataType::INT64, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)), + E_OK); + + // v1 has data only outside the query range; v2 has data inside it. + TsRecord r1(100, device); + r1.add_point("v1", static_cast(1)); + ASSERT_EQ(tsfile_writer_->write_record(r1), E_OK); + TsRecord r2(101, device); + r2.add_point("v1", static_cast(2)); + ASSERT_EQ(tsfile_writer_->write_record(r2), E_OK); + TsRecord r3(1000, device); + r3.add_point("v2", static_cast(20)); + ASSERT_EQ(tsfile_writer_->write_record(r3), E_OK); + TsRecord r4(1001, device); + r4.add_point("v2", static_cast(21)); + ASSERT_EQ(tsfile_writer_->write_record(r4), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + storage::TsFileReader reader; + ASSERT_EQ(reader.open(file_name_), E_OK); + std::vector paths = {"root.t.v1", "root.t.v2"}; + storage::ResultSet* result = nullptr; + ASSERT_EQ(reader.query(paths, 1000, 1001, result), E_OK); + ASSERT_NE(result, nullptr); + + auto metadata = result->get_metadata(); + ASSERT_EQ(metadata->get_column_count(), 3u); + ASSERT_EQ(metadata->get_column_name(1), "time"); + ASSERT_EQ(metadata->get_column_name(2), "root.t.v1"); + ASSERT_EQ(metadata->get_column_name(3), "root.t.v2"); + ASSERT_EQ(metadata->get_column_type(2), TSDataType::INT64); + ASSERT_EQ(metadata->get_column_type(3), TSDataType::INT64); + + bool has_next = false; + ASSERT_EQ(result->next(has_next), E_OK); + ASSERT_TRUE(has_next); + EXPECT_TRUE(result->is_null(2)); // v1 has no data in range -> NULL + EXPECT_FALSE(result->is_null(3)); + EXPECT_EQ(result->get_value(3), 20); + + ASSERT_EQ(result->next(has_next), E_OK); + ASSERT_TRUE(has_next); + EXPECT_TRUE(result->is_null(2)); + EXPECT_FALSE(result->is_null(3)); + EXPECT_EQ(result->get_value(3), 21); + + ASSERT_EQ(result->next(has_next), E_OK); + EXPECT_FALSE(has_next); + + reader.destroy_query_data_set(result); + reader.close(); +} From b3040b17d3aa179a0b00ffc5aa4d8e5db9ba1eb2 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Fri, 27 Nov 2026 15:59:50 +0800 Subject: [PATCH 2/7] test(cpp): cover missing series in the time-generator predicate The construct_node_tree change keeps a leaf (empty stream) for a series that does not exist in the file but appears in the query predicate. Add regression tests for that path: OR preserves the live series' timestamps, AND returns no rows, and the result set stays destroyable. Cover both a missing measurement and a missing device. --- .../reader/qds_with_timegenerator_test.cc | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/cpp/test/reader/qds_with_timegenerator_test.cc b/cpp/test/reader/qds_with_timegenerator_test.cc index 8bc756ff0..7b1d3e63a 100644 --- a/cpp/test/reader/qds_with_timegenerator_test.cc +++ b/cpp/test/reader/qds_with_timegenerator_test.cc @@ -398,6 +398,52 @@ TEST_F(QDSWithTimeGeneratorTest, MissingSeriesFailsTheQuery) { EXPECT_EQ(result, nullptr); } +TEST_F(QDSWithTimeGeneratorTest, OrWithMissingMeasurementKeepsLiveSeries) { + // A measurement that does not exist in the file yields an empty leaf (no + // timestamps); the OR must still emit the existing series' rows and the + // result must remain destroyable. + Expression* expression = + new Expression(OR_EXPR, series_expr(device_, "s1", TimeFilter::eq(2)), + series_expr(device_, "missing", TimeFilter::gt(0))); + ResultSet* result = query(expression, {"s1"}); + ASSERT_NE(result, nullptr); + + std::vector rows; + collect_rows(result, rows); + ASSERT_EQ(timestamps(rows), (std::vector{2})); + EXPECT_EQ(rows[0].value1, 20); + reader_.destroy_query_data_set(result); +} + +TEST_F(QDSWithTimeGeneratorTest, AndWithMissingMeasurementReturnsNoRows) { + // The missing measurement's empty leaf means the AND can never match. + Expression* expression = + new Expression(AND_EXPR, series_expr(device_, "s1", TimeFilter::eq(2)), + series_expr(device_, "missing", TimeFilter::gt(0))); + ResultSet* result = query(expression, {"s1"}); + ASSERT_NE(result, nullptr); + + bool has_next = true; + ASSERT_EQ(result->next(has_next), E_OK); + EXPECT_FALSE(has_next); + reader_.destroy_query_data_set(result); +} + +TEST_F(QDSWithTimeGeneratorTest, OrWithMissingDeviceKeepsLiveSeries) { + // A predicate on a device that does not exist also produces an empty leaf. + Expression* expression = new Expression( + OR_EXPR, series_expr(device_, "s1", TimeFilter::eq(2)), + series_expr("root.qds_no_such_device", "x", TimeFilter::gt(0))); + ResultSet* result = query(expression, {"s1"}); + ASSERT_NE(result, nullptr); + + std::vector rows; + collect_rows(result, rows); + ASSERT_EQ(timestamps(rows), (std::vector{2})); + EXPECT_EQ(rows[0].value1, 20); + reader_.destroy_query_data_set(result); +} + class QDSWithTimeGeneratorMultiBlockTest : public ::testing::Test { protected: void SetUp() override { From 9c0692316823b63d0acb248c6cdf58472f77531d Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Fri, 27 Nov 2026 17:16:42 +0800 Subject: [PATCH 3/7] fix(cpp): preserve errors and alloc_ssi ABI in empty-series handling do_load_timeseries_index() only maps a fully-scanned, no-match index range to E_NOT_EXIST; deserialization errors such as E_OOM now propagate instead of being swallowed as a missing series. Keep the five-argument alloc_ssi() overload so clients compiled against the previous header keep linking; the new six-argument overload carries the optional series-type out-param. --- cpp/src/file/tsfile_io_reader.cc | 14 +++++++++++++- cpp/src/file/tsfile_io_reader.h | 13 +++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/cpp/src/file/tsfile_io_reader.cc b/cpp/src/file/tsfile_io_reader.cc index 66ee94835..8372696dc 100644 --- a/cpp/src/file/tsfile_io_reader.cc +++ b/cpp/src/file/tsfile_io_reader.cc @@ -86,6 +86,14 @@ void TsFileIOReader::reset() { } } +int TsFileIOReader::alloc_ssi(std::shared_ptr device_id, + const std::string& measurement_name, + TsFileSeriesScanIterator*& ssi, + common::PageArena& pa, Filter* time_filter) { + return alloc_ssi(device_id, measurement_name, ssi, pa, time_filter, + nullptr); +} + int TsFileIOReader::alloc_ssi(std::shared_ptr device_id, const std::string& measurement_name, TsFileSeriesScanIterator*& ssi, @@ -1360,7 +1368,11 @@ int TsFileIOReader::do_load_timeseries_index( break; } } // end while - if (!found) { + if (!found && deserialize_buf_not_enough(ret)) { + // A complete scan of the index range found no matching + // measurement (the read ran off the end of the buffer). Keep hard + // errors such as E_OOM or E_TSFILE_CORRUPTED so callers can + // distinguish them from a genuinely missing series. ret = E_NOT_EXIST; } } diff --git a/cpp/src/file/tsfile_io_reader.h b/cpp/src/file/tsfile_io_reader.h index 81c945ef9..f996991cd 100644 --- a/cpp/src/file/tsfile_io_reader.h +++ b/cpp/src/file/tsfile_io_reader.h @@ -82,11 +82,20 @@ class TsFileIOReader { void reset(); + // Backward-compatible overload for callers compiled against the + // previous signature; forwards a null series-type out-param. int alloc_ssi(std::shared_ptr device_id, const std::string& measurement_name, TsFileSeriesScanIterator*& ssi, common::PageArena& pa, - Filter* time_filter = nullptr, - common::TSDataType* out_series_type = nullptr); + Filter* time_filter = nullptr); + // Extended overload: also reports the series data type via + // out_series_type when the series exists but has no data in the query + // range. The final argument is required to keep overload resolution + // unambiguous with the overload above. + int alloc_ssi(std::shared_ptr device_id, + const std::string& measurement_name, + TsFileSeriesScanIterator*& ssi, common::PageArena& pa, + Filter* time_filter, common::TSDataType* out_series_type); int alloc_multi_ssi(std::shared_ptr device_id, const std::vector& measurement_names, From eb29fa2f4fc21792ab09abca4e018251529e0d96 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Fri, 27 Nov 2026 18:35:40 +0800 Subject: [PATCH 4/7] test(cpp): cover single-path and all-empty result lifecycles Add regression tests for a single selected series that is empty in the query range and for all-selected-series-empty queries, asserting retained column names/types, no rows, and safe destruction. Document the tree-model result-column semantics (empty-in-range keeps a typed NULL column; a missing measurement drops the column) in the SDK skill so callers can rely on the result schema. --- cpp/test/reader/tsfile_reader_test.cc | 79 +++++++++++++++++++++++ skills/tsfile/references/core-concepts.md | 17 +++++ 2 files changed, 96 insertions(+) diff --git a/cpp/test/reader/tsfile_reader_test.cc b/cpp/test/reader/tsfile_reader_test.cc index 6e93c3b77..01033d067 100644 --- a/cpp/test/reader/tsfile_reader_test.cc +++ b/cpp/test/reader/tsfile_reader_test.cc @@ -2367,6 +2367,85 @@ TEST_F(TsFileReaderTest, MultiPathKeepsNullColumnForSeriesEmptyInRange) { reader.close(); } +TEST_F(TsFileReaderTest, SinglePathEmptyInRangeKeepsColumnWithNoRows) { + const std::string device = "root.t"; + ASSERT_EQ(tsfile_writer_->register_timeseries( + device, + MeasurementSchema("v1", TSDataType::INT64, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)), + E_OK); + TsRecord r1(100, device); + r1.add_point("v1", static_cast(1)); + ASSERT_EQ(tsfile_writer_->write_record(r1), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + storage::TsFileReader reader; + ASSERT_EQ(reader.open(file_name_), E_OK); + std::vector paths = {"root.t.v1"}; + storage::ResultSet* result = nullptr; + ASSERT_EQ(reader.query(paths, 1000, 1001, result), E_OK); + ASSERT_NE(result, nullptr); + + auto metadata = result->get_metadata(); + ASSERT_EQ(metadata->get_column_count(), 2u); + ASSERT_EQ(metadata->get_column_name(1), "time"); + ASSERT_EQ(metadata->get_column_name(2), "root.t.v1"); + ASSERT_EQ(metadata->get_column_type(2), TSDataType::INT64); + + bool has_next = false; + ASSERT_EQ(result->next(has_next), E_OK); + EXPECT_FALSE(has_next); + + reader.destroy_query_data_set(result); + reader.close(); +} + +TEST_F(TsFileReaderTest, AllSelectedEmptyInRangeKeepColumnsWithNoRows) { + const std::string device = "root.t"; + ASSERT_EQ(tsfile_writer_->register_timeseries( + device, + MeasurementSchema("v1", TSDataType::INT64, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)), + E_OK); + ASSERT_EQ(tsfile_writer_->register_timeseries( + device, + MeasurementSchema("v2", TSDataType::INT64, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)), + E_OK); + + TsRecord r1(100, device); + r1.add_point("v1", static_cast(1)); + ASSERT_EQ(tsfile_writer_->write_record(r1), E_OK); + TsRecord r2(200, device); + r2.add_point("v2", static_cast(2)); + ASSERT_EQ(tsfile_writer_->write_record(r2), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + storage::TsFileReader reader; + ASSERT_EQ(reader.open(file_name_), E_OK); + std::vector paths = {"root.t.v1", "root.t.v2"}; + storage::ResultSet* result = nullptr; + ASSERT_EQ(reader.query(paths, 1000, 1001, result), E_OK); + ASSERT_NE(result, nullptr); + + auto metadata = result->get_metadata(); + ASSERT_EQ(metadata->get_column_count(), 3u); + ASSERT_EQ(metadata->get_column_name(1), "time"); + ASSERT_EQ(metadata->get_column_name(2), "root.t.v1"); + ASSERT_EQ(metadata->get_column_name(3), "root.t.v2"); + ASSERT_EQ(metadata->get_column_type(2), TSDataType::INT64); + ASSERT_EQ(metadata->get_column_type(3), TSDataType::INT64); + + bool has_next = false; + ASSERT_EQ(result->next(has_next), E_OK); + EXPECT_FALSE(has_next); + + reader.destroy_query_data_set(result); + reader.close(); +} + // Regression: querying a closed TsFileReader used to dereference the // already-deleted internal executor and crash with SIGSEGV. After close() // every query/execute entry point must return a clear error instead. diff --git a/skills/tsfile/references/core-concepts.md b/skills/tsfile/references/core-concepts.md index 4cebe21e9..8e1502634 100644 --- a/skills/tsfile/references/core-concepts.md +++ b/skills/tsfile/references/core-concepts.md @@ -69,6 +69,23 @@ reference separately only after selecting the binding. 5. Consume rows or columnar batches incrementally. 6. Close the result set before closing the reader. +## Result-Column Semantics (Tree Model) + +A multi-path tree query returns the leading `time` column plus one column per +selected measurement, in selection order. The result schema depends on whether +each selected measurement exists in the file: + +- **Exists but has no data in the query range**: the column is kept with the + measurement's declared data type, and every emitted row carries NULL in that + column (Java, C++, and Python agree). +- **Does not exist in the file**: the column is dropped from the result schema + (Java, C++, and Python agree). + +Because a missing measurement drops its column, do not assume a fixed column +count or positional index. Look values up by column name (or inspect the +result metadata), and treat NULL as a legitimate "no data in range" signal +rather than an absent column. + ## Cross-Language Files - Write with one binding and read with every binding required by the target From a24b479668389d73edb14c13fa0c60fa3ee4f154 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Fri, 27 Nov 2026 18:55:38 +0800 Subject: [PATCH 5/7] fix(cpp): propagate partial reads inside a timeseries index entry do_load_timeseries_index() now only scans complete entries, checking bs.has_remaining() before each one, and returns E_NOT_EXIST solely after a full scan without a match. A deserialization error mid-entry (E_PARTIAL_READ, E_OOM, ...) is propagated instead of being masked as a missing series. --- cpp/src/file/tsfile_io_reader.cc | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/cpp/src/file/tsfile_io_reader.cc b/cpp/src/file/tsfile_io_reader.cc index 8372696dc..6de4ed20d 100644 --- a/cpp/src/file/tsfile_io_reader.cc +++ b/cpp/src/file/tsfile_io_reader.cc @@ -1319,7 +1319,7 @@ int TsFileIOReader::do_load_timeseries_index( std::cout << "do_load_timeseries_index, reader file at " << start_offset << " to " << end_offset << std::endl; #endif - while (IS_SUCC(ret)) { + while (IS_SUCC(ret) && bs.has_remaining()) { TimeseriesIndex cur_timeseries_index; PageArena cur_timeseries_index_pa; cur_timeseries_index_pa.init(512, MOD_TSFILE_READER); // TODO 512 @@ -1368,11 +1368,10 @@ int TsFileIOReader::do_load_timeseries_index( break; } } // end while - if (!found && deserialize_buf_not_enough(ret)) { - // A complete scan of the index range found no matching - // measurement (the read ran off the end of the buffer). Keep hard - // errors such as E_OOM or E_TSFILE_CORRUPTED so callers can - // distinguish them from a genuinely missing series. + if (!found && IS_SUCC(ret)) { + // Every complete entry in the range was scanned without a match. + // A deserialization error mid-entry (E_PARTIAL_READ, E_OOM, ...) + // is propagated instead of being masked as a missing series. ret = E_NOT_EXIST; } } From 7ea7c5fab038d2719f82b5dbd7aff85ba2d99307 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Mon, 30 Nov 2026 15:14:46 +0800 Subject: [PATCH 6/7] fix(cpp): merge matching tree paths and retain scan ownership Start each merged row at the first path with its timestamp. Keep the reader on predicate streams so cleanup releases their scan iterators through the owning reader. Cover the difference between a missing measurement and an incomplete index entry, and document tree-query projection semantics. --- cpp/src/reader/qds_with_timegenerator.cc | 1 + cpp/src/reader/qds_without_timegenerator.cc | 13 +++--- cpp/test/reader/tsfile_reader_test.cc | 49 +++++++++++++++++++++ skills/tsfile/references/core-concepts.md | 28 ++++++------ 4 files changed, 70 insertions(+), 21 deletions(-) diff --git a/cpp/src/reader/qds_with_timegenerator.cc b/cpp/src/reader/qds_with_timegenerator.cc index ff0f7e5e7..a4bed7e9c 100644 --- a/cpp/src/reader/qds_with_timegenerator.cc +++ b/cpp/src/reader/qds_with_timegenerator.cc @@ -427,6 +427,7 @@ int QDSWithTimeGenerator::construct_node_tree(Expression* expr, Node*& node) { } else if (expr->type_ == SERIES_EXPR) { Node* leaf = new Node(LEAF_NODE); Path& path = expr->series_path_; + leaf->sss_.io_reader_ = io_reader_; ret = io_reader_->alloc_ssi(path.device_id_, path.measurement_, leaf->sss_.ssi_, pa_, expr->filter_); if (E_OK == ret) { diff --git a/cpp/src/reader/qds_without_timegenerator.cc b/cpp/src/reader/qds_without_timegenerator.cc index 458a55935..f4d869aaa 100644 --- a/cpp/src/reader/qds_without_timegenerator.cc +++ b/cpp/src/reader/qds_without_timegenerator.cc @@ -334,13 +334,14 @@ int QDSWithoutTimeGenerator::next(bool& has_next) { return E_OK; } - int64_t time = heap_time_.begin()->first; + // Start at the first entry so every path at this timestamp is merged. + auto iter = heap_time_.begin(); + int64_t time = iter->first; row_record_->set_timestamp(time); row_record_->get_field(0)->set_value(INT64, &time, get_len(INT64), pa_); - uint32_t count = heap_time_.count(time); - std::multimap::iterator iter = heap_time_.find(time); - for (uint32_t i = 0; i < count; ++i) { + const auto count = heap_time_.count(time); + for (size_t i = 0; i < count; ++i) { uint32_t len = 0; bool is_null_val = false; auto val_datatype = value_iters_[iter->second]->get_data_type(); @@ -366,9 +367,7 @@ int QDSWithoutTimeGenerator::next(bool& has_next) { return read_error_; } } - std::multimap::iterator cur = iter; - iter++; // cppcheck-suppress postfixOperator - heap_time_.erase(cur); + iter = heap_time_.erase(iter); } // Apply offset: skip this row. diff --git a/cpp/test/reader/tsfile_reader_test.cc b/cpp/test/reader/tsfile_reader_test.cc index 01033d067..eb8d38999 100644 --- a/cpp/test/reader/tsfile_reader_test.cc +++ b/cpp/test/reader/tsfile_reader_test.cc @@ -426,6 +426,55 @@ class DeviceIndexReadTest : public TsFileReaderTest { std::vector bytes_; }; +TEST_F(DeviceIndexReadTest, MissingMeasurementRequiresACompleteIndexScan) { + const auto device = std::make_shared("root.sg.d0"); + InMemoryRandomAccessReadFile source(bytes_); + TsFileIOReader reader; + ASSERT_EQ(reader.init(&source), E_OK); + TsFileMeta* meta = nullptr; + ASSERT_EQ(reader.get_tsfile_meta(meta), E_OK); + PageArena arena; + arena.init(512, MOD_TSFILE_READER); + + // "z" sorts after the only measurement ("value"), so finding it absent + // requires scanning the entire leaf. + std::vector indexes(1, nullptr); + ASSERT_EQ(reader.get_timeseries_indexes(device, {"z"}, indexes, arena), + E_OK); + EXPECT_EQ(indexes[0], nullptr); + + std::shared_ptr device_entry; + int64_t node_end = 0; + ASSERT_EQ(reader.load_device_index_entry( + std::make_shared(device), device_entry, + node_end), + E_OK); + const int64_t node_start = device_entry->get_offset(); + MetaIndexNode* raw_node = nullptr; + ASSERT_EQ(reader.read_device_meta_index(node_start, node_end, arena, + raw_node, /*leaf=*/true), + E_OK); + std::shared_ptr node(raw_node, MetaIndexNode::self_deleter); + // Shorten the indexed range by one byte. The file still supplies every + // requested byte, so the partial read comes from parsing the last entry. + --node->end_offset_; + ByteStream encoded(ByteStream::DEFAULT_PAGE_SIZE, MOD_DEFAULT); + ASSERT_EQ(node->serialize_to(encoded), E_OK); + ASSERT_EQ(encoded.total_size(), node_end - node_start); + uint32_t copied = 0; + ASSERT_EQ(encoded.read_buf(bytes_.data() + node_start, encoded.total_size(), + copied), + E_OK); + + InMemoryRandomAccessReadFile partial_source(bytes_); + TsFileIOReader partial_reader; + ASSERT_EQ(partial_reader.init(&partial_source), E_OK); + ASSERT_EQ(partial_reader.get_tsfile_meta(meta), E_OK); + EXPECT_EQ( + partial_reader.get_timeseries_indexes(device, {"z"}, indexes, arena), + E_PARTIAL_READ); +} + TEST_F(DeviceIndexReadTest, MetadataEnumerationRejectsShortDeviceIndex) { for (int fail_at : {0, 1, 2}) { for (bool report_zero : {false, true}) { diff --git a/skills/tsfile/references/core-concepts.md b/skills/tsfile/references/core-concepts.md index 8e1502634..5b0ebf667 100644 --- a/skills/tsfile/references/core-concepts.md +++ b/skills/tsfile/references/core-concepts.md @@ -71,20 +71,20 @@ reference separately only after selecting the binding. ## Result-Column Semantics (Tree Model) -A multi-path tree query returns the leading `time` column plus one column per -selected measurement, in selection order. The result schema depends on whether -each selected measurement exists in the file: - -- **Exists but has no data in the query range**: the column is kept with the - measurement's declared data type, and every emitted row carries NULL in that - column (Java, C++, and Python agree). -- **Does not exist in the file**: the column is dropped from the result schema - (Java, C++, and Python agree). - -Because a missing measurement drops its column, do not assume a fixed column -count or positional index. Look values up by column name (or inspect the -result metadata), and treat NULL as a legitimate "no data in range" signal -rather than an absent column. +For tree-model time-range queries using C++ `TsFileReader::query(paths, +start_time, end_time, result_set)` or Python `query_timeseries()`, the result +starts with `time` and lists the selected measurements found in the file in +selection order. Measurements that share a timestamp contribute their values to +the same row. A measurement with no data in the range keeps its declared +type and has a NULL value in every returned row. When all selected measurements +are empty in the range, the result keeps those columns and returns no rows. +Missing measurements are omitted, so use the result metadata to locate columns. +Java tree queries with a global time filter also retain selected measurements +whose data all fall outside the requested range. + +For C++ `TsFileReader::query(QueryExpression*, ResultSet*&)` with a series +predicate, selecting a missing measurement makes the query fail. A missing +measurement used only in the predicate contributes no matching timestamps. ## Cross-Language Files From 61375f1709cf9581c75a601118a6e0e6ad48fe5b Mon Sep 17 00:00:00 2001 From: ColinLee Date: Mon, 30 Nov 2026 15:53:42 +0800 Subject: [PATCH 7/7] Fix arena statistic ownership on incomplete index reads Track the statistic allocation when replacing it so short reads and index reuse release the correct storage. Cover the failure path and the all-null row on a shared aligned timestamp, and clarify the tree query contract. --- cpp/src/common/tsfile_common.h | 46 +++++++++++++---------- cpp/test/common/tsfile_common_test.cc | 17 +++++++++ cpp/test/reader/tsfile_reader_test.cc | 45 ++++++++++++++++++++++ skills/tsfile/references/core-concepts.md | 7 +++- 4 files changed, 93 insertions(+), 22 deletions(-) diff --git a/cpp/src/common/tsfile_common.h b/cpp/src/common/tsfile_common.h index 49b54603d..ed9f24b50 100644 --- a/cpp/src/common/tsfile_common.h +++ b/cpp/src/common/tsfile_common.h @@ -386,10 +386,8 @@ class TimeseriesIndex : public ITimeseriesIndex { measurement_name_.reset(); data_type_ = common::VECTOR; chunk_meta_list_serialized_buf_.reset(); - if (statistic_ != nullptr && !statistic_from_pa_) { - StatisticFactory::free(statistic_); - statistic_ = nullptr; - } + replace_statistic(nullptr, false); + chunk_meta_list_ = nullptr; } int add_chunk_meta(ChunkMeta* chunk_meta, bool serialize_statistic); @@ -426,12 +424,7 @@ class TimeseriesIndex : public ITimeseriesIndex { return metadata_length_; } int init_statistic(common::TSDataType data_type) { - if (statistic_ != nullptr && - !statistic_from_pa_) { // clear old statistic - StatisticFactory::free(statistic_); - statistic_ = nullptr; - } - statistic_ = StatisticFactory::alloc_statistic(data_type); + replace_statistic(StatisticFactory::alloc_statistic(data_type), false); if (IS_NULL(statistic_)) { return common::E_OOM; } @@ -471,13 +464,8 @@ class TimeseriesIndex : public ITimeseriesIndex { (char&)data_type_, in))) { } else if (RET_FAIL(common::SerializationUtil::read_var_uint( chunk_meta_list_data_size_, in))) { - } else if (nullptr == - (statistic_ = StatisticFactory::alloc_statistic_with_pa( - data_type_, pa))) { - ret = common::E_OOM; - } else if (RET_FAIL(statistic_->deserialize_from(in))) { + } else if (RET_FAIL(deserialize_statistic(in, pa))) { } else { - statistic_from_pa_ = true; void* chunk_meta_list_buf = pa->alloc(sizeof(*chunk_meta_list_)); if (IS_NULL(chunk_meta_list_buf)) { return common::E_OOM; @@ -508,6 +496,15 @@ class TimeseriesIndex : public ITimeseriesIndex { return ret; } + int deserialize_statistic(common::ByteStream& in, common::PageArena* pa) { + replace_statistic( + StatisticFactory::alloc_statistic_with_pa(data_type_, pa), true); + if (IS_NULL(statistic_)) { + return common::E_OOM; + } + return statistic_->deserialize_from(in); + } + int clone_from(const TimeseriesIndex& that, common::PageArena* pa) { int ret = common::E_OK; timeseries_meta_type_ = that.timeseries_meta_type_; @@ -516,12 +513,13 @@ class TimeseriesIndex : public ITimeseriesIndex { metadata_length_ = that.metadata_length_; data_type_ = that.data_type_; - statistic_ = StatisticFactory::alloc_statistic_with_pa(data_type_, pa); - if (IS_NULL(statistic_)) { + Statistic* statistic = + StatisticFactory::alloc_statistic_with_pa(data_type_, pa); + if (IS_NULL(statistic)) { return common::E_OOM; } - clone_statistic(that.statistic_, this->statistic_, data_type_); - statistic_from_pa_ = true; + clone_statistic(that.statistic_, statistic, data_type_); + replace_statistic(statistic, true); if (RET_FAIL(measurement_name_.dup_from(that.measurement_name_, *pa))) { return ret; @@ -576,6 +574,14 @@ class TimeseriesIndex : public ITimeseriesIndex { } #endif private: + void replace_statistic(Statistic* statistic, bool from_pa) { + if (statistic_ != nullptr && !statistic_from_pa_) { + StatisticFactory::free(statistic_); + } + statistic_ = statistic; + statistic_from_pa_ = from_pa; + } + /* * If this timeseries has more than one chunk meta, timeseries_meta_type_ * is 1. Otherwise timeseries_meta_type_ is 0. It also should OR with mask diff --git a/cpp/test/common/tsfile_common_test.cc b/cpp/test/common/tsfile_common_test.cc index 0a25c28df..42a37b653 100644 --- a/cpp/test/common/tsfile_common_test.cc +++ b/cpp/test/common/tsfile_common_test.cc @@ -181,6 +181,23 @@ TEST_F(TimeseriesIndexTest, ResetFunction) { EXPECT_EQ(tsIndex.get_chunk_meta_list(), nullptr); } +TEST_F(TimeseriesIndexTest, CanReuseIndexAfterStatisticReadFails) { + common::PageArena arena; + arena.init(1024, common::MOD_TIMESERIES_INDEX_OBJ); + common::ByteStream stats(1024, common::MOD_TIMESERIES_INDEX_OBJ); + ASSERT_EQ(common::SerializationUtil::write_var_uint(1, stats), + common::E_OK); + TimeseriesIndex index; + index.set_data_type(common::INT32); + ASSERT_EQ(index.init_statistic(common::INT32), common::E_OK); + ASSERT_EQ(index.deserialize_statistic(stats, &arena), + common::E_PARTIAL_READ); + index.reset(); + EXPECT_EQ(index.get_statistic(), nullptr); + ASSERT_EQ(index.init_statistic(common::INT64), common::E_OK); + EXPECT_EQ(index.get_statistic()->get_type(), common::INT64); +} + TEST_F(TimeseriesIndexTest, SerializeAndDeserialize) { common::PageArena arena; arena.init(1024, common::MOD_TIMESERIES_INDEX_OBJ); diff --git a/cpp/test/reader/tsfile_reader_test.cc b/cpp/test/reader/tsfile_reader_test.cc index eb8d38999..d611856a4 100644 --- a/cpp/test/reader/tsfile_reader_test.cc +++ b/cpp/test/reader/tsfile_reader_test.cc @@ -2450,6 +2450,51 @@ TEST_F(TsFileReaderTest, SinglePathEmptyInRangeKeepsColumnWithNoRows) { reader.close(); } +TEST_F(TsFileReaderTest, AlignedQueryKeepsTimestampWithOnlyUnselectedValues) { + const std::string device = "root.aligned"; + std::vector schemas = { + new MeasurementSchema("s", INT64, PLAIN, UNCOMPRESSED), + new MeasurementSchema("q", INT32, PLAIN, UNCOMPRESSED), + new MeasurementSchema("z", INT32, PLAIN, UNCOMPRESSED)}; + ASSERT_EQ(tsfile_writer_->register_aligned_timeseries(device, schemas), + E_OK); + for (int32_t time : {1, 2, 3}) { + TsRecord record(time, device); + if (time == 2) { + record.add_point("z", time); + } else { + record.add_point("s", static_cast(time)); + record.add_point("q", time); + } + ASSERT_EQ(tsfile_writer_->write_record_aligned(record), E_OK); + } + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + storage::TsFileReader reader; + ASSERT_EQ(reader.open(file_name_), E_OK); + std::vector paths = {device + ".s", device + ".q"}; + storage::ResultSet* result = nullptr; + ASSERT_EQ(reader.query(paths, 2, 2, result), E_OK); + ASSERT_NE(result, nullptr); + auto metadata = result->get_metadata(); + ASSERT_EQ(metadata->get_column_count(), 3u); + EXPECT_EQ(metadata->get_column_name(2), paths[0]); + EXPECT_EQ(metadata->get_column_type(2), INT64); + EXPECT_EQ(metadata->get_column_name(3), paths[1]); + EXPECT_EQ(metadata->get_column_type(3), INT32); + bool has_next = false; + ASSERT_EQ(result->next(has_next), E_OK); + ASSERT_TRUE(has_next); + EXPECT_EQ(result->get_row_record()->get_timestamp(), 2); + EXPECT_TRUE(result->is_null(2)); + EXPECT_TRUE(result->is_null(3)); + ASSERT_EQ(result->next(has_next), E_OK); + EXPECT_FALSE(has_next); + reader.destroy_query_data_set(result); + reader.close(); +} + TEST_F(TsFileReaderTest, AllSelectedEmptyInRangeKeepColumnsWithNoRows) { const std::string device = "root.t"; ASSERT_EQ(tsfile_writer_->register_timeseries( diff --git a/skills/tsfile/references/core-concepts.md b/skills/tsfile/references/core-concepts.md index 5b0ebf667..bdab156a6 100644 --- a/skills/tsfile/references/core-concepts.md +++ b/skills/tsfile/references/core-concepts.md @@ -76,8 +76,11 @@ start_time, end_time, result_set)` or Python `query_timeseries()`, the result starts with `time` and lists the selected measurements found in the file in selection order. Measurements that share a timestamp contribute their values to the same row. A measurement with no data in the range keeps its declared -type and has a NULL value in every returned row. When all selected measurements -are empty in the range, the result keeps those columns and returns no rows. +type and has a NULL value in every returned row. If time statistics rule out the +requested range for every selected series, the result keeps the columns and +returns zero rows. On an aligned device, the shared time axis can also supply a +timestamp at which only unselected measurements have values. The query may +return that timestamp with NULL in every selected measurement column. Missing measurements are omitted, so use the result metadata to locate columns. Java tree queries with a global time filter also retain selected measurements whose data all fall outside the requested range.