diff --git a/cpp/src/common/schema.h b/cpp/src/common/schema.h index feb2eb799..007e1f1db 100644 --- a/cpp/src/common/schema.h +++ b/cpp/src/common/schema.h @@ -173,9 +173,15 @@ struct MeasurementSchemaGroup { // measurement_name -> MeasurementSchema MeasurementSchemaMap measurement_schema_map_; bool is_aligned_ = false; + bool has_last_time_ = false; TimeChunkWriter* time_chunk_writer_ = nullptr; int64_t last_time_ = INT64_MIN; + void update_last_time(int64_t timestamp) { + last_time_ = std::max(last_time_, timestamp); + has_last_time_ = true; + } + ~MeasurementSchemaGroup() { if (time_chunk_writer_ != nullptr) { delete time_chunk_writer_; diff --git a/cpp/src/writer/time_chunk_writer.cc b/cpp/src/writer/time_chunk_writer.cc index 0a0623686..7825ad459 100644 --- a/cpp/src/writer/time_chunk_writer.cc +++ b/cpp/src/writer/time_chunk_writer.cc @@ -19,6 +19,9 @@ #include "time_chunk_writer.h" +#include +#include + #include "common/logger/elog.h" using namespace common; @@ -199,4 +202,17 @@ bool TimeChunkWriter::hasData() { time_page_writer_.get_statistic()->count_ > 0); } +int64_t TimeChunkWriter::get_last_time() { + int64_t last = std::numeric_limits::min(); + if (chunk_statistic_ != nullptr && chunk_statistic_->get_count() > 0) { + last = chunk_statistic_->get_end_time(); + } + if (time_page_writer_.get_statistic() != nullptr && + time_page_writer_.get_statistic()->get_count() > 0) { + last = + std::max(last, time_page_writer_.get_statistic()->get_end_time()); + } + return last; +} + } // end namespace storage diff --git a/cpp/src/writer/time_chunk_writer.h b/cpp/src/writer/time_chunk_writer.h index f7360c369..6b189d71f 100644 --- a/cpp/src/writer/time_chunk_writer.h +++ b/cpp/src/writer/time_chunk_writer.h @@ -100,6 +100,11 @@ class TimeChunkWriter { bool hasData(); + // Highest timestamp written so far (sealed pages plus the current + // unsealed page). Only meaningful when hasData() is true; returns the + // minimum int64 value when nothing has been written. + int64_t get_last_time(); + int64_t estimate_max_series_mem_size(); // Current (unsealed) page point count. @@ -122,6 +127,14 @@ class TimeChunkWriter { } private: + friend class TsFileWriter; + + // The aligned table writer has validated these timestamps and splits + // ranges at the same page boundaries as the value columns. + int write_ordered_page_batch(const int64_t* timestamps, uint32_t count) { + return time_page_writer_.encode_ordered_batch(timestamps, count); + } + FORCE_INLINE bool is_cur_page_full() const { // FIXME return (time_page_writer_.get_point_numer() >= diff --git a/cpp/src/writer/time_page_writer.h b/cpp/src/writer/time_page_writer.h index 33d6860ed..0117489e9 100644 --- a/cpp/src/writer/time_page_writer.h +++ b/cpp/src/writer/time_page_writer.h @@ -19,6 +19,8 @@ #ifndef WRITER_PAGE_TIME_WRITER_H #define WRITER_PAGE_TIME_WRITER_H +#include + #include "common/allocator/byte_stream.h" #include "common/global.h" #include "common/statistic.h" @@ -85,26 +87,32 @@ class TimePageWriter { return ret; } + // Reject a timestamp only when it is strictly less than the previous one + // (allow_non_decreasing_timestamps_ enabled), or at most equal to it + // (flag disabled, the historical behavior). + FORCE_INLINE static bool is_out_of_order(int64_t time, int64_t last_time) { + return common::g_config_value_.allow_non_decreasing_timestamps_ + ? time < last_time + : time <= last_time; + } + + static bool is_batch_in_order(const int64_t* times, uint32_t count) { + return common::g_config_value_.allow_non_decreasing_timestamps_ + ? batch_in_order(times, count) + : batch_in_order(times, count); + } + int write_batch(const int64_t* timestamps, uint32_t count) { - int ret = common::E_OK; - if (count == 0) return ret; + if (count == 0) return common::E_OK; // Check order: first timestamp vs existing end_time if (statistic_->count_ != 0 && is_inited_ && is_out_of_order(timestamps[0], statistic_->end_time_)) { return common::E_OUT_OF_ORDER; } - // Check monotonicity within batch - for (uint32_t i = 1; i < count; i++) { - if (is_out_of_order(timestamps[i], timestamps[i - 1])) { - return common::E_OUT_OF_ORDER; - } - } - if (RET_FAIL(time_encoder_->encode_batch(timestamps, count, - time_out_stream_))) { - } else { - statistic_->update_time_batch(timestamps, count); + if (!is_batch_in_order(timestamps, count)) { + return common::E_OUT_OF_ORDER; } - return ret; + return encode_ordered_batch(timestamps, count); } FORCE_INLINE uint32_t get_point_numer() const { return statistic_->count_; } @@ -136,14 +144,35 @@ class TimePageWriter { void destroy_page_data() { cur_page_data_.destroy(); } private: - // Reject a timestamp only when it is strictly less than the previous one - // (allow_non_decreasing_timestamps_ enabled), or at most equal to it - // (flag disabled, the historical behavior). - FORCE_INLINE static bool is_out_of_order(int64_t time, int64_t last_time) { - return common::g_config_value_.allow_non_decreasing_timestamps_ - ? time < last_time - : time <= last_time; + friend class TimeChunkWriter; + + int encode_ordered_batch(const int64_t* timestamps, uint32_t count) { + int ret = + time_encoder_->encode_batch(timestamps, count, time_out_stream_); + if (ret == common::E_OK) { + statistic_->update_time_batch(timestamps, count); + } + return ret; } + + template + static bool batch_in_order(const int64_t* times, uint32_t count) { + // Compare directly to avoid signed overflow. Reduce comparisons in + // blocks so long ordered ranges vectorize and bad input fails early. + while (count > 1) { + const uint32_t pairs = std::min(count - 1, 256); + bool invalid = false; + for (uint32_t i = 0; i < pairs; ++i) { + invalid |= AllowEqual ? times[i + 1] < times[i] + : times[i + 1] <= times[i]; + } + if (invalid) return false; + times += pairs; + count -= pairs; + } + return true; + } + FORCE_INLINE int prepare_end_page() { int ret = common::E_OK; if (RET_FAIL(time_encoder_->flush(time_out_stream_))) { diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index dcf6afe17..95e899ee1 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -227,8 +227,7 @@ int TsFileWriter::init(RestorableTsFileIOWriter* rw) { // Track the highest end_time across recovered chunks so that // appending writes can refuse out-of-order timestamps. if (cm->statistic_ != nullptr && cm->statistic_->count_ > 0) { - group->last_time_ = - std::max(group->last_time_, cm->statistic_->end_time_); + group->update_last_time(cm->statistic_->end_time_); } std::string mname = cm->measurement_name_.to_std_string(); if (mname.empty()) { @@ -816,7 +815,8 @@ bool TsFileWriter::recovered_last_time_order_violated( return false; } auto schema_it = schemas_.find(device_id); - if (schema_it == schemas_.end() || schema_it->second == nullptr) { + if (schema_it == schemas_.end() || schema_it->second == nullptr || + !schema_it->second->has_last_time_) { return false; } return common::g_config_value_.allow_non_decreasing_timestamps_ @@ -856,8 +856,7 @@ int TsFileWriter::write_record(const TsRecord& record) { if (enforce_recovered_last_time_order_) { auto schema_it = schemas_.find(device_id); if (schema_it != schemas_.end() && schema_it->second != nullptr) { - schema_it->second->last_time_ = - std::max(schema_it->second->last_time_, record.timestamp_); + schema_it->second->update_last_time(record.timestamp_); } } record_count_since_last_flush_++; @@ -972,8 +971,7 @@ int TsFileWriter::write_record_aligned(const TsRecord& record) { if (enforce_recovered_last_time_order_) { auto schema_it = schemas_.find(device_id); if (schema_it != schemas_.end() && schema_it->second != nullptr) { - schema_it->second->last_time_ = - std::max(schema_it->second->last_time_, record.timestamp_); + schema_it->second->update_last_time(record.timestamp_); } } return ret; @@ -1216,9 +1214,8 @@ int TsFileWriter::write_tablet_aligned(const Tablet& tablet) { tablet.timestamps_ != nullptr) { auto schema_it = schemas_.find(device_id); if (schema_it != schemas_.end() && schema_it->second != nullptr) { - schema_it->second->last_time_ = - std::max(schema_it->second->last_time_, - tablet.timestamps_[total_rows - 1]); + schema_it->second->update_last_time( + tablet.timestamps_[total_rows - 1]); } } return ret; @@ -1276,9 +1273,8 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { tablet.timestamps_ != nullptr) { auto schema_it = schemas_.find(device_id); if (schema_it != schemas_.end() && schema_it->second != nullptr) { - schema_it->second->last_time_ = - std::max(schema_it->second->last_time_, - tablet.timestamps_[total_rows - 1]); + schema_it->second->update_last_time( + tablet.timestamps_[total_rows - 1]); } } record_count_since_last_flush_ += total_rows; @@ -1324,6 +1320,13 @@ int TsFileWriter::write_table(Tablet& tablet) { return ret; } + if (tablet.get_cur_row_size() > tablet.max_row_num_) { + return E_OUT_OF_RANGE; + } + if (table_aligned_ && tablet.get_cur_row_size() != 0 && + !tablet.timestamps_) { + return E_INVALID_ARG; + } auto device_id_end_index_pairs = split_tablet_by_device(tablet); if (table_aligned_) { @@ -1336,10 +1339,11 @@ int TsFileWriter::write_table(Tablet& tablet) { uint32_t ei; }; struct DeviceWriteCtx { - TimeChunkWriter* tcw; + std::shared_ptr device_id; + TimeChunkWriter* tcw = nullptr; std::vector value_tasks; std::vector segments; - uint32_t initial_page_points; + uint32_t initial_page_points = 0; }; const uint32_t page_max_points = @@ -1348,95 +1352,102 @@ int TsFileWriter::write_table(Tablet& tablet) { std::vector device_ctxs; std::map, size_t, IDeviceIDComparator> device_ctx_index; - int start_idx = 0; - for (auto& pair : device_id_end_index_pairs) { - auto device_id = pair.first; - int end_idx = pair.second; - if (end_idx == 0) continue; + // Keep the ranges in input order for each device. Validate every + // range before preparing writers, which can seal existing pages. + const int64_t* times = tablet.timestamps_; + uint32_t start = 0; + for (const auto& pair : device_id_end_index_pairs) { + const uint32_t end = pair.second; + if (end == 0) continue; + const auto& device_id = pair.first; + const auto index = + device_ctx_index.emplace(device_id, device_ctxs.size()); + if (index.second) { + device_ctxs.emplace_back(); + device_ctxs.back().device_id = device_id; + auto schema_it = schemas_.find(device_id); + if (schema_it != schemas_.end() && schema_it->second) { + const auto* group = schema_it->second; + auto* chunk = group->time_chunk_writer_; + if ((group->has_last_time_ && + TimePageWriter::is_out_of_order(times[start], + group->last_time_)) || + (chunk && chunk->hasData() && + TimePageWriter::is_out_of_order( + times[start], chunk->get_last_time()))) { + return E_OUT_OF_ORDER; + } + } + } - const uint32_t si = static_cast(start_idx); - const uint32_t ei = static_cast(end_idx); - // Recovery: refuse any segment whose first timestamp would land - // at or before a flushed chunk's end_time for this device. This - // mirrors the per-record / per-tablet check on the tree path. - if (tablet.timestamps_ && ei > si && - recovered_last_time_order_violated(device_id, - tablet.timestamps_[si])) { + auto& segments = device_ctxs[index.first->second].segments; + if ((!segments.empty() && + TimePageWriter::is_out_of_order( + times[start], times[segments.back().ei - 1])) || + !TimePageWriter::is_batch_in_order(times + start, + end - start)) { return E_OUT_OF_ORDER; } - auto idx_it = device_ctx_index.find(device_id); - if (idx_it == device_ctx_index.end()) { - SimpleVector value_chunk_writers; - TimeChunkWriter* time_chunk_writer = nullptr; - if (RET_FAIL(do_check_schema_table(device_id, tablet, - time_chunk_writer, - value_chunk_writers))) { - return ret; - } + segments.push_back({start, end}); + start = end; + } - // device_ctx_index tracks devices seen in *this* tablet, but - // do_check_schema_table returns the device's persistent chunk - // writer, which may already hold points from earlier - // tablets/records in the same un-flushed chunk group — so - // time_cur_points can be > 0 even on first sight in this - // tablet. - uint32_t time_cur_points = time_chunk_writer->get_point_numer(); - if (time_cur_points >= page_max_points) { - // Seal the time page first, then every value page in - // lockstep. Any failure leaves columns at different - // page boundaries and the chunk group can no longer be - // sealed coherently — mark the writer unrecoverable. - if (time_chunk_writer->has_current_page_data()) { - if (RET_FAIL(time_chunk_writer->seal_current_page())) { + for (auto& ctx : device_ctxs) { + SimpleVector value_chunk_writers; + TimeChunkWriter* time_chunk_writer = nullptr; + if (RET_FAIL(do_check_schema_table(ctx.device_id, tablet, + time_chunk_writer, + value_chunk_writers))) { + return ret; + } + + // Earlier tablets may have left a partially filled page. + uint32_t time_cur_points = time_chunk_writer->get_point_numer(); + if (time_cur_points >= page_max_points) { + // Seal the time page first, then every value page in + // lockstep. Any failure leaves columns at different + // page boundaries and the chunk group can no longer be + // sealed coherently — mark the writer unrecoverable. + if (time_chunk_writer->has_current_page_data()) { + if (RET_FAIL(time_chunk_writer->seal_current_page())) { + unrecoverable_ = true; + return ret; + } + } + for (uint32_t k = 0; k < value_chunk_writers.size(); k++) { + if (!IS_NULL(value_chunk_writers[k]) && + value_chunk_writers[k]->has_current_page_data()) { + if (RET_FAIL( + value_chunk_writers[k]->seal_current_page())) { unrecoverable_ = true; return ret; } } - for (uint32_t k = 0; k < value_chunk_writers.size(); k++) { - if (!IS_NULL(value_chunk_writers[k]) && - value_chunk_writers[k]->has_current_page_data()) { - if (RET_FAIL(value_chunk_writers[k] - ->seal_current_page())) { - unrecoverable_ = true; - return ret; - } - } - } - time_cur_points = 0; } + time_cur_points = 0; + } - DeviceWriteCtx ctx; - ctx.tcw = time_chunk_writer; - ctx.initial_page_points = time_cur_points; - uint32_t field_col_count = 0; - for (uint32_t i = 0; i < tablet.get_column_count(); ++i) { - if (tablet.column_categories_[i] == - common::ColumnCategory::FIELD) { - ValueChunkWriter* vcw = - value_chunk_writers[field_col_count]; - if (!IS_NULL(vcw)) { - ctx.value_tasks.push_back({vcw, i}); - } - field_col_count++; + ctx.tcw = time_chunk_writer; + ctx.initial_page_points = time_cur_points; + uint32_t field_col_count = 0; + for (uint32_t i = 0; i < tablet.get_column_count(); ++i) { + if (tablet.column_categories_[i] == + common::ColumnCategory::FIELD) { + ValueChunkWriter* vcw = + value_chunk_writers[field_col_count]; + if (!IS_NULL(vcw)) { + ctx.value_tasks.push_back({vcw, i}); } + field_col_count++; } - device_ctxs.push_back(std::move(ctx)); - idx_it = device_ctx_index - .insert(std::make_pair(device_id, - device_ctxs.size() - 1)) - .first; } - - device_ctxs[idx_it->second].segments.push_back({si, ei}); - start_idx = end_idx; } auto write_time_segments = - [this, &tablet, page_max_points]( - TimeChunkWriter* tcw, const std::vector& segments, - uint32_t initial_page_points) -> int { + [times, page_max_points](TimeChunkWriter* tcw, + const std::vector& segments, + uint32_t initial_page_points) -> int { int r = E_OK; - tcw->set_enable_page_seal_if_full(false); // The caller seals and resets time_cur_points to 0 once it reaches // page_max_points, so initial_page_points is always in // [0, page_max_points): >0 means a partial page (room is the @@ -1452,23 +1463,20 @@ int TsFileWriter::write_table(Tablet& tablet) { while (seg_pos < segment.ei) { uint32_t batch = std::min(page_remaining, segment.ei - seg_pos); - if ((r = time_write_column_batch( - tcw, tablet, seg_pos, seg_pos + batch)) != E_OK) { - tcw->set_enable_page_seal_if_full(true); + if ((r = tcw->write_ordered_page_batch(times + seg_pos, + batch)) != E_OK) { return r; } seg_pos += batch; page_remaining -= batch; if (page_remaining == 0) { if ((r = tcw->seal_current_page()) != E_OK) { - tcw->set_enable_page_seal_if_full(true); return r; } page_remaining = page_max_points; } } } - tcw->set_enable_page_seal_if_full(true); return r; }; @@ -1560,9 +1568,11 @@ int TsFileWriter::write_table(Tablet& tablet) { for (auto& ctx : device_ctxs) { if (RET_FAIL(write_time_segments(ctx.tcw, ctx.segments, ctx.initial_page_points))) { - // Time wrote partial rows before failing; value columns - // still hold the prior count. Same column-alignment - // hazard as the parallel path. + // Time may have partially written before failing (e.g. an + // encoder or allocation error); the value columns then lag + // the time column, so the aligned chunk group can no + // longer be sealed coherently. Out-of-order input is + // already rejected by the up-front check above. unrecoverable_ = true; return ret; } @@ -1659,9 +1669,8 @@ int TsFileWriter::write_table(Tablet& tablet) { auto schema_it = schemas_.find(pair.first); if (schema_it != schemas_.end() && schema_it->second != nullptr) { - schema_it->second->last_time_ = - std::max(schema_it->second->last_time_, - tablet.timestamps_[end_idx - 1]); + schema_it->second->update_last_time( + tablet.timestamps_[end_idx - 1]); } } update_start = end_idx; @@ -2102,6 +2111,13 @@ int TsFileWriter::flush_chunk_group(MeasurementSchemaGroup* chunk_group, if (chunk_group->is_aligned_) { TimeChunkWriter*& time_chunk_writer = chunk_group->time_chunk_writer_; ChunkHeader chunk_header = time_chunk_writer->get_chunk_header(); + // Retain the device's last accepted timestamp across the flush so + // the next write's up-front order check can still compare against + // data that has already been flushed (the chunk writer is reset + // below). + if (time_chunk_writer->hasData()) { + chunk_group->update_last_time(time_chunk_writer->get_last_time()); + } FLUSH_CHUNK(time_chunk_writer, io_writer_, chunk_header.measurement_name_, chunk_header.data_type_, chunk_header.encoding_type_, chunk_header.compression_type_, diff --git a/cpp/test/reader/table_view/tsfile_reader_table_test.cc b/cpp/test/reader/table_view/tsfile_reader_table_test.cc index b53e86ad4..9cc236cba 100644 --- a/cpp/test/reader/table_view/tsfile_reader_table_test.cc +++ b/cpp/test/reader/table_view/tsfile_reader_table_test.cc @@ -127,9 +127,18 @@ class TsFileTableReaderTest : public ::testing::Test { static_cast(i)); break; case TSDataType::STRING: - tablet.add_value(row_index, - column_schema->measurement_name_, - literal_str); + if (device_num > 1 && + column_schema->measurement_name_ == "id1") { + std::string id_value = + "device_id_" + std::to_string(i); + tablet.add_value( + row_index, column_schema->measurement_name_, + id_value.c_str()); + } else { + tablet.add_value( + row_index, column_schema->measurement_name_, + literal_str); + } break; default: break; @@ -179,21 +188,43 @@ class TsFileTableReaderTest : public ::testing::Test { (row_num / points_per_device) % device_num); break; case TSDataType::STRING: - ASSERT_EQ(table_result_set - ->get_value( - column_schema->measurement_name_) - ->compare(literal_str), - 0); + if (device_num > 1 && + column_schema->measurement_name_ == "id1") { + std::string expected = + "device_id_" + + std::to_string((row_num / points_per_device) % + device_num); + ASSERT_EQ(table_result_set + ->get_value( + column_schema->measurement_name_) + ->to_std_string(), + expected); + } else { + ASSERT_EQ(table_result_set + ->get_value( + column_schema->measurement_name_) + ->compare(literal_str), + 0); + } break; default: break; } } for (int i = 2; i <= 6; i++) { - ASSERT_EQ( - table_result_set->get_value(i)->compare( - literal_str), - 0); + if (device_num > 1 && i == 3) { + std::string expected = + "device_id_" + + std::to_string((row_num / points_per_device) % + device_num); + ASSERT_EQ(table_result_set->get_value(i) + ->to_std_string(), + expected); + } else { + ASSERT_EQ(table_result_set->get_value(i) + ->compare(literal_str), + 0); + } } for (int i = 7; i <= 11; i++) { ASSERT_EQ(table_result_set->get_value(i), diff --git a/cpp/test/writer/table_view/tsfile_writer_table_test.cc b/cpp/test/writer/table_view/tsfile_writer_table_test.cc index a24a92126..c4b62bb0f 100644 --- a/cpp/test/writer/table_view/tsfile_writer_table_test.cc +++ b/cpp/test/writer/table_view/tsfile_writer_table_test.cc @@ -19,7 +19,9 @@ #include #include +#include +#include "common/global.h" #include "common/record.h" #include "common/schema.h" #include "common/tablet.h" @@ -326,12 +328,266 @@ TEST_F(TsFileWriterTableTest, WriteDisorderTest) { ASSERT_EQ(tsfile_table_writer_->write_table(tablet), common::E_OUT_OF_ORDER); - ASSERT_EQ(tsfile_table_writer_->flush(), common::E_DATA_INCONSISTENCY); - ASSERT_EQ(tsfile_table_writer_->close(), common::E_DATA_INCONSISTENCY); - ASSERT_EQ(tsfile_table_writer_->close(), common::E_DATA_INCONSISTENCY); + // The whole tablet is validated up front, so the out-of-order batch + // writes no rows and leaves the writer usable; flush/close succeed. + ASSERT_EQ(tsfile_table_writer_->flush(), common::E_OK); + ASSERT_EQ(tsfile_table_writer_->close(), common::E_OK); + delete table_schema; +} + +TEST_F(TsFileWriterTableTest, WriteOutOfOrderThenCloseKeepsData) { + // The sequential aligned write path must not poison the writer when a + // pure out-of-order batch is rejected before any time row is written: + // data written so far has to survive a later flush/close and the file + // must stay readable. + const bool parallel_enabled = common::get_parallel_write_enabled(); + common::set_parallel_write_enabled(false); + + std::vector measurement_schemas; + std::vector column_categories; + measurement_schemas.emplace_back( + new MeasurementSchema("device", TSDataType::STRING)); + measurement_schemas.emplace_back( + new MeasurementSchema("value", TSDataType::INT64)); + column_categories.emplace_back(ColumnCategory::TAG); + column_categories.emplace_back(ColumnCategory::FIELD); + TableSchema* table_schema = + new TableSchema("test_table", measurement_schemas, column_categories); + + auto tsfile_table_writer = + std::make_shared(&write_file_, table_schema); + + const int normal_row_count = 10; + Tablet normal_tablet(table_schema->get_measurement_names(), + table_schema->get_data_types(), normal_row_count); + normal_tablet.set_table_name("test_table"); + for (int i = 0; i < normal_row_count; ++i) { + normal_tablet.add_timestamp(i, static_cast(i)); + normal_tablet.add_value(i, "device", "d0"); + normal_tablet.add_value(i, "value", static_cast(i)); + } + ASSERT_EQ(tsfile_table_writer->write_table(normal_tablet), common::E_OK); + + // A single out-of-order row (5 <= 9, the device's last timestamp) must be + // rejected before any time point is appended. + Tablet ooo_tablet(table_schema->get_measurement_names(), + table_schema->get_data_types(), 1); + ooo_tablet.set_table_name("test_table"); + ooo_tablet.add_timestamp(0, static_cast(5)); + ooo_tablet.add_value(0, "device", "d0"); + ooo_tablet.add_value(0, "value", static_cast(-1)); + ASSERT_EQ(tsfile_table_writer->write_table(ooo_tablet), + common::E_OUT_OF_ORDER); + + // The writer stays coherent: flush and close succeed, and the normal data + // written before the failure is still readable. + ASSERT_EQ(tsfile_table_writer->flush(), common::E_OK); + ASSERT_EQ(tsfile_table_writer->close(), common::E_OK); + + TsFileReader reader; + ASSERT_EQ(reader.open(file_name_), common::E_OK); + ResultSet* result_set = nullptr; + ASSERT_EQ(reader.query(table_schema->get_table_name(), {"value"}, 0, + INT32_MAX, result_set), + common::E_OK); + auto* table_result_set = static_cast(result_set); + bool has_next = false; + int64_t row_count = 0; + while (true) { + ASSERT_EQ(table_result_set->next(has_next), common::E_OK); + if (!has_next) { + break; + } + ++row_count; + } + EXPECT_EQ(row_count, normal_row_count); + table_result_set->close(); + reader.destroy_query_data_set(table_result_set); + ASSERT_EQ(reader.close(), common::E_OK); + + common::set_parallel_write_enabled(parallel_enabled); + delete table_schema; +} + +TEST_F(TsFileWriterTableTest, WriteOutOfOrderAfterFlushRejected) { + // The up-front order check must also catch a timestamp that is out + // of order against data already flushed to disk, not just data still + // held by the in-memory chunk writer. + const bool parallel_enabled = common::get_parallel_write_enabled(); + common::set_parallel_write_enabled(false); + + std::vector measurement_schemas; + std::vector column_categories; + measurement_schemas.emplace_back( + new MeasurementSchema("device", TSDataType::STRING)); + measurement_schemas.emplace_back( + new MeasurementSchema("value", TSDataType::INT64)); + column_categories.emplace_back(ColumnCategory::TAG); + column_categories.emplace_back(ColumnCategory::FIELD); + TableSchema* table_schema = + new TableSchema("test_table", measurement_schemas, column_categories); + + auto tsfile_table_writer = + std::make_shared(&write_file_, table_schema); + + Tablet normal_tablet(table_schema->get_measurement_names(), + table_schema->get_data_types(), 10); + normal_tablet.set_table_name("test_table"); + for (int i = 0; i < 10; ++i) { + normal_tablet.add_timestamp(i, static_cast(i)); + normal_tablet.add_value(i, "device", "d0"); + normal_tablet.add_value(i, "value", static_cast(i)); + } + ASSERT_EQ(tsfile_table_writer->write_table(normal_tablet), common::E_OK); + ASSERT_EQ(tsfile_table_writer->flush(), common::E_OK); + + // 5 <= 9, the last timestamp of d0 that was flushed above. + Tablet ooo_tablet(table_schema->get_measurement_names(), + table_schema->get_data_types(), 1); + ooo_tablet.set_table_name("test_table"); + ooo_tablet.add_timestamp(0, static_cast(5)); + ooo_tablet.add_value(0, "device", "d0"); + ooo_tablet.add_value(0, "value", static_cast(-1)); + ASSERT_EQ(tsfile_table_writer->write_table(ooo_tablet), + common::E_OUT_OF_ORDER); + ASSERT_EQ(tsfile_table_writer->close(), common::E_OK); + + common::set_parallel_write_enabled(parallel_enabled); delete table_schema; } +// Tablet::reset asserts the capacity precondition in debug builds. +#ifdef NDEBUG +TEST_F(TsFileWriterTableTest, RejectsOversizedRowCountBeforeWriting) { + std::unique_ptr schema(gen_table_schema(0, 0, 1)); + TsFileTableWriter writer(&write_file_, schema.get()); + Tablet tablet(schema->get_measurement_names(), schema->get_data_types(), 1); + tablet.set_table_name(schema->get_table_name()); + tablet.reset(2); + ASSERT_EQ(writer.write_table(tablet), E_OUT_OF_RANGE); + + tablet.reset(); + ASSERT_EQ(tablet.add_timestamp(0, 7), E_OK); + ASSERT_EQ(tablet.add_value(0, "s0", int64_t(42)), E_OK); + ASSERT_EQ(writer.write_table(tablet), E_OK); + ASSERT_EQ(writer.close(), E_OK); + + TsFileReader reader; + ASSERT_EQ(reader.open(file_name_), E_OK); + ResultSet* result = nullptr; + ASSERT_EQ(reader.query(schema->get_table_name(), {"s0"}, INT64_MIN, + INT64_MAX, result), + E_OK); + bool has_next = false; + ASSERT_EQ(result->next(has_next), E_OK); + ASSERT_TRUE(has_next); + EXPECT_EQ(result->get_value("time"), 7); + EXPECT_EQ(result->get_value("s0"), 42); + ASSERT_EQ(result->next(has_next), E_OK); + EXPECT_FALSE(has_next); + reader.destroy_query_data_set(result); + ASSERT_EQ(reader.close(), E_OK); +} +#endif + +TEST_F(TsFileWriterTableTest, CheckOrderAcrossInterleavedDeviceRanges) { + std::unique_ptr schema(gen_table_schema(0, 1, 1)); + TsFileTableWriter writer(&write_file_, schema.get()); + Tablet previous(schema->get_measurement_names(), schema->get_data_types(), + 1); + previous.set_table_name(schema->get_table_name()); + ASSERT_EQ(previous.add_timestamp(0, 2), E_OK); + ASSERT_EQ(previous.add_value(0, "id0", "b"), E_OK); + ASSERT_EQ(previous.add_value(0, "s0", int64_t(0)), E_OK); + ASSERT_EQ(writer.write_table(previous), E_OK); + + Tablet rows(schema->get_measurement_names(), schema->get_data_types(), 4); + rows.set_table_name(schema->get_table_name()); + const char* devices[] = {"a", "a", "b", "a"}; + const int64_t times[] = {10, 11, 1, 12}; + for (uint32_t i = 0; i < 4; ++i) { + ASSERT_EQ(rows.add_timestamp(i, times[i]), E_OK); + ASSERT_EQ(rows.add_value(i, "id0", devices[i]), E_OK); + ASSERT_EQ(rows.add_value(i, "s0", static_cast(i)), E_OK); + } + EXPECT_EQ(writer.write_table(rows), E_OUT_OF_ORDER); // b starts before 2. + ASSERT_EQ(rows.add_timestamp(2, 3), E_OK); + ASSERT_EQ(rows.add_timestamp(3, 9), E_OK); + EXPECT_EQ(writer.write_table(rows), E_OUT_OF_ORDER); // a returns to 9. + // A failed batch leaves both devices untouched; the corrected rows can + // be submitted again, even though b starts earlier than a. + ASSERT_EQ(rows.add_timestamp(3, 12), E_OK); + EXPECT_EQ(writer.write_table(rows), E_OK); + EXPECT_EQ(writer.close(), E_OK); +} + +class MinimumTableTimestampTest + : public TsFileWriterTableTest, + public ::testing::WithParamInterface> { + protected: + void SetUp() override { + TsFileWriterTableTest::SetUp(); + previous_policy_ = g_config_value_.allow_non_decreasing_timestamps_; + common::set_allow_non_decreasing_timestamps(std::get<0>(GetParam())); + } + + void TearDown() override { + common::set_allow_non_decreasing_timestamps(previous_policy_); + TsFileWriterTableTest::TearDown(); + } + + private: + bool previous_policy_; +}; + +TEST_P(MinimumTableTimestampTest, DuplicateThenContinue) { + const bool allow_equal = std::get<0>(GetParam()); + const bool flush_first = std::get<1>(GetParam()); + std::unique_ptr schema(gen_table_schema(0, 0, 1)); + TsFileTableWriter writer(&write_file_, schema.get()); + Tablet row(schema->get_measurement_names(), schema->get_data_types(), 1); + row.set_table_name(schema->get_table_name()); + ASSERT_EQ(row.add_timestamp(0, INT64_MIN), E_OK); + ASSERT_EQ(row.add_value(0, "s0", int64_t(1)), E_OK); + ASSERT_EQ(writer.write_table(row), E_OK); + if (flush_first) { + ASSERT_EQ(writer.flush(), E_OK); + } + + ASSERT_EQ(row.add_value(0, "s0", int64_t(2)), E_OK); + EXPECT_EQ(writer.write_table(row), allow_equal ? E_OK : E_OUT_OF_ORDER); + ASSERT_EQ(row.add_timestamp(0, INT64_MIN + 1), E_OK); + ASSERT_EQ(row.add_value(0, "s0", int64_t(3)), E_OK); + ASSERT_EQ(writer.write_table(row), E_OK); + ASSERT_EQ(writer.close(), E_OK); + + TsFileReader reader; + ASSERT_EQ(reader.open(file_name_), E_OK); + ResultSet* result = nullptr; + ASSERT_EQ(reader.query(schema->get_table_name(), {"s0"}, INT64_MIN, + INT64_MIN + 1, result), + E_OK); + const std::vector expected = allow_equal + ? std::vector{1, 2, 3} + : std::vector{1, 3}; + bool has_next = false; + for (int64_t value : expected) { + ASSERT_EQ(result->next(has_next), E_OK); + ASSERT_TRUE(has_next); + EXPECT_EQ(result->get_value("s0"), value); + EXPECT_EQ(result->get_value("time"), + value == 3 ? INT64_MIN + 1 : INT64_MIN); + } + ASSERT_EQ(result->next(has_next), E_OK); + EXPECT_FALSE(has_next); + reader.destroy_query_data_set(result); + ASSERT_EQ(reader.close(), E_OK); +} + +INSTANTIATE_TEST_SUITE_P(TimestampPoliciesAndFlush, MinimumTableTimestampTest, + ::testing::Combine(::testing::Bool(), + ::testing::Bool())); + TEST_F(TsFileWriterTableTest, WriteTableTestMultiFlush) { auto table_schema = gen_table_schema(0); auto tsfile_table_writer_ = std::make_shared( diff --git a/cpp/test/writer/time_chunk_writer_test.cc b/cpp/test/writer/time_chunk_writer_test.cc index 2a014422a..447953db5 100644 --- a/cpp/test/writer/time_chunk_writer_test.cc +++ b/cpp/test/writer/time_chunk_writer_test.cc @@ -59,6 +59,20 @@ TEST_F(TimeChunkWriterTest, WriteLargeDataSet) { EXPECT_EQ(time_chunk_writer.get_chunk_statistic()->count_, 10000); } +TEST_F(TimeChunkWriterTest, WriteBatchChecksOrderBeforeEncoding) { + const auto previous_page_limit = g_config_value_.page_writer_max_point_num_; + g_config_value_.page_writer_max_point_num_ = 8; + time_chunk_writer.set_enable_page_seal_if_full(false); + const int64_t disordered[] = {10, 12, 11}; + EXPECT_EQ(time_chunk_writer.write_batch(disordered, 3), E_OUT_OF_ORDER); + EXPECT_FALSE(time_chunk_writer.hasData()); + + const int64_t ordered[] = {10, 11, 12}; + EXPECT_EQ(time_chunk_writer.write_batch(ordered, 3), E_OK); + EXPECT_EQ(time_chunk_writer.get_last_time(), 12); + g_config_value_.page_writer_max_point_num_ = previous_page_limit; +} + TEST_F(TimeChunkWriterTest, EndEncodeChunk) { EXPECT_EQ(time_chunk_writer.write(1234567890), E_OK); EXPECT_EQ(time_chunk_writer.end_encode_chunk(), E_OK); @@ -70,4 +84,4 @@ TEST_F(TimeChunkWriterTest, DestroyTimeChunkWriter) { time_chunk_writer.destroy(); EXPECT_EQ(time_chunk_writer.get_chunk_statistic(), nullptr); EXPECT_EQ(time_chunk_writer.get_chunk_data().total_size(), 0); -} \ No newline at end of file +} diff --git a/cpp/test/writer/time_page_writer_test.cc b/cpp/test/writer/time_page_writer_test.cc index 2fe7ae90c..778cc1b76 100644 --- a/cpp/test/writer/time_page_writer_test.cc +++ b/cpp/test/writer/time_page_writer_test.cc @@ -20,6 +20,9 @@ #include +#include +#include + #include "common/allocator/byte_stream.h" #include "common/statistic.h" #include "encoding/plain_encoder.h" @@ -55,6 +58,34 @@ TEST_F(TimePageWriterTest, WriteLargeDataSet) { EXPECT_EQ(page_writer.get_point_numer(), 10000); } +TEST_F(TimePageWriterTest, AdjacentTimeOrderAcrossFullInt64Range) { + const bool previous_policy = common::get_allow_non_decreasing_timestamps(); + for (bool allow_equal : {false, true}) { + common::set_allow_non_decreasing_timestamps(allow_equal); + int64_t times[] = {INT64_MIN, INT64_MAX}; + EXPECT_EQ(page_writer_->write_batch(times, 2), E_OK); + page_writer_->reset(); + + std::vector range(259); + for (size_t i = 0; i < range.size(); ++i) { + range[i] = static_cast(i); + } + for (size_t i = 1; i < range.size(); ++i) { + range[i] = range[i - 1]; + EXPECT_EQ( + TimePageWriter::is_batch_in_order(range.data(), range.size()), + allow_equal); + range[i] = INT64_MIN; + EXPECT_FALSE( + TimePageWriter::is_batch_in_order(range.data(), range.size())); + range[i] = static_cast(i); + } + std::swap(times[0], times[1]); + EXPECT_EQ(page_writer_->write_batch(times, 2), E_OUT_OF_ORDER); + } + common::set_allow_non_decreasing_timestamps(previous_policy); +} + TEST_F(TimePageWriterTest, ResetTimePageWriter) { TimePageWriter page_writer; page_writer.init(TSEncoding::PLAIN, UNCOMPRESSED); diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index 90e32b273..3f5881fbb 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -44,6 +44,18 @@ This is process-wide, including Python constructor defaults; avoid conflicting writers. Decreases remain invalid. See `properties-filters.md` for the persisted policy; CLI `write` has no opt-in. +C++ aligned table writes check each device's first timestamp against its last +accepted timestamp, including `INT64_MIN`, across tablets and chunk-group flushes. +Later rows for that device follow the configured order even when other devices' +rows appear in between. An out-of-order tablet +returns `E_OUT_OF_ORDER` before writing any of its rows. The writer can then +accept an ordered tablet and flush or close normally. + +When reusing a C++ tablet, keep the row count passed to `Tablet::reset` +within its allocated capacity. Debug builds assert this limit at reset. +In release builds, a table write returns `E_OUT_OF_RANGE` for an oversized +tablet before reading its rows. Reset and refill the tablet to retry. + ## Timeseries Metadata - C++ `TsFileReader::get_timeseries_metadata()` returns metadata for all