From 9ce2a3275a70bad390cbc81af67440c6e3510b79 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Thu, 26 Nov 2026 11:20:28 +0800 Subject: [PATCH 1/6] fix(cpp): keep table writer usable after out-of-order batch rejection In the sequential aligned table write path, TsFileWriter::write_table marked the writer unrecoverable whenever write_time_segments failed. A pure out-of-order batch is rejected by TimePageWriter::write_batch before any time point is appended, so every column's row count stays unchanged and the writer remains coherent. Marking it unrecoverable made a later flush()/close() fail with E_DATA_INCONSISTENCY, leaving the file unreadable and discarding data written before the rejected batch. Only mark the writer unrecoverable when the time chunk actually made progress (wrote into the current page or sealed a page) before failing; otherwise the out-of-order error is returned and the writer stays usable, matching the Java behavior. Add a regression test that writes normal rows, then an out-of-order batch, and asserts close succeeds and the normal data stays readable. --- cpp/src/writer/tsfile_writer.cc | 19 ++++- .../table_view/tsfile_writer_table_test.cc | 75 +++++++++++++++++++ 2 files changed, 90 insertions(+), 4 deletions(-) diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index dcf6afe17..dd018b7f9 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -1340,6 +1340,7 @@ int TsFileWriter::write_table(Tablet& tablet) { std::vector value_tasks; std::vector segments; uint32_t initial_page_points; + int32_t initial_num_of_pages; }; const uint32_t page_max_points = @@ -1408,6 +1409,7 @@ int TsFileWriter::write_table(Tablet& tablet) { DeviceWriteCtx ctx; ctx.tcw = time_chunk_writer; ctx.initial_page_points = time_cur_points; + ctx.initial_num_of_pages = time_chunk_writer->num_of_pages(); uint32_t field_col_count = 0; for (uint32_t i = 0; i < tablet.get_column_count(); ++i) { if (tablet.column_categories_[i] == @@ -1560,10 +1562,19 @@ 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. - unrecoverable_ = true; + // A pure out-of-order batch is rejected before any time + // point is written, leaving every column's row count + // unchanged -- the writer stays coherent and the data + // written so far must survive a later flush/close. Only + // poison the writer when the time chunk actually made + // progress (points into the current page, or a sealed + // page) before failing: then the value columns lag the + // time column and the aligned chunk group can no longer + // be sealed coherently. + if (ctx.tcw->get_point_numer() > ctx.initial_page_points || + ctx.tcw->num_of_pages() > ctx.initial_num_of_pages) { + unrecoverable_ = true; + } return ret; } for (auto& vt : ctx.value_tasks) { 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..06f2547c1 100644 --- a/cpp/test/writer/table_view/tsfile_writer_table_test.cc +++ b/cpp/test/writer/table_view/tsfile_writer_table_test.cc @@ -20,6 +20,7 @@ #include +#include "common/global.h" #include "common/record.h" #include "common/schema.h" #include "common/tablet.h" @@ -332,6 +333,80 @@ TEST_F(TsFileWriterTableTest, WriteDisorderTest) { 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, WriteTableTestMultiFlush) { auto table_schema = gen_table_schema(0); auto tsfile_table_writer_ = std::make_shared( From a7c5d01ea40bf5c2390e4b596d6c79aae9f2012c Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Fri, 27 Nov 2026 12:23:47 +0800 Subject: [PATCH 2/6] fix(cpp): validate table time order before writing any rows Reject an out-of-order tablet up front instead of writing the in-order prefix and then poisoning the writer. For each device, check that its timestamps are monotonic across all of its (possibly non-contiguous) segments and that its first timestamp comes after the device's already-written data. A rejected batch now writes zero rows and leaves the writer usable, matching the Java behavior and removing the partial-write ambiguity. Add TimeChunkWriter::get_last_time() so the check can read the highest timestamp written so far (sealed pages plus the current page), and update WriteDisorderTest to expect flush/close to succeed after the up-front rejection. --- cpp/src/writer/time_chunk_writer.cc | 16 ++++++ cpp/src/writer/time_chunk_writer.h | 5 ++ cpp/src/writer/tsfile_writer.cc | 56 +++++++++++++++++++ .../table_view/tsfile_writer_table_test.cc | 7 ++- 4 files changed, 81 insertions(+), 3 deletions(-) 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..3050baf8d 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. diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index dd018b7f9..2ddfd7347 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -1327,6 +1327,62 @@ int TsFileWriter::write_table(Tablet& tablet) { auto device_id_end_index_pairs = split_tablet_by_device(tablet); if (table_aligned_) { + // Validate the whole tablet's time order up front so a rejected + // batch leaves no partial rows behind: a device's timestamps must be + // monotonic across all of its (possibly non-contiguous) segments, and + // its first timestamp must come after that device's already-written + // data. Out-of-order input is rejected here before anything is + // written, keeping the writer coherent for a later flush/close. + if (tablet.timestamps_) { + const bool allow_non_decreasing = + g_config_value_.allow_non_decreasing_timestamps_; + auto out_of_order = [allow_non_decreasing](int64_t time, + int64_t last_time) { + return allow_non_decreasing ? time < last_time + : time <= last_time; + }; + std::map, int64_t, IDeviceIDComparator> + last_time_in_tablet; + int order_start = 0; + for (auto& pair : device_id_end_index_pairs) { + int order_end = pair.second; + if (order_end == 0) continue; + const int64_t first_ts = tablet.timestamps_[order_start]; + const int64_t last_ts = tablet.timestamps_[order_end - 1]; + + auto seen = last_time_in_tablet.find(pair.first); + if (seen != last_time_in_tablet.end()) { + // A later segment of an already-seen device must continue + // monotonically from the previous segment's last time. + if (out_of_order(first_ts, seen->second)) { + return E_OUT_OF_ORDER; + } + } else { + // First segment of this device: it must come after the + // device's existing (un-flushed) chunk data. + auto schema_it = schemas_.find(pair.first); + if (schema_it != schemas_.end() && + schema_it->second != nullptr && + schema_it->second->time_chunk_writer_ != nullptr && + schema_it->second->time_chunk_writer_->hasData() && + out_of_order(first_ts, + schema_it->second->time_chunk_writer_ + ->get_last_time())) { + return E_OUT_OF_ORDER; + } + } + + for (int i = order_start + 1; i < order_end; i++) { + if (out_of_order(tablet.timestamps_[i], + tablet.timestamps_[i - 1])) { + return E_OUT_OF_ORDER; + } + } + last_time_in_tablet[pair.first] = last_ts; + order_start = order_end; + } + } + struct ValueTask { ValueChunkWriter* vcw; uint32_t col_idx; 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 06f2547c1..95e7ec8dc 100644 --- a/cpp/test/writer/table_view/tsfile_writer_table_test.cc +++ b/cpp/test/writer/table_view/tsfile_writer_table_test.cc @@ -327,9 +327,10 @@ 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; } From 73cf4633b1ea0b2c2a86cc3ca9a2b9316bdb6f12 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Fri, 27 Nov 2026 17:13:18 +0800 Subject: [PATCH 3/6] fix(cpp): retain last time across flush and fix table test fixture Address review feedback on the table-model out-of-order handling: - Restore unconditional unrecoverable_ on a write_time_segments failure: the up-front check already rejects out-of-order input before encoding, so the only remaining failure is a genuine encoder/allocation error that may have advanced the time stream without updating the point counters. - Retain each device's last accepted timestamp across a chunk-group flush (in MeasurementSchemaGroup::last_time_) so the up-front check still rejects a timestamp that is out of order against already-flushed data. - Give each device a distinct id1 value in the TableModelQueryMultiDevices fixture so it actually writes ten devices, and cover the flush case in a new WriteOutOfOrderAfterFlushRejected regression test. --- cpp/src/writer/tsfile_writer.cc | 53 ++++++++++-------- .../table_view/tsfile_reader_table_test.cc | 55 +++++++++++++++---- .../table_view/tsfile_writer_table_test.cc | 47 ++++++++++++++++ 3 files changed, 120 insertions(+), 35 deletions(-) diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index 2ddfd7347..a4ad3e81c 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -1359,16 +1359,24 @@ int TsFileWriter::write_table(Tablet& tablet) { } } else { // First segment of this device: it must come after the - // device's existing (un-flushed) chunk data. + // device's existing data, whether still in memory or + // already flushed (the last accepted timestamp survives + // a chunk-group flush in last_time_). auto schema_it = schemas_.find(pair.first); if (schema_it != schemas_.end() && - schema_it->second != nullptr && - schema_it->second->time_chunk_writer_ != nullptr && - schema_it->second->time_chunk_writer_->hasData() && - out_of_order(first_ts, - schema_it->second->time_chunk_writer_ - ->get_last_time())) { - return E_OUT_OF_ORDER; + schema_it->second != nullptr) { + int64_t existing_last = schema_it->second->last_time_; + if (schema_it->second->time_chunk_writer_ != nullptr && + schema_it->second->time_chunk_writer_->hasData()) { + existing_last = + std::max(existing_last, + schema_it->second->time_chunk_writer_ + ->get_last_time()); + } + if (existing_last != INT64_MIN && + out_of_order(first_ts, existing_last)) { + return E_OUT_OF_ORDER; + } } } @@ -1396,7 +1404,6 @@ int TsFileWriter::write_table(Tablet& tablet) { std::vector value_tasks; std::vector segments; uint32_t initial_page_points; - int32_t initial_num_of_pages; }; const uint32_t page_max_points = @@ -1465,7 +1472,6 @@ int TsFileWriter::write_table(Tablet& tablet) { DeviceWriteCtx ctx; ctx.tcw = time_chunk_writer; ctx.initial_page_points = time_cur_points; - ctx.initial_num_of_pages = time_chunk_writer->num_of_pages(); uint32_t field_col_count = 0; for (uint32_t i = 0; i < tablet.get_column_count(); ++i) { if (tablet.column_categories_[i] == @@ -1618,19 +1624,12 @@ 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))) { - // A pure out-of-order batch is rejected before any time - // point is written, leaving every column's row count - // unchanged -- the writer stays coherent and the data - // written so far must survive a later flush/close. Only - // poison the writer when the time chunk actually made - // progress (points into the current page, or a sealed - // page) before failing: then the value columns lag the - // time column and the aligned chunk group can no longer - // be sealed coherently. - if (ctx.tcw->get_point_numer() > ctx.initial_page_points || - ctx.tcw->num_of_pages() > ctx.initial_num_of_pages) { - unrecoverable_ = true; - } + // 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; } for (auto& vt : ctx.value_tasks) { @@ -2169,6 +2168,14 @@ 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->last_time_ = std::max( + chunk_group->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 95e7ec8dc..81764f946 100644 --- a/cpp/test/writer/table_view/tsfile_writer_table_test.cc +++ b/cpp/test/writer/table_view/tsfile_writer_table_test.cc @@ -408,6 +408,53 @@ TEST_F(TsFileWriterTableTest, WriteOutOfOrderThenCloseKeepsData) { 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; +} + TEST_F(TsFileWriterTableTest, WriteTableTestMultiFlush) { auto table_schema = gen_table_schema(0); auto tsfile_table_writer_ = std::make_shared( From a1907505f097354b64794c5f95132c86921aa6ee Mon Sep 17 00:00:00 2001 From: ColinLee Date: Mon, 30 Nov 2026 14:12:25 +0800 Subject: [PATCH 4/6] fix(cpp): enforce table timestamp ordering at INT64_MIN --- cpp/src/common/schema.h | 6 ++ cpp/src/writer/tsfile_writer.cc | 46 +++++-------- .../table_view/tsfile_writer_table_test.cc | 68 +++++++++++++++++++ skills/tsfile/references/advanced-apis.md | 5 ++ 4 files changed, 97 insertions(+), 28 deletions(-) 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/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index a4ad3e81c..2a7fd100e 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; @@ -1365,16 +1361,12 @@ int TsFileWriter::write_table(Tablet& tablet) { auto schema_it = schemas_.find(pair.first); if (schema_it != schemas_.end() && schema_it->second != nullptr) { - int64_t existing_last = schema_it->second->last_time_; - if (schema_it->second->time_chunk_writer_ != nullptr && - schema_it->second->time_chunk_writer_->hasData()) { - existing_last = - std::max(existing_last, - schema_it->second->time_chunk_writer_ - ->get_last_time()); - } - if (existing_last != INT64_MIN && - out_of_order(first_ts, existing_last)) { + const auto* group = schema_it->second; + auto* chunk = group->time_chunk_writer_; + if ((group->has_last_time_ && + out_of_order(first_ts, group->last_time_)) || + (chunk != nullptr && chunk->hasData() && + out_of_order(first_ts, chunk->get_last_time()))) { return E_OUT_OF_ORDER; } } @@ -1725,9 +1717,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; @@ -2173,8 +2164,7 @@ int TsFileWriter::flush_chunk_group(MeasurementSchemaGroup* chunk_group, // data that has already been flushed (the chunk writer is reset // below). if (time_chunk_writer->hasData()) { - chunk_group->last_time_ = std::max( - chunk_group->last_time_, time_chunk_writer->get_last_time()); + 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_, 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 81764f946..a62ab571f 100644 --- a/cpp/test/writer/table_view/tsfile_writer_table_test.cc +++ b/cpp/test/writer/table_view/tsfile_writer_table_test.cc @@ -19,6 +19,7 @@ #include #include +#include #include "common/global.h" #include "common/record.h" @@ -455,6 +456,73 @@ TEST_F(TsFileWriterTableTest, WriteOutOfOrderAfterFlushRejected) { delete table_schema; } +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/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index 90e32b273..230f409e7 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -44,6 +44,11 @@ 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 across tablets and chunk-group +flushes, including timestamps equal to `INT64_MIN`. 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. + ## Timeseries Metadata - C++ `TsFileReader::get_timeseries_metadata()` returns metadata for all From 03fa32259be3b2aabc1710e2c1b29daf77e707c6 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Mon, 30 Nov 2026 18:23:53 +0800 Subject: [PATCH 5/6] perf(cpp): validate aligned table timestamps once per device range --- cpp/src/writer/time_chunk_writer.h | 8 + cpp/src/writer/time_page_writer.h | 69 ++++-- cpp/src/writer/tsfile_writer.cc | 227 +++++++----------- .../table_view/tsfile_writer_table_test.cc | 31 +++ cpp/test/writer/time_chunk_writer_test.cc | 16 +- cpp/test/writer/time_page_writer_test.cc | 31 +++ skills/tsfile/references/advanced-apis.md | 6 +- 7 files changed, 226 insertions(+), 162 deletions(-) diff --git a/cpp/src/writer/time_chunk_writer.h b/cpp/src/writer/time_chunk_writer.h index 3050baf8d..6b189d71f 100644 --- a/cpp/src/writer/time_chunk_writer.h +++ b/cpp/src/writer/time_chunk_writer.h @@ -127,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 2a7fd100e..5f2b904f7 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -1320,69 +1320,13 @@ int TsFileWriter::write_table(Tablet& tablet) { return ret; } + 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_) { - // Validate the whole tablet's time order up front so a rejected - // batch leaves no partial rows behind: a device's timestamps must be - // monotonic across all of its (possibly non-contiguous) segments, and - // its first timestamp must come after that device's already-written - // data. Out-of-order input is rejected here before anything is - // written, keeping the writer coherent for a later flush/close. - if (tablet.timestamps_) { - const bool allow_non_decreasing = - g_config_value_.allow_non_decreasing_timestamps_; - auto out_of_order = [allow_non_decreasing](int64_t time, - int64_t last_time) { - return allow_non_decreasing ? time < last_time - : time <= last_time; - }; - std::map, int64_t, IDeviceIDComparator> - last_time_in_tablet; - int order_start = 0; - for (auto& pair : device_id_end_index_pairs) { - int order_end = pair.second; - if (order_end == 0) continue; - const int64_t first_ts = tablet.timestamps_[order_start]; - const int64_t last_ts = tablet.timestamps_[order_end - 1]; - - auto seen = last_time_in_tablet.find(pair.first); - if (seen != last_time_in_tablet.end()) { - // A later segment of an already-seen device must continue - // monotonically from the previous segment's last time. - if (out_of_order(first_ts, seen->second)) { - return E_OUT_OF_ORDER; - } - } else { - // First segment of this device: it must come after the - // device's existing data, whether still in memory or - // already flushed (the last accepted timestamp survives - // a chunk-group flush in last_time_). - auto schema_it = schemas_.find(pair.first); - if (schema_it != schemas_.end() && - schema_it->second != nullptr) { - const auto* group = schema_it->second; - auto* chunk = group->time_chunk_writer_; - if ((group->has_last_time_ && - out_of_order(first_ts, group->last_time_)) || - (chunk != nullptr && chunk->hasData() && - out_of_order(first_ts, chunk->get_last_time()))) { - return E_OUT_OF_ORDER; - } - } - } - - for (int i = order_start + 1; i < order_end; i++) { - if (out_of_order(tablet.timestamps_[i], - tablet.timestamps_[i - 1])) { - return E_OUT_OF_ORDER; - } - } - last_time_in_tablet[pair.first] = last_ts; - order_start = order_end; - } - } - struct ValueTask { ValueChunkWriter* vcw; uint32_t col_idx; @@ -1392,10 +1336,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 = @@ -1404,95 +1349,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 @@ -1508,23 +1460,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; }; 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 a62ab571f..2420dd27e 100644 --- a/cpp/test/writer/table_view/tsfile_writer_table_test.cc +++ b/cpp/test/writer/table_view/tsfile_writer_table_test.cc @@ -456,6 +456,37 @@ TEST_F(TsFileWriterTableTest, WriteOutOfOrderAfterFlushRejected) { delete table_schema; } +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> { 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 230f409e7..de1699c48 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -44,8 +44,10 @@ 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 across tablets and chunk-group -flushes, including timestamps equal to `INT64_MIN`. An out-of-order tablet +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. From abfa6d18dfec5e211795f422cf0679c4dd73d191 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Mon, 30 Nov 2026 22:40:52 +0800 Subject: [PATCH 6/6] fix(cpp): reject table row counts exceeding tablet capacity --- cpp/src/writer/tsfile_writer.cc | 3 ++ .../table_view/tsfile_writer_table_test.cc | 34 +++++++++++++++++++ skills/tsfile/references/advanced-apis.md | 5 +++ 3 files changed, 42 insertions(+) diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index 5f2b904f7..95e899ee1 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -1320,6 +1320,9 @@ 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; 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 2420dd27e..c4b62bb0f 100644 --- a/cpp/test/writer/table_view/tsfile_writer_table_test.cc +++ b/cpp/test/writer/table_view/tsfile_writer_table_test.cc @@ -456,6 +456,40 @@ TEST_F(TsFileWriterTableTest, WriteOutOfOrderAfterFlushRejected) { 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()); diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index de1699c48..3f5881fbb 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -51,6 +51,11 @@ 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