Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions be/src/load/memtable/memtable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include "bvar/bvar.h"
#include "common/config.h"
#include "core/column/column.h"
#include "core/data_type/data_type_factory.hpp"
#include "exprs/aggregate/aggregate_function_reader.h"
#include "exprs/aggregate/aggregate_function_simple_factory.h"
#include "load/memtable/memtable_memory_limiter.h"
Expand Down Expand Up @@ -123,6 +124,7 @@ void MemTable::_init_agg_functions(const Block* block) {
}
} else {
function = _tablet_schema->column(cid).get_aggregate_function(
DataTypeFactory::instance().create_data_type(_tablet_schema->column(cid)),
AGG_LOAD_SUFFIX, _tablet_schema->column(cid).get_be_exec_version());
if (function == nullptr) {
LOG(WARNING) << "column get aggregate function failed, column="
Expand Down
5 changes: 4 additions & 1 deletion be/src/storage/iterator/block_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -501,8 +501,11 @@ Status BlockReader::_init_agg_state(const ReaderParams& read_params) {
for (auto idx : _agg_columns_idx) {
auto column = tablet_schema.column(
read_params.origin_return_columns->at(_return_columns_loc[idx]));
// Use the stored block's column type (already the FE-pruned type for a pruned
// complex column) so the aggregate function's argument type matches.
AggregateFunctionPtr function =
column.get_aggregate_function(AGG_READER_SUFFIX, read_params.get_be_exec_version());
column.get_aggregate_function(_next_row.block->get_by_position(idx).type,
AGG_READER_SUFFIX, read_params.get_be_exec_version());

// to avoid coredump when something goes wrong(i.e. column missmatch)
if (!function) {
Expand Down
7 changes: 4 additions & 3 deletions be/src/storage/iterator/vertical_block_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
#include "core/block/column_with_type_and_name.h"
#include "core/column/column_nullable.h"
#include "core/column/column_vector.h"
#include "core/data_type/data_type_factory.hpp"
#include "core/data_type/data_type_number.h"
#include "exprs/aggregate/aggregate_function_reader.h"
#include "storage/compaction/compaction.h"
Expand Down Expand Up @@ -194,10 +195,10 @@ void VerticalBlockReader::_init_agg_state(const ReaderParams& read_params) {

auto& tablet_schema = *_tablet_schema;
for (size_t idx = 0; idx < _return_columns.size(); ++idx) {
const auto& column = tablet_schema.column(_return_columns.at(idx));
AggregateFunctionPtr function =
tablet_schema.column(_return_columns.at(idx))
.get_aggregate_function(AGG_READER_SUFFIX,
read_params.get_be_exec_version());
column.get_aggregate_function(DataTypeFactory::instance().create_data_type(column),
AGG_READER_SUFFIX, read_params.get_be_exec_version());
DCHECK(function != nullptr);
const auto* column_ptr = _stored_data_columns[idx].get();
const IColumn* columns[] = {column_ptr};
Expand Down
7 changes: 6 additions & 1 deletion be/src/storage/iterator/vgeneric_iterators.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ Status VMergeIteratorContext::block_reset(const std::shared_ptr<Block>& block) {
const auto& column_ids = _output_schema->column_ids();
for (size_t i = 0; i < _output_schema->num_column_ids(); ++i) {
auto column_desc = _output_schema->column(column_ids[i]);
auto data_type = Schema::get_data_type_ptr(*column_desc);
auto data_type = _data_type_maybe_pruned(*column_desc);
if (data_type == nullptr) {
return Status::RuntimeError("invalid data type");
}
Expand Down Expand Up @@ -294,6 +294,11 @@ Status VAutoIncrementIterator::init(const StorageReadOptions& opts) {
Status VMergeIteratorContext::init(const StorageReadOptions& opts) {
_block_row_max = opts.block_row_max;
_record_rowids = opts.record_rowids;
// For query reads that prune nested sub-columns, block_reset() must build the
// merge block with the FE-pruned complex types recorded on the tablet schema.
if (opts.tablet_schema != nullptr && opts.tablet_schema->has_pruned_columns()) {
_pruned_columns_data_type = &opts.tablet_schema->pruned_columns_data_type();
}
RETURN_IF_ERROR(_load_next_block());
if (valid()) {
RETURN_IF_ERROR(advance());
Expand Down
18 changes: 18 additions & 0 deletions be/src/storage/iterator/vgeneric_iterators.h
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,20 @@ class VMergeIteratorContext {
// Load next block into _block
Status _load_next_block();

// Data type used to materialize `column` in the merge block: the FE-pruned
// type when the query pruned this complex column's sub-columns (so the block's
// struct children line up with the pruned sub-column iterators), otherwise the
// full storage type.
DataTypePtr _data_type_maybe_pruned(const TabletColumn& column) const {
if (_pruned_columns_data_type) {
auto it = _pruned_columns_data_type->find(column.unique_id());
if (it != _pruned_columns_data_type->end()) {
return it->second;
}
}
return Schema::get_data_type_ptr(column);
}

RowwiseIteratorUPtr _iter;

int _sequence_id_idx = -1;
Expand All @@ -209,6 +223,10 @@ class VMergeIteratorContext {
// block_reset() uses _output_schema to build _block, and copy_rows() iterates over
// _output_schema->num_column_ids() columns to copy from _block to the destination.
const SchemaSPtr _output_schema;
// col unique id -> FE-pruned type for pruned complex columns; null otherwise. Set in
// init() from opts.tablet_schema (outlives this context); block_reset() uses it so the
// merge block's struct children line up with the pruned sub-column iterators.
const std::map<int32_t, DataTypePtr>* _pruned_columns_data_type = nullptr;
int _num_key_columns;
std::vector<uint32_t>* _compare_columns;
std::vector<RowLocation> _block_row_locations;
Expand Down
2 changes: 2 additions & 0 deletions be/src/storage/schema_change/schema_change.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
#include "core/block/column_with_type_and_name.h"
#include "core/column/column.h"
#include "core/column/column_nullable.h"
#include "core/data_type/data_type_factory.hpp"
#include "exec/common/util.hpp"
#include "exec/common/variant_util.h"
#include "exprs/aggregate/aggregate_function.h"
Expand Down Expand Up @@ -174,6 +175,7 @@ class MultiBlockMerger {
for (int i = key_number; i < columns; i++) {
try {
AggregateFunctionPtr function = tablet_schema->column(i).get_aggregate_function(
DataTypeFactory::instance().create_data_type(tablet_schema->column(i)),
AGG_LOAD_SUFFIX, tablet_schema->column(i).get_be_exec_version());
if (!function) {
return Status::InternalError(
Expand Down
3 changes: 1 addition & 2 deletions be/src/storage/tablet/tablet_schema.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -788,11 +788,10 @@ AggregateFunctionPtr TabletColumn::get_aggregate_function_union(DataTypePtr type
return AggregateStateUnion::create(state_type->get_nested_function(), {type}, type);
}

AggregateFunctionPtr TabletColumn::get_aggregate_function(std::string suffix,
AggregateFunctionPtr TabletColumn::get_aggregate_function(DataTypePtr type, std::string suffix,
int current_be_exec_version) const {
AggregateFunctionPtr function = nullptr;

auto type = DataTypeFactory::instance().create_data_type(*this);
if (type && type->get_primitive_type() == PrimitiveType::TYPE_AGG_STATE) {
function = get_aggregate_function_union(type, current_be_exec_version);
} else {
Expand Down
8 changes: 7 additions & 1 deletion be/src/storage/tablet/tablet_schema.h
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,9 @@ class TabletColumn : public MetadataAdder<TabletColumn> {
FieldAggregationMethod aggregation() const { return _aggregation; }
AggregateFunctionPtr get_aggregate_function_union(DataTypePtr type,
int current_be_exec_version) const;
AggregateFunctionPtr get_aggregate_function(std::string suffix,
// `type` is the data type of the column as actually read (the FE-pruned type
// when the query prunes nested sub-columns, otherwise the full column type).
AggregateFunctionPtr get_aggregate_function(DataTypePtr type, std::string suffix,
int current_be_exec_version) const;
int precision() const { return _precision; }
int frac() const { return _frac; }
Expand Down Expand Up @@ -753,6 +755,10 @@ class TabletSchema : public MetadataAdder<TabletSchema> {

bool has_pruned_columns() const { return !_pruned_columns_data_type.empty(); }

const std::map<int32_t, DataTypePtr>& pruned_columns_data_type() const {
return _pruned_columns_data_type;
}

TabletStorageFormatPB storage_format() const { return _storage_format; }
void set_storage_format(TabletStorageFormatPB v) { _storage_format = v; }

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// 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.

// Regression case for the pruned-struct read misalignment on the inline topn scan path.
//
// Root cause: when a topn ordered read (order by key limit N) hits a rowset with
// multiple OVERLAPPING segments, BetaRowsetReader picks VMergeIterator, whose
// VMergeIteratorContext::init() eagerly loads the first block of every segment.
// That block is created from the storage Schema (FULL struct type, all children),
// while the struct sub-column iterators have been filtered down to the pruned
// subset by set_access_paths()/remove_pruned_sub_iterators(). The pairing loop in
// StructFileColumnIterator::next_batch() indexes _sub_column_iterators[i] by the
// dst tuple position, so the two ordinal spaces disagree:
// - text/dict child data decoded into a TINYINT child column
// -> [E-3110] insert_many_dict_data is not supported for TINYINT
// - same-typed children shift silently, and the loop runs past the pruned
// iterator vector -> out-of-bounds -> BE SIGSEGV
//
// The FE TopN lazy materialization (VMaterializeNode) usually shields this path
// on master; setting topn_lazy_materialization_threshold=-1 (or any state where
// the rule bails, e.g. light_schema_change=false tables) exposes it.
//
// Layout construction: MemTable.need_flush debug point forces one segment per
// inserted block (batch_size=500, 2000 rows -> 4 segments, below the
// segcompaction_batch_size=10 threshold so segcompaction never merges them), and
// the NULL k1 rows in every block make every segment's key lower bound NULL, so
// the segments overlap and the rowset is marked OVERLAPPING.
suite("test_topn_pruned_struct_overlapping_segments", "nonConcurrent") {
def dictTable = "test_topn_pruned_struct_ovlp_dict"
def intTable = "test_topn_pruned_struct_ovlp_int"
def aggTable = "test_topn_pruned_struct_ovlp_agg"

sql "DROP TABLE IF EXISTS ${dictTable}"
sql "DROP TABLE IF EXISTS ${intTable}"
sql "DROP TABLE IF EXISTS ${aggTable}"
sql """
CREATE TABLE ${dictTable} (
k1 BIGINT,
c ARRAY<ARRAY<STRUCT<col1:INT, col2:TINYINT, col17:TEXT>>>
) DUPLICATE KEY(k1)
DISTRIBUTED BY HASH(k1) BUCKETS 1
PROPERTIES('replication_num' = '1')
"""
sql """
CREATE TABLE ${intTable} (
k1 BIGINT,
c ARRAY<ARRAY<STRUCT<col1:INT, col2:INT, col3:INT>>>
) DUPLICATE KEY(k1)
DISTRIBUTED BY HASH(k1) BUCKETS 1
PROPERTIES('replication_num' = '1')
"""

try {
GetDebugPoint().enableDebugPointForAllBEs("MemTable.need_flush")
// 4 blocks of 500 rows -> 4 segments per tablet; k1 NULL every 20 rows so
// every segment starts at NULL -> overlapping key ranges -> OVERLAPPING rowset.
sql "SET batch_size = 500"
sql """
INSERT INTO ${dictTable}
SELECT if(number % 20 = 0, NULL, number),
array(array(named_struct(
'col1', CAST(number AS INT),
'col2', CAST(number % 127 AS TINYINT),
'col17', concat('s', number))))
FROM numbers('number' = '2000')
"""
sql """
INSERT INTO ${intTable}
SELECT if(number % 20 = 0, NULL, number),
array(array(named_struct(
'col1', CAST(number + 1000000 AS INT),
'col2', CAST(number + 2000000 AS INT),
'col3', CAST(number + 3000000 AS INT))))
FROM numbers('number' = '2000')
"""
} finally {
GetDebugPoint().disableDebugPointForAllBEs("MemTable.need_flush")
}

// Self-check the storage layout: the test is void unless the rowset really is
// a multi-segment OVERLAPPING one (that is what selects VMergeIterator).
for (def tbl : [dictTable, intTable]) {
def tablets = sql_return_maparray("SHOW TABLETS FROM ${tbl}")
def (code, out, err) = curl("GET", tablets[0].MetaUrl)
assertEquals(0, code)
assertTrue(out.contains('"segments_overlap_pb": "OVERLAPPING"'),
Comment thread
csun5285 marked this conversation as resolved.
"expected an OVERLAPPING multi-segment rowset in ${tbl}, tablet meta: check MemTable.need_flush debug point")
}

// AGG-table variant: the same ordinal-space mismatch also hits the aggregate
// merge path (BlockReader::_init_agg_state used to build the reader_replace
// argument type from the full TabletColumn while the stored block uses the
// pruned type). It needs no debug point, no topn and no special session vars:
// two ordinary inserts (two rowsets) + a pruned read used to fail with
// "Aggregate function reader_replace argument 0 type check failed".
sql """
CREATE TABLE ${aggTable} (
k1 BIGINT,
c ARRAY<ARRAY<STRUCT<col1:INT, col2:TINYINT, col17:TEXT>>> REPLACE
) AGGREGATE KEY(k1)
DISTRIBUTED BY HASH(k1) BUCKETS 1
PROPERTIES('replication_num' = '1')
"""
sql """
INSERT INTO ${aggTable}
SELECT number, array(array(named_struct(
'col1', CAST(number AS INT),
'col2', CAST(number % 127 AS TINYINT),
'col17', concat('s', number))))
FROM numbers('number' = '1000')
"""
sql """
INSERT INTO ${aggTable}
SELECT number + 1000, array(array(named_struct(
'col1', CAST(number + 1000 AS INT),
'col2', CAST(number % 127 AS TINYINT),
'col17', concat('s', number + 1000))))
FROM numbers('number' = '1000')
"""

def expectedTwoCols = (1..10).collect { [String.valueOf(it), "s" + it] }
def expectedOneCol = (1..10).collect { ["s" + it] }
def expectedIntCol = (1..10).collect { [String.valueOf(3000000 + it)] }

def assertRows = { List<List<Object>> actual, List<List<String>> expected, String tag ->
assertEquals(expected.size(), actual.size(), "row count mismatch for ${tag}")
for (int i = 0; i < expected.size(); i++) {
for (int j = 0; j < expected[i].size(); j++) {
assertEquals(expected[i][j], String.valueOf(actual[i][j]),
"value mismatch for ${tag} at row ${i} col ${j}")
}
}
}

// 1. Default session: on master this plans VMaterializeNode (TopN lazy
// materialization + rowid fetch); guards that path stays correct too.
assertRows(sql("""
SELECT element_at(c[1][1], 1), element_at(c[1][1], 'col17')
FROM ${dictTable} WHERE k1 IS NOT NULL ORDER BY k1 LIMIT 10
"""), expectedTwoCols, "dict table, default session")

// AGG merge path, pure default session (no topn involved at all).
assertRows(sql("""
SELECT element_at(c[1][1], 1), element_at(c[1][1], 'col17')
FROM ${aggTable} WHERE k1 >= 1 AND k1 <= 10 ORDER BY k1
"""), expectedTwoCols, "agg table, default session")
// Rows from the second rowset must merge and read correctly too.
assertRows(sql("""
SELECT element_at(c[1][1], 'col17')
FROM ${aggTable} WHERE k1 >= 1501 AND k1 <= 1510 ORDER BY k1
"""), (1501..1510).collect { ["s" + it] }, "agg table second rowset, default session")

// 2. Force the inline topn scan path (no VMaterializeNode). This is the exact
// path that used to fail with
// "[E-3110] Method insert_many_dict_data is not supported for TINYINT".
sql "SET topn_lazy_materialization_threshold = -1"

assertRows(sql("""
SELECT element_at(c[1][1], 1), element_at(c[1][1], 'col17')
FROM ${dictTable} WHERE k1 IS NOT NULL ORDER BY k1 LIMIT 10
"""), expectedTwoCols, "dict table, inline topn path")

// Single pruned child: the misalignment shifts col17 data onto col1 (INT),
// which used to fail with "... is not supported for INT".
assertRows(sql("""
SELECT element_at(c[1][1], 'col17')
FROM ${dictTable} WHERE k1 IS NOT NULL ORDER BY k1 LIMIT 10
"""), expectedOneCol, "dict table single child, inline topn path")

// Same-typed children: the shifted decode does not error out, so the pairing
// loop used to run past the pruned iterator vector and SIGSEGV the BE; a
// partial regression could also return col1's values (1000001..) here.
assertRows(sql("""
SELECT element_at(c[1][1], 'col3')
FROM ${intTable} WHERE k1 IS NOT NULL ORDER BY k1 LIMIT 10
"""), expectedIntCol, "int table last child, inline topn path")

sql "DROP TABLE IF EXISTS ${dictTable}"
sql "DROP TABLE IF EXISTS ${intTable}"
sql "DROP TABLE IF EXISTS ${aggTable}"
}
Loading