diff --git a/cpp/src/file/restorable_tsfile_io_writer.cc b/cpp/src/file/restorable_tsfile_io_writer.cc index 605ff6e03..25f9057c3 100644 --- a/cpp/src/file/restorable_tsfile_io_writer.cc +++ b/cpp/src/file/restorable_tsfile_io_writer.cc @@ -33,6 +33,7 @@ #include "compress/compressor_factory.h" #include "encoding/decoder_factory.h" #include "file/utf8_file_open.h" +#include "reader/read_chunk_header.h" #include "utils/errno_define.h" #ifdef _WIN32 @@ -176,32 +177,31 @@ static int parse_chunk_header_and_skip(SelfCheckReader& reader, int64_t chunk_start, int64_t& bytes_consumed, ChunkHeader* header_out = nullptr) { - int32_t file_size = reader.file_size(); - int32_t max_read = static_cast( - std::min(static_cast(BUF_SIZE), file_size - chunk_start)); - if (max_read < ChunkHeader::MIN_SERIALIZED_SIZE) { + const int32_t file_size = reader.file_size(); + if (chunk_start < 0 || chunk_start >= file_size || + file_size - chunk_start < ChunkHeader::MIN_SERIALIZED_SIZE) { return E_TSFILE_CORRUPTED; } - std::vector buf(max_read); - int32_t read_len = 0; - int ret = reader.read(static_cast(chunk_start), buf.data(), - max_read, read_len); - if (ret != E_OK || read_len < ChunkHeader::MIN_SERIALIZED_SIZE) { - return E_TSFILE_CORRUPTED; + // The chunk header embeds the measurement name, so a long name can make it + // longer than BUF_SIZE; read_chunk_header() grows the window until the + // header fits instead of mistaking a valid chunk for a corrupt tail. + int32_t buf_size = BUF_SIZE; + char* buf = static_cast(mem_alloc(buf_size, MOD_CHUNK_READER)); + if (IS_NULL(buf)) { + return common::E_OOM; } - - ByteStream bs; - bs.wrap_from(buf.data(), read_len); - + int32_t read_len = 0; ChunkHeader header; - ret = header.deserialize_from(bs); + int ret = read_chunk_header(&reader, chunk_start, header, buf, buf_size, + read_len); + mem_free(buf); if (ret != E_OK) { - return E_TSFILE_CORRUPTED; + return ret == common::E_OOM ? ret : E_TSFILE_CORRUPTED; } - int header_len = bs.read_pos(); - int64_t total = header_len + header.data_size_; + const int64_t total = + static_cast(header.serialized_size_) + header.data_size_; if (chunk_start + total > file_size) { return E_TSFILE_CORRUPTED; } @@ -825,6 +825,23 @@ int RestorableTsFileIOWriter::self_check(bool truncate_corrupted) { return E_TSFILE_CORRUPTED; } + // A failed allocation during the scan says nothing about the file: do not + // treat it as a corrupt tail and truncate a valid file. Fail the recovery + // and leave the file untouched. + if (ret == common::E_OOM) { + // The in-progress chunk group lives in the arena, whose destroy() does + // not run destructors, so release the device id it owns here; the + // fully-built groups are released by close() through + // self_check_recovered_cgm_. + if (cur_cgm != nullptr) { + cur_cgm->device_id_.reset(); + cur_cgm = nullptr; + } + truncated_size_ = TSFILE_CHECK_INCOMPATIBLE; + reader.close(); + return ret; + } + flush_chunk_group(); get_schema()->finalize_table_schemas(); reader.close(); diff --git a/cpp/src/reader/aligned_chunk_reader.cc b/cpp/src/reader/aligned_chunk_reader.cc index 7ecda10f7..815c917a0 100644 --- a/cpp/src/reader/aligned_chunk_reader.cc +++ b/cpp/src/reader/aligned_chunk_reader.cc @@ -29,6 +29,7 @@ #endif #include "compress/compressor_factory.h" #include "encoding/decoder_factory.h" +#include "reader/read_chunk_header.h" using namespace common; namespace storage { @@ -256,6 +257,8 @@ int AlignedChunkReader::load_by_aligned_meta(ChunkMeta* time_chunk_meta, << ", " << *value_chunk_meta << std::endl; #endif /* ================ deserialize time_chunk_header ================*/ + // The window grows when the chunk header embeds a long measurement name + // (see read_chunk_header()). // TODO configurable file_data_time_buf_size_ = 1024; file_data_value_buf_size_ = 1024; @@ -265,33 +268,21 @@ int AlignedChunkReader::load_by_aligned_meta(ChunkMeta* time_chunk_meta, if (IS_NULL(time_file_data_buf)) { return E_OOM; } - ret = read_file_->read(time_chunk_meta_->offset_of_chunk_header_, - time_file_data_buf, file_data_time_buf_size_, - ret_read_len); - if (IS_SUCC(ret) && - ret_read_len < - UTIL_MIN(static_cast(file_data_time_buf_size_), - read_file_->file_size() - - time_chunk_meta_->offset_of_chunk_header_)) { - ret = E_FILE_READ_ERR; - } - if (!IS_SUCC(ret)) { - mem_free(time_file_data_buf); - return ret; - } - if (ret_read_len < ChunkHeader::MIN_SERIALIZED_SIZE) { - ret = E_TSFILE_CORRUPTED; - LOGE("file corrupted, ret=" << ret << ", offset=" - << time_chunk_meta_->offset_of_chunk_header_ - << "read_len=" << ret_read_len); + ret = + read_chunk_header(read_file_, time_chunk_meta_->offset_of_chunk_header_, + time_chunk_header_, time_file_data_buf, + file_data_time_buf_size_, ret_read_len); + if (IS_SUCC(ret)) { + time_in_stream_.wrap_from(time_file_data_buf, ret_read_len); + // read_chunk_header() parses on its own stream, so move this stream's + // cursor past the chunk header to the first page header. + time_in_stream_.wrapped_buf_advance_read_pos( + time_chunk_header_.serialized_size_); + time_chunk_visit_offset_ = time_chunk_header_.serialized_size_; + } else { mem_free(time_file_data_buf); return ret; } - time_in_stream_.wrap_from(time_file_data_buf, ret_read_len); - if (RET_FAIL(time_chunk_header_.deserialize_from(time_in_stream_))) { - return ret; - } - time_chunk_visit_offset_ = time_in_stream_.read_pos(); /* ================ deserialize value_chunk_header ================*/ ret_read_len = 0; char* value_file_data_buf = @@ -299,49 +290,34 @@ int AlignedChunkReader::load_by_aligned_meta(ChunkMeta* time_chunk_meta, if (IS_NULL(value_file_data_buf)) { return E_OOM; } - ret = read_file_->read(value_chunk_meta_->offset_of_chunk_header_, - value_file_data_buf, file_data_value_buf_size_, - ret_read_len); - if (IS_SUCC(ret) && - ret_read_len < - UTIL_MIN(static_cast(file_data_value_buf_size_), - read_file_->file_size() - - value_chunk_meta_->offset_of_chunk_header_)) { - ret = E_FILE_READ_ERR; - } - if (!IS_SUCC(ret)) { - mem_free(value_file_data_buf); - return ret; - } - if (ret_read_len < ChunkHeader::MIN_SERIALIZED_SIZE) { - ret = E_TSFILE_CORRUPTED; - LOGE("file corrupted, ret=" - << ret << ", offset=" << value_chunk_meta_->offset_of_chunk_header_ - << "read_len=" << ret_read_len); + ret = read_chunk_header(read_file_, + value_chunk_meta_->offset_of_chunk_header_, + value_chunk_header_, value_file_data_buf, + file_data_value_buf_size_, ret_read_len); + if (IS_SUCC(ret)) { + value_in_stream_.wrap_from(value_file_data_buf, ret_read_len); + value_in_stream_.wrapped_buf_advance_read_pos( + value_chunk_header_.serialized_size_); + value_chunk_visit_offset_ = value_chunk_header_.serialized_size_; + } else { mem_free(value_file_data_buf); return ret; } - value_in_stream_.wrap_from(value_file_data_buf, ret_read_len); - if (RET_FAIL(value_chunk_header_.deserialize_from(value_in_stream_))) { - } else if (RET_FAIL(alloc_compressor_and_decoder( - time_decoder_, time_compressor_, - time_chunk_header_.encoding_type_, - time_chunk_header_.data_type_, - time_chunk_header_.compression_type_))) { + if (RET_FAIL(alloc_compressor_and_decoder( + time_decoder_, time_compressor_, time_chunk_header_.encoding_type_, + time_chunk_header_.data_type_, + time_chunk_header_.compression_type_))) { } else if (RET_FAIL(alloc_compressor_and_decoder( value_decoder_, value_compressor_, value_chunk_header_.encoding_type_, value_chunk_header_.data_type_, value_chunk_header_.compression_type_))) { - } else { - value_chunk_visit_offset_ = value_in_stream_.read_pos(); + } #if DEBUG_SE - std::cout << "AlignedChunkReader::load_by_meta, time_chunk_header=" - << time_chunk_header_ - << ", value_chunk_header=" << value_chunk_header_ - << std::endl; + std::cout << "AlignedChunkReader::load_by_meta, time_chunk_header=" + << time_chunk_header_ + << ", value_chunk_header=" << value_chunk_header_ << std::endl; #endif - } return ret; } @@ -1254,36 +1230,29 @@ int AlignedChunkReader::load_by_aligned_meta_multi( page_time_cursor_ = 0; // ── Load time chunk header ── + // The window grows when the chunk header embeds a long measurement name + // (see read_chunk_header()). file_data_time_buf_size_ = 1024; int32_t ret_read_len = 0; char* time_file_data_buf = (char*)mem_alloc(file_data_time_buf_size_, MOD_CHUNK_READER); if (IS_NULL(time_file_data_buf)) return E_OOM; - ret = read_file_->read(time_chunk_meta_->offset_of_chunk_header_, - time_file_data_buf, file_data_time_buf_size_, - ret_read_len); - if (IS_SUCC(ret) && - ret_read_len < - UTIL_MIN(static_cast(file_data_time_buf_size_), - read_file_->file_size() - - time_chunk_meta_->offset_of_chunk_header_)) { - ret = E_FILE_READ_ERR; - } - if (!IS_SUCC(ret)) { - mem_free(time_file_data_buf); - return ret; - } - if (ret_read_len < ChunkHeader::MIN_SERIALIZED_SIZE) { - ret = E_TSFILE_CORRUPTED; + ret = + read_chunk_header(read_file_, time_chunk_meta_->offset_of_chunk_header_, + time_chunk_header_, time_file_data_buf, + file_data_time_buf_size_, ret_read_len); + if (IS_SUCC(ret)) { + time_in_stream_.wrap_from(time_file_data_buf, ret_read_len); + // read_chunk_header() parses on its own stream, so move this stream's + // cursor past the chunk header to the first page header. + time_in_stream_.wrapped_buf_advance_read_pos( + time_chunk_header_.serialized_size_); + time_chunk_visit_offset_ = time_chunk_header_.serialized_size_; + } else { mem_free(time_file_data_buf); return ret; } - time_in_stream_.wrap_from(time_file_data_buf, ret_read_len); - if (RET_FAIL(time_chunk_header_.deserialize_from(time_in_stream_))) { - return ret; - } - time_chunk_visit_offset_ = time_in_stream_.read_pos(); // Alloc time decoder/compressor if (IS_SUCC(ret)) { @@ -1316,29 +1285,17 @@ int AlignedChunkReader::load_by_aligned_meta_multi( (char*)mem_alloc(col->file_data_buf_size, MOD_CHUNK_READER); if (IS_NULL(vbuf)) return E_OOM; - ret = read_file_->read(col->chunk_meta->offset_of_chunk_header_, vbuf, - col->file_data_buf_size, ret_read_len); - if (IS_SUCC(ret) && - ret_read_len < - UTIL_MIN(static_cast(col->file_data_buf_size), - read_file_->file_size() - - col->chunk_meta->offset_of_chunk_header_)) { - ret = E_FILE_READ_ERR; - } - if (!IS_SUCC(ret)) { - mem_free(vbuf); - return ret; - } - if (ret_read_len < ChunkHeader::MIN_SERIALIZED_SIZE) { - ret = E_TSFILE_CORRUPTED; + ret = read_chunk_header( + read_file_, col->chunk_meta->offset_of_chunk_header_, + col->chunk_header, vbuf, col->file_data_buf_size, ret_read_len); + if (IS_FAIL(ret)) { mem_free(vbuf); - return ret; - } - col->in_stream.wrap_from(vbuf, ret_read_len); - if (RET_FAIL(col->chunk_header.deserialize_from(col->in_stream))) { break; } - col->chunk_visit_offset = col->in_stream.read_pos(); + col->in_stream.wrap_from(vbuf, ret_read_len); + col->in_stream.wrapped_buf_advance_read_pos( + col->chunk_header.serialized_size_); + col->chunk_visit_offset = col->chunk_header.serialized_size_; if (RET_FAIL(alloc_compressor_and_decoder( col->decoder, col->compressor, col->chunk_header.encoding_type_, col->chunk_header.data_type_, diff --git a/cpp/src/reader/chunk_reader.cc b/cpp/src/reader/chunk_reader.cc index 3c51d28f7..590dc08af 100644 --- a/cpp/src/reader/chunk_reader.cc +++ b/cpp/src/reader/chunk_reader.cc @@ -23,6 +23,7 @@ #include "compress/compressor_factory.h" #include "encoding/decoder_factory.h" +#include "reader/read_chunk_header.h" using namespace common; namespace storage { @@ -100,7 +101,9 @@ int ChunkReader::load_by_meta(ChunkMeta* meta) { std::cout << "ChunkReader::load_by_meta, meta=" << *meta << std::endl; #endif /* ================ Step 1: reader data from file ================*/ - // at least, we can reader the chunk header and the first page header. + // At least the chunk header and the first page header are read. The + // window grows when the chunk header embeds a long measurement name (see + // read_chunk_header()). // TODO configurable file_data_buf_size_ = 1024; int32_t ret_read_len = 0; @@ -109,43 +112,28 @@ int ChunkReader::load_by_meta(ChunkMeta* meta) { if (IS_NULL(file_data_buf)) { return E_OOM; } - ret = read_file_->read(chunk_meta_->offset_of_chunk_header_, file_data_buf, - file_data_buf_size_, ret_read_len); - if (IS_SUCC(ret) && - ret_read_len < UTIL_MIN(static_cast(file_data_buf_size_), - read_file_->file_size() - - chunk_meta_->offset_of_chunk_header_)) { - ret = E_FILE_READ_ERR; - } - if (!IS_SUCC(ret)) { - mem_free(file_data_buf); - return ret; - } - if (ret_read_len < ChunkHeader::MIN_SERIALIZED_SIZE) { - ret = E_TSFILE_CORRUPTED; - LOGE("file corrupted, ret=" << ret << ", offset=" - << chunk_meta_->offset_of_chunk_header_ - << "read_len=" << ret_read_len); - mem_free(file_data_buf); - } /* ================ Step 2: deserialize chunk_header ================*/ + ret = read_chunk_header(read_file_, chunk_meta_->offset_of_chunk_header_, + chunk_header_, file_data_buf, file_data_buf_size_, + ret_read_len); if (IS_SUCC(ret)) { in_stream_.wrap_from(file_data_buf, ret_read_len); - // std::cout << "in_stream_.wrap_from " << (void*)file_data_buf << - // std::endl; - if (RET_FAIL(chunk_header_.deserialize_from(in_stream_))) { - } else if (RET_FAIL(alloc_compressor_and_value_decoder( - chunk_header_.encoding_type_, chunk_header_.data_type_, - chunk_header_.compression_type_))) { - } else { - chunk_visit_offset_ = - in_stream_.read_pos(); // point to end of chunk_header_ + // read_chunk_header() parses on its own stream, so move this stream's + // cursor past the chunk header to the first page header. + in_stream_.wrapped_buf_advance_read_pos(chunk_header_.serialized_size_); + chunk_visit_offset_ = + chunk_header_.serialized_size_; // end of chunk_header_ + if (RET_FAIL(alloc_compressor_and_value_decoder( + chunk_header_.encoding_type_, chunk_header_.data_type_, + chunk_header_.compression_type_))) { + } #if DEBUG_SE - std::cout << "ChunkReader::load_by_meta, chunk_header=" - << chunk_header_ << std::endl; + std::cout << "ChunkReader::load_by_meta, chunk_header=" << chunk_header_ + << std::endl; #endif - } + } else { + mem_free(file_data_buf); } return ret; } diff --git a/cpp/src/reader/read_chunk_header.h b/cpp/src/reader/read_chunk_header.h new file mode 100644 index 000000000..3f587434c --- /dev/null +++ b/cpp/src/reader/read_chunk_header.h @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#ifndef READER_READ_CHUNK_HEADER_H +#define READER_READ_CHUNK_HEADER_H + +#include + +#include "common/allocator/alloc_base.h" +#include "common/allocator/byte_stream.h" +#include "common/tsfile_common.h" + +namespace storage { + +// Upper bound for a chunk-header read window. A valid header embeds the +// measurement name, so the window has to grow with the name; this cap keeps a +// corrupt length field from driving an arbitrarily large read/allocation. It +// matches the CLI sketch-layout probe limit (kMaxHeaderProbeBytes in +// cpp/tools/commands/sketch_layout.cc). +constexpr int32_t kMaxChunkHeaderWindow = 1 << 20; + +// A serialized chunk header embeds the measurement name verbatim +// (chunk_type, var_str measurement_name, data_size, data_type, compression, +// encoding), so the header grows with the name and a long name can exceed any +// fixed read window. This reads and deserializes the chunk header at @p offset, +// starting from @p buf_size bytes and doubling the window while deserialization +// reports that more bytes are needed, up to the end of the file and to +// kMaxChunkHeaderWindow. A header that does not fit is reported as truncated +// rather than read into an unbounded buffer. +// +// @p buf is a caller-owned, non-null buffer of @p buf_size (> 0) bytes. +// mem_realloc() may move it, so the helper writes the final pointer back; the +// caller keeps ownership and must mem_free() it. On success @p read_len holds +// the bytes read into the window and @p header holds the parsed header; the +// caller wraps @p buf with @p read_len and then advances its stream by +// @p header.serialized_size_ so that the cursor lands on the first page header. +// On failure the caller must free @p buf as well. +template +inline int read_chunk_header(ReadFileT* read_file, int64_t offset, + ChunkHeader& header, char*& buf, int32_t& buf_size, + int32_t& read_len) { + if (read_file == nullptr || buf == nullptr || buf_size <= 0) { + return common::E_INVALID_ARG; + } + const int64_t file_size = read_file->file_size(); + if (offset < 0) { + return common::E_INVALID_ARG; + } + if (offset >= file_size) { + // Mirrors the old fixed-window read: an offset at or beyond EOF yields + // no bytes at all, which is a corrupt chunk reference. + return common::E_TSFILE_CORRUPTED; + } + const int64_t remaining = file_size - offset; + const int64_t max_window = + UTIL_MIN(static_cast(std::numeric_limits::max()), + static_cast(kMaxChunkHeaderWindow)); + int64_t want = buf_size; + int ret = common::E_OK; + while (true) { + int64_t window = UTIL_MIN(UTIL_MIN(want, remaining), max_window); + if (window < ChunkHeader::MIN_SERIALIZED_SIZE) { + return common::E_TSFILE_CORRUPTED; + } + if (buf_size < window) { + char* resized = static_cast( + common::mem_realloc(buf, static_cast(window))); + if (resized == nullptr) { + return common::E_OOM; + } + buf = resized; + buf_size = static_cast(window); + } + read_len = 0; + if (RET_FAIL(read_file->read(offset, buf, static_cast(window), + read_len))) { + return ret; + } else if (read_len < window) { + return common::E_FILE_READ_ERR; + } + common::ByteStream bs; + bs.wrap_from(buf, read_len); + header.reset(); + ret = header.deserialize_from(bs); + if (!common::deserialize_buf_not_enough(ret)) { + return ret; + } + // The header needs more bytes than this window holds. If the window + // already covers the rest of the file or the window cap, it cannot be + // a complete header: report it as truncated instead of reading more. + if (window >= remaining || window >= max_window) { + return ret; + } + want = window * 2; + } +} + +} // namespace storage + +#endif // READER_READ_CHUNK_HEADER_H diff --git a/cpp/test/file/restorable_tsfile_io_writer_test.cc b/cpp/test/file/restorable_tsfile_io_writer_test.cc index 09296a996..6284da426 100644 --- a/cpp/test/file/restorable_tsfile_io_writer_test.cc +++ b/cpp/test/file/restorable_tsfile_io_writer_test.cc @@ -142,6 +142,88 @@ class RestorableTsFileIOWriterTest : public ::testing::Test { // header-only // ----------------------------------------------------------------------------- +// A chunk header embeds the measurement name, so a name longer than the +// self-check read window must not be mistaken for a corrupt tail: recovery has +// to keep the existing chunk and allow appending to it. +TEST_F(RestorableTsFileIOWriterTest, + RecoverChunkWithLongMeasurementNameAndAppend) { + std::string long_name; + const std::string alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; + while (long_name.size() < 4096) { + long_name += alphabet; + } + long_name.resize(4096); + + { + TsFileWriter tw; + ASSERT_EQ(tw.open(file_name_, GetWriteCreateFlags(), 0666), E_OK); + ASSERT_EQ( + tw.register_timeseries("d1", MeasurementSchema(long_name, INT64)), + E_OK); + TsRecord r1(1, "d1"); + r1.add_point(long_name, static_cast(11)); + ASSERT_EQ(tw.write_record(r1), 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()); + { + TsFileTreeWriter tree_writer(&rw); + TsRecord r2(2, "d1"); + r2.add_point(long_name, static_cast(22)); + ASSERT_EQ(tree_writer.write(r2), E_OK); + ASSERT_EQ(tree_writer.flush(), E_OK); + ASSERT_EQ(tree_writer.close(), E_OK); + } + + TsFileTreeReader reader; + ASSERT_EQ(reader.open(file_name_), E_OK); + ResultSet* result = nullptr; + ASSERT_EQ(reader.query({"d1"}, {long_name}, INT64_MIN, INT64_MAX, result), + E_OK); + ASSERT_NE(result, nullptr); + std::vector values; + for (auto it = result->iterator(); it.hasNext();) { + values.push_back(it.next()->get_field(1)->get_value()); + } + reader.destroy_query_data_set(result); + ASSERT_EQ(values, (std::vector{11, 22})); + ASSERT_EQ(reader.close(), E_OK); +} + +// A memory failure during the self-check scan must fail the recovery instead of +// being mistaken for a corrupt tail and truncating a valid file. +TEST_F(RestorableTsFileIOWriterTest, OomDuringSelfCheckDoesNotTruncate) { + std::string long_name(4096, 'n'); + { + TsFileWriter tw; + ASSERT_EQ(tw.open(file_name_, GetWriteCreateFlags(), 0666), E_OK); + ASSERT_EQ( + tw.register_timeseries("d1", MeasurementSchema(long_name, INT64)), + E_OK); + TsRecord r1(1, "d1"); + r1.add_point(long_name, static_cast(11)); + ASSERT_EQ(tw.write_record(r1), E_OK); + ASSERT_EQ(tw.flush(), E_OK); + ASSERT_EQ(tw.close(), E_OK); + } + CorruptCurrentFileTail(3); + const int64_t size_before = GetCurrentFileSize(); + + RestorableTsFileIOWriter rw; + // The long-name chunk header forces the self-check read window to grow, + // which is the first mem_realloc() on this path. + common::TEST_fail_next_mem_realloc(); + EXPECT_EQ(common::E_OOM, rw.open(file_name_, true)); + EXPECT_EQ(GetCurrentFileSize(), size_before); + EXPECT_EQ(rw.get_truncated_size(), TSFILE_CHECK_INCOMPATIBLE); +} + TEST_F(RestorableTsFileIOWriterTest, OpenEmptyFile) { RestorableTsFileIOWriter writer; ASSERT_EQ(writer.open(file_name_, true), E_OK); diff --git a/cpp/test/reader/long_measurement_name_test.cc b/cpp/test/reader/long_measurement_name_test.cc new file mode 100644 index 000000000..ea39e3510 --- /dev/null +++ b/cpp/test/reader/long_measurement_name_test.cc @@ -0,0 +1,297 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// A serialized chunk header embeds the measurement/column name, so a long name +// makes the header longer than the fixed 1024-byte window the chunk readers +// used to read. These cases write and read back names around that boundary +// (writing a table column name of 1018+ characters succeeded but +// the first read returned E_PARTIAL_READ). + +#include +#include + +#include +#include +#include +#include +#include + +#include "common/record.h" +#include "common/row_record.h" +#include "common/schema.h" +#include "common/tablet.h" +#include "file/write_file.h" +#include "reader/filter/tag_filter.h" +#include "reader/table_result_set.h" +#include "reader/tsfile_reader.h" +#include "reader/tsfile_tree_reader.h" +#include "writer/tsfile_table_writer.h" +#include "writer/tsfile_tree_writer.h" + +using namespace storage; +using namespace common; + +namespace { + +const size_t kNameLengths[] = {1017, 1018, 1024, 4096}; +const char kTagValue[] = "device_id"; + +std::string make_name(size_t total_len) { + const std::string alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; + std::string name; + name.reserve(total_len); + while (name.size() < total_len) { + name += alphabet; + } + name.resize(total_len); + return name; +} + +class LongMeasurementNameTest : public ::testing::Test { + protected: + void SetUp() override { libtsfile_init(); } + void TearDown() override { libtsfile_destroy(); } + + std::string make_file_name(size_t name_len) const { + return std::string("long_measurement_name_test_") + + testing::UnitTest::GetInstance()->current_test_info()->name() + + "_" + std::to_string(name_len) + ".tsfile"; + } + + static void create_file(const std::string& file_name, WriteFile& file) { + remove(file_name.c_str()); + int flags = O_WRONLY | O_CREAT | O_TRUNC; +#ifdef _WIN32 + flags |= O_BINARY; +#endif + ASSERT_EQ(E_OK, file.create(file_name, flags, 0666)); + } + + // Table model: a short TAG column, a FIELD column whose name has + // @p name_len characters, and a second short FIELD column. The long FIELD + // chunk header is what used to overflow the reader's fixed read window. + void check_table_field_name(size_t name_len) { + const std::string long_name = make_name(name_len); + const std::string file_name = make_file_name(name_len); + WriteFile write_file; + create_file(file_name, write_file); + + std::vector measurement_schemas; + std::vector column_categories; + measurement_schemas.emplace_back( + new MeasurementSchema("tag0", TSDataType::STRING, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)); + column_categories.emplace_back(ColumnCategory::TAG); + measurement_schemas.emplace_back(new MeasurementSchema( + long_name, TSDataType::INT64, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)); + column_categories.emplace_back(ColumnCategory::FIELD); + measurement_schemas.emplace_back( + new MeasurementSchema("s1", TSDataType::INT64, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)); + column_categories.emplace_back(ColumnCategory::FIELD); + std::unique_ptr table_schema( + new TableSchema("t", measurement_schemas, column_categories)); + + const int kRows = 3; + { + TsFileTableWriter writer(&write_file, table_schema.get()); + Tablet tablet(table_schema->get_table_name(), + table_schema->get_measurement_names(), + table_schema->get_data_types(), + table_schema->get_column_categories(), kRows); + char literal[] = "device_id"; + String literal_str(literal, std::strlen(literal)); + for (int i = 0; i < kRows; i++) { + ASSERT_EQ(E_OK, tablet.add_timestamp(i, i)); + ASSERT_EQ(E_OK, tablet.add_value(i, "tag0", literal_str)); + ASSERT_EQ(E_OK, tablet.add_value(i, long_name, + static_cast(i))); + ASSERT_EQ(E_OK, tablet.add_value( + i, "s1", static_cast(100 + i))); + } + ASSERT_EQ(E_OK, writer.write_table(tablet)); + ASSERT_EQ(E_OK, writer.flush()); + ASSERT_EQ(E_OK, writer.close()); + } + + TsFileReader reader; + ASSERT_EQ(E_OK, reader.open(file_name)); + ResultSet* result_set = nullptr; + std::vector columns{long_name, "s1"}; + ASSERT_EQ(E_OK, reader.query("t", columns, 0, kRows, result_set)); + auto* table_result_set = static_cast(result_set); + ASSERT_NE(table_result_set, nullptr); + int64_t row_num = 0; + bool has_next = false; + while (table_result_set->next(has_next) == E_OK && has_next) { + ASSERT_EQ(table_result_set->get_value(long_name), row_num); + // The sibling column after the long-named chunk must stay readable. + ASSERT_EQ(table_result_set->get_value("s1"), + 100 + row_num); + row_num++; + } + ASSERT_EQ(row_num, kRows); + reader.destroy_query_data_set(table_result_set); + ASSERT_EQ(E_OK, reader.close()); + remove(file_name.c_str()); + } + + // Table model: a TAG column with a long name. Tag values are resolved from + // the device id instead of a value chunk, so this covers schema lookup and + // tag-filter resolution with a long name. It passes without the reader fix; + // it is coverage for long tag names, not evidence of the chunk-header bug + // (the FIELD column case above is the regression case). + void check_table_tag_name(size_t name_len) { + const std::string long_name = make_name(name_len); + const std::string file_name = make_file_name(name_len); + WriteFile write_file; + create_file(file_name, write_file); + + std::vector measurement_schemas; + std::vector column_categories; + measurement_schemas.emplace_back(new MeasurementSchema( + long_name, TSDataType::STRING, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)); + column_categories.emplace_back(ColumnCategory::TAG); + measurement_schemas.emplace_back( + new MeasurementSchema("s0", TSDataType::INT64, TSEncoding::PLAIN, + CompressionType::UNCOMPRESSED)); + column_categories.emplace_back(ColumnCategory::FIELD); + std::unique_ptr table_schema( + new TableSchema("t", measurement_schemas, column_categories)); + + const int kRows = 2; + { + TsFileTableWriter writer(&write_file, table_schema.get()); + Tablet tablet(table_schema->get_table_name(), + table_schema->get_measurement_names(), + table_schema->get_data_types(), + table_schema->get_column_categories(), kRows); + char literal[] = "device_id"; + String literal_str(literal, std::strlen(literal)); + for (int i = 0; i < kRows; i++) { + ASSERT_EQ(E_OK, tablet.add_timestamp(i, i)); + ASSERT_EQ(E_OK, tablet.add_value(i, long_name, literal_str)); + ASSERT_EQ(E_OK, + tablet.add_value(i, "s0", static_cast(i))); + } + ASSERT_EQ(E_OK, writer.write_table(tablet)); + ASSERT_EQ(E_OK, writer.flush()); + ASSERT_EQ(E_OK, writer.close()); + } + + TsFileReader reader; + ASSERT_EQ(E_OK, reader.open(file_name)); + ResultSet* result_set = nullptr; + std::vector columns{long_name, "s0"}; + Filter* tag_filter = + TagFilterBuilder(table_schema.get()).eq(long_name, kTagValue); + ASSERT_NE(tag_filter, nullptr); + ASSERT_EQ(E_OK, + reader.query("t", columns, 0, kRows, result_set, tag_filter)); + auto* table_result_set = static_cast(result_set); + ASSERT_NE(table_result_set, nullptr); + char literal[] = "device_id"; + String expected_tag(literal, std::strlen(literal)); + int64_t row_num = 0; + bool has_next = false; + while (table_result_set->next(has_next) == E_OK && has_next) { + ASSERT_EQ(table_result_set->get_value("s0"), row_num); + String* tag_value = + table_result_set->get_value(long_name); + ASSERT_NE(tag_value, nullptr); + ASSERT_EQ(tag_value->compare(expected_tag), 0); + row_num++; + } + ASSERT_EQ(row_num, kRows); + reader.destroy_query_data_set(table_result_set); + delete tag_filter; + ASSERT_EQ(E_OK, reader.close()); + remove(file_name.c_str()); + } + + // Tree model: the measurement name is embedded in the chunk header of the + // non-aligned chunk, exercised through ChunkReader::load_by_meta(). + void check_tree_measurement_name(size_t name_len) { + const std::string long_name = make_name(name_len); + const std::string file_name = make_file_name(name_len); + WriteFile write_file; + create_file(file_name, write_file); + + std::string device_id = "root.db.d1"; + { + TsFileTreeWriter writer(&write_file); + auto* measurement = + new MeasurementSchema(long_name, TSDataType::INT64); + ASSERT_EQ(E_OK, writer.register_timeseries(device_id, measurement)); + delete measurement; + TsRecord record(device_id, 0); + ASSERT_EQ(E_OK, + record.add_point(long_name, static_cast(7))); + ASSERT_EQ(E_OK, writer.write(record)); + ASSERT_EQ(E_OK, writer.flush()); + ASSERT_EQ(E_OK, writer.close()); + } + + TsFileTreeReader reader; + ASSERT_EQ(E_OK, reader.open(file_name)); + ResultSet* result_set = nullptr; + ASSERT_EQ(E_OK, reader.query(std::vector{device_id}, + std::vector{long_name}, + INT64_MIN, INT64_MAX, result_set)); + ASSERT_NE(result_set, nullptr); + auto iter = result_set->iterator(); + int64_t rows = 0; + while (iter.hasNext()) { + Field* field = iter.next()->get_field(1); + ASSERT_NE(field, nullptr); + ASSERT_EQ(field->type_, INT64); + ASSERT_EQ(field->get_value(), 7); + rows++; + } + ASSERT_EQ(rows, 1); + reader.destroy_query_data_set(result_set); + ASSERT_EQ(E_OK, reader.close()); + remove(file_name.c_str()); + } +}; + +TEST_F(LongMeasurementNameTest, TableFieldColumnName) { + for (size_t len : kNameLengths) { + SCOPED_TRACE(::testing::Message() << "column name length=" << len); + check_table_field_name(len); + } +} + +TEST_F(LongMeasurementNameTest, TableTagColumnName) { + for (size_t len : kNameLengths) { + SCOPED_TRACE(::testing::Message() << "column name length=" << len); + check_table_tag_name(len); + } +} + +TEST_F(LongMeasurementNameTest, TreeMeasurementName) { + for (size_t len : kNameLengths) { + SCOPED_TRACE(::testing::Message() << "measurement name length=" << len); + check_tree_measurement_name(len); + } +} + +} // namespace diff --git a/cpp/test/reader/read_chunk_header_test.cc b/cpp/test/reader/read_chunk_header_test.cc new file mode 100644 index 000000000..8fbe777b0 --- /dev/null +++ b/cpp/test/reader/read_chunk_header_test.cc @@ -0,0 +1,166 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// Unit tests for read_chunk_header(): a serialized chunk header embeds the +// measurement name, so the read window must grow with the name, but it must +// stay bounded when a corrupt length field claims an enormous name. + +#include "reader/read_chunk_header.h" + +#include + +#include +#include +#include +#include + +#include "common/allocator/alloc_base.h" +#include "common/allocator/byte_stream.h" +#include "common/tsfile_common.h" +#include "file/random_access_read_file.h" + +using namespace common; +using namespace storage; + +namespace { + +class MemoryReadFile : public RandomAccessReadFile { + public: + explicit MemoryReadFile(std::vector bytes) + : bytes_(std::move(bytes)) {} + bool is_opened() const override { return true; } + int64_t file_size() const override { + return static_cast(bytes_.size()); + } + const std::string& file_path() const override { return path_; } + int generation(uint64_t& size, uint64_t& fingerprint) const override { + size = bytes_.size(); + fingerprint = 0; + return E_OK; + } + int read(int64_t offset, char* buffer, int32_t size, + int32_t& read_size) override { + read_size = 0; + if (offset < 0 || size < 0 || + offset >= static_cast(bytes_.size())) { + return E_OK; + } + read_size = static_cast( + std::min(size, bytes_.size() - offset)); + std::memcpy(buffer, bytes_.data() + offset, read_size); + return E_OK; + } + void close() override {} + + private: + std::vector bytes_; + std::string path_; +}; + +std::vector take_stream_bytes(ByteStream& stream) { + const int32_t size = static_cast(stream.total_size()); + char* raw = get_bytes_from_bytestream(stream); + std::vector bytes(raw, raw + size); + mem_free(raw); + return bytes; +} + +ChunkHeader make_header(const std::string& name) { + ChunkHeader header; + header.measurement_name_ = name; + header.data_size_ = 16; + header.data_type_ = INT64; + header.compression_type_ = UNCOMPRESSED; + header.encoding_type_ = PLAIN; + header.num_of_pages_ = 1; + header.chunk_type_ = ONLY_ONE_PAGE_CHUNK_HEADER_MARKER; + return header; +} + +class ReadChunkHeaderTest : public ::testing::Test {}; + +TEST_F(ReadChunkHeaderTest, GrowsWindowForLongMeasurementName) { + std::string name(4096, 'n'); + ChunkHeader source = make_header(name); + ByteStream out(1024, MOD_DEFAULT); // owning stream, copied out below + ASSERT_EQ(E_OK, source.serialize_to(out)); + std::vector bytes = take_stream_bytes(out); + MemoryReadFile file(bytes); + + int32_t buf_size = 1024; + int32_t read_len = 0; + char* buf = static_cast(mem_alloc(buf_size, MOD_CHUNK_READER)); + ASSERT_NE(buf, nullptr); + ChunkHeader parsed; + ASSERT_EQ(E_OK, + read_chunk_header(&file, 0, parsed, buf, buf_size, read_len)); + EXPECT_EQ(parsed.measurement_name_, name); + EXPECT_EQ(parsed.data_size_, source.data_size_); + // The helper parses the one header the stream holds, and reports its full + // serialized length (ChunkHeader::serialize_to does not fill it in). + EXPECT_EQ(parsed.serialized_size_, static_cast(bytes.size())); + EXPECT_GT(parsed.serialized_size_, 1024); + EXPECT_GT(buf_size, 1024); + EXPECT_GE(read_len, parsed.serialized_size_); + mem_free(buf); +} + +TEST_F(ReadChunkHeaderTest, CorruptLengthFailsWithinWindowCap) { + // A corrupt length field claims a 2 MiB name. The window must stop at + // kMaxChunkHeaderWindow instead of reading/allocating the whole tail. + ByteStream out(1024, MOD_DEFAULT); + ASSERT_EQ(E_OK, SerializationUtil::write_char( + ONLY_ONE_PAGE_CHUNK_HEADER_MARKER, out)); + ASSERT_EQ(E_OK, SerializationUtil::write_var_int(2 * 1024 * 1024, out)); + const char tail[] = "abcd"; + ASSERT_EQ(E_OK, out.write_buf(tail, 4)); + std::vector bytes = take_stream_bytes(out); + bytes.resize(3 * 1024 * 1024, 0); // file tail larger than the cap + MemoryReadFile file(bytes); + + int32_t buf_size = 1024; + int32_t read_len = 0; + char* buf = static_cast(mem_alloc(buf_size, MOD_CHUNK_READER)); + ASSERT_NE(buf, nullptr); + ChunkHeader parsed; + EXPECT_EQ(E_PARTIAL_READ, + read_chunk_header(&file, 0, parsed, buf, buf_size, read_len)); + EXPECT_EQ(buf_size, kMaxChunkHeaderWindow); + mem_free(buf); +} + +TEST_F(ReadChunkHeaderTest, RejectsOffsetAtOrBeyondEof) { + ChunkHeader source = make_header("s"); + ByteStream out(1024, MOD_DEFAULT); + ASSERT_EQ(E_OK, source.serialize_to(out)); + std::vector bytes = take_stream_bytes(out); + MemoryReadFile file(bytes); + const int64_t file_size = file.file_size(); + + int32_t buf_size = 1024; + int32_t read_len = 0; + char* buf = static_cast(mem_alloc(buf_size, MOD_CHUNK_READER)); + ASSERT_NE(buf, nullptr); + ChunkHeader parsed; + EXPECT_EQ(E_TSFILE_CORRUPTED, read_chunk_header(&file, file_size, parsed, + buf, buf_size, read_len)); + mem_free(buf); +} + +} // namespace