From c61c032ef1e82b70d9169acb2f1995ba84cacd71 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Mon, 30 Nov 2026 18:21:50 +0800 Subject: [PATCH 1/7] fix(cpp): reject out-of-order timestamps on non-aligned writes The non-aligned write paths (TsFileWriter::write_record, write_tablet and row/tablet batches) never checked timestamp order, so a strictly decreasing timestamp was accepted even with allow_non_decreasing_timestamps_ enabled, and duplicates/decreases were accepted with the flag off. - ChunkWriter now validates write / write_batch / write_string_batch against the last timestamp it appended and returns E_OUT_OF_ORDER on violation. The state lives in ChunkWriter rather than the per-page statistic, so it survives page seals and chunk flushes. - TsFileWriter pre-validates a whole record/tablet (write_record, write_tablet, and the non-aligned table path) before writing any column, so a rejected write leaves no partial measurement columns behind. This also protects the table path's parallel column writes. - The ordering predicate is shared via common::timestamp_out_of_order; the TimePageWriter and recovery checks now use it too. - Two stale-chunk reader fixtures that require a later flush with an earlier time range are built at the chunk layer instead of through TsFileWriter. - C++ and Python tree-model tests cover record/tablet writes, the flag on and off, page-seal and flush boundaries, and partial-write atomicity. Skills docs are updated. --- cpp/src/common/global.h | 9 + cpp/src/writer/chunk_writer.cc | 6 + cpp/src/writer/chunk_writer.h | 57 +++ cpp/src/writer/time_page_writer.h | 4 +- cpp/src/writer/tsfile_writer.cc | 112 +++- cpp/src/writer/tsfile_writer.h | 14 + .../tsfile_tree_query_by_row_test.cc | 115 ++--- cpp/test/writer/tsfile_writer_test.cc | 477 +++++++++++++++++- .../test_allow_non_decreasing_timestamps.py | 101 ++++ skills/tsfile/references/advanced-apis.md | 5 +- 10 files changed, 833 insertions(+), 67 deletions(-) diff --git a/cpp/src/common/global.h b/cpp/src/common/global.h index f9d1ddf4e6..fd487d9e59 100644 --- a/cpp/src/common/global.h +++ b/cpp/src/common/global.h @@ -218,6 +218,15 @@ FORCE_INLINE bool get_allow_non_decreasing_timestamps() { return g_config_value_.allow_non_decreasing_timestamps_; } +// Shared timestamp-ordering predicate for every write path. By default a +// timestamp must be strictly greater than the previous one; with +// allow_non_decreasing_timestamps_ enabled equal timestamps are accepted, but +// a strictly decreasing one is still rejected. +FORCE_INLINE bool timestamp_out_of_order(int64_t time, int64_t last_time) { + return g_config_value_.allow_non_decreasing_timestamps_ ? time < last_time + : time <= last_time; +} + // Select the backend used by subsequently opened local files. Existing // LocalRandomAccessReadFile instances retain the backend selected when opened. // This setting deliberately lives outside exported ConfigValue so adding it diff --git a/cpp/src/writer/chunk_writer.cc b/cpp/src/writer/chunk_writer.cc index acdb4951db..d6879f8307 100644 --- a/cpp/src/writer/chunk_writer.cc +++ b/cpp/src/writer/chunk_writer.cc @@ -33,6 +33,9 @@ int ChunkWriter::init(const ColumnSchema& col_schema) { int ChunkWriter::init(const std::string& measurement_name, TSDataType data_type, TSEncoding encoding, CompressionType compression_type) { int ret = E_OK; + // A freshly initialized writer owns no timestamp history yet. + has_last_timestamp_ = false; + last_timestamp_ = 0; chunk_statistic_ = StatisticFactory::alloc_statistic(data_type); if (chunk_statistic_ == nullptr) { return E_OOM; @@ -70,6 +73,9 @@ void ChunkWriter::destroy() { } void ChunkWriter::reset() { + // has_last_timestamp_ / last_timestamp_ are deliberately not cleared here: + // reset() starts a new chunk after a flush, but timestamp ordering has to + // hold across chunk boundaries of the same series too. if (chunk_statistic_ != nullptr) { chunk_statistic_->reset(); } diff --git a/cpp/src/writer/chunk_writer.h b/cpp/src/writer/chunk_writer.h index 3d0d6dd32f..09b635d729 100644 --- a/cpp/src/writer/chunk_writer.h +++ b/cpp/src/writer/chunk_writer.h @@ -31,9 +31,14 @@ namespace storage { #define CW_DO_WRITE_FOR_TYPE() \ { \ int ret = common::E_OK; \ + if (UNLIKELY(timestamp_order_violated(timestamp))) { \ + return common::E_OUT_OF_ORDER; \ + } \ if (RET_FAIL(page_writer_.write(timestamp, value))) { \ return ret; \ } \ + last_timestamp_ = timestamp; \ + has_last_timestamp_ = true; \ if (RET_FAIL(seal_cur_page_if_full())) { \ return ret; \ } \ @@ -107,6 +112,12 @@ class ChunkWriter { int write_batch(const int64_t* timestamps, const T* values, uint32_t count) { int ret = common::E_OK; + if (count == 0) return ret; + // Validate the whole batch before touching a page so an order + // violation never leaves a partially written batch behind. + if (RET_FAIL(check_batch_timestamp_order(timestamps, count))) { + return ret; + } uint32_t offset = 0; const uint32_t page_cap = common::g_config_value_.page_writer_max_point_num_; @@ -127,6 +138,10 @@ class ChunkWriter { timestamps + offset, values + offset, batch_size))) { return ret; } + // Remember the last point appended; the page statistic is reset + // on every page seal, so it cannot carry this across pages. + last_timestamp_ = timestamps[offset + batch_size - 1]; + has_last_timestamp_ = true; offset += batch_size; if (RET_FAIL(seal_cur_page_if_full())) { return ret; @@ -139,6 +154,11 @@ class ChunkWriter { const uint32_t* offsets, uint32_t start_idx, uint32_t count) { int ret = common::E_OK; + if (count == 0) return ret; + // See write_batch: reject the whole batch before writing anything. + if (RET_FAIL(check_batch_timestamp_order(timestamps, count))) { + return ret; + } uint32_t offset = 0; const uint32_t page_cap = common::g_config_value_.page_writer_max_point_num_; @@ -164,6 +184,8 @@ class ChunkWriter { batch_size))) { return ret; } + last_timestamp_ = timestamps[offset + batch_size - 1]; + has_last_timestamp_ = true; offset += batch_size; if (RET_FAIL(seal_cur_page_if_full())) { return ret; @@ -175,6 +197,16 @@ class ChunkWriter { int end_encode_chunk(); common::ByteStream& get_chunk_data() { return chunk_data_; } Statistic* get_chunk_statistic() { return chunk_statistic_; } + // True when appending `timestamp` to this chunk would violate the + // configured order (strictly increasing by default, non-decreasing when + // allow_non_decreasing_timestamps_ is enabled). Unlike the per-page + // statistic this state survives page seals and chunk flushes, so callers + // can also pre-validate a multi-column row/tablet before writing any + // column. + FORCE_INLINE bool timestamp_order_violated(int64_t timestamp) const { + return has_last_timestamp_ && + is_out_of_order(timestamp, last_timestamp_); + } bool hasData() { return num_of_pages_ > 0 || (page_writer_.get_statistic() != nullptr && page_writer_.get_statistic()->count_ > 0); @@ -192,6 +224,26 @@ class ChunkWriter { int64_t estimate_max_series_mem_size(); private: + FORCE_INLINE static bool is_out_of_order(int64_t time, int64_t last_time) { + return common::timestamp_out_of_order(time, last_time); + } + // Validates `count` timestamps both against the last timestamp already + // held by this chunk and among themselves. + FORCE_INLINE int check_batch_timestamp_order(const int64_t* timestamps, + uint32_t count) const { + if (count == 0) { + return common::E_OK; + } + if (timestamp_order_violated(timestamps[0])) { + return common::E_OUT_OF_ORDER; + } + for (uint32_t i = 1; i < count; i++) { + if (is_out_of_order(timestamps[i], timestamps[i - 1])) { + return common::E_OUT_OF_ORDER; + } + } + return common::E_OK; + } FORCE_INLINE bool is_cur_page_full() const { // FIXME return (page_writer_.get_point_numer() >= @@ -227,6 +279,11 @@ class ChunkWriter { ChunkHeader chunk_header_; int32_t num_of_pages_; + // Last timestamp appended to this chunk. Kept across page seals (the + // PageWriter statistic is reset per page) and across chunk flushes + // (reset()), so ordering is enforced for the whole series in this writer. + int64_t last_timestamp_ = 0; + bool has_last_timestamp_ = false; }; } // end namespace storage diff --git a/cpp/src/writer/time_page_writer.h b/cpp/src/writer/time_page_writer.h index 33d6860edf..549a175ad8 100644 --- a/cpp/src/writer/time_page_writer.h +++ b/cpp/src/writer/time_page_writer.h @@ -140,9 +140,7 @@ class TimePageWriter { // (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; + return common::timestamp_out_of_order(time, last_time); } FORCE_INLINE int prepare_end_page() { int ret = common::E_OK; diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index 4b8f8a3114..256a7e2b37 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -837,9 +837,95 @@ bool TsFileWriter::recovered_last_time_order_violated( if (schema_it == schemas_.end() || schema_it->second == nullptr) { return false; } - return common::g_config_value_.allow_non_decreasing_timestamps_ - ? timestamp < schema_it->second->last_time_ - : timestamp <= schema_it->second->last_time_; + return common::timestamp_out_of_order(timestamp, + schema_it->second->last_time_); +} + +int TsFileWriter::check_record_timestamp_order( + common::SimpleVector& chunk_writers, int64_t timestamp) { + for (uint32_t c = 0; c < chunk_writers.size(); c++) { + ChunkWriter* chunk_writer = chunk_writers[c]; + if (IS_NULL(chunk_writer)) { + continue; + } + if (chunk_writer->timestamp_order_violated(timestamp)) { + return E_OUT_OF_ORDER; + } + // A record may carry the same measurement twice. Under strictly + // increasing semantics the second write of the same timestamp would + // fail after the first point had already been appended, so reject the + // whole record up front instead. With the non-decreasing flag on, + // equal timestamps are legal and both points can be written. + if (!common::g_config_value_.allow_non_decreasing_timestamps_) { + for (uint32_t p = 0; p < c; p++) { + if (chunk_writers[p] == chunk_writer) { + return E_OUT_OF_ORDER; + } + } + } + } + return E_OK; +} + +int TsFileWriter::check_tablet_timestamp_order( + const Tablet& tablet, common::SimpleVector& chunk_writers, + uint32_t start_idx, uint32_t end_idx) { + if (tablet.timestamps_ == nullptr || start_idx >= end_idx) { + return E_OK; + } + end_idx = std::min(end_idx, tablet.max_row_num_); + // Columns of one tablet normally map to distinct chunk writers, but two + // columns can share a measurement. Track the timestamp each chunk writer + // would have after the columns processed so far so the pre-check matches + // the real write order. + std::vector> last_written; + last_written.reserve(4); + for (uint32_t c = 0; c < chunk_writers.size(); c++) { + ChunkWriter* chunk_writer = chunk_writers[c]; + if (IS_NULL(chunk_writer)) { + continue; + } + // Null rows are skipped entirely on the non-aligned path, so only the + // non-null rows of this column reach the chunk writer. + common::BitMap& null_map = tablet.bitmaps_[c]; + bool has_last = false; + int64_t last_time = 0; + for (size_t i = 0; i < last_written.size(); i++) { + if (last_written[i].first == chunk_writer) { + has_last = true; + last_time = last_written[i].second; + break; + } + } + for (uint32_t r = start_idx; r < end_idx; r++) { + if (null_map.test(r)) { + continue; + } + const int64_t timestamp = tablet.timestamps_[r]; + const bool violated = + has_last ? common::timestamp_out_of_order(timestamp, last_time) + : chunk_writer->timestamp_order_violated(timestamp); + if (violated) { + return E_OUT_OF_ORDER; + } + has_last = true; + last_time = timestamp; + } + if (has_last) { + bool found = false; + for (size_t i = 0; i < last_written.size(); i++) { + if (last_written[i].first == chunk_writer) { + last_written[i].second = last_time; + found = true; + break; + } + } + if (!found) { + last_written.emplace_back(chunk_writer, last_time); + } + } + } + return E_OK; } int TsFileWriter::write_record(const TsRecord& record) { @@ -862,6 +948,12 @@ int TsFileWriter::write_record(const TsRecord& record) { } ASSERT(chunk_writers.size() == record.points_.size()); + // Validate every target column before writing any point: a rejected + // timestamp must not leave a partial write in a subset of measurements. + if (RET_FAIL( + check_record_timestamp_order(chunk_writers, record.timestamp_))) { + return ret; + } for (uint32_t c = 0; c < chunk_writers.size(); c++) { ChunkWriter* chunk_writer = chunk_writers[c]; if (IS_NULL(chunk_writer)) { @@ -1276,6 +1368,12 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { } } ASSERT(chunk_writers.size() == tablet.get_column_count()); + // Pre-validate the whole tablet before writing any column so a rejected + // batch leaves no partially written measurements behind. + if (RET_FAIL(check_tablet_timestamp_order(tablet, chunk_writers, 0, + total_rows))) { + return ret; + } uint32_t columns_written = 0; for (uint32_t c = 0; c < chunk_writers.size(); c++) { ChunkWriter* chunk_writer = chunk_writers[c]; @@ -1622,6 +1720,14 @@ int TsFileWriter::write_table(Tablet& tablet) { return ret; } ASSERT(chunk_writers.size() == tablet.get_column_count()); + // Pre-validate this device segment before dispatching any column + // write (serial or parallel): a rejected timestamp must not leave + // some columns written while others were skipped. + if (RET_FAIL(check_tablet_timestamp_order( + tablet, chunk_writers, si, + device_id_end_index_pair.second))) { + return ret; + } #ifdef ENABLE_THREADS if (chunk_writers.size() >= 2 && diff --git a/cpp/src/writer/tsfile_writer.h b/cpp/src/writer/tsfile_writer.h index 953cc67e1d..1c68616705 100644 --- a/cpp/src/writer/tsfile_writer.h +++ b/cpp/src/writer/tsfile_writer.h @@ -251,6 +251,20 @@ class TsFileWriter { bool recovered_last_time_order_violated( const std::shared_ptr& device_id, int64_t timestamp) const; + // Non-aligned pre-validation. Both helpers reject a whole record / + // tablet before any column is written when a timestamp would violate the + // configured order (strictly increasing by default, non-decreasing when + // allow_non_decreasing_timestamps_ is enabled). They mirror exactly + // which rows the non-aligned path actually writes: every point of a + // record, and every non-null row of every tablet column. + int check_record_timestamp_order( + common::SimpleVector& chunk_writers, + int64_t timestamp); + int check_tablet_timestamp_order( + const Tablet& tablet, + common::SimpleVector& chunk_writers, + uint32_t start_idx, uint32_t end_idx); + int write_column_batch(storage::ChunkWriter* chunk_writer, const Tablet& tablet, int col_idx, uint32_t start_idx, uint32_t end_idx); diff --git a/cpp/test/reader/tree_view/tsfile_tree_query_by_row_test.cc b/cpp/test/reader/tree_view/tsfile_tree_query_by_row_test.cc index 870b30aaff..dae6033f79 100644 --- a/cpp/test/reader/tree_view/tsfile_tree_query_by_row_test.cc +++ b/cpp/test/reader/tree_view/tsfile_tree_query_by_row_test.cc @@ -24,9 +24,11 @@ #include "common/global.h" #include "common/record.h" #include "common/schema.h" +#include "file/tsfile_io_writer.h" #include "file/write_file.h" #include "reader/tsfile_reader.h" #include "reader/tsfile_tree_reader.h" +#include "writer/chunk_writer.h" #include "writer/tsfile_tree_writer.h" using namespace storage; @@ -1263,6 +1265,41 @@ TEST_F(TreeQueryByRowTest, MultiPath_OffsetAtMergedChunkBoundary) { // ============================================================ // Multi-path: min_time_hint skips stale (out-of-order) chunks // ============================================================ +namespace { +// Writes one non-aligned chunk group straight through TsFileIOWriter + +// ChunkWriter. TsFileWriter now rejects timestamps that do not follow the +// series' last written one, so the stale-chunk fixtures below — which have to +// contain a later flush whose time range lies entirely before an earlier +// chunk's — are built at the chunk layer instead. A fresh ChunkWriter per +// group holds no history, so each group is internally ordered. +void write_raw_chunk_group( + TsFileIOWriter& io_writer, + const std::shared_ptr& device_id, + const std::string& measurement_name, int64_t start_time, int64_t end_time, + int64_t value_scale) { + ASSERT_EQ(io_writer.start_flush_chunk_group(device_id, false), E_OK); + ChunkWriter chunk_writer; + ASSERT_EQ( + chunk_writer.init(measurement_name, TSDataType::INT64, + TSEncoding::PLAIN, CompressionType::UNCOMPRESSED), + E_OK); + for (int64_t t = start_time; t < end_time; ++t) { + ASSERT_EQ(chunk_writer.write(t, t * value_scale), E_OK); + } + ASSERT_EQ(chunk_writer.end_encode_chunk(), E_OK); + std::string name = measurement_name; + ASSERT_EQ(io_writer.start_flush_chunk(chunk_writer.get_chunk_data(), name, + TSDataType::INT64, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED, + chunk_writer.num_of_pages()), + E_OK); + ASSERT_EQ(io_writer.flush_chunk(chunk_writer.get_chunk_data()), E_OK); + ASSERT_EQ(io_writer.end_flush_chunk(chunk_writer.get_chunk_statistic()), + E_OK); + ASSERT_EQ(io_writer.end_flush_chunk_group(false), E_OK); +} +} // namespace + // // TsFile allows multiple flushes for the same path. A later flush can // produce a chunk whose time range is entirely BEFORE the current merge @@ -1285,39 +1322,19 @@ TEST_F(TreeQueryByRowTest, MultiPath_OffsetAtMergedChunkBoundary) { // - No out-of-order or duplicate timestamps. TEST_F(TreeQueryByRowTest, MultiPath_TimeHint_SkipsStaleChunk) { { - TsFileTreeWriter writer(&write_file_); - std::string d1 = "d1", d2 = "d2"; - auto* sd1 = new MeasurementSchema("s1", TSDataType::INT64); - auto* sd2 = new MeasurementSchema("s1", TSDataType::INT64); - ASSERT_EQ(E_OK, writer.register_timeseries(d1, sd1)); - ASSERT_EQ(E_OK, writer.register_timeseries(d2, sd2)); - delete sd1; - delete sd2; + TsFileIOWriter io_writer; + ASSERT_EQ(io_writer.init(&write_file_), E_OK); + ASSERT_EQ(io_writer.start_file(), E_OK); + auto d1 = std::make_shared("d1"); + auto d2 = std::make_shared("d2"); // d2 chunk1: t=50..59 - for (int64_t t = 50; t < 60; ++t) { - TsRecord rec("d2", t); - rec.add_point("s1", t * 10); - ASSERT_EQ(E_OK, writer.write(rec)); - } - ASSERT_EQ(E_OK, writer.flush()); - + write_raw_chunk_group(io_writer, d2, "s1", 50, 60, 10); // d1: t=0..99 - for (int64_t t = 0; t < 100; ++t) { - TsRecord rec("d1", t); - rec.add_point("s1", t); - ASSERT_EQ(E_OK, writer.write(rec)); - } - ASSERT_EQ(E_OK, writer.flush()); - + write_raw_chunk_group(io_writer, d1, "s1", 0, 100, 1); // d2 chunk2 (stale): t=0..9 - for (int64_t t = 0; t < 10; ++t) { - TsRecord rec("d2", t); - rec.add_point("s1", t * 10); - ASSERT_EQ(E_OK, writer.write(rec)); - } - ASSERT_EQ(E_OK, writer.flush()); - writer.close(); + write_raw_chunk_group(io_writer, d2, "s1", 0, 10, 10); + ASSERT_EQ(io_writer.end_file(), E_OK); } TsFileTreeReader reader; @@ -1359,36 +1376,16 @@ TEST_F(TreeQueryByRowTest, MultiPath_TimeHint_SkipsStaleChunk) { // Verifies that offset counting is not confused by the skipped stale chunk. TEST_F(TreeQueryByRowTest, MultiPath_TimeHint_SkipsStaleChunk_WithOffset) { { - TsFileTreeWriter writer(&write_file_); - std::string d1 = "d1", d2 = "d2"; - auto* sd1 = new MeasurementSchema("s1", TSDataType::INT64); - auto* sd2 = new MeasurementSchema("s1", TSDataType::INT64); - ASSERT_EQ(E_OK, writer.register_timeseries(d1, sd1)); - ASSERT_EQ(E_OK, writer.register_timeseries(d2, sd2)); - delete sd1; - delete sd2; - - for (int64_t t = 50; t < 60; ++t) { - TsRecord rec("d2", t); - rec.add_point("s1", t * 10); - ASSERT_EQ(E_OK, writer.write(rec)); - } - ASSERT_EQ(E_OK, writer.flush()); - - for (int64_t t = 0; t < 100; ++t) { - TsRecord rec("d1", t); - rec.add_point("s1", t); - ASSERT_EQ(E_OK, writer.write(rec)); - } - ASSERT_EQ(E_OK, writer.flush()); - - for (int64_t t = 0; t < 10; ++t) { - TsRecord rec("d2", t); - rec.add_point("s1", t * 10); - ASSERT_EQ(E_OK, writer.write(rec)); - } - ASSERT_EQ(E_OK, writer.flush()); - writer.close(); + TsFileIOWriter io_writer; + ASSERT_EQ(io_writer.init(&write_file_), E_OK); + ASSERT_EQ(io_writer.start_file(), E_OK); + auto d1 = std::make_shared("d1"); + auto d2 = std::make_shared("d2"); + + write_raw_chunk_group(io_writer, d2, "s1", 50, 60, 10); + write_raw_chunk_group(io_writer, d1, "s1", 0, 100, 1); + write_raw_chunk_group(io_writer, d2, "s1", 0, 10, 10); + ASSERT_EQ(io_writer.end_file(), E_OK); } TsFileTreeReader reader; diff --git a/cpp/test/writer/tsfile_writer_test.cc b/cpp/test/writer/tsfile_writer_test.cc index c927cc3af1..e68ae522fb 100644 --- a/cpp/test/writer/tsfile_writer_test.cc +++ b/cpp/test/writer/tsfile_writer_test.cc @@ -135,6 +135,37 @@ class TsFileWriterTest : public ::testing::Test { return ss.str(); } } + + // Reads back every row for `select_paths` and renders each value with + // field_to_string. Row i is {timestamp, {value of path 0, ...}}. + static std::vector>> ReadRows( + const std::string& file_name, + const std::vector& select_paths) { + std::vector>> rows; + std::vector paths = select_paths; + storage::QueryExpression* qe = + storage::QueryExpression::create(paths, nullptr); + storage::TsFileReader reader; + EXPECT_EQ(reader.open(file_name), common::E_OK); + storage::ResultSet* tmp = nullptr; + EXPECT_EQ(reader.query(qe, tmp), common::E_OK); + if (tmp == nullptr) { + return rows; + } + auto* qds = (QDSWithoutTimeGenerator*)tmp; + bool has_next = false; + while (IS_SUCC(qds->next(has_next)) && has_next) { + auto* rec = qds->get_row_record(); + std::vector values; + for (uint32_t c = 1; c <= select_paths.size(); c++) { + values.push_back(field_to_string(rec->get_field(c))); + } + rows.emplace_back(rec->get_timestamp(), std::move(values)); + } + reader.destroy_query_data_set(qds); + EXPECT_EQ(reader.close(), common::E_OK); + return rows; + } }; class TsFileWriterTestSimple : public ::testing::Test {}; @@ -428,7 +459,8 @@ TEST_F(TsFileWriterTest, WriteDiffrentTypeCombination) { std::strcpy(literal, "literal"); String literal_str(literal, std::strlen("literal")); for (size_t l = 0; l < 100; ++l) { - TsRecord record(1622505600000 + 1 * 1000, device_path); + TsRecord record(1622505600000 + static_cast(l) * 1000, + device_path); for (size_t i = 0; i < schema_vecs.size(); ++i) { if (schema_vecs[i].data_type_ == TSDataType::INT32) { record.add_point(schema_vecs[i].measurement_name_, (int32_t)i); @@ -2493,6 +2525,21 @@ class ScopedAllowNonDecreasingTimestamps { common::set_allow_non_decreasing_timestamps(false); } }; + +// page_writer_max_point_num_ is process-global; restore it on scope exit. +class ScopedPageMaxPointCount { + public: + explicit ScopedPageMaxPointCount(uint32_t value) + : saved_(common::g_config_value_.page_writer_max_point_num_) { + common::g_config_value_.page_writer_max_point_num_ = value; + } + ~ScopedPageMaxPointCount() { + common::g_config_value_.page_writer_max_point_num_ = saved_; + } + + private: + uint32_t saved_; +}; } // namespace // With the flag on, equal timestamps must be accepted on the aligned batch @@ -2690,3 +2737,431 @@ TEST_F(TsFileWriterTest, AllowNonDecreasingNonAlignedRecordWriteAndRead) { reader.destroy_query_data_set(tmp_qds); ASSERT_EQ(reader.close(), E_OK); } + +// --------------------------------------------------------------------------- +// Non-aligned (tree model) timestamp ordering. +// +// Before the fix, ChunkWriter::write / write_batch / write_string_batch had no +// order check at all, so the non-aligned path accepted strictly decreasing and +// duplicate timestamps regardless of allow_non_decreasing_timestamps_. The +// chunk writer now remembers the last appended timestamp across page seals and +// chunk flushes, and TsFileWriter pre-validates a whole record/tablet so a +// rejected write never leaves a partial row across measurement columns. +// --------------------------------------------------------------------------- + +// Default (strictly increasing) semantics on the non-aligned row path: both +// equal and decreasing timestamps must be rejected with E_OUT_OF_ORDER, and +// the rejected rows must not advance any column. +TEST_F(TsFileWriterTest, NonAlignedRecordOutOfOrderRejected) { + ScopedAllowNonDecreasingTimestamps guard(false); + std::string device_name = "root.dev_na_record"; + ASSERT_EQ( + tsfile_writer_->register_timeseries( + device_name, MeasurementSchema("v0", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + ASSERT_EQ( + tsfile_writer_->register_timeseries( + device_name, MeasurementSchema("v1", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + + TsRecord first(10, device_name); + first.add_point("v0", static_cast(0)); + first.add_point("v1", static_cast(100)); + ASSERT_EQ(tsfile_writer_->write_record(first), E_OK); + + TsRecord duplicate(10, device_name); + duplicate.add_point("v0", static_cast(1)); + duplicate.add_point("v1", static_cast(101)); + EXPECT_EQ(tsfile_writer_->write_record(duplicate), E_OUT_OF_ORDER); + + TsRecord older(5, device_name); + older.add_point("v0", static_cast(2)); + older.add_point("v1", static_cast(102)); + EXPECT_EQ(tsfile_writer_->write_record(older), E_OUT_OF_ORDER); + + TsRecord next(11, device_name); + next.add_point("v0", static_cast(3)); + next.add_point("v1", static_cast(103)); + ASSERT_EQ(tsfile_writer_->write_record(next), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0", v1 = "v1"; + select.emplace_back(device_name, v0); + select.emplace_back(device_name, v1); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 2u); + EXPECT_EQ(rows[0].first, 10); + EXPECT_EQ(rows[0].second[0], "0"); + EXPECT_EQ(rows[0].second[1], "100"); + EXPECT_EQ(rows[1].first, 11); + EXPECT_EQ(rows[1].second[0], "3"); + EXPECT_EQ(rows[1].second[1], "103"); +} + +// A rejected record must not leave a partial write in a column that had no +// data yet: only the pre-validation can prevent v1 from being written while +// v0 rejects the row. +TEST_F(TsFileWriterTest, NonAlignedRecordRejectionWritesNoColumn) { + ScopedAllowNonDecreasingTimestamps guard(false); + std::string device_name = "root.dev_na_record_partial"; + ASSERT_EQ( + tsfile_writer_->register_timeseries( + device_name, MeasurementSchema("v0", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + ASSERT_EQ( + tsfile_writer_->register_timeseries( + device_name, MeasurementSchema("v1", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + + TsRecord first(10, device_name); + first.add_point("v0", static_cast(0)); + ASSERT_EQ(tsfile_writer_->write_record(first), E_OK); + + // v0 already holds ts=10, v1 is still empty. The row is rejected because + // of v0, so v1 must not receive ts=5. + TsRecord rejected(5, device_name); + rejected.add_point("v1", static_cast(105)); + rejected.add_point("v0", static_cast(5)); + EXPECT_EQ(tsfile_writer_->write_record(rejected), E_OUT_OF_ORDER); + + TsRecord next(11, device_name); + next.add_point("v0", static_cast(1)); + next.add_point("v1", static_cast(111)); + ASSERT_EQ(tsfile_writer_->write_record(next), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector v1_path; + std::string v1 = "v1"; + v1_path.emplace_back(device_name, v1); + auto v1_rows = ReadRows(file_name_, v1_path); + ASSERT_EQ(v1_rows.size(), 1u); + EXPECT_EQ(v1_rows[0].first, 11); + EXPECT_EQ(v1_rows[0].second[0], "111"); + + std::vector v0_path; + std::string v0 = "v0"; + v0_path.emplace_back(device_name, v0); + auto v0_rows = ReadRows(file_name_, v0_path); + ASSERT_EQ(v0_rows.size(), 2u); + EXPECT_EQ(v0_rows[0].first, 10); + EXPECT_EQ(v0_rows[1].first, 11); +} + +// A record that carries the same measurement twice would append the second +// point at an equal timestamp; under strict semantics the whole record must be +// rejected before the first point is written. +TEST_F(TsFileWriterTest, + NonAlignedRecordDuplicateMeasurementRejectedWhenStrict) { + ScopedAllowNonDecreasingTimestamps guard(false); + std::string device_name = "root.dev_na_record_dup_measurement"; + ASSERT_EQ( + tsfile_writer_->register_timeseries( + device_name, MeasurementSchema("v0", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + + TsRecord duplicated(10, device_name); + duplicated.add_point("v0", static_cast(1)); + duplicated.add_point("v0", static_cast(2)); + EXPECT_EQ(tsfile_writer_->write_record(duplicated), E_OUT_OF_ORDER); + + // Nothing from the rejected record may have been written. + TsRecord first(10, device_name); + first.add_point("v0", static_cast(3)); + ASSERT_EQ(tsfile_writer_->write_record(first), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0"; + select.emplace_back(device_name, v0); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 1u); + EXPECT_EQ(rows[0].first, 10); + EXPECT_EQ(rows[0].second[0], "3"); +} + +// With allow_non_decreasing_timestamps_ enabled, equal timestamps are legal on +// the non-aligned row path but strictly decreasing ones are still rejected. +TEST_F(TsFileWriterTest, + AllowNonDecreasingNonAlignedRecordStillRejectsStrictlyDecreasing) { + ScopedAllowNonDecreasingTimestamps guard(true); + std::string device_name = "root.dev_na_record_non_decreasing"; + ASSERT_EQ( + tsfile_writer_->register_timeseries( + device_name, MeasurementSchema("v0", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + + const int64_t times[5] = {10, 11, 11, 9, 12}; + for (int i = 0; i < 5; ++i) { + TsRecord record(times[i], device_name); + record.add_point("v0", static_cast(i)); + if (i == 3) { + EXPECT_EQ(tsfile_writer_->write_record(record), E_OUT_OF_ORDER); + } else { + ASSERT_EQ(tsfile_writer_->write_record(record), E_OK); + } + } + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0"; + select.emplace_back(device_name, v0); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 4u); + EXPECT_EQ(rows[0].first, 10); + EXPECT_EQ(rows[1].first, 11); + EXPECT_EQ(rows[2].first, 11); + EXPECT_EQ(rows[3].first, 12); +} + +// Default semantics on the non-aligned tablet path: internal duplicates, +// internal decreases and rows that do not follow the previous tablet are all +// rejected, and a rejected tablet writes no column at all. +TEST_F(TsFileWriterTest, NonAlignedTabletOutOfOrderRejected) { + ScopedAllowNonDecreasingTimestamps guard(false); + std::string device_name = "root.dev_na_tablet"; + std::vector schema_vec; + schema_vec.emplace_back("v0", INT64, PLAIN, UNCOMPRESSED); + schema_vec.emplace_back("v1", INT64, PLAIN, UNCOMPRESSED); + { + std::vector reg; + for (auto& s : schema_vec) reg.push_back(new MeasurementSchema(s)); + ASSERT_EQ(tsfile_writer_->register_timeseries(device_name, reg), E_OK); + } + + auto build_tablet = [&](const int64_t* times, int rows, + int64_t value_base) { + Tablet tablet( + device_name, + std::make_shared>(schema_vec), rows); + for (int i = 0; i < rows; ++i) { + EXPECT_EQ(tablet.add_timestamp(i, times[i]), E_OK); + const int64_t v = value_base + i; + EXPECT_EQ(tablet.add_value(i, 0u, v), E_OK); + EXPECT_EQ(tablet.add_value(i, 1u, v * 10), E_OK); + } + return tablet; + }; + + const int64_t first_times[4] = {10, 11, 12, 13}; + Tablet first = build_tablet(first_times, 4, 0); + ASSERT_EQ(tsfile_writer_->write_tablet(first), E_OK); + + // Duplicate inside the batch, but the first row is > the last written + // timestamp: only the in-batch check can reject it. + const int64_t dup_times[4] = {14, 15, 15, 16}; + Tablet duplicated = build_tablet(dup_times, 4, 100); + EXPECT_EQ(tsfile_writer_->write_tablet(duplicated), E_OUT_OF_ORDER); + + // Decrease inside the batch. + const int64_t decreasing_times[4] = {14, 16, 15, 17}; + Tablet decreasing = build_tablet(decreasing_times, 4, 200); + EXPECT_EQ(tsfile_writer_->write_tablet(decreasing), E_OUT_OF_ORDER); + + // First row of the batch does not follow the last written timestamp. + const int64_t overlapping_times[4] = {12, 13, 14, 15}; + Tablet overlapping = build_tablet(overlapping_times, 4, 300); + EXPECT_EQ(tsfile_writer_->write_tablet(overlapping), E_OUT_OF_ORDER); + + const int64_t next_times[4] = {14, 15, 16, 17}; + Tablet next = build_tablet(next_times, 4, 400); + ASSERT_EQ(tsfile_writer_->write_tablet(next), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0", v1 = "v1"; + select.emplace_back(device_name, v0); + select.emplace_back(device_name, v1); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 8u); + for (int i = 0; i < 8; ++i) { + const int64_t expected_time = 10 + i; + const int64_t expected_value = (i < 4) ? i : 400 + (i - 4); + EXPECT_EQ(rows[i].first, expected_time); + EXPECT_EQ(rows[i].second[0], std::to_string(expected_value)); + EXPECT_EQ(rows[i].second[1], std::to_string(expected_value * 10)); + } +} + +// With the flag on, the non-aligned tablet path accepts equal timestamps +// (including across tablets) but still rejects a strictly decreasing one. +TEST_F(TsFileWriterTest, + AllowNonDecreasingNonAlignedTabletAllowsEqualRejectsDecreasing) { + ScopedAllowNonDecreasingTimestamps guard(true); + std::string device_name = "root.dev_na_tablet_non_decreasing"; + std::vector schema_vec; + schema_vec.emplace_back("v0", INT64, PLAIN, UNCOMPRESSED); + { + std::vector reg; + reg.push_back(new MeasurementSchema(schema_vec[0])); + ASSERT_EQ(tsfile_writer_->register_timeseries(device_name, reg), E_OK); + } + + auto build_tablet = [&](const int64_t* times, int rows) { + Tablet tablet( + device_name, + std::make_shared>(schema_vec), rows); + for (int i = 0; i < rows; ++i) { + EXPECT_EQ(tablet.add_timestamp(i, times[i]), E_OK); + EXPECT_EQ(tablet.add_value(i, 0u, static_cast(i)), E_OK); + } + return tablet; + }; + + const int64_t first_times[4] = {10, 11, 11, 12}; + Tablet first = build_tablet(first_times, 4); + ASSERT_EQ(tsfile_writer_->write_tablet(first), E_OK); + + // Equals the previous tablet's last timestamp (12) and repeats 13. + const int64_t equal_times[4] = {12, 13, 13, 14}; + Tablet equal = build_tablet(equal_times, 4); + ASSERT_EQ(tsfile_writer_->write_tablet(equal), E_OK); + + // Strictly decreasing against the last accepted timestamp (14). + const int64_t decreasing_times[4] = {13, 14, 15, 16}; + Tablet decreasing = build_tablet(decreasing_times, 4); + EXPECT_EQ(tsfile_writer_->write_tablet(decreasing), E_OUT_OF_ORDER); + + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0"; + select.emplace_back(device_name, v0); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 8u); + const int64_t expected[8] = {10, 11, 11, 12, 12, 13, 13, 14}; + for (int i = 0; i < 8; ++i) { + EXPECT_EQ(rows[i].first, expected[i]); + } +} + +// The last timestamp must survive page seals inside a chunk: with a page +// capacity of 3, ten records span several pages before the decreasing row is +// attempted. +TEST_F(TsFileWriterTest, NonAlignedRecordOrderCheckSurvivesPageSeal) { + ScopedAllowNonDecreasingTimestamps guard(false); + ScopedPageMaxPointCount page_guard(3); + std::string device_name = "root.dev_na_record_page"; + ASSERT_EQ( + tsfile_writer_->register_timeseries( + device_name, MeasurementSchema("v0", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + + for (int i = 0; i < 10; ++i) { + TsRecord record(100 + i, device_name); + record.add_point("v0", static_cast(i)); + ASSERT_EQ(tsfile_writer_->write_record(record), E_OK); + } + TsRecord older(105, device_name); + older.add_point("v0", static_cast(1000)); + EXPECT_EQ(tsfile_writer_->write_record(older), E_OUT_OF_ORDER); + TsRecord duplicate(109, device_name); + duplicate.add_point("v0", static_cast(1001)); + EXPECT_EQ(tsfile_writer_->write_record(duplicate), E_OUT_OF_ORDER); + TsRecord next(110, device_name); + next.add_point("v0", static_cast(10)); + ASSERT_EQ(tsfile_writer_->write_record(next), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0"; + select.emplace_back(device_name, v0); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 11u); + for (int i = 0; i < 11; ++i) { + EXPECT_EQ(rows[i].first, 100 + i); + EXPECT_EQ(rows[i].second[0], std::to_string(i)); + } +} + +// Same page-seal survival check for the non-aligned batch (tablet) path, +// where ChunkWriter::write_batch itself splits the batch across pages. +TEST_F(TsFileWriterTest, NonAlignedTabletOrderCheckSurvivesPageSeal) { + ScopedAllowNonDecreasingTimestamps guard(false); + ScopedPageMaxPointCount page_guard(3); + std::string device_name = "root.dev_na_tablet_page"; + std::vector schema_vec; + schema_vec.emplace_back("v0", INT64, PLAIN, UNCOMPRESSED); + { + std::vector reg; + reg.push_back(new MeasurementSchema(schema_vec[0])); + ASSERT_EQ(tsfile_writer_->register_timeseries(device_name, reg), E_OK); + } + + auto build_tablet = [&](int64_t first_time, int rows) { + Tablet tablet( + device_name, + std::make_shared>(schema_vec), rows); + for (int i = 0; i < rows; ++i) { + EXPECT_EQ(tablet.add_timestamp(i, first_time + i), E_OK); + EXPECT_EQ(tablet.add_value(i, 0u, static_cast(i)), E_OK); + } + return tablet; + }; + + Tablet first = build_tablet(100, 10); + ASSERT_EQ(tsfile_writer_->write_tablet(first), E_OK); + + Tablet older = build_tablet(105, 4); + EXPECT_EQ(tsfile_writer_->write_tablet(older), E_OUT_OF_ORDER); + + Tablet next = build_tablet(110, 10); + ASSERT_EQ(tsfile_writer_->write_tablet(next), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0"; + select.emplace_back(device_name, v0); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 20u); + for (int i = 0; i < 20; ++i) { + EXPECT_EQ(rows[i].first, 100 + i); + EXPECT_EQ(rows[i].second[0], std::to_string(i % 10)); + } +} + +// A manual flush starts a new chunk, but timestamp ordering must still hold +// across the flushed chunk boundary for the same series. +TEST_F(TsFileWriterTest, NonAlignedRecordOrderCheckSurvivesFlush) { + ScopedAllowNonDecreasingTimestamps guard(false); + std::string device_name = "root.dev_na_record_flush"; + ASSERT_EQ( + tsfile_writer_->register_timeseries( + device_name, MeasurementSchema("v0", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + + TsRecord first(10, device_name); + first.add_point("v0", static_cast(0)); + ASSERT_EQ(tsfile_writer_->write_record(first), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + + // The chunk writer was reset by the flush; the last timestamp is not. + TsRecord older(9, device_name); + older.add_point("v0", static_cast(1)); + EXPECT_EQ(tsfile_writer_->write_record(older), E_OUT_OF_ORDER); + + TsRecord next(10, device_name); + next.add_point("v0", static_cast(2)); + EXPECT_EQ(tsfile_writer_->write_record(next), E_OUT_OF_ORDER); + + TsRecord later(11, device_name); + later.add_point("v0", static_cast(3)); + ASSERT_EQ(tsfile_writer_->write_record(later), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0"; + select.emplace_back(device_name, v0); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 2u); + EXPECT_EQ(rows[0].first, 10); + EXPECT_EQ(rows[1].first, 11); +} diff --git a/python/tests/test_allow_non_decreasing_timestamps.py b/python/tests/test_allow_non_decreasing_timestamps.py index 2fba75a37d..2187f25ea2 100644 --- a/python/tests/test_allow_non_decreasing_timestamps.py +++ b/python/tests/test_allow_non_decreasing_timestamps.py @@ -26,11 +26,15 @@ TIME_COLUMN, ColumnCategory, ColumnSchema, + Field, + RowRecord, TableSchema, TSDataType, Tablet, + TimeseriesSchema, TsFileReader, TsFileTableWriter, + TsFileWriter, to_dataframe, ) from tsfile.exceptions import OutOfOrderError @@ -129,3 +133,100 @@ def _assert_write_rejected(allow_non_decreasing_timestamps, times): pass finally: shutil.rmtree(tmpdir, ignore_errors=True) + + +# --------------------------------------------------------------------------- +# Tree model (non-aligned device) write paths. C++ used to accept any +# timestamp order here; like the table writer, these paths now reject +# violations with OutOfOrderError and leave the writer usable. +# --------------------------------------------------------------------------- + + +def _open_tree_writer(tmpdir, allow_non_decreasing_timestamps): + path = os.path.join(tmpdir, "tree_order.tsfile") + writer = TsFileWriter( + path, allow_non_decreasing_timestamps=allow_non_decreasing_timestamps + ) + return writer, path + + +def _row_record(device, timestamp, value): + return RowRecord(device, timestamp, [Field("v0", value, TSDataType.INT64)]) + + +def test_tree_writer_rejects_equal_and_decreasing_by_default(): + tmpdir = _new_tmpdir() + device = "root.tree_strict" + writer, _ = _open_tree_writer(tmpdir, False) + try: + writer.register_timeseries(device, TimeseriesSchema("v0", TSDataType.INT64)) + writer.write_row_record(_row_record(device, 10, 1)) + with pytest.raises(OutOfOrderError): + writer.write_row_record(_row_record(device, 10, 2)) + with pytest.raises(OutOfOrderError): + writer.write_row_record(_row_record(device, 9, 3)) + # Rejected rows were not partially written, so the writer still works. + writer.write_row_record(_row_record(device, 11, 4)) + writer.close() + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + +def test_tree_writer_non_decreasing_allows_equal_rejects_decreasing(): + tmpdir = _new_tmpdir() + device = "root.tree_non_decreasing" + writer, _ = _open_tree_writer(tmpdir, True) + try: + writer.register_timeseries(device, TimeseriesSchema("v0", TSDataType.INT64)) + writer.write_row_record(_row_record(device, 10, 1)) + writer.write_row_record(_row_record(device, 10, 2)) + writer.write_row_record(_row_record(device, 11, 3)) + with pytest.raises(OutOfOrderError): + writer.write_row_record(_row_record(device, 9, 4)) + writer.close() + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + +def _build_tree_tablet(device, times): + tablet = Tablet(["v0"], [TSDataType.INT64], len(times)) + tablet.set_table_name(device) + for i, timestamp in enumerate(times): + tablet.add_timestamp(i, timestamp) + tablet.add_value_by_index(0, i, i) + return tablet + + +def test_tree_writer_tablet_order_checked_by_default(): + tmpdir = _new_tmpdir() + device = "root.tree_tablet_strict" + writer, _ = _open_tree_writer(tmpdir, False) + try: + writer.register_timeseries(device, TimeseriesSchema("v0", TSDataType.INT64)) + with pytest.raises(OutOfOrderError): + writer.write_tablet(_build_tree_tablet(device, [10, 11, 11])) + with pytest.raises(OutOfOrderError): + writer.write_tablet(_build_tree_tablet(device, [10, 12, 11])) + # The rejected tablets wrote nothing, so this batch starts cleanly. + writer.write_tablet(_build_tree_tablet(device, [10, 11, 12])) + with pytest.raises(OutOfOrderError): + writer.write_tablet(_build_tree_tablet(device, [11, 12, 13])) + writer.write_tablet(_build_tree_tablet(device, [13, 14, 15])) + writer.close() + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + +def test_tree_writer_tablet_non_decreasing_allows_duplicates(): + tmpdir = _new_tmpdir() + device = "root.tree_tablet_non_decreasing" + writer, _ = _open_tree_writer(tmpdir, True) + try: + writer.register_timeseries(device, TimeseriesSchema("v0", TSDataType.INT64)) + writer.write_tablet(_build_tree_tablet(device, [10, 11, 11, 12])) + writer.write_tablet(_build_tree_tablet(device, [12, 13, 13, 14])) + with pytest.raises(OutOfOrderError): + writer.write_tablet(_build_tree_tablet(device, [13, 14, 15, 16])) + writer.close() + finally: + shutil.rmtree(tmpdir, ignore_errors=True) diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index 90e32b273d..aa77eb6c89 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -41,7 +41,10 @@ Before writer creation, use Java config `setAllowNonDecreasingTimestamps(true)`, C++ `common::set_allow_non_decreasing_timestamps(true)` (C: without `common::`), or Python writer argument `allow_non_decreasing_timestamps=True` (default `False`). This is process-wide, including Python constructor defaults; avoid conflicting -writers. Decreases remain invalid. See `properties-filters.md` for the persisted +writers. Decreases remain invalid. The check applies to every write path, +including non-aligned tree-model records and tablets: a violating write is +rejected as a whole with `E_OUT_OF_ORDER` (`OutOfOrderError` in Python) and +writes no measurement column. See `properties-filters.md` for the persisted policy; CLI `write` has no opt-in. ## Timeseries Metadata From 869b8cc4c1503edc69f81ab614e00f54a9768e05 Mon Sep 17 00:00:00 2001 From: Colin Lee Date: Mon, 30 Nov 2026 19:14:15 +0800 Subject: [PATCH 2/7] fix(cpp): harden non-aligned order pre-check after review Follow-up to c61c032e from the third-party review: - check_tablet_timestamp_order now also applies the recovered per-device last_time_ floor to each column's first actually written row. A tablet whose leading rows are null for every column previously slipped past the existing tablet.timestamps_[0] check and could write its first non-null row below the recovered end_time. - ChunkWriter::destroy() clears the order state (init() already did). - Document in write_record that the new guarantee covers ordering only; other per-point failures are still ignored as before. - Mark the non-aligned write_table pre-check as currently unreachable (table_aligned_ is fixed to true) and note it is kept in step with write_tablet. - Tests: ChunkWriter string-batch ordering and batch state across page seals; tablet atomicity when the violating row is in a later column; a timestamp decrease on a null row is not a write; the recovered-floor case with a leading all-null row. - Docs: scope the all-or-nothing statement to the non-aligned tree paths. --- cpp/src/writer/chunk_writer.cc | 2 + cpp/src/writer/tsfile_writer.cc | 27 +++-- cpp/src/writer/tsfile_writer.h | 7 +- .../file/restorable_tsfile_io_writer_test.cc | 52 ++++++++++ cpp/test/writer/chunk_writer_test.cc | 73 ++++++++++++++ cpp/test/writer/tsfile_writer_test.cc | 98 +++++++++++++++++++ skills/tsfile/references/advanced-apis.md | 13 ++- 7 files changed, 258 insertions(+), 14 deletions(-) diff --git a/cpp/src/writer/chunk_writer.cc b/cpp/src/writer/chunk_writer.cc index d6879f8307..3eae0ba687 100644 --- a/cpp/src/writer/chunk_writer.cc +++ b/cpp/src/writer/chunk_writer.cc @@ -55,6 +55,8 @@ int ChunkWriter::init(const std::string& measurement_name, TSDataType data_type, } void ChunkWriter::destroy() { + has_last_timestamp_ = false; + last_timestamp_ = 0; if (num_of_pages_ == 1) { free_first_writer_data(); } diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index 256a7e2b37..06010dc011 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -868,8 +868,9 @@ int TsFileWriter::check_record_timestamp_order( } int TsFileWriter::check_tablet_timestamp_order( - const Tablet& tablet, common::SimpleVector& chunk_writers, - uint32_t start_idx, uint32_t end_idx) { + const Tablet& tablet, const std::shared_ptr& device_id, + common::SimpleVector& chunk_writers, uint32_t start_idx, + uint32_t end_idx) { if (tablet.timestamps_ == nullptr || start_idx >= end_idx) { return E_OK; } @@ -902,9 +903,16 @@ int TsFileWriter::check_tablet_timestamp_order( continue; } const int64_t timestamp = tablet.timestamps_[r]; + // When the column has no timestamp history yet, also apply the + // recovered per-device floor: leading all-null rows mean the first + // row the chunk writer actually sees may differ from + // tablet.timestamps_[start_idx], which is what the caller's + // recovered-range check looks at. const bool violated = has_last ? common::timestamp_out_of_order(timestamp, last_time) - : chunk_writer->timestamp_order_violated(timestamp); + : (chunk_writer->timestamp_order_violated(timestamp) || + recovered_last_time_order_violated(device_id, + timestamp)); if (violated) { return E_OUT_OF_ORDER; } @@ -959,6 +967,8 @@ int TsFileWriter::write_record(const TsRecord& record) { if (IS_NULL(chunk_writer)) { continue; } + // Ordering violations were rejected above; other per-point failures + // (e.g. OOM) are still ignored here, as before this change. // ignore point writer failure write_point(chunk_writer, record.timestamp_, data_types[c], record.points_[c]); @@ -1370,8 +1380,8 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { ASSERT(chunk_writers.size() == tablet.get_column_count()); // Pre-validate the whole tablet before writing any column so a rejected // batch leaves no partially written measurements behind. - if (RET_FAIL(check_tablet_timestamp_order(tablet, chunk_writers, 0, - total_rows))) { + if (RET_FAIL(check_tablet_timestamp_order(tablet, device_id, chunk_writers, + 0, total_rows))) { return ret; } uint32_t columns_written = 0; @@ -1722,9 +1732,12 @@ int TsFileWriter::write_table(Tablet& tablet) { ASSERT(chunk_writers.size() == tablet.get_column_count()); // Pre-validate this device segment before dispatching any column // write (serial or parallel): a rejected timestamp must not leave - // some columns written while others were skipped. + // some columns written while others were skipped. Note that + // table_aligned_ is fixed to true today, so this non-aligned + // branch is not reachable; it is kept in step with write_tablet + // for a future non-aligned table mode. if (RET_FAIL(check_tablet_timestamp_order( - tablet, chunk_writers, si, + tablet, device_id, chunk_writers, si, device_id_end_index_pair.second))) { return ret; } diff --git a/cpp/src/writer/tsfile_writer.h b/cpp/src/writer/tsfile_writer.h index 1c68616705..c7182380b7 100644 --- a/cpp/src/writer/tsfile_writer.h +++ b/cpp/src/writer/tsfile_writer.h @@ -256,12 +256,15 @@ class TsFileWriter { // configured order (strictly increasing by default, non-decreasing when // allow_non_decreasing_timestamps_ is enabled). They mirror exactly // which rows the non-aligned path actually writes: every point of a - // record, and every non-null row of every tablet column. + // record, and every non-null row of every tablet column. The tablet + // check also applies the recovered per-device floor to each column's + // first written row, which can differ from tablet.timestamps_[0] when the + // leading rows are null. int check_record_timestamp_order( common::SimpleVector& chunk_writers, int64_t timestamp); int check_tablet_timestamp_order( - const Tablet& tablet, + const Tablet& tablet, const std::shared_ptr& device_id, common::SimpleVector& chunk_writers, uint32_t start_idx, uint32_t end_idx); diff --git a/cpp/test/file/restorable_tsfile_io_writer_test.cc b/cpp/test/file/restorable_tsfile_io_writer_test.cc index 09296a9966..9e85fa3da3 100644 --- a/cpp/test/file/restorable_tsfile_io_writer_test.cc +++ b/cpp/test/file/restorable_tsfile_io_writer_test.cc @@ -440,6 +440,58 @@ TEST_F(RestorableTsFileIOWriterTest, } } +// A recovered device's per-device floor must also cover a tablet whose leading +// rows are null: the first *written* row is what must not land back inside the +// flushed range. +TEST_F(RestorableTsFileIOWriterTest, + TreeWriterTabletWithLeadingNullRowRespectsRecoveredFloor) { + TsFileWriter tw; + ASSERT_EQ(tw.open(file_name_, GetWriteCreateFlags(), 0666), E_OK); + ASSERT_EQ( + tw.register_timeseries( + "root.d1", MeasurementSchema("s1", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + TsRecord record(15, "root.d1"); + record.add_point("s1", static_cast(15)); + ASSERT_EQ(tw.write_record(record), E_OK); + ASSERT_EQ(tw.flush(), E_OK); + ASSERT_EQ(tw.close(), E_OK); + + CorruptCurrentFileTail(3); + + RestorableTsFileIOWriter rw; + ASSERT_EQ(rw.open(file_name_, true), E_OK); + ASSERT_TRUE(rw.can_write()); + + TsFileWriter tw2; + ASSERT_EQ(tw2.init(&rw), E_OK); + + std::vector schema_vec; + schema_vec.emplace_back("s1", INT64, PLAIN, UNCOMPRESSED); + Tablet tablet("root.d1", + std::make_shared>(schema_vec), + 2); + ASSERT_EQ(tablet.add_timestamp(0, 16), E_OK); + ASSERT_EQ(tablet.add_timestamp(1, 10), E_OK); + const int64_t values[2] = {0, 10}; // row 0 is null for s1 + const uint8_t nulls[1] = {0x01}; + ASSERT_EQ(tablet.set_column_values(0u, values, nulls, 2), E_OK); + + // Row 0 (16) is above the recovered floor, so the old row-0 check passes; + // the first row actually written (10) is below it. + EXPECT_EQ(tw2.write_tablet(tablet), E_OUT_OF_ORDER); + + TsRecord next(16, "root.d1"); + next.add_point("s1", static_cast(16)); + ASSERT_EQ(tw2.write_record(next), E_OK); + ASSERT_EQ(tw2.close(), E_OK); + + TsFileTreeReader reader; + ASSERT_EQ(reader.open(file_name_), E_OK); + ASSERT_EQ(CountTreeReaderRows(reader, {"s1"}), 2); + reader.close(); +} + // ----------------------------------------------------------------------------- // Tree model + Recovery + continued write with aligned timeseries, then // read-back verify diff --git a/cpp/test/writer/chunk_writer_test.cc b/cpp/test/writer/chunk_writer_test.cc index 883c3a8124..80a777fcb3 100644 --- a/cpp/test/writer/chunk_writer_test.cc +++ b/cpp/test/writer/chunk_writer_test.cc @@ -92,4 +92,77 @@ TEST_F(ChunkWriterTest, DestroyChunkWriter) { chunk_writer.destroy(); EXPECT_EQ(chunk_writer.get_chunk_statistic(), nullptr); EXPECT_EQ(chunk_writer.get_chunk_data().total_size(), 0); +} + +namespace { +struct PagePointCapGuard { + explicit PagePointCapGuard(uint32_t cap) + : saved_(common::g_config_value_.page_writer_max_point_num_) { + common::g_config_value_.page_writer_max_point_num_ = cap; + } + ~PagePointCapGuard() { + common::g_config_value_.page_writer_max_point_num_ = saved_; + } + + private: + uint32_t saved_; +}; +} // namespace + +// A string batch must be rejected as a whole when it does not follow the +// timestamps already appended, and a rejected batch must not advance the +// chunk's last timestamp. +TEST_F(ChunkWriterTest, WriteStringBatchRejectsOutOfOrder) { + common::set_allow_non_decreasing_timestamps(false); + ChunkWriter writer; + ASSERT_EQ(writer.init("string_measurement", TSDataType::STRING, + TSEncoding::PLAIN, CompressionType::UNCOMPRESSED), + E_OK); + const char* buffer = "aabbccdd"; + const uint32_t offsets[5] = {0, 2, 4, 6, 8}; + const int64_t first[3] = {10, 11, 13}; + ASSERT_EQ(writer.write_string_batch(first, buffer, offsets, 0, 3), E_OK); + + // Equal to the last timestamp: rejected under the default policy. + const int64_t equal[1] = {13}; + EXPECT_EQ(writer.write_string_batch(equal, buffer, offsets, 0, 1), + E_OUT_OF_ORDER); + // Strictly decreasing. + const int64_t older[1] = {12}; + EXPECT_EQ(writer.write_string_batch(older, buffer, offsets, 0, 1), + E_OUT_OF_ORDER); + // A decrease inside the batch rejects the whole batch. + const int64_t unordered[3] = {14, 16, 15}; + EXPECT_EQ(writer.write_string_batch(unordered, buffer, offsets, 0, 3), + E_OUT_OF_ORDER); + + // Nothing from the rejected batches advanced the last timestamp. + const int64_t next[1] = {14}; + EXPECT_EQ(writer.write_string_batch(next, buffer, offsets, 0, 1), E_OK); + EXPECT_EQ(writer.write_string_batch(equal, buffer, offsets, 0, 1), + E_OUT_OF_ORDER); + writer.destroy(); +} + +// The last appended timestamp survives page seals for batched writes too. +TEST_F(ChunkWriterTest, WriteBatchOrderCheckSurvivesPageSeal) { + common::set_allow_non_decreasing_timestamps(false); + PagePointCapGuard page_guard(3); + ChunkWriter writer; + ASSERT_EQ(writer.init("int64_measurement", TSDataType::INT64, + TSEncoding::PLAIN, CompressionType::UNCOMPRESSED), + E_OK); + int64_t values[6] = {0, 1, 2, 3, 4, 5}; + int64_t timestamps[6] = {10, 11, 12, 13, 14, 15}; + ASSERT_EQ(writer.write_batch(timestamps, values, 6), E_OK); + ASSERT_GE(writer.num_of_pages(), 2); + + int64_t older_ts[1] = {12}; + int64_t older_val[1] = {9}; + EXPECT_EQ(writer.write_batch(older_ts, older_val, 1), E_OUT_OF_ORDER); + + int64_t next_ts[1] = {16}; + int64_t next_val[1] = {16}; + EXPECT_EQ(writer.write_batch(next_ts, next_val, 1), E_OK); + writer.destroy(); } \ No newline at end of file diff --git a/cpp/test/writer/tsfile_writer_test.cc b/cpp/test/writer/tsfile_writer_test.cc index e68ae522fb..e8d36790f4 100644 --- a/cpp/test/writer/tsfile_writer_test.cc +++ b/cpp/test/writer/tsfile_writer_test.cc @@ -3165,3 +3165,101 @@ TEST_F(TsFileWriterTest, NonAlignedRecordOrderCheckSurvivesFlush) { EXPECT_EQ(rows[0].first, 10); EXPECT_EQ(rows[1].first, 11); } + +// A tablet whose violation is only visible in a later column must still be +// rejected before the earlier column is written. +TEST_F(TsFileWriterTest, NonAlignedTabletRejectionWritesNoColumn) { + ScopedAllowNonDecreasingTimestamps guard(false); + std::string device_name = "root.dev_na_tablet_partial"; + std::vector schema_vec; + schema_vec.emplace_back("v0", INT64, PLAIN, UNCOMPRESSED); + schema_vec.emplace_back("v1", INT64, PLAIN, UNCOMPRESSED); + { + std::vector reg; + for (auto& s : schema_vec) reg.push_back(new MeasurementSchema(s)); + ASSERT_EQ(tsfile_writer_->register_timeseries(device_name, reg), E_OK); + } + + TsRecord first(10, device_name); + first.add_point("v0", static_cast(0)); + first.add_point("v1", static_cast(100)); + ASSERT_EQ(tsfile_writer_->write_record(first), E_OK); + + // v0 would accept ts=11 (row 0), but v1's only row (ts=9) is older than + // the ts=10 it already holds. The whole tablet must be rejected. + Tablet tablet(device_name, + std::make_shared>(schema_vec), + 2); + ASSERT_EQ(tablet.add_timestamp(0, 11), E_OK); + ASSERT_EQ(tablet.add_timestamp(1, 9), E_OK); + // v0: row 0 valid (1), row 1 null; v1: row 0 null, row 1 valid (109). + const int64_t v0_values[2] = {1, 0}; + const int64_t v1_values[2] = {0, 109}; + const uint8_t v0_nulls[1] = {0x02}; + const uint8_t v1_nulls[1] = {0x01}; + ASSERT_EQ(tablet.set_column_values(0u, v0_values, v0_nulls, 2), E_OK); + ASSERT_EQ(tablet.set_column_values(1u, v1_values, v1_nulls, 2), E_OK); + EXPECT_EQ(tsfile_writer_->write_tablet(tablet), E_OUT_OF_ORDER); + + // v0 must not have received the ts=11 row from the rejected tablet. + TsRecord next(11, device_name); + next.add_point("v0", static_cast(2)); + next.add_point("v1", static_cast(111)); + ASSERT_EQ(tsfile_writer_->write_record(next), E_OK); + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0", v1 = "v1"; + select.emplace_back(device_name, v0); + select.emplace_back(device_name, v1); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 2u); + EXPECT_EQ(rows[0].first, 10); + EXPECT_EQ(rows[0].second[0], "0"); + EXPECT_EQ(rows[0].second[1], "100"); + EXPECT_EQ(rows[1].first, 11); + EXPECT_EQ(rows[1].second[0], "2"); + EXPECT_EQ(rows[1].second[1], "111"); +} + +// A timestamp decrease on a row that is null for the measurement is not a +// write to that series: the non-aligned path skips such rows entirely, so the +// tablet is accepted (matching Java's per-column write loop). +TEST_F(TsFileWriterTest, NonAlignedTabletIgnoresDecreaseOnNullRows) { + ScopedAllowNonDecreasingTimestamps guard(false); + std::string device_name = "root.dev_na_tablet_null_rows"; + ASSERT_EQ( + tsfile_writer_->register_timeseries( + device_name, MeasurementSchema("v0", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + + TsRecord first(10, device_name); + first.add_point("v0", static_cast(0)); + ASSERT_EQ(tsfile_writer_->write_record(first), E_OK); + + std::vector schema_vec; + schema_vec.emplace_back("v0", INT64, PLAIN, UNCOMPRESSED); + Tablet tablet(device_name, + std::make_shared>(schema_vec), + 3); + ASSERT_EQ(tablet.add_timestamp(0, 12), E_OK); + ASSERT_EQ(tablet.add_timestamp(1, 11), E_OK); + ASSERT_EQ(tablet.add_timestamp(2, 13), E_OK); + const int64_t values[3] = {12, 0, 13}; // row 1 (ts=11) is null for v0 + const uint8_t nulls[1] = {0x02}; + ASSERT_EQ(tablet.set_column_values(0u, values, nulls, 3), E_OK); + ASSERT_EQ(tsfile_writer_->write_tablet(tablet), E_OK); + + ASSERT_EQ(tsfile_writer_->flush(), E_OK); + ASSERT_EQ(tsfile_writer_->close(), E_OK); + + std::vector select; + std::string v0 = "v0"; + select.emplace_back(device_name, v0); + auto rows = ReadRows(file_name_, select); + ASSERT_EQ(rows.size(), 3u); + EXPECT_EQ(rows[0].first, 10); + EXPECT_EQ(rows[1].first, 12); + EXPECT_EQ(rows[2].first, 13); +} diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index aa77eb6c89..21c652b301 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -41,11 +41,14 @@ Before writer creation, use Java config `setAllowNonDecreasingTimestamps(true)`, C++ `common::set_allow_non_decreasing_timestamps(true)` (C: without `common::`), or Python writer argument `allow_non_decreasing_timestamps=True` (default `False`). This is process-wide, including Python constructor defaults; avoid conflicting -writers. Decreases remain invalid. The check applies to every write path, -including non-aligned tree-model records and tablets: a violating write is -rejected as a whole with `E_OUT_OF_ORDER` (`OutOfOrderError` in Python) and -writes no measurement column. See `properties-filters.md` for the persisted -policy; CLI `write` has no opt-in. +writers. Decreases remain invalid. On the non-aligned C++ tree paths +(`TsFileWriter::write_record` and `write_tablet`, also reached from C and +Python), a violating write is rejected as a whole with `E_OUT_OF_ORDER` +(`OutOfOrderError` in Python) before any measurement column is written. +Aligned row/tablet calls check the time column first, so they write no value +column when rejected; Table-model calls are per device segment and may already +have written earlier segments. Java has no all-or-nothing guarantee here. See +`properties-filters.md` for the persisted policy; CLI `write` has no opt-in. ## Timeseries Metadata From 799b6141331a5dc8c62539c738fc98a8512d7ba2 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 12:22:41 +0800 Subject: [PATCH 3/7] Validate non-aligned tablet time order once before writing columns --- cpp/src/common/schema.h | 4 + cpp/src/writer/chunk_writer.h | 187 +++++++----------- cpp/src/writer/tsfile_writer.cc | 163 ++++++--------- cpp/src/writer/tsfile_writer.h | 12 +- .../file/restorable_tsfile_io_writer_test.cc | 28 ++- cpp/test/writer/chunk_writer_test.cc | 1 + cpp/test/writer/tsfile_writer_test.cc | 32 +-- skills/tsfile/references/advanced-apis.md | 4 + 8 files changed, 186 insertions(+), 245 deletions(-) diff --git a/cpp/src/common/schema.h b/cpp/src/common/schema.h index 007e1f1db4..ed920c9f00 100644 --- a/cpp/src/common/schema.h +++ b/cpp/src/common/schema.h @@ -177,6 +177,10 @@ struct MeasurementSchemaGroup { TimeChunkWriter* time_chunk_writer_ = nullptr; int64_t last_time_ = INT64_MIN; + // Transferred to each non-aligned chunk writer on its first use after + // recovery. + std::map recovered_series_end_times_; + void update_last_time(int64_t timestamp) { last_time_ = std::max(last_time_, timestamp); has_last_time_ = true; diff --git a/cpp/src/writer/chunk_writer.h b/cpp/src/writer/chunk_writer.h index 09b635d729..482dfda216 100644 --- a/cpp/src/writer/chunk_writer.h +++ b/cpp/src/writer/chunk_writer.h @@ -25,26 +25,10 @@ #include "common/statistic.h" #include "common/tsfile_common.h" #include "page_writer.h" +#include "time_page_writer.h" namespace storage { -#define CW_DO_WRITE_FOR_TYPE() \ - { \ - int ret = common::E_OK; \ - if (UNLIKELY(timestamp_order_violated(timestamp))) { \ - return common::E_OUT_OF_ORDER; \ - } \ - if (RET_FAIL(page_writer_.write(timestamp, value))) { \ - return ret; \ - } \ - last_timestamp_ = timestamp; \ - has_last_timestamp_ = true; \ - if (RET_FAIL(seal_cur_page_if_full())) { \ - return ret; \ - } \ - return ret; \ - } - class ChunkWriter { public: static const int32_t PAGES_DATA_PAGE_SIZE = 1024; @@ -71,33 +55,33 @@ class ChunkWriter { if (UNLIKELY(data_type_ != common::BOOLEAN)) { return common::E_TYPE_NOT_MATCH; } - CW_DO_WRITE_FOR_TYPE(); + return write_checked_point(timestamp, value); } FORCE_INLINE int write(int64_t timestamp, int32_t value) { if (UNLIKELY(data_type_ != common::INT32 && data_type_ != common::DATE)) { return common::E_TYPE_NOT_MATCH; } - CW_DO_WRITE_FOR_TYPE(); + return write_checked_point(timestamp, value); } FORCE_INLINE int write(int64_t timestamp, int64_t value) { if (UNLIKELY(data_type_ != common::INT64 && data_type_ != common::TIMESTAMP)) { return common::E_TYPE_NOT_MATCH; } - CW_DO_WRITE_FOR_TYPE(); + return write_checked_point(timestamp, value); } FORCE_INLINE int write(int64_t timestamp, float value) { if (UNLIKELY(data_type_ != common::FLOAT)) { return common::E_TYPE_NOT_MATCH; } - CW_DO_WRITE_FOR_TYPE(); + return write_checked_point(timestamp, value); } FORCE_INLINE int write(int64_t timestamp, double value) { if (UNLIKELY(data_type_ != common::DOUBLE)) { return common::E_TYPE_NOT_MATCH; } - CW_DO_WRITE_FOR_TYPE(); + return write_checked_point(timestamp, value); } FORCE_INLINE int write(int64_t timestamp, common::String value) { if (UNLIKELY(data_type_ != common::STRING && @@ -105,93 +89,28 @@ class ChunkWriter { data_type_ != common::BLOB)) { return common::E_TYPE_NOT_MATCH; } - CW_DO_WRITE_FOR_TYPE(); + return write_checked_point(timestamp, value); } template int write_batch(const int64_t* timestamps, const T* values, uint32_t count) { - int ret = common::E_OK; - if (count == 0) return ret; - // Validate the whole batch before touching a page so an order - // violation never leaves a partially written batch behind. - if (RET_FAIL(check_batch_timestamp_order(timestamps, count))) { - return ret; - } - uint32_t offset = 0; - const uint32_t page_cap = - common::g_config_value_.page_writer_max_point_num_; - while (offset < count) { - uint32_t cur_points = page_writer_.get_point_numer(); - // Seal whenever cur_points is at or past the cap; the counter is - // size_ (rows including the just-written batch) and may exceed - // page_cap, so a plain subtraction would underflow uint32_t. - if (cur_points >= page_cap) { - if (RET_FAIL(seal_cur_page(false))) { - return ret; - } - cur_points = 0; - } - uint32_t page_remaining = page_cap - cur_points; - uint32_t batch_size = std::min(count - offset, page_remaining); - if (RET_FAIL(page_writer_.write_batch( - timestamps + offset, values + offset, batch_size))) { - return ret; - } - // Remember the last point appended; the page statistic is reset - // on every page seal, so it cannot carry this across pages. - last_timestamp_ = timestamps[offset + batch_size - 1]; - has_last_timestamp_ = true; - offset += batch_size; - if (RET_FAIL(seal_cur_page_if_full())) { - return ret; - } + if (count && (timestamp_order_violated(timestamps[0]) || + !TimePageWriter::is_batch_in_order(timestamps, count))) { + return common::E_OUT_OF_ORDER; } - return ret; + return write_ordered_batch(timestamps, values, count); } int write_string_batch(const int64_t* timestamps, const char* buffer, const uint32_t* offsets, uint32_t start_idx, uint32_t count) { - int ret = common::E_OK; - if (count == 0) return ret; - // See write_batch: reject the whole batch before writing anything. - if (RET_FAIL(check_batch_timestamp_order(timestamps, count))) { - return ret; - } - uint32_t offset = 0; - const uint32_t page_cap = - common::g_config_value_.page_writer_max_point_num_; - while (offset < count) { - uint32_t cur_points = page_writer_.get_point_numer(); - if (cur_points >= page_cap) { - if (RET_FAIL(seal_cur_page(false))) { - return ret; - } - cur_points = 0; - } - uint32_t page_remaining = page_cap - cur_points; - uint32_t batch_size = std::min(count - offset, page_remaining); - // TODO: for variable-length types (STRING/TEXT/BLOB), batch_size is - // capped by row count alone; a single sub-batch can push the page - // memory far past page_writer_max_memory_bytes_ before - // seal_cur_page_if_full() runs. Add byte-budget tracking here: - // estimate bytes remaining in the current page and cap batch_size - // so that one write cannot exceed the memory limit by more than one - // value. - if (RET_FAIL(page_writer_.write_string_batch( - timestamps + offset, buffer, offsets, start_idx + offset, - batch_size))) { - return ret; - } - last_timestamp_ = timestamps[offset + batch_size - 1]; - has_last_timestamp_ = true; - offset += batch_size; - if (RET_FAIL(seal_cur_page_if_full())) { - return ret; - } + if (count && (timestamp_order_violated(timestamps[0]) || + !TimePageWriter::is_batch_in_order(timestamps, count))) { + return common::E_OUT_OF_ORDER; } - return ret; + return write_ordered_string_batch(timestamps, buffer, offsets, + start_idx, count); } int end_encode_chunk(); @@ -205,7 +124,7 @@ class ChunkWriter { // column. FORCE_INLINE bool timestamp_order_violated(int64_t timestamp) const { return has_last_timestamp_ && - is_out_of_order(timestamp, last_timestamp_); + common::timestamp_out_of_order(timestamp, last_timestamp_); } bool hasData() { return num_of_pages_ > 0 || (page_writer_.get_statistic() != nullptr && @@ -224,26 +143,68 @@ class ChunkWriter { int64_t estimate_max_series_mem_size(); private: - FORCE_INLINE static bool is_out_of_order(int64_t time, int64_t last_time) { - return common::timestamp_out_of_order(time, last_time); - } - // Validates `count` timestamps both against the last timestamp already - // held by this chunk and among themselves. - FORCE_INLINE int check_batch_timestamp_order(const int64_t* timestamps, - uint32_t count) const { - if (count == 0) { - return common::E_OK; - } - if (timestamp_order_violated(timestamps[0])) { + friend class TsFileWriter; + + template + int write_checked_point(int64_t timestamp, T value) { + if (UNLIKELY(timestamp_order_violated(timestamp))) { return common::E_OUT_OF_ORDER; } - for (uint32_t i = 1; i < count; i++) { - if (is_out_of_order(timestamps[i], timestamps[i - 1])) { - return common::E_OUT_OF_ORDER; + return write_ordered_point(timestamp, value); + } + + template + int write_ordered_point(int64_t timestamp, T value) { + int ret = page_writer_.write(timestamp, value); + if (ret != common::E_OK) return ret; + last_timestamp_ = timestamp; + has_last_timestamp_ = true; + return seal_cur_page_if_full(); + } + + template + int write_ordered_batch(const int64_t* times, const T* values, + uint32_t count) { + return append_ordered_pages( + times, count, [&](uint32_t offset, uint32_t size) { + return page_writer_.write_batch(times + offset, values + offset, + size); + }); + } + + int write_ordered_string_batch(const int64_t* times, const char* buffer, + const uint32_t* offsets, uint32_t start, + uint32_t count) { + return append_ordered_pages( + times, count, [&](uint32_t offset, uint32_t size) { + return page_writer_.write_string_batch( + times + offset, buffer, offsets, start + offset, size); + }); + } + + template + int append_ordered_pages(const int64_t* times, uint32_t count, + WritePage write_page) { + int ret = common::E_OK; + const uint32_t page_cap = + common::g_config_value_.page_writer_max_point_num_; + uint32_t offset = 0; + while (offset < count) { + uint32_t points = page_writer_.get_point_numer(); + if (points >= page_cap) { + if (RET_FAIL(seal_cur_page(false))) return ret; + points = 0; } + const uint32_t size = std::min(count - offset, page_cap - points); + if (RET_FAIL(write_page(offset, size))) return ret; + offset += size; + last_timestamp_ = times[offset - 1]; + has_last_timestamp_ = true; + if (RET_FAIL(seal_cur_page_if_full())) return ret; } - return common::E_OK; + return ret; } + FORCE_INLINE bool is_cur_page_full() const { // FIXME return (page_writer_.get_point_numer() >= diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index a2e8a7e860..da73b76ca9 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -24,6 +24,7 @@ #include #include #include +#include #include "chunk_writer.h" #include "common/config/config.h" @@ -229,12 +230,18 @@ int TsFileWriter::init(RestorableTsFileIOWriter* rw) { if (cm == nullptr) { continue; } - // Track the highest end_time across recovered chunks so that - // appending writes can refuse out-of-order timestamps. + std::string mname = cm->measurement_name_.to_std_string(); if (cm->statistic_ != nullptr && cm->statistic_->count_ > 0) { - group->update_last_time(cm->statistic_->end_time_); + const int64_t end_time = cm->statistic_->end_time_; + if (group->is_aligned_) { + group->update_last_time(end_time); + } else { + auto entry = group->recovered_series_end_times_ + .emplace(mname, end_time) + .first; + entry->second = std::max(entry->second, end_time); + } } - std::string mname = cm->measurement_name_.to_std_string(); if (mname.empty()) { continue; } @@ -576,6 +583,15 @@ int TsFileWriter::do_check_schema( ms->data_type_, ms->encoding_, ms->compression_type_); if (IS_SUCC(ret)) { + if (enforce_recovered_last_time_order_) { + auto& ends = device_schema->recovered_series_end_times_; + auto it = ends.find(ms->measurement_name_); + if (it != ends.end()) { + ms->chunk_writer_->last_timestamp_ = it->second; + ms->chunk_writer_->has_last_timestamp_ = true; + ends.erase(it); + } + } chunk_writers.push_back(ms->chunk_writer_); } else { for (size_t chunk_writer_idx = 0; @@ -868,69 +884,39 @@ int TsFileWriter::check_record_timestamp_order( } int TsFileWriter::check_tablet_timestamp_order( - const Tablet& tablet, const std::shared_ptr& device_id, - common::SimpleVector& chunk_writers, uint32_t start_idx, - uint32_t end_idx) { - if (tablet.timestamps_ == nullptr || start_idx >= end_idx) { - return E_OK; + const Tablet& tablet, common::SimpleVector& chunk_writers, + uint32_t start, uint32_t end) { + if (end > tablet.max_row_num_) return E_OUT_OF_RANGE; + if (start == end) return E_OK; + if (tablet.timestamps_ == nullptr) return E_INVALID_ARG; + const int64_t* times = tablet.timestamps_; + if (!TimePageWriter::is_batch_in_order(times + start, end - start)) { + return E_OUT_OF_ORDER; } - end_idx = std::min(end_idx, tablet.max_row_num_); - // Columns of one tablet normally map to distinct chunk writers, but two - // columns can share a measurement. Track the timestamp each chunk writer - // would have after the columns processed so far so the pre-check matches - // the real write order. - std::vector> last_written; - last_written.reserve(4); - for (uint32_t c = 0; c < chunk_writers.size(); c++) { - ChunkWriter* chunk_writer = chunk_writers[c]; - if (IS_NULL(chunk_writer)) { - continue; - } - // Null rows are skipped entirely on the non-aligned path, so only the - // non-null rows of this column reach the chunk writer. - common::BitMap& null_map = tablet.bitmaps_[c]; - bool has_last = false; - int64_t last_time = 0; - for (size_t i = 0; i < last_written.size(); i++) { - if (last_written[i].first == chunk_writer) { - has_last = true; - last_time = last_written[i].second; - break; - } - } - for (uint32_t r = start_idx; r < end_idx; r++) { - if (null_map.test(r)) { - continue; - } - const int64_t timestamp = tablet.timestamps_[r]; - // When the column has no timestamp history yet, also apply the - // recovered per-device floor: leading all-null rows mean the first - // row the chunk writer actually sees may differ from - // tablet.timestamps_[start_idx], which is what the caller's - // recovered-range check looks at. - const bool violated = - has_last ? common::timestamp_out_of_order(timestamp, last_time) - : (chunk_writer->timestamp_order_violated(timestamp) || - recovered_last_time_order_violated(device_id, - timestamp)); - if (violated) { + + std::unordered_map previous_columns; + for (uint32_t c = 0; c < chunk_writers.size(); ++c) { + ChunkWriter* writer = chunk_writers[c]; + if (writer == nullptr) continue; + BitMap& nulls = tablet.bitmaps_[c]; + uint32_t first = start; + while (first < end && nulls.test(first)) ++first; + if (first == end) continue; + if (writer->timestamp_order_violated(times[first])) + return E_OUT_OF_ORDER; + + // Tablet construction enforces unique names, but columns can be + // renamed. An alias must also follow the previous column targeting the + // same series. + auto entry = previous_columns.emplace(writer, c); + if (!entry.second) { + BitMap& previous_nulls = tablet.bitmaps_[entry.first->second]; + uint32_t last = end - 1; + while (previous_nulls.test(last)) --last; + if (common::timestamp_out_of_order(times[first], times[last])) { return E_OUT_OF_ORDER; } - has_last = true; - last_time = timestamp; - } - if (has_last) { - bool found = false; - for (size_t i = 0; i < last_written.size(); i++) { - if (last_written[i].first == chunk_writer) { - last_written[i].second = last_time; - found = true; - break; - } - } - if (!found) { - last_written.emplace_back(chunk_writer, last_time); - } + entry.first->second = c; } } return E_OK; @@ -941,12 +927,6 @@ int TsFileWriter::write_record(const TsRecord& record) { if (UNLIKELY(unrecoverable_)) return E_DATA_INCONSISTENCY; int ret = E_OK; auto device_id = std::make_shared(record.device_id_); - // After recovery, refuse writes whose timestamp would land at or before - // any already-flushed chunk's end_time for this device. - if (recovered_last_time_order_violated(device_id, record.timestamp_)) { - return E_OUT_OF_ORDER; - } - // std::vector chunk_writers; SimpleVector chunk_writers; SimpleVector data_types; MeasurementNamesFromRecord mnames_getter(record); @@ -974,12 +954,6 @@ int TsFileWriter::write_record(const TsRecord& record) { record.points_[c]); } - 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->update_last_time(record.timestamp_); - } - } record_count_since_last_flush_++; ret = check_memory_size_and_may_flush_chunks(); return ret; @@ -1354,10 +1328,7 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { // and would let uninitialized timestamps/values past the live range leak // into the chunk. const uint32_t total_rows = tablet.get_cur_row_size(); - if (total_rows > 0 && tablet.timestamps_ != nullptr && - recovered_last_time_order_violated(device_id, tablet.timestamps_[0])) { - return E_OUT_OF_ORDER; - } + if (tablet.err_code_ != E_OK) return tablet.err_code_; SimpleVector chunk_writers; SimpleVector data_types; MeasurementNamesFromTablet mnames_getter(tablet); @@ -1377,8 +1348,8 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { ASSERT(chunk_writers.size() == tablet.get_column_count()); // Pre-validate the whole tablet before writing any column so a rejected // batch leaves no partially written measurements behind. - if (RET_FAIL(check_tablet_timestamp_order(tablet, device_id, chunk_writers, - 0, total_rows))) { + if (RET_FAIL(check_tablet_timestamp_order(tablet, chunk_writers, 0, + total_rows))) { return ret; } uint32_t columns_written = 0; @@ -1399,14 +1370,6 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { columns_written++; } - if (enforce_recovered_last_time_order_ && total_rows > 0 && - tablet.timestamps_ != nullptr) { - auto schema_it = schemas_.find(device_id); - if (schema_it != schemas_.end() && schema_it->second != nullptr) { - schema_it->second->update_last_time( - tablet.timestamps_[total_rows - 1]); - } - } record_count_since_last_flush_ += total_rows; ret = check_memory_size_and_may_flush_chunks(); return ret; @@ -1747,7 +1710,7 @@ int TsFileWriter::write_table(Tablet& tablet) { // branch is not reachable; it is kept in step with write_tablet // for a future non-aligned table mode. if (RET_FAIL(check_tablet_timestamp_order( - tablet, device_id, chunk_writers, si, + tablet, chunk_writers, si, device_id_end_index_pair.second))) { return ret; } @@ -1936,7 +1899,8 @@ int TsFileWriter::write_typed_column(ChunkWriter* chunk_writer, int ret = E_OK; for (uint32_t r = start_idx; r < end_idx; r++) { if (LIKELY(!col_notnull_bitmap.test(r))) { - if (RET_FAIL(chunk_writer->write(timestamps[r], col_values[r]))) { + if (RET_FAIL(chunk_writer->write_ordered_point(timestamps[r], + col_values[r]))) { return ret; } } @@ -1955,7 +1919,8 @@ int TsFileWriter::write_typed_column(ChunkWriter* chunk_writer, common::String val( string_col->buffer + string_col->offsets[r], string_col->offsets[r + 1] - string_col->offsets[r]); - if (RET_FAIL(chunk_writer->write(timestamps[r], val))) { + if (RET_FAIL( + chunk_writer->write_ordered_point(timestamps[r], val))) { return ret; } } @@ -2003,29 +1968,29 @@ int TsFileWriter::write_column_batch(ChunkWriter* chunk_writer, if (!has_null) { switch (data_type) { case common::BOOLEAN: - ret = chunk_writer->write_batch( + ret = chunk_writer->write_ordered_batch( timestamps + start_idx, col_values.bool_data + start_idx, count); break; case common::INT32: case common::DATE: - ret = chunk_writer->write_batch( + ret = chunk_writer->write_ordered_batch( timestamps + start_idx, col_values.int32_data + start_idx, count); break; case common::INT64: case common::TIMESTAMP: - ret = chunk_writer->write_batch( + ret = chunk_writer->write_ordered_batch( timestamps + start_idx, col_values.int64_data + start_idx, count); break; case common::FLOAT: - ret = chunk_writer->write_batch( + ret = chunk_writer->write_ordered_batch( timestamps + start_idx, col_values.float_data + start_idx, count); break; case common::DOUBLE: - ret = chunk_writer->write_batch( + ret = chunk_writer->write_ordered_batch( timestamps + start_idx, col_values.double_data + start_idx, count); break; @@ -2039,7 +2004,7 @@ int TsFileWriter::write_column_batch(ChunkWriter* chunk_writer, // construction so the bit pattern is identical — cast at the // boundary until the downstream chain is converted in a // follow-up. - ret = chunk_writer->write_string_batch( + ret = chunk_writer->write_ordered_string_batch( timestamps + start_idx, sc->buffer, reinterpret_cast(sc->offsets), start_idx, count); diff --git a/cpp/src/writer/tsfile_writer.h b/cpp/src/writer/tsfile_writer.h index c7182380b7..334802e482 100644 --- a/cpp/src/writer/tsfile_writer.h +++ b/cpp/src/writer/tsfile_writer.h @@ -251,20 +251,12 @@ class TsFileWriter { bool recovered_last_time_order_violated( const std::shared_ptr& device_id, int64_t timestamp) const; - // Non-aligned pre-validation. Both helpers reject a whole record / - // tablet before any column is written when a timestamp would violate the - // configured order (strictly increasing by default, non-decreasing when - // allow_non_decreasing_timestamps_ is enabled). They mirror exactly - // which rows the non-aligned path actually writes: every point of a - // record, and every non-null row of every tablet column. The tablet - // check also applies the recovered per-device floor to each column's - // first written row, which can differ from tablet.timestamps_[0] when the - // leading rows are null. + // Validate all non-aligned columns before appending to any of them. int check_record_timestamp_order( common::SimpleVector& chunk_writers, int64_t timestamp); int check_tablet_timestamp_order( - const Tablet& tablet, const std::shared_ptr& device_id, + const Tablet& tablet, common::SimpleVector& chunk_writers, uint32_t start_idx, uint32_t end_idx); diff --git a/cpp/test/file/restorable_tsfile_io_writer_test.cc b/cpp/test/file/restorable_tsfile_io_writer_test.cc index 9e85fa3da3..7525a26bf0 100644 --- a/cpp/test/file/restorable_tsfile_io_writer_test.cc +++ b/cpp/test/file/restorable_tsfile_io_writer_test.cc @@ -440,17 +440,21 @@ TEST_F(RestorableTsFileIOWriterTest, } } -// A recovered device's per-device floor must also cover a tablet whose leading -// rows are null: the first *written* row is what must not land back inside the -// flushed range. TEST_F(RestorableTsFileIOWriterTest, - TreeWriterTabletWithLeadingNullRowRespectsRecoveredFloor) { + NonAlignedTabletChecksEachRecoveredSeriesAtItsFirstValue) { TsFileWriter tw; ASSERT_EQ(tw.open(file_name_, GetWriteCreateFlags(), 0666), E_OK); ASSERT_EQ( tw.register_timeseries( "root.d1", MeasurementSchema("s1", INT64, PLAIN, UNCOMPRESSED)), E_OK); + ASSERT_EQ( + tw.register_timeseries( + "root.d1", MeasurementSchema("s2", INT64, PLAIN, UNCOMPRESSED)), + E_OK); + TsRecord earlier(5, "root.d1"); + earlier.add_point("s2", static_cast(5)); + ASSERT_EQ(tw.write_record(earlier), E_OK); TsRecord record(15, "root.d1"); record.add_point("s1", static_cast(15)); ASSERT_EQ(tw.write_record(record), E_OK); @@ -468,27 +472,31 @@ TEST_F(RestorableTsFileIOWriterTest, std::vector schema_vec; schema_vec.emplace_back("s1", INT64, PLAIN, UNCOMPRESSED); + schema_vec.emplace_back("s2", INT64, PLAIN, UNCOMPRESSED); Tablet tablet("root.d1", std::make_shared>(schema_vec), 2); - ASSERT_EQ(tablet.add_timestamp(0, 16), E_OK); + ASSERT_EQ(tablet.add_timestamp(0, 7), E_OK); ASSERT_EQ(tablet.add_timestamp(1, 10), E_OK); const int64_t values[2] = {0, 10}; // row 0 is null for s1 const uint8_t nulls[1] = {0x01}; ASSERT_EQ(tablet.set_column_values(0u, values, nulls, 2), E_OK); - // Row 0 (16) is above the recovered floor, so the old row-0 check passes; - // the first row actually written (10) is below it. + ASSERT_EQ(tablet.add_value(0, 1u, static_cast(7)), E_OK); + // s2 can take 7, but s1 cannot take 10 after 15. EXPECT_EQ(tw2.write_tablet(tablet), E_OUT_OF_ORDER); - TsRecord next(16, "root.d1"); - next.add_point("s1", static_cast(16)); + ASSERT_EQ(tablet.add_timestamp(1, 16), E_OK); + ASSERT_EQ(tw2.write_tablet(tablet), E_OK); + ASSERT_EQ(tw2.flush(), E_OK); + TsRecord next(8, "root.d1"); + next.add_point("s2", static_cast(8)); ASSERT_EQ(tw2.write_record(next), E_OK); ASSERT_EQ(tw2.close(), E_OK); TsFileTreeReader reader; ASSERT_EQ(reader.open(file_name_), E_OK); - ASSERT_EQ(CountTreeReaderRows(reader, {"s1"}), 2); + ASSERT_EQ(CountTreeReaderRows(reader, {"s1", "s2"}), 5); reader.close(); } diff --git a/cpp/test/writer/chunk_writer_test.cc b/cpp/test/writer/chunk_writer_test.cc index 80a777fcb3..1430f335bc 100644 --- a/cpp/test/writer/chunk_writer_test.cc +++ b/cpp/test/writer/chunk_writer_test.cc @@ -113,6 +113,7 @@ struct PagePointCapGuard { // timestamps already appended, and a rejected batch must not advance the // chunk's last timestamp. TEST_F(ChunkWriterTest, WriteStringBatchRejectsOutOfOrder) { + PagePointCapGuard page_guard(3); common::set_allow_non_decreasing_timestamps(false); ChunkWriter writer; ASSERT_EQ(writer.init("string_measurement", TSDataType::STRING, diff --git a/cpp/test/writer/tsfile_writer_test.cc b/cpp/test/writer/tsfile_writer_test.cc index e8d36790f4..e19e3fa8c8 100644 --- a/cpp/test/writer/tsfile_writer_test.cc +++ b/cpp/test/writer/tsfile_writer_test.cc @@ -3182,16 +3182,19 @@ TEST_F(TsFileWriterTest, NonAlignedTabletRejectionWritesNoColumn) { TsRecord first(10, device_name); first.add_point("v0", static_cast(0)); - first.add_point("v1", static_cast(100)); + ASSERT_EQ(tsfile_writer_->write_record(first), E_OK); - // v0 would accept ts=11 (row 0), but v1's only row (ts=9) is older than - // the ts=10 it already holds. The whole tablet must be rejected. + TsRecord later(20, device_name); + later.add_point("v1", static_cast(100)); + ASSERT_EQ(tsfile_writer_->write_record(later), E_OK); + + // The time column is ordered. Only v1 conflicts with its history. Tablet tablet(device_name, std::make_shared>(schema_vec), 2); ASSERT_EQ(tablet.add_timestamp(0, 11), E_OK); - ASSERT_EQ(tablet.add_timestamp(1, 9), E_OK); + ASSERT_EQ(tablet.add_timestamp(1, 12), E_OK); // v0: row 0 valid (1), row 1 null; v1: row 0 null, row 1 valid (109). const int64_t v0_values[2] = {1, 0}; const int64_t v1_values[2] = {0, 109}; @@ -3204,7 +3207,7 @@ TEST_F(TsFileWriterTest, NonAlignedTabletRejectionWritesNoColumn) { // v0 must not have received the ts=11 row from the rejected tablet. TsRecord next(11, device_name); next.add_point("v0", static_cast(2)); - next.add_point("v1", static_cast(111)); + ASSERT_EQ(tsfile_writer_->write_record(next), E_OK); ASSERT_EQ(tsfile_writer_->flush(), E_OK); ASSERT_EQ(tsfile_writer_->close(), E_OK); @@ -3214,19 +3217,17 @@ TEST_F(TsFileWriterTest, NonAlignedTabletRejectionWritesNoColumn) { select.emplace_back(device_name, v0); select.emplace_back(device_name, v1); auto rows = ReadRows(file_name_, select); - ASSERT_EQ(rows.size(), 2u); + ASSERT_EQ(rows.size(), 3u); EXPECT_EQ(rows[0].first, 10); EXPECT_EQ(rows[0].second[0], "0"); - EXPECT_EQ(rows[0].second[1], "100"); + EXPECT_EQ(rows[1].first, 11); EXPECT_EQ(rows[1].second[0], "2"); - EXPECT_EQ(rows[1].second[1], "111"); + EXPECT_EQ(rows[2].first, 20); + EXPECT_EQ(rows[2].second[1], "100"); } -// A timestamp decrease on a row that is null for the measurement is not a -// write to that series: the non-aligned path skips such rows entirely, so the -// tablet is accepted (matching Java's per-column write loop). -TEST_F(TsFileWriterTest, NonAlignedTabletIgnoresDecreaseOnNullRows) { +TEST_F(TsFileWriterTest, NonAlignedTabletChecksTimeOrderEvenOnNullRows) { ScopedAllowNonDecreasingTimestamps guard(false); std::string device_name = "root.dev_na_tablet_null_rows"; ASSERT_EQ( @@ -3249,6 +3250,11 @@ TEST_F(TsFileWriterTest, NonAlignedTabletIgnoresDecreaseOnNullRows) { const int64_t values[3] = {12, 0, 13}; // row 1 (ts=11) is null for v0 const uint8_t nulls[1] = {0x02}; ASSERT_EQ(tablet.set_column_values(0u, values, nulls, 3), E_OK); + ASSERT_EQ(tsfile_writer_->write_tablet(tablet), E_OUT_OF_ORDER); + ASSERT_EQ(tablet.add_timestamp(1, 12), E_OK); + EXPECT_EQ(tsfile_writer_->write_tablet(tablet), E_OUT_OF_ORDER); + ASSERT_EQ(tablet.add_timestamp(2, 14), E_OK); + ASSERT_EQ(tablet.add_timestamp(1, 13), E_OK); ASSERT_EQ(tsfile_writer_->write_tablet(tablet), E_OK); ASSERT_EQ(tsfile_writer_->flush(), E_OK); @@ -3261,5 +3267,5 @@ TEST_F(TsFileWriterTest, NonAlignedTabletIgnoresDecreaseOnNullRows) { ASSERT_EQ(rows.size(), 3u); EXPECT_EQ(rows[0].first, 10); EXPECT_EQ(rows[1].first, 12); - EXPECT_EQ(rows[2].first, 13); + EXPECT_EQ(rows[2].first, 14); } diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index 56b9513696..cecc136eb5 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -45,6 +45,10 @@ writers. Decreases remain invalid. On the non-aligned C++ tree paths (`TsFileWriter::write_record` and `write_tablet`, also reached from C and Python), a violating write is rejected as a whole with `E_OUT_OF_ORDER` (`OutOfOrderError` in Python) before any measurement column is written. +A non-aligned tree tablet must have ordered timestamps across all its rows, +including all-null rows. Across writes, each measurement keeps its own last +non-null timestamp, including across flushes and recovery. For a sparse +column, its first non-null timestamp must follow that measurement's history. Aligned tree row/tablet calls validate the time column first, so a rejected call writes no value column. Table-model writes are validated per device before writing any row (see below). Java has no all-or-nothing guarantee here. See From 6c71696b041295a39b0985a8de124dea2950bf87 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 16:18:35 +0800 Subject: [PATCH 4/7] Limit non-aligned timestamp checks to tree writer entry points --- cpp/src/common/global.h | 9 -- cpp/src/writer/chunk_writer.cc | 7 - cpp/src/writer/chunk_writer.h | 175 +++++++++++----------- cpp/src/writer/time_page_writer.h | 4 +- cpp/src/writer/tsfile_writer.cc | 156 +++++++------------ cpp/src/writer/tsfile_writer.h | 9 -- cpp/test/writer/chunk_writer_test.cc | 74 --------- skills/tsfile/references/advanced-apis.md | 20 +-- 8 files changed, 149 insertions(+), 305 deletions(-) diff --git a/cpp/src/common/global.h b/cpp/src/common/global.h index fd487d9e59..f9d1ddf4e6 100644 --- a/cpp/src/common/global.h +++ b/cpp/src/common/global.h @@ -218,15 +218,6 @@ FORCE_INLINE bool get_allow_non_decreasing_timestamps() { return g_config_value_.allow_non_decreasing_timestamps_; } -// Shared timestamp-ordering predicate for every write path. By default a -// timestamp must be strictly greater than the previous one; with -// allow_non_decreasing_timestamps_ enabled equal timestamps are accepted, but -// a strictly decreasing one is still rejected. -FORCE_INLINE bool timestamp_out_of_order(int64_t time, int64_t last_time) { - return g_config_value_.allow_non_decreasing_timestamps_ ? time < last_time - : time <= last_time; -} - // Select the backend used by subsequently opened local files. Existing // LocalRandomAccessReadFile instances retain the backend selected when opened. // This setting deliberately lives outside exported ConfigValue so adding it diff --git a/cpp/src/writer/chunk_writer.cc b/cpp/src/writer/chunk_writer.cc index 3eae0ba687..a428ed2370 100644 --- a/cpp/src/writer/chunk_writer.cc +++ b/cpp/src/writer/chunk_writer.cc @@ -33,9 +33,7 @@ int ChunkWriter::init(const ColumnSchema& col_schema) { int ChunkWriter::init(const std::string& measurement_name, TSDataType data_type, TSEncoding encoding, CompressionType compression_type) { int ret = E_OK; - // A freshly initialized writer owns no timestamp history yet. has_last_timestamp_ = false; - last_timestamp_ = 0; chunk_statistic_ = StatisticFactory::alloc_statistic(data_type); if (chunk_statistic_ == nullptr) { return E_OOM; @@ -55,8 +53,6 @@ int ChunkWriter::init(const std::string& measurement_name, TSDataType data_type, } void ChunkWriter::destroy() { - has_last_timestamp_ = false; - last_timestamp_ = 0; if (num_of_pages_ == 1) { free_first_writer_data(); } @@ -75,9 +71,6 @@ void ChunkWriter::destroy() { } void ChunkWriter::reset() { - // has_last_timestamp_ / last_timestamp_ are deliberately not cleared here: - // reset() starts a new chunk after a flush, but timestamp ordering has to - // hold across chunk boundaries of the same series too. if (chunk_statistic_ != nullptr) { chunk_statistic_->reset(); } diff --git a/cpp/src/writer/chunk_writer.h b/cpp/src/writer/chunk_writer.h index 482dfda216..f9c14ccc3c 100644 --- a/cpp/src/writer/chunk_writer.h +++ b/cpp/src/writer/chunk_writer.h @@ -25,10 +25,23 @@ #include "common/statistic.h" #include "common/tsfile_common.h" #include "page_writer.h" -#include "time_page_writer.h" namespace storage { +#define CW_DO_WRITE_FOR_TYPE() \ + { \ + int ret = common::E_OK; \ + if (RET_FAIL(page_writer_.write(timestamp, value))) { \ + return ret; \ + } \ + last_timestamp_ = timestamp; \ + has_last_timestamp_ = true; \ + if (RET_FAIL(seal_cur_page_if_full())) { \ + return ret; \ + } \ + return ret; \ + } + class ChunkWriter { public: static const int32_t PAGES_DATA_PAGE_SIZE = 1024; @@ -55,33 +68,33 @@ class ChunkWriter { if (UNLIKELY(data_type_ != common::BOOLEAN)) { return common::E_TYPE_NOT_MATCH; } - return write_checked_point(timestamp, value); + CW_DO_WRITE_FOR_TYPE(); } FORCE_INLINE int write(int64_t timestamp, int32_t value) { if (UNLIKELY(data_type_ != common::INT32 && data_type_ != common::DATE)) { return common::E_TYPE_NOT_MATCH; } - return write_checked_point(timestamp, value); + CW_DO_WRITE_FOR_TYPE(); } FORCE_INLINE int write(int64_t timestamp, int64_t value) { if (UNLIKELY(data_type_ != common::INT64 && data_type_ != common::TIMESTAMP)) { return common::E_TYPE_NOT_MATCH; } - return write_checked_point(timestamp, value); + CW_DO_WRITE_FOR_TYPE(); } FORCE_INLINE int write(int64_t timestamp, float value) { if (UNLIKELY(data_type_ != common::FLOAT)) { return common::E_TYPE_NOT_MATCH; } - return write_checked_point(timestamp, value); + CW_DO_WRITE_FOR_TYPE(); } FORCE_INLINE int write(int64_t timestamp, double value) { if (UNLIKELY(data_type_ != common::DOUBLE)) { return common::E_TYPE_NOT_MATCH; } - return write_checked_point(timestamp, value); + CW_DO_WRITE_FOR_TYPE(); } FORCE_INLINE int write(int64_t timestamp, common::String value) { if (UNLIKELY(data_type_ != common::STRING && @@ -89,43 +102,85 @@ class ChunkWriter { data_type_ != common::BLOB)) { return common::E_TYPE_NOT_MATCH; } - return write_checked_point(timestamp, value); + CW_DO_WRITE_FOR_TYPE(); } template int write_batch(const int64_t* timestamps, const T* values, uint32_t count) { - if (count && (timestamp_order_violated(timestamps[0]) || - !TimePageWriter::is_batch_in_order(timestamps, count))) { - return common::E_OUT_OF_ORDER; + int ret = common::E_OK; + uint32_t offset = 0; + const uint32_t page_cap = + common::g_config_value_.page_writer_max_point_num_; + while (offset < count) { + uint32_t cur_points = page_writer_.get_point_numer(); + // Seal whenever cur_points is at or past the cap; the counter is + // size_ (rows including the just-written batch) and may exceed + // page_cap, so a plain subtraction would underflow uint32_t. + if (cur_points >= page_cap) { + if (RET_FAIL(seal_cur_page(false))) { + return ret; + } + cur_points = 0; + } + uint32_t page_remaining = page_cap - cur_points; + uint32_t batch_size = std::min(count - offset, page_remaining); + if (RET_FAIL(page_writer_.write_batch( + timestamps + offset, values + offset, batch_size))) { + return ret; + } + offset += batch_size; + last_timestamp_ = timestamps[offset - 1]; + has_last_timestamp_ = true; + if (RET_FAIL(seal_cur_page_if_full())) { + return ret; + } } - return write_ordered_batch(timestamps, values, count); + return ret; } int write_string_batch(const int64_t* timestamps, const char* buffer, const uint32_t* offsets, uint32_t start_idx, uint32_t count) { - if (count && (timestamp_order_violated(timestamps[0]) || - !TimePageWriter::is_batch_in_order(timestamps, count))) { - return common::E_OUT_OF_ORDER; + int ret = common::E_OK; + uint32_t offset = 0; + const uint32_t page_cap = + common::g_config_value_.page_writer_max_point_num_; + while (offset < count) { + uint32_t cur_points = page_writer_.get_point_numer(); + if (cur_points >= page_cap) { + if (RET_FAIL(seal_cur_page(false))) { + return ret; + } + cur_points = 0; + } + uint32_t page_remaining = page_cap - cur_points; + uint32_t batch_size = std::min(count - offset, page_remaining); + // TODO: for variable-length types (STRING/TEXT/BLOB), batch_size is + // capped by row count alone; a single sub-batch can push the page + // memory far past page_writer_max_memory_bytes_ before + // seal_cur_page_if_full() runs. Add byte-budget tracking here: + // estimate bytes remaining in the current page and cap batch_size + // so that one write cannot exceed the memory limit by more than one + // value. + if (RET_FAIL(page_writer_.write_string_batch( + timestamps + offset, buffer, offsets, start_idx + offset, + batch_size))) { + return ret; + } + offset += batch_size; + last_timestamp_ = timestamps[offset - 1]; + has_last_timestamp_ = true; + if (RET_FAIL(seal_cur_page_if_full())) { + return ret; + } } - return write_ordered_string_batch(timestamps, buffer, offsets, - start_idx, count); + return ret; } int end_encode_chunk(); common::ByteStream& get_chunk_data() { return chunk_data_; } Statistic* get_chunk_statistic() { return chunk_statistic_; } - // True when appending `timestamp` to this chunk would violate the - // configured order (strictly increasing by default, non-decreasing when - // allow_non_decreasing_timestamps_ is enabled). Unlike the per-page - // statistic this state survives page seals and chunk flushes, so callers - // can also pre-validate a multi-column row/tablet before writing any - // column. - FORCE_INLINE bool timestamp_order_violated(int64_t timestamp) const { - return has_last_timestamp_ && - common::timestamp_out_of_order(timestamp, last_timestamp_); - } bool hasData() { return num_of_pages_ > 0 || (page_writer_.get_statistic() != nullptr && page_writer_.get_statistic()->count_ > 0); @@ -143,68 +198,6 @@ class ChunkWriter { int64_t estimate_max_series_mem_size(); private: - friend class TsFileWriter; - - template - int write_checked_point(int64_t timestamp, T value) { - if (UNLIKELY(timestamp_order_violated(timestamp))) { - return common::E_OUT_OF_ORDER; - } - return write_ordered_point(timestamp, value); - } - - template - int write_ordered_point(int64_t timestamp, T value) { - int ret = page_writer_.write(timestamp, value); - if (ret != common::E_OK) return ret; - last_timestamp_ = timestamp; - has_last_timestamp_ = true; - return seal_cur_page_if_full(); - } - - template - int write_ordered_batch(const int64_t* times, const T* values, - uint32_t count) { - return append_ordered_pages( - times, count, [&](uint32_t offset, uint32_t size) { - return page_writer_.write_batch(times + offset, values + offset, - size); - }); - } - - int write_ordered_string_batch(const int64_t* times, const char* buffer, - const uint32_t* offsets, uint32_t start, - uint32_t count) { - return append_ordered_pages( - times, count, [&](uint32_t offset, uint32_t size) { - return page_writer_.write_string_batch( - times + offset, buffer, offsets, start + offset, size); - }); - } - - template - int append_ordered_pages(const int64_t* times, uint32_t count, - WritePage write_page) { - int ret = common::E_OK; - const uint32_t page_cap = - common::g_config_value_.page_writer_max_point_num_; - uint32_t offset = 0; - while (offset < count) { - uint32_t points = page_writer_.get_point_numer(); - if (points >= page_cap) { - if (RET_FAIL(seal_cur_page(false))) return ret; - points = 0; - } - const uint32_t size = std::min(count - offset, page_cap - points); - if (RET_FAIL(write_page(offset, size))) return ret; - offset += size; - last_timestamp_ = times[offset - 1]; - has_last_timestamp_ = true; - if (RET_FAIL(seal_cur_page_if_full())) return ret; - } - return ret; - } - FORCE_INLINE bool is_cur_page_full() const { // FIXME return (page_writer_.get_point_numer() >= @@ -240,9 +233,9 @@ class ChunkWriter { ChunkHeader chunk_header_; int32_t num_of_pages_; - // Last timestamp appended to this chunk. Kept across page seals (the - // PageWriter statistic is reset per page) and across chunk flushes - // (reset()), so ordering is enforced for the whole series in this writer. + + // Tree writes compare with the last point of this series across flushes. + friend class TsFileWriter; int64_t last_timestamp_ = 0; bool has_last_timestamp_ = false; }; diff --git a/cpp/src/writer/time_page_writer.h b/cpp/src/writer/time_page_writer.h index 20157ddd6f..0117489e95 100644 --- a/cpp/src/writer/time_page_writer.h +++ b/cpp/src/writer/time_page_writer.h @@ -91,7 +91,9 @@ class TimePageWriter { // (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::timestamp_out_of_order(time, 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) { diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index da73b76ca9..76188202d1 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -25,6 +25,7 @@ #include #include #include +#include #include "chunk_writer.h" #include "common/config/config.h" @@ -853,73 +854,9 @@ bool TsFileWriter::recovered_last_time_order_violated( !schema_it->second->has_last_time_) { return false; } - return common::timestamp_out_of_order(timestamp, - schema_it->second->last_time_); -} - -int TsFileWriter::check_record_timestamp_order( - common::SimpleVector& chunk_writers, int64_t timestamp) { - for (uint32_t c = 0; c < chunk_writers.size(); c++) { - ChunkWriter* chunk_writer = chunk_writers[c]; - if (IS_NULL(chunk_writer)) { - continue; - } - if (chunk_writer->timestamp_order_violated(timestamp)) { - return E_OUT_OF_ORDER; - } - // A record may carry the same measurement twice. Under strictly - // increasing semantics the second write of the same timestamp would - // fail after the first point had already been appended, so reject the - // whole record up front instead. With the non-decreasing flag on, - // equal timestamps are legal and both points can be written. - if (!common::g_config_value_.allow_non_decreasing_timestamps_) { - for (uint32_t p = 0; p < c; p++) { - if (chunk_writers[p] == chunk_writer) { - return E_OUT_OF_ORDER; - } - } - } - } - return E_OK; -} - -int TsFileWriter::check_tablet_timestamp_order( - const Tablet& tablet, common::SimpleVector& chunk_writers, - uint32_t start, uint32_t end) { - if (end > tablet.max_row_num_) return E_OUT_OF_RANGE; - if (start == end) return E_OK; - if (tablet.timestamps_ == nullptr) return E_INVALID_ARG; - const int64_t* times = tablet.timestamps_; - if (!TimePageWriter::is_batch_in_order(times + start, end - start)) { - return E_OUT_OF_ORDER; - } - - std::unordered_map previous_columns; - for (uint32_t c = 0; c < chunk_writers.size(); ++c) { - ChunkWriter* writer = chunk_writers[c]; - if (writer == nullptr) continue; - BitMap& nulls = tablet.bitmaps_[c]; - uint32_t first = start; - while (first < end && nulls.test(first)) ++first; - if (first == end) continue; - if (writer->timestamp_order_violated(times[first])) - return E_OUT_OF_ORDER; - - // Tablet construction enforces unique names, but columns can be - // renamed. An alias must also follow the previous column targeting the - // same series. - auto entry = previous_columns.emplace(writer, c); - if (!entry.second) { - BitMap& previous_nulls = tablet.bitmaps_[entry.first->second]; - uint32_t last = end - 1; - while (previous_nulls.test(last)) --last; - if (common::timestamp_out_of_order(times[first], times[last])) { - return E_OUT_OF_ORDER; - } - entry.first->second = c; - } - } - return E_OK; + return common::g_config_value_.allow_non_decreasing_timestamps_ + ? timestamp < schema_it->second->last_time_ + : timestamp <= schema_it->second->last_time_; } int TsFileWriter::write_record(const TsRecord& record) { @@ -936,19 +873,23 @@ int TsFileWriter::write_record(const TsRecord& record) { } ASSERT(chunk_writers.size() == record.points_.size()); - // Validate every target column before writing any point: a rejected - // timestamp must not leave a partial write in a subset of measurements. - if (RET_FAIL( - check_record_timestamp_order(chunk_writers, record.timestamp_))) { - return ret; + std::unordered_set seen; + for (uint32_t c = 0; c < chunk_writers.size(); ++c) { + ChunkWriter* writer = chunk_writers[c]; + if (writer == nullptr) continue; + if ((writer->has_last_timestamp_ && + TimePageWriter::is_out_of_order(record.timestamp_, + writer->last_timestamp_)) || + (!common::get_allow_non_decreasing_timestamps() && + !seen.insert(writer).second)) { + return E_OUT_OF_ORDER; + } } for (uint32_t c = 0; c < chunk_writers.size(); c++) { ChunkWriter* chunk_writer = chunk_writers[c]; if (IS_NULL(chunk_writer)) { continue; } - // Ordering violations were rejected above; other per-point failures - // (e.g. OOM) are still ignored here, as before this change. // ignore point writer failure write_point(chunk_writer, record.timestamp_, data_types[c], record.points_[c]); @@ -1329,6 +1270,11 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { // into the chunk. const uint32_t total_rows = tablet.get_cur_row_size(); if (tablet.err_code_ != E_OK) return tablet.err_code_; + if (total_rows > tablet.max_row_num_) return E_OUT_OF_RANGE; + if (total_rows > 0 && tablet.timestamps_ == nullptr) return E_INVALID_ARG; + if (!TimePageWriter::is_batch_in_order(tablet.timestamps_, total_rows)) { + return E_OUT_OF_ORDER; + } SimpleVector chunk_writers; SimpleVector data_types; MeasurementNamesFromTablet mnames_getter(tablet); @@ -1337,6 +1283,8 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { return ret; } ASSERT(data_types.size() == tablet.get_column_count()); + ASSERT(chunk_writers.size() == tablet.get_column_count()); + std::unordered_map previous_columns; for (uint32_t c = 0; c < data_types.size(); c++) { if (data_types[c] == common::NULL_TYPE) { continue; @@ -1344,13 +1292,30 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { if (data_types[c] != tablet.schema_vec_->at(c).data_type_) { return E_TYPE_NOT_MATCH; } - } - ASSERT(chunk_writers.size() == tablet.get_column_count()); - // Pre-validate the whole tablet before writing any column so a rejected - // batch leaves no partially written measurements behind. - if (RET_FAIL(check_tablet_timestamp_order(tablet, chunk_writers, 0, - total_rows))) { - return ret; + ChunkWriter* writer = chunk_writers[c]; + BitMap& nulls = tablet.bitmaps_[c]; + uint32_t first = 0; + while (first < total_rows && nulls.test(first)) ++first; + if (first == total_rows) continue; + const int64_t first_time = tablet.timestamps_[first]; + if (writer->has_last_timestamp_ && + TimePageWriter::is_out_of_order(first_time, + writer->last_timestamp_)) { + return E_OUT_OF_ORDER; + } + + // Column names are unique at construction, but a column can be renamed. + auto entry = previous_columns.emplace(writer, c); + if (!entry.second) { + const uint32_t previous = entry.first->second; + uint32_t last = total_rows - 1; + while (tablet.bitmaps_[previous].test(last)) --last; + if (TimePageWriter::is_out_of_order(first_time, + tablet.timestamps_[last])) { + return E_OUT_OF_ORDER; + } + entry.first->second = c; + } } uint32_t columns_written = 0; for (uint32_t c = 0; c < chunk_writers.size(); c++) { @@ -1703,17 +1668,6 @@ int TsFileWriter::write_table(Tablet& tablet) { return ret; } ASSERT(chunk_writers.size() == tablet.get_column_count()); - // Pre-validate this device segment before dispatching any column - // write (serial or parallel): a rejected timestamp must not leave - // some columns written while others were skipped. Note that - // table_aligned_ is fixed to true today, so this non-aligned - // branch is not reachable; it is kept in step with write_tablet - // for a future non-aligned table mode. - if (RET_FAIL(check_tablet_timestamp_order( - tablet, chunk_writers, si, - device_id_end_index_pair.second))) { - return ret; - } #ifdef ENABLE_THREADS if (chunk_writers.size() >= 2 && @@ -1899,8 +1853,7 @@ int TsFileWriter::write_typed_column(ChunkWriter* chunk_writer, int ret = E_OK; for (uint32_t r = start_idx; r < end_idx; r++) { if (LIKELY(!col_notnull_bitmap.test(r))) { - if (RET_FAIL(chunk_writer->write_ordered_point(timestamps[r], - col_values[r]))) { + if (RET_FAIL(chunk_writer->write(timestamps[r], col_values[r]))) { return ret; } } @@ -1919,8 +1872,7 @@ int TsFileWriter::write_typed_column(ChunkWriter* chunk_writer, common::String val( string_col->buffer + string_col->offsets[r], string_col->offsets[r + 1] - string_col->offsets[r]); - if (RET_FAIL( - chunk_writer->write_ordered_point(timestamps[r], val))) { + if (RET_FAIL(chunk_writer->write(timestamps[r], val))) { return ret; } } @@ -1968,29 +1920,29 @@ int TsFileWriter::write_column_batch(ChunkWriter* chunk_writer, if (!has_null) { switch (data_type) { case common::BOOLEAN: - ret = chunk_writer->write_ordered_batch( + ret = chunk_writer->write_batch( timestamps + start_idx, col_values.bool_data + start_idx, count); break; case common::INT32: case common::DATE: - ret = chunk_writer->write_ordered_batch( + ret = chunk_writer->write_batch( timestamps + start_idx, col_values.int32_data + start_idx, count); break; case common::INT64: case common::TIMESTAMP: - ret = chunk_writer->write_ordered_batch( + ret = chunk_writer->write_batch( timestamps + start_idx, col_values.int64_data + start_idx, count); break; case common::FLOAT: - ret = chunk_writer->write_ordered_batch( + ret = chunk_writer->write_batch( timestamps + start_idx, col_values.float_data + start_idx, count); break; case common::DOUBLE: - ret = chunk_writer->write_ordered_batch( + ret = chunk_writer->write_batch( timestamps + start_idx, col_values.double_data + start_idx, count); break; @@ -2004,7 +1956,7 @@ int TsFileWriter::write_column_batch(ChunkWriter* chunk_writer, // construction so the bit pattern is identical — cast at the // boundary until the downstream chain is converted in a // follow-up. - ret = chunk_writer->write_ordered_string_batch( + ret = chunk_writer->write_string_batch( timestamps + start_idx, sc->buffer, reinterpret_cast(sc->offsets), start_idx, count); diff --git a/cpp/src/writer/tsfile_writer.h b/cpp/src/writer/tsfile_writer.h index 334802e482..953cc67e1d 100644 --- a/cpp/src/writer/tsfile_writer.h +++ b/cpp/src/writer/tsfile_writer.h @@ -251,15 +251,6 @@ class TsFileWriter { bool recovered_last_time_order_violated( const std::shared_ptr& device_id, int64_t timestamp) const; - // Validate all non-aligned columns before appending to any of them. - int check_record_timestamp_order( - common::SimpleVector& chunk_writers, - int64_t timestamp); - int check_tablet_timestamp_order( - const Tablet& tablet, - common::SimpleVector& chunk_writers, - uint32_t start_idx, uint32_t end_idx); - int write_column_batch(storage::ChunkWriter* chunk_writer, const Tablet& tablet, int col_idx, uint32_t start_idx, uint32_t end_idx); diff --git a/cpp/test/writer/chunk_writer_test.cc b/cpp/test/writer/chunk_writer_test.cc index 1430f335bc..883c3a8124 100644 --- a/cpp/test/writer/chunk_writer_test.cc +++ b/cpp/test/writer/chunk_writer_test.cc @@ -92,78 +92,4 @@ TEST_F(ChunkWriterTest, DestroyChunkWriter) { chunk_writer.destroy(); EXPECT_EQ(chunk_writer.get_chunk_statistic(), nullptr); EXPECT_EQ(chunk_writer.get_chunk_data().total_size(), 0); -} - -namespace { -struct PagePointCapGuard { - explicit PagePointCapGuard(uint32_t cap) - : saved_(common::g_config_value_.page_writer_max_point_num_) { - common::g_config_value_.page_writer_max_point_num_ = cap; - } - ~PagePointCapGuard() { - common::g_config_value_.page_writer_max_point_num_ = saved_; - } - - private: - uint32_t saved_; -}; -} // namespace - -// A string batch must be rejected as a whole when it does not follow the -// timestamps already appended, and a rejected batch must not advance the -// chunk's last timestamp. -TEST_F(ChunkWriterTest, WriteStringBatchRejectsOutOfOrder) { - PagePointCapGuard page_guard(3); - common::set_allow_non_decreasing_timestamps(false); - ChunkWriter writer; - ASSERT_EQ(writer.init("string_measurement", TSDataType::STRING, - TSEncoding::PLAIN, CompressionType::UNCOMPRESSED), - E_OK); - const char* buffer = "aabbccdd"; - const uint32_t offsets[5] = {0, 2, 4, 6, 8}; - const int64_t first[3] = {10, 11, 13}; - ASSERT_EQ(writer.write_string_batch(first, buffer, offsets, 0, 3), E_OK); - - // Equal to the last timestamp: rejected under the default policy. - const int64_t equal[1] = {13}; - EXPECT_EQ(writer.write_string_batch(equal, buffer, offsets, 0, 1), - E_OUT_OF_ORDER); - // Strictly decreasing. - const int64_t older[1] = {12}; - EXPECT_EQ(writer.write_string_batch(older, buffer, offsets, 0, 1), - E_OUT_OF_ORDER); - // A decrease inside the batch rejects the whole batch. - const int64_t unordered[3] = {14, 16, 15}; - EXPECT_EQ(writer.write_string_batch(unordered, buffer, offsets, 0, 3), - E_OUT_OF_ORDER); - - // Nothing from the rejected batches advanced the last timestamp. - const int64_t next[1] = {14}; - EXPECT_EQ(writer.write_string_batch(next, buffer, offsets, 0, 1), E_OK); - EXPECT_EQ(writer.write_string_batch(equal, buffer, offsets, 0, 1), - E_OUT_OF_ORDER); - writer.destroy(); -} - -// The last appended timestamp survives page seals for batched writes too. -TEST_F(ChunkWriterTest, WriteBatchOrderCheckSurvivesPageSeal) { - common::set_allow_non_decreasing_timestamps(false); - PagePointCapGuard page_guard(3); - ChunkWriter writer; - ASSERT_EQ(writer.init("int64_measurement", TSDataType::INT64, - TSEncoding::PLAIN, CompressionType::UNCOMPRESSED), - E_OK); - int64_t values[6] = {0, 1, 2, 3, 4, 5}; - int64_t timestamps[6] = {10, 11, 12, 13, 14, 15}; - ASSERT_EQ(writer.write_batch(timestamps, values, 6), E_OK); - ASSERT_GE(writer.num_of_pages(), 2); - - int64_t older_ts[1] = {12}; - int64_t older_val[1] = {9}; - EXPECT_EQ(writer.write_batch(older_ts, older_val, 1), E_OUT_OF_ORDER); - - int64_t next_ts[1] = {16}; - int64_t next_val[1] = {16}; - EXPECT_EQ(writer.write_batch(next_ts, next_val, 1), E_OK); - writer.destroy(); } \ No newline at end of file diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index cecc136eb5..404d533fd3 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -41,18 +41,14 @@ Before writer creation, use Java config `setAllowNonDecreasingTimestamps(true)`, C++ `common::set_allow_non_decreasing_timestamps(true)` (C: without `common::`), or Python writer argument `allow_non_decreasing_timestamps=True` (default `False`). This is process-wide, including Python constructor defaults; avoid conflicting -writers. Decreases remain invalid. On the non-aligned C++ tree paths -(`TsFileWriter::write_record` and `write_tablet`, also reached from C and -Python), a violating write is rejected as a whole with `E_OUT_OF_ORDER` -(`OutOfOrderError` in Python) before any measurement column is written. -A non-aligned tree tablet must have ordered timestamps across all its rows, -including all-null rows. Across writes, each measurement keeps its own last -non-null timestamp, including across flushes and recovery. For a sparse -column, its first non-null timestamp must follow that measurement's history. -Aligned tree row/tablet calls validate the time column first, so a rejected -call writes no value column. Table-model writes are validated per device before -writing any row (see below). Java has no all-or-nothing guarantee here. See -`properties-filters.md` for the persisted policy; CLI `write` has no opt-in. +writers. Decreases remain invalid. See `properties-filters.md` for the persisted +policy; CLI `write` has no opt-in. + +C++ non-aligned tree tablets require ordered timestamps across all rows, +including all-null rows. Each measurement's first non-null timestamp must +follow its own last written point, including across flushes and recovery. +An out-of-order tree record or tablet returns `E_OUT_OF_ORDER` before writing +any measurement. Python reports `OutOfOrderError`. C++ aligned table writes check each device's first timestamp against its last accepted timestamp, including `INT64_MIN`, across tablets and chunk-group flushes. From 80651067737b0db640f5c5a0bee85c89cb75b2d6 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 17:47:46 +0800 Subject: [PATCH 5/7] Fix alignment detection during TsFile recovery --- cpp/src/file/restorable_tsfile_io_writer.cc | 16 +++++++++++++--- cpp/src/file/restorable_tsfile_io_writer.h | 9 ++++++--- cpp/src/writer/tsfile_writer.cc | 3 +-- .../file/restorable_tsfile_io_writer_test.cc | 18 +++++++++++++++--- skills/tsfile/references/advanced-apis.md | 3 +++ 5 files changed, 38 insertions(+), 11 deletions(-) diff --git a/cpp/src/file/restorable_tsfile_io_writer.cc b/cpp/src/file/restorable_tsfile_io_writer.cc index 605ff6e033..6a4f50bf3b 100644 --- a/cpp/src/file/restorable_tsfile_io_writer.cc +++ b/cpp/src/file/restorable_tsfile_io_writer.cc @@ -540,6 +540,7 @@ void RestorableTsFileIOWriter::close() { cgm->device_id_.reset(); } self_check_recovered_cgm_.clear(); + aligned_devices_.clear(); self_check_arena_.destroy(); } @@ -813,7 +814,7 @@ int RestorableTsFileIOWriter::self_check(bool truncate_corrupted) { // For aligned series, a time chunk implies this device // uses aligned layout. Record it so recovered writer state // can keep alignment behavior consistent. - aligned_devices_.insert(cur_device_id->get_table_name()); + aligned_devices_.insert(cur_device_id); } } continue; @@ -871,8 +872,17 @@ int RestorableTsFileIOWriter::self_check(bool truncate_corrupted) { } bool RestorableTsFileIOWriter::is_device_aligned( - const std::string& device) const { - return aligned_devices_.find(device) != aligned_devices_.end(); + const std::shared_ptr& device) const { + return device != nullptr && + aligned_devices_.find(device) != aligned_devices_.end(); +} + +bool RestorableTsFileIOWriter::is_device_aligned( + const std::string& table_name) const { + return std::any_of(aligned_devices_.begin(), aligned_devices_.end(), + [&table_name](const std::shared_ptr& device) { + return device->get_table_name() == table_name; + }); } TsFileIOWriter* RestorableTsFileIOWriter::get_tsfile_io_writer() { diff --git a/cpp/src/file/restorable_tsfile_io_writer.h b/cpp/src/file/restorable_tsfile_io_writer.h index 8c06c49074..52d0b0bb00 100644 --- a/cpp/src/file/restorable_tsfile_io_writer.h +++ b/cpp/src/file/restorable_tsfile_io_writer.h @@ -81,8 +81,11 @@ class RestorableTsFileIOWriter : public TsFileIOWriter { int64_t get_truncated_size() const { return truncated_size_; } std::shared_ptr get_known_schema() { return get_schema(); } - /** True if the device was recovered as aligned (has time column). */ - bool is_device_aligned(const std::string& device) const; + /** True if this device was recovered with an aligned time chunk. */ + bool is_device_aligned(const std::shared_ptr& device) const; + + /** True if any recovered device under this table name is aligned. */ + bool is_device_aligned(const std::string& table_name) const; /** * Recovered chunk group metas from self_check (actual device_id and chunk @@ -122,7 +125,7 @@ class RestorableTsFileIOWriter : public TsFileIOWriter { bool crashed_; bool can_write_; - std::set aligned_devices_; + std::set, IDeviceIDComparator> aligned_devices_; common::PageArena self_check_arena_; /** ChunkGroupMeta* allocated from self_check_arena_; reset device_id before * arena destroy to avoid leak. */ diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index 76188202d1..0d61cc096c 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -219,8 +219,7 @@ int TsFileWriter::init(RestorableTsFileIOWriter* rw) { group = it->second; } else { group = new MeasurementSchemaGroup; - group->is_aligned_ = - rw->is_device_aligned(device_id->get_table_name()); + group->is_aligned_ = rw->is_device_aligned(device_id); schemas_.insert(std::make_pair(device_id, group)); } diff --git a/cpp/test/file/restorable_tsfile_io_writer_test.cc b/cpp/test/file/restorable_tsfile_io_writer_test.cc index 7525a26bf0..cf1d231e1c 100644 --- a/cpp/test/file/restorable_tsfile_io_writer_test.cc +++ b/cpp/test/file/restorable_tsfile_io_writer_test.cc @@ -452,6 +452,13 @@ TEST_F(RestorableTsFileIOWriterTest, tw.register_timeseries( "root.d1", MeasurementSchema("s2", INT64, PLAIN, UNCOMPRESSED)), E_OK); + // Both device IDs have the same table-name prefix. + std::vector aligned_schemas{ + new MeasurementSchema("s1", INT64, PLAIN, UNCOMPRESSED)}; + ASSERT_EQ(tw.register_aligned_timeseries("root.d2", aligned_schemas), E_OK); + TsRecord aligned(30, "root.d2"); + aligned.add_point("s1", int64_t(30)); + ASSERT_EQ(tw.write_tree(aligned), E_OK); TsRecord earlier(5, "root.d1"); earlier.add_point("s2", static_cast(5)); ASSERT_EQ(tw.write_record(earlier), E_OK); @@ -485,18 +492,23 @@ TEST_F(RestorableTsFileIOWriterTest, ASSERT_EQ(tablet.add_value(0, 1u, static_cast(7)), E_OK); // s2 can take 7, but s1 cannot take 10 after 15. EXPECT_EQ(tw2.write_tablet(tablet), E_OUT_OF_ORDER); + record.timestamp_ = 12; + EXPECT_EQ(tw2.write_record(record), E_OUT_OF_ORDER); ASSERT_EQ(tablet.add_timestamp(1, 16), E_OK); - ASSERT_EQ(tw2.write_tablet(tablet), E_OK); + ASSERT_EQ(tw2.write_tree(tablet), E_OK); ASSERT_EQ(tw2.flush(), E_OK); TsRecord next(8, "root.d1"); next.add_point("s2", static_cast(8)); - ASSERT_EQ(tw2.write_record(next), E_OK); + ASSERT_EQ(tw2.write_tree(next), E_OK); + EXPECT_EQ(tw2.write_tree(aligned), E_OUT_OF_ORDER); + aligned.timestamp_ = 31; + ASSERT_EQ(tw2.write_tree(aligned), E_OK); ASSERT_EQ(tw2.close(), E_OK); TsFileTreeReader reader; ASSERT_EQ(reader.open(file_name_), E_OK); - ASSERT_EQ(CountTreeReaderRows(reader, {"s1", "s2"}), 5); + ASSERT_EQ(CountTreeReaderRows(reader, {"s1", "s2"}), 7); reader.close(); } diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index 404d533fd3..12c63c81ac 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -112,6 +112,9 @@ incomplete file before continuing a write. After `open(path, true)`, require do not register a replacement schema. A complete file reports `can_write() == false`. Keep the restorable writer alive longer than the facade writer and preserve increasing timestamps beyond the recovered last values. +Tree recovery restores alignment per device, including when aligned and +non-aligned devices share a path prefix. The recovered timestamp boundary is per +device for aligned writes and per measurement for non-aligned writes. ## Java BitMap Ranges From f452f913fced86a620239a59a20beaa7d8099817 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 19:47:47 +0800 Subject: [PATCH 6/7] Remove table-name alignment lookup from recovery --- cpp/src/file/restorable_tsfile_io_writer.cc | 8 -------- cpp/src/file/restorable_tsfile_io_writer.h | 3 --- 2 files changed, 11 deletions(-) diff --git a/cpp/src/file/restorable_tsfile_io_writer.cc b/cpp/src/file/restorable_tsfile_io_writer.cc index 6a4f50bf3b..d29e91a375 100644 --- a/cpp/src/file/restorable_tsfile_io_writer.cc +++ b/cpp/src/file/restorable_tsfile_io_writer.cc @@ -877,14 +877,6 @@ bool RestorableTsFileIOWriter::is_device_aligned( aligned_devices_.find(device) != aligned_devices_.end(); } -bool RestorableTsFileIOWriter::is_device_aligned( - const std::string& table_name) const { - return std::any_of(aligned_devices_.begin(), aligned_devices_.end(), - [&table_name](const std::shared_ptr& device) { - return device->get_table_name() == table_name; - }); -} - TsFileIOWriter* RestorableTsFileIOWriter::get_tsfile_io_writer() { return can_write_ ? this : nullptr; } diff --git a/cpp/src/file/restorable_tsfile_io_writer.h b/cpp/src/file/restorable_tsfile_io_writer.h index 52d0b0bb00..6223e38ff1 100644 --- a/cpp/src/file/restorable_tsfile_io_writer.h +++ b/cpp/src/file/restorable_tsfile_io_writer.h @@ -84,9 +84,6 @@ class RestorableTsFileIOWriter : public TsFileIOWriter { /** True if this device was recovered with an aligned time chunk. */ bool is_device_aligned(const std::shared_ptr& device) const; - /** True if any recovered device under this table name is aligned. */ - bool is_device_aligned(const std::string& table_name) const; - /** * Recovered chunk group metas from self_check (actual device_id and chunk * metas from file). TsFileWriter::init() uses this to rebuild schemas_ From 27cbed0ae017e316f8673769849a68d73e0c3bf2 Mon Sep 17 00:00:00 2001 From: ColinLee Date: Wed, 2 Dec 2026 19:47:47 +0800 Subject: [PATCH 7/7] Reject duplicate measurements in tree records --- cpp/src/writer/tsfile_writer.cc | 53 +++++++--------------- cpp/test/writer/tsfile_writer_test.cc | 54 ++++++++++++----------- skills/tsfile/references/advanced-apis.md | 5 +++ 3 files changed, 50 insertions(+), 62 deletions(-) diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index 0d61cc096c..e1871918df 100644 --- a/cpp/src/writer/tsfile_writer.cc +++ b/cpp/src/writer/tsfile_writer.cc @@ -24,7 +24,6 @@ #include #include #include -#include #include #include "chunk_writer.h" @@ -861,6 +860,12 @@ bool TsFileWriter::recovered_last_time_order_violated( int TsFileWriter::write_record(const TsRecord& record) { std::lock_guard write_lock(write_mutex_); if (UNLIKELY(unrecoverable_)) return E_DATA_INCONSISTENCY; + std::unordered_set measurements; + for (const auto& point : record.points_) { + if (!measurements.insert(point.measurement_name_).second) { + return E_INVALID_ARG; + } + } int ret = E_OK; auto device_id = std::make_shared(record.device_id_); SimpleVector chunk_writers; @@ -872,15 +877,12 @@ int TsFileWriter::write_record(const TsRecord& record) { } ASSERT(chunk_writers.size() == record.points_.size()); - std::unordered_set seen; for (uint32_t c = 0; c < chunk_writers.size(); ++c) { ChunkWriter* writer = chunk_writers[c]; if (writer == nullptr) continue; - if ((writer->has_last_timestamp_ && - TimePageWriter::is_out_of_order(record.timestamp_, - writer->last_timestamp_)) || - (!common::get_allow_non_decreasing_timestamps() && - !seen.insert(writer).second)) { + if (writer->has_last_timestamp_ && + TimePageWriter::is_out_of_order(record.timestamp_, + writer->last_timestamp_)) { return E_OUT_OF_ORDER; } } @@ -902,6 +904,12 @@ int TsFileWriter::write_record(const TsRecord& record) { int TsFileWriter::write_record_aligned(const TsRecord& record) { std::lock_guard write_lock(write_mutex_); if (UNLIKELY(unrecoverable_)) return E_DATA_INCONSISTENCY; + std::unordered_set measurements; + for (const auto& point : record.points_) { + if (!measurements.insert(point.measurement_name_).second) { + return E_INVALID_ARG; + } + } int ret = E_OK; auto device_id = std::make_shared(record.device_id_); if (recovered_last_time_order_violated(device_id, record.timestamp_)) { @@ -924,13 +932,6 @@ int TsFileWriter::write_record_aligned(const TsRecord& record) { return E_DEVICE_NOT_EXIST; } MeasurementSchemaGroup* device_schema = dev_it->second; - // Index of the point that carries each measurement of this row. A - // duplicate point for the same measurement keeps the last one, so that - // every value column advances exactly one row per timestamp. - std::map row_point_index; - for (uint32_t c = 0; c < record.points_.size(); c++) { - row_point_index[record.points_[c].measurement_name_] = c; - } // A record may only carry a subset of the device's measurements. The // measurements it does not mention still have to advance one row (as a // NULL) so that every value column's not-null bitmap stays aligned with @@ -947,7 +948,7 @@ int TsFileWriter::write_record_aligned(const TsRecord& record) { MeasurementSchemaMap& msm = device_schema->measurement_schema_map_; for (MeasurementSchemaMapIter ms_iter = msm.begin(); ms_iter != msm.end(); ms_iter++) { - if (row_point_index.find(ms_iter->first) != row_point_index.end()) { + if (measurements.find(ms_iter->first) != measurements.end()) { continue; } MeasurementSchema* ms = ms_iter->second; @@ -975,14 +976,8 @@ int TsFileWriter::write_record_aligned(const TsRecord& record) { if (IS_NULL(value_chunk_writer)) { continue; } - const DataPoint& point = record.points_[c]; - if (row_point_index[point.measurement_name_] != c) { - // Duplicate point for this measurement: skipped, the last one is - // written below (one row per column per timestamp). - continue; - } if (RET_FAIL(write_point_aligned(value_chunk_writer, record.timestamp_, - data_types[c], point))) { + data_types[c], record.points_[c]))) { // Time wrote the row but at least one value column failed // mid-record; the per-column row counts no longer agree. // Mark the writer unrecoverable so flush/close refuses to @@ -1283,7 +1278,6 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { } ASSERT(data_types.size() == tablet.get_column_count()); ASSERT(chunk_writers.size() == tablet.get_column_count()); - std::unordered_map previous_columns; for (uint32_t c = 0; c < data_types.size(); c++) { if (data_types[c] == common::NULL_TYPE) { continue; @@ -1302,19 +1296,6 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { writer->last_timestamp_)) { return E_OUT_OF_ORDER; } - - // Column names are unique at construction, but a column can be renamed. - auto entry = previous_columns.emplace(writer, c); - if (!entry.second) { - const uint32_t previous = entry.first->second; - uint32_t last = total_rows - 1; - while (tablet.bitmaps_[previous].test(last)) --last; - if (TimePageWriter::is_out_of_order(first_time, - tablet.timestamps_[last])) { - return E_OUT_OF_ORDER; - } - entry.first->second = c; - } } uint32_t columns_written = 0; for (uint32_t c = 0; c < chunk_writers.size(); c++) { diff --git a/cpp/test/writer/tsfile_writer_test.cc b/cpp/test/writer/tsfile_writer_test.cc index e19e3fa8c8..dbe842dc0e 100644 --- a/cpp/test/writer/tsfile_writer_test.cc +++ b/cpp/test/writer/tsfile_writer_test.cc @@ -1770,6 +1770,18 @@ TEST_F(TsFileWriterTest, UnrecoverableLatchRefusesFlushCloseAndWrites) { namespace { +// The allow_non_decreasing_timestamps_ flag is process-global; restore it to +// false even when an ASSERT_* aborts a test early. +class ScopedAllowNonDecreasingTimestamps { + public: + explicit ScopedAllowNonDecreasingTimestamps(bool value) { + common::set_allow_non_decreasing_timestamps(value); + } + ~ScopedAllowNonDecreasingTimestamps() { + common::set_allow_non_decreasing_timestamps(false); + } +}; + WriteFile* OpenWriteFileFor(const std::string& path) { int flags = O_WRONLY | O_CREAT | O_TRUNC; #ifdef _WIN32 @@ -2052,9 +2064,7 @@ TEST_F(TsFileWriterTest, AlignedTabletMissingColumnStaysRowAligned) { ASSERT_EQ(reader.close(), E_OK); } -// A record that repeats the same measurement must still advance that column a -// single time, otherwise the column would run ahead of the time column. -TEST_F(TsFileWriterTest, AlignedRecordDuplicateMeasurementWritesOneRow) { +TEST_F(TsFileWriterTest, AlignedRecordDuplicateMeasurementRejected) { std::string device_name = "device_dup_m"; std::vector schemas; schemas.push_back(new MeasurementSchema("s0", INT64, PLAIN, UNCOMPRESSED)); @@ -2065,7 +2075,14 @@ TEST_F(TsFileWriterTest, AlignedRecordDuplicateMeasurementWritesOneRow) { record.add_point("s0", static_cast(1)); record.add_point("s0", static_cast(2)); record.add_point("s1", static_cast(3)); - ASSERT_EQ(tsfile_writer_->write_record_aligned(record), E_OK); + for (bool allow_equal : {false, true}) { + ScopedAllowNonDecreasingTimestamps guard(allow_equal); + EXPECT_EQ(tsfile_writer_->write_record_aligned(record), E_INVALID_ARG); + } + TsRecord retry(7, device_name); + retry.add_point("s0", static_cast(4)); + retry.add_point("s1", static_cast(5)); + ASSERT_EQ(tsfile_writer_->write_record_aligned(retry), E_OK); ASSERT_EQ(tsfile_writer_->flush(), E_OK); ASSERT_EQ(tsfile_writer_->close(), E_OK); @@ -2087,9 +2104,8 @@ TEST_F(TsFileWriterTest, AlignedRecordDuplicateMeasurementWritesOneRow) { auto* rec = qds->get_row_record(); ASSERT_NE(rec, nullptr); EXPECT_EQ(rec->get_timestamp(), 7); - // The last point of the duplicated measurement wins. - EXPECT_EQ(field_to_string(rec->get_field(1)), "2"); - EXPECT_EQ(field_to_string(rec->get_field(2)), "3"); + EXPECT_EQ(field_to_string(rec->get_field(1)), "4"); + EXPECT_EQ(field_to_string(rec->get_field(2)), "5"); rows++; } EXPECT_EQ(rows, 1); @@ -2514,18 +2530,6 @@ TEST_F(TsFileWriterTest, AlignedRecordPointOrderDoesNotMatter) { } namespace { -// The allow_non_decreasing_timestamps_ flag is process-global; restore it to -// false even when an ASSERT_* aborts a test early. -class ScopedAllowNonDecreasingTimestamps { - public: - explicit ScopedAllowNonDecreasingTimestamps(bool value) { - common::set_allow_non_decreasing_timestamps(value); - } - ~ScopedAllowNonDecreasingTimestamps() { - common::set_allow_non_decreasing_timestamps(false); - } -}; - // page_writer_max_point_num_ is process-global; restore it on scope exit. class ScopedPageMaxPointCount { public: @@ -2850,12 +2854,7 @@ TEST_F(TsFileWriterTest, NonAlignedRecordRejectionWritesNoColumn) { EXPECT_EQ(v0_rows[1].first, 11); } -// A record that carries the same measurement twice would append the second -// point at an equal timestamp; under strict semantics the whole record must be -// rejected before the first point is written. -TEST_F(TsFileWriterTest, - NonAlignedRecordDuplicateMeasurementRejectedWhenStrict) { - ScopedAllowNonDecreasingTimestamps guard(false); +TEST_F(TsFileWriterTest, NonAlignedRecordDuplicateMeasurementRejected) { std::string device_name = "root.dev_na_record_dup_measurement"; ASSERT_EQ( tsfile_writer_->register_timeseries( @@ -2865,7 +2864,10 @@ TEST_F(TsFileWriterTest, TsRecord duplicated(10, device_name); duplicated.add_point("v0", static_cast(1)); duplicated.add_point("v0", static_cast(2)); - EXPECT_EQ(tsfile_writer_->write_record(duplicated), E_OUT_OF_ORDER); + for (bool allow_equal : {false, true}) { + ScopedAllowNonDecreasingTimestamps guard(allow_equal); + EXPECT_EQ(tsfile_writer_->write_record(duplicated), E_INVALID_ARG); + } // Nothing from the rejected record may have been written. TsRecord first(10, device_name); diff --git a/skills/tsfile/references/advanced-apis.md b/skills/tsfile/references/advanced-apis.md index 12c63c81ac..5f9b23afbc 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -50,6 +50,11 @@ follow its own last written point, including across flushes and recovery. An out-of-order tree record or tablet returns `E_OUT_OF_ORDER` before writing any measurement. Python reports `OutOfOrderError`. +C++ tree records require unique measurement names. A duplicate returns +`E_INVALID_ARG` before any points are written under either timestamp policy. +Python reports `InvalidArgumentError`. Keep Tablet column names unique when +renaming columns. + 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'