hello-stephen commented on code in PR #70408:
URL: https://github.com/apache/doris/pull/70408#discussion_r4792966668


##########
be/src/exec/common/variant_util.cpp:
##########
@@ -183,6 +183,43 @@ PathToDataTypes collect_regular_types_outside_nested_group(
     return regular_path_to_data_types;
 }
 
+namespace {
+
+// The dynamic paths of a doc column, chosen once for all doc buckets: each 
bucket writer sees only
+// its own paths. Typed paths do not count.
+void choose_doc_compaction_subpaths(const TabletSchema& target, const 
TabletColumn& column,
+                                    const PathToNoneNullValues& path_stats,
+                                    VariantCompactionPaths& paths_set_info) {
+    PathToNoneNullValues dynamic_path_stats;
+    for (const auto& [path, size] : path_stats) {

Review Comment:
   [P2] Bound the extra memory for DOC path selection. Compaction now 
aggregates all distinct DOC paths and then resolves templates and copies every 
dynamic path into a second map before checking the budget. With V2/count-zero 
it selects none, and with V1/count-zero each bucket can select every local path 
directly. For a positive budget, `get_subpaths` retains every unselected path 
in `sparse_path_set`, which the DOC writer never reads. Skip the global stats 
pass for zero budgets and retain only selected DOC paths for a positive budget.



##########
fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnTest.java:
##########
@@ -248,6 +250,50 @@ public void testSchemaChangeDoubleToVarchar() throws 
DdlException {
         });
     }
 
+    @Test
+    public void testVariantSerializeTypeReachesThriftAndPb() throws 
DdlException {
+        Column v1Zero = new Column("v", new VariantType(new ArrayList<>(), 0, 
false, 10000, 1, false, 0L, 64, false,
+                TVariantSerializeType.V1), false, null, true, null, "");
+        Column v2Zero = new Column("v", new VariantType(new ArrayList<>(), 0, 
false, 10000, 1, false, 0L, 64, false,
+                TVariantSerializeType.V2), false, null, true, null, "");
+        Assertions.assertEquals(TVariantSerializeType.V2,
+                ColumnToThrift.toThrift(v2Zero).getVariantSerializeType());
+        
Assertions.assertEquals(OlapFile.VariantSerializeTypePB.VARIANT_SERIALIZE_V2,
+                ColumnToProtobuf.toPb(v2Zero, null, 
null).getVariantSerializeType());
+        
Assertions.assertEquals(OlapFile.VariantSerializeTypePB.VARIANT_SERIALIZE_V1,
+                ColumnToProtobuf.toPb(v1Zero, null, 
null).getVariantSerializeType());
+    }
+
+    @Test
+    public void testVariantSchemaChangeOfTheRowThreshold() throws DdlException 
{
+        // a new column without doc mode can change its row threshold
+        Column ordinary = new Column("v", new VariantType(new ArrayList<>(), 
2048, false, 10000, 2, false, 0L, 0,
+                false, TVariantSerializeType.V2), false, null, true, null, "");
+        ordinary.checkSchemaChangeAllowed(new Column("v", new VariantType(new 
ArrayList<>(), 2048, false, 10000, 2,
+                false, 100L, 0, false, TVariantSerializeType.V2), false, null, 
true, null, ""));
+        // a column of an older version with a count above 0 behaves as a new 
one and takes a threshold too
+        Column oldOrdinary = new Column("v", new VariantType(new 
ArrayList<>(), 2048, false, 10000, 2, false, 0L, 0,
+                false, TVariantSerializeType.V1), false, null, true, null, "");
+        oldOrdinary.checkSchemaChangeAllowed(new Column("v", new 
VariantType(new ArrayList<>(), 2048, false, 10000, 2,
+                false, 100L, 0, false, TVariantSerializeType.V2), false, null, 
true, null, ""));
+        // without doc mode a count of 0 on a column of an older version 
extracts every path, so it takes none
+        Column oldCountZero = new Column("v", new VariantType(new 
ArrayList<>(), 0, false, 10000, 2, false, 0L, 0,
+                false, TVariantSerializeType.V1), false, null, true, null, "");
+        Assertions.assertThrows(DdlException.class, () -> 
oldCountZero.checkSchemaChangeAllowed(new Column("v",
+                new VariantType(new ArrayList<>(), 0, false, 10000, 2, false, 
100L, 0, false,
+                        TVariantSerializeType.V2), false, null, true, null, 
"")));

Review Comment:
   [P3] Keep both operands V1 in the negative threshold and shard tests. Both 
target types switch to V2 at count zero, so `checkSchemaChangeAllowed` throws 
the serialize-type error before reaching either intended guard. Use V1 for both 
targets and assert the specific row-threshold or shard error.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/types/VariantType.java:
##########
@@ -130,14 +152,136 @@ public DataType conversion() {
                                 .collect(Collectors.toList()), 
variantMaxSubcolumnsCount, enableTypedPathsToSparse,
                                     variantMaxSparseColumnStatisticsSize, 
variantSparseHashShardCount,
                                     enableVariantDocMode, 
variantDocMaterializationMinRows,
-                                    variantDocShardCount, enableNestedGroup);
+                                    variantDocShardCount, enableNestedGroup, 
variantSerializeType);
+    }
+
+    /** This type with the given serialize type, as a new instance. */
+    public VariantType withSerializeType(TVariantSerializeType serializeType) {
+        return new VariantType(predefinedFields, variantMaxSubcolumnsCount, 
enableTypedPathsToSparse,
+                variantMaxSparseColumnStatisticsSize, 
variantSparseHashShardCount, enableVariantDocMode,
+                variantDocMaterializationMinRows, variantDocShardCount, 
enableNestedGroup, serializeType);
+    }
+
+    /**
+     * Collects {@link Alias} definitions and {@link LogicalCTEConsumer} slot 
mappings across an
+     * analyzed plan so output slots can be traced back to their defining 
expressions.
+     */
+    public static Map<ExprId, Expression> collectExprDefinitions(Plan 
analyzedPlan) {
+        Map<ExprId, Expression> definitions = Maps.newHashMap();
+        collectExprDefinitions(analyzedPlan, definitions);
+        return definitions;
+    }
+
+    private static void collectExprDefinitions(Plan node, Map<ExprId, 
Expression> definitions) {
+        for (Plan extra : node.extraPlans()) {
+            collectExprDefinitions(extra, definitions);
+        }
+        for (Plan child : node.children()) {
+            collectExprDefinitions(child, definitions);
+        }
+        if (node instanceof LogicalCTEConsumer) {
+            ((LogicalCTEConsumer) node).getConsumerToProducerOutputMap()
+                    .forEach((consumer, producer) -> 
definitions.putIfAbsent(consumer.getExprId(), producer));
+        } else if (node instanceof PhysicalCTEConsumer) {
+            ((PhysicalCTEConsumer) 
node).getProducerToConsumerSlotMap().entries()
+                    .forEach(e -> 
definitions.putIfAbsent(e.getValue().getExprId(), e.getKey()));
+        }
+        for (Expression expr : node.getExpressions()) {
+            if (expr instanceof Alias) {
+                Alias alias = (Alias) expr;
+                definitions.putIfAbsent(alias.getExprId(), alias.child());
+            }
+        }
+    }
+
+    /**
+     * Resolves an analyzed query expression's type for a newly created CTAS, 
sync MV, or async MTMV column.
+     *
+     * <p>A direct whole-column reference to a managed table column keeps its 
storage layout (and its
+     * V1/V2 serialize type when {@code keepManagedSerializeType} is true for 
MVs, whereas CTAS
+     * upgrades it to V2 and strips source-table templates). An explicit SQL 
{@code CAST(... AS VARIANT<...>)}
+     * preserves its declared V2 properties and templates, while every other 
VARIANT expression
+     * (window/aggregate outputs such as {@code first_value}, sub-paths, 
{@code parse_to_variant},
+     * {@code coalesce}, {@code UNION}, external catalogs, TVFs) uses fresh 
default V2 storage properties.
+     */
+    public static DataType resolveForNewColumn(Expression expr, @Nullable 
ConnectContext ctx,
+            boolean keepManagedSerializeType) {
+        return resolveForNewColumn(expr, ImmutableMap.of(), ctx, 
keepManagedSerializeType);
+    }
+
+    /** Resolves {@code expr} using pre-collected analyzed-plan alias/CTE 
definitions. */
+    public static DataType resolveForNewColumn(Expression expr, Map<ExprId, 
Expression> exprDefinitions,
+            @Nullable ConnectContext ctx, boolean keepManagedSerializeType) {
+        DataType convertedType = expr.getDataType().conversion();
+        if (!(convertedType instanceof VariantType)) {
+            return convertedType;
+        }
+        Expression unwrapped = unwrapExpression(expr, exprDefinitions);
+        VariantType unwrappedVariant = (VariantType) 
unwrapped.getDataType().conversion();
+        boolean managedRootColumn = unwrapped instanceof SlotReference
+                && ((SlotReference) unwrapped).getOriginalColumn().isPresent()
+                && ((SlotReference) unwrapped).getSubPath().isEmpty()
+                && ((SlotReference) 
unwrapped).getOriginalTable().filter(TableIf::isManagedTable).isPresent();
+        if (managedRootColumn) {
+            return keepManagedSerializeType
+                    ? unwrappedVariant
+                    : 
unwrappedVariant.withoutPredefinedFields().withSerializeType(TVariantSerializeType.V2);
+        }
+        if (unwrapped instanceof Cast && ((Cast) unwrapped).isExplicitType()) {
+            return 
unwrappedVariant.withSerializeType(TVariantSerializeType.V2);
+        }
+        return LogicalPlanBuilder.defaultStorageVariantType(ctx);
+    }
+
+    private static Expression unwrapExpression(Expression expr, Map<ExprId, 
Expression> exprDefinitions) {
+        Expression unwrapped = expr;
+        Set<ExprId> visited = Sets.newHashSet();
+        while (true) {
+            if (unwrapped instanceof Alias) {
+                unwrapped = ((Alias) unwrapped).child();
+            } else if (unwrapped instanceof SlotReference) {
+                ExprId exprId = ((SlotReference) unwrapped).getExprId();
+                Expression defined = exprDefinitions.get(exprId);
+                if (defined != null && visited.add(exprId)) {
+                    unwrapped = defined;
+                } else {
+                    break;
+                }
+            } else {
+                break;
+            }
+        }
+        return unwrapped;
+    }
+
+    /**
+     * Whether {@code expr} is a derived {@code VARIANT} output (such as a 
pruned sub-path, scalar/window/agg
+     * function over {@code VARIANT}, or set-operation slot) that pre-4.2 
could persist with an ancestor
+     * column's template or {@code NestedGroup}, rather than a direct column 
projection or explicit {@code CAST}.
+     */
+    public static boolean isLegacyDerivedVariantOutput(Expression expr,
+            Map<ExprId, Expression> exprDefinitions) {
+        if (!(expr.getDataType().conversion() instanceof VariantType)) {
+            return false;
+        }
+        Expression unwrapped = unwrapExpression(expr, exprDefinitions);
+        if (unwrapped instanceof SlotReference) {
+            SlotReference slot = (SlotReference) unwrapped;
+            return !slot.getSubPath().isEmpty() || 
!slot.getOriginalColumn().isPresent();
+        }
+        if (unwrapped instanceof Cast && ((Cast) unwrapped).isExplicitType()) {
+            return false;
+        }
+        return unwrapped.anyMatch(node -> node != unwrapped

Review Comment:
   [P2] Check the current template for legacy forwarding expressions. Before 
upgrade, an async MV with `Project(k, fv) → Window(first_value(v) OVER (ORDER 
BY k) AS fv) → View(v VARIANT<'x':INT>)` stores the forwarded INT template in 
`fv`. After upgrade, alter the view to project a `VARIANT<'x':STRING>` from 
another table. The new inference gives the window result an empty V2 template, 
and this predicate grants the legacy exemption simply because the expression 
has a VARIANT child. Complete refresh then accepts the schema change and writes 
into the existing INT template, so `x='001'` is stored as `1`. Preserve enough 
template information to distinguish an unchanged legacy expression from a 
changed input, and cover ALTER VIEW followed by complete refresh.



##########
be/src/exec/common/variant_util.cpp:
##########
@@ -1274,9 +1342,27 @@ Status 
VariantCompactionUtil::get_extended_compaction_schema(
             for (int b = 0; b < bucket_num; ++b) {
                 
output_schema->append_column(create_doc_value_compaction_column(*column, b));
             }
+            choose_doc_compaction_subpaths(*target, *column, 
extended_info.path_to_none_null_values,

Review Comment:
   [P2] Rank DOC paths from the rows compaction writes. With a budget of 1 and 
threshold of 0, load three low-key rows containing `p` and one containing `r`, 
then load a separate rowset containing only `q`. With an inherited inverted 
index, the second rowset materializes and indexes `q`. Delete the three `p` 
rows by key and full-compact. The planner still ranks `p` first from raw input 
DOC stats, but the writer sees only the surviving `r` and `q` rows. It leaves 
`q` DOC-only, so `SEARCH('v.q:hit')` now fails with the unavailable-index 
error. Choose paths from each output segment’s surviving rows, across its DOC 
shards, and cover a delete before compaction.



##########
regression-test/suites/variant_p0/dotted_key_escape_sparse_promotion.groovy:
##########
@@ -25,7 +25,7 @@ suite("dotted_key_escape_sparse_promotion", 
"p0,nonConcurrent") {
     sql "set batch_size=1024"
     sql "set debug_variant_enable_doc_mode=false"
     sql "set debug_variant_enable_nested_group=false"
-    sql "set debug_variant_max_subcolumns_count=0"
+    sql "set debug_variant_max_subcolumns_count=2048"

Review Comment:
   [P2] Pin the row threshold so the sparse-promotion test exercises promotion. 
This suite leaves `debug_variant_doc_materialization_min_rows` at its fuzzy 
value. When that value is 16–19, the three five-row loads and their first full 
compaction all fall below it. The result and compaction-status assertions can 
still pass while every `hot_i` and `a` path stays sparse. Set the debug 
threshold to zero here, as `sparse_ancestor_promotion_extended.groovy` does.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to