diff --git a/cpp/src/common/schema.h b/cpp/src/common/schema.h index 007e1f1db..ed920c9f0 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/file/restorable_tsfile_io_writer.cc b/cpp/src/file/restorable_tsfile_io_writer.cc index 605ff6e03..d29e91a37 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,9 @@ 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(); } 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 8c06c4907..6223e38ff 100644 --- a/cpp/src/file/restorable_tsfile_io_writer.h +++ b/cpp/src/file/restorable_tsfile_io_writer.h @@ -81,8 +81,8 @@ 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; /** * Recovered chunk group metas from self_check (actual device_id and chunk @@ -122,7 +122,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/chunk_writer.cc b/cpp/src/writer/chunk_writer.cc index acdb4951d..a428ed237 100644 --- a/cpp/src/writer/chunk_writer.cc +++ b/cpp/src/writer/chunk_writer.cc @@ -33,6 +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; + has_last_timestamp_ = false; chunk_statistic_ = StatisticFactory::alloc_statistic(data_type); if (chunk_statistic_ == nullptr) { return E_OOM; diff --git a/cpp/src/writer/chunk_writer.h b/cpp/src/writer/chunk_writer.h index 3d0d6dd32..f9c14ccc3 100644 --- a/cpp/src/writer/chunk_writer.h +++ b/cpp/src/writer/chunk_writer.h @@ -34,6 +34,8 @@ namespace storage { 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; \ } \ @@ -128,6 +130,8 @@ class ChunkWriter { return ret; } offset += batch_size; + last_timestamp_ = timestamps[offset - 1]; + has_last_timestamp_ = true; if (RET_FAIL(seal_cur_page_if_full())) { return ret; } @@ -165,6 +169,8 @@ class ChunkWriter { return ret; } offset += batch_size; + last_timestamp_ = timestamps[offset - 1]; + has_last_timestamp_ = true; if (RET_FAIL(seal_cur_page_if_full())) { return ret; } @@ -227,6 +233,11 @@ class ChunkWriter { ChunkHeader chunk_header_; int32_t num_of_pages_; + + // 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; }; } // end namespace storage diff --git a/cpp/src/writer/tsfile_writer.cc b/cpp/src/writer/tsfile_writer.cc index 5e8cbb683..e1871918d 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" @@ -217,8 +218,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)); } @@ -229,12 +229,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 +582,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; @@ -845,14 +860,14 @@ 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_); - // 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); @@ -862,6 +877,15 @@ int TsFileWriter::write_record(const TsRecord& record) { } ASSERT(chunk_writers.size() == record.points_.size()); + 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_)) { + 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)) { @@ -872,12 +896,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; @@ -886,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_)) { @@ -908,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 @@ -931,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; @@ -959,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 @@ -1252,8 +1263,10 @@ 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])) { + 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; @@ -1264,6 +1277,7 @@ 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()); for (uint32_t c = 0; c < data_types.size(); c++) { if (data_types[c] == common::NULL_TYPE) { continue; @@ -1271,8 +1285,18 @@ int TsFileWriter::write_tablet(const Tablet& tablet) { if (data_types[c] != tablet.schema_vec_->at(c).data_type_) { return E_TYPE_NOT_MATCH; } + 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; + } } - ASSERT(chunk_writers.size() == tablet.get_column_count()); uint32_t columns_written = 0; for (uint32_t c = 0; c < chunk_writers.size(); c++) { ChunkWriter* chunk_writer = chunk_writers[c]; @@ -1291,14 +1315,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; diff --git a/cpp/test/file/restorable_tsfile_io_writer_test.cc b/cpp/test/file/restorable_tsfile_io_writer_test.cc index 09296a996..cf1d231e1 100644 --- a/cpp/test/file/restorable_tsfile_io_writer_test.cc +++ b/cpp/test/file/restorable_tsfile_io_writer_test.cc @@ -440,6 +440,78 @@ TEST_F(RestorableTsFileIOWriterTest, } } +TEST_F(RestorableTsFileIOWriterTest, + 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); + // 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); + 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); + schema_vec.emplace_back("s2", INT64, PLAIN, UNCOMPRESSED); + Tablet tablet("root.d1", + std::make_shared>(schema_vec), + 2); + 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); + + 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_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_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"}), 7); + reader.close(); +} + // ----------------------------------------------------------------------------- // Tree model + Recovery + continued write with aligned timeseries, then // read-back verify 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 870b30aaf..dae6033f7 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 c927cc3af..dbe842dc0 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); @@ -1738,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 @@ -2020,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)); @@ -2033,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); @@ -2055,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); @@ -2482,16 +2530,19 @@ 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 { +// page_writer_max_point_num_ is process-global; restore it on scope exit. +class ScopedPageMaxPointCount { public: - explicit ScopedAllowNonDecreasingTimestamps(bool value) { - common::set_allow_non_decreasing_timestamps(value); + 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; } - ~ScopedAllowNonDecreasingTimestamps() { - common::set_allow_non_decreasing_timestamps(false); + ~ScopedPageMaxPointCount() { + common::g_config_value_.page_writer_max_point_num_ = saved_; } + + private: + uint32_t saved_; }; } // namespace @@ -2690,3 +2741,533 @@ 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); +} + +TEST_F(TsFileWriterTest, NonAlignedRecordDuplicateMeasurementRejected) { + 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)); + 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); + 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); +} + +// 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)); + + ASSERT_EQ(tsfile_writer_->write_record(first), E_OK); + + 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, 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}; + 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)); + + 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(), 3u); + EXPECT_EQ(rows[0].first, 10); + EXPECT_EQ(rows[0].second[0], "0"); + + EXPECT_EQ(rows[1].first, 11); + EXPECT_EQ(rows[1].second[0], "2"); + EXPECT_EQ(rows[2].first, 20); + EXPECT_EQ(rows[2].second[1], "100"); +} + +TEST_F(TsFileWriterTest, NonAlignedTabletChecksTimeOrderEvenOnNullRows) { + 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_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); + 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, 14); +} diff --git a/python/tests/test_allow_non_decreasing_timestamps.py b/python/tests/test_allow_non_decreasing_timestamps.py index 2fba75a37..2187f25ea 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 3f5881fbb..5f9b23afb 100644 --- a/skills/tsfile/references/advanced-apis.md +++ b/skills/tsfile/references/advanced-apis.md @@ -44,6 +44,17 @@ This is process-wide, including Python constructor defaults; avoid conflicting writers. Decreases remain invalid. See `properties-filters.md` for the persisted policy; CLI `write` has no opt-in. +C++ 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++ 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' @@ -106,6 +117,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