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/src/file/tsfile_io_reader.cc b/cpp/src/file/tsfile_io_reader.cc index 1c4cac29f..6de4ed20d 100644 --- a/cpp/src/file/tsfile_io_reader.cc +++ b/cpp/src/file/tsfile_io_reader.cc @@ -90,11 +90,24 @@ 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, + 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 +119,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) { @@ -1303,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 @@ -1352,7 +1368,10 @@ int TsFileIOReader::do_load_timeseries_index( break; } } // end while - if (!found) { + 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; } } diff --git a/cpp/src/file/tsfile_io_reader.h b/cpp/src/file/tsfile_io_reader.h index 22283ebc5..f996991cd 100644 --- a/cpp/src/file/tsfile_io_reader.h +++ b/cpp/src/file/tsfile_io_reader.h @@ -82,10 +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); + // 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, diff --git a/cpp/src/reader/qds_with_timegenerator.cc b/cpp/src/reader/qds_with_timegenerator.cc index d5398bbc9..a4bed7e9c 100644 --- a/cpp/src/reader/qds_with_timegenerator.cc +++ b/cpp/src/reader/qds_with_timegenerator.cc @@ -427,14 +427,17 @@ 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) { 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..f4d869aaa 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(); @@ -304,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(); @@ -336,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/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/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 { diff --git a/cpp/test/reader/tsfile_reader_test.cc b/cpp/test/reader/tsfile_reader_test.cc index bef1dfe9f..d611856a4 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}) { @@ -2303,6 +2352,194 @@ TEST_F(TsFileReaderTest, RepeatedGetTimeseriesMetadataDoesNotLeakArena) { 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(); +} + +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, 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( + 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..bdab156a6 100644 --- a/skills/tsfile/references/core-concepts.md +++ b/skills/tsfile/references/core-concepts.md @@ -69,6 +69,26 @@ 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) + +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. 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. + +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 - Write with one binding and read with every binding required by the target