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


##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -171,6 +175,24 @@ public class SchemaChangeHandler extends AlterHandler {
 
     public final Map<Long, IndexChangeJob> runnableIndexChangeJob = 
Maps.newConcurrentMap();
 
+    // The partitions of a BUILD IMMEDIATE ADD INDEX that have no build job 
yet.
+    private static class PendingIndexBuild {
+        private final long dbId;
+        private final List<Index> indexes;
+        private final Set<String> partitionNames;
+
+        private PendingIndexBuild(long dbId, List<Index> indexes, Set<String> 
partitionNames) {
+            this.dbId = dbId;
+            this.indexes = indexes;
+            this.partitionNames = partitionNames;
+        }
+    }
+
+    // Pending BUILD IMMEDIATE builds by table id. Applying the index metadata 
of a BUILD IMMEDIATE ADD INDEX, on the
+    // master or in replay, adds an entry, and every build job of one of its 
partitions removes that partition. A
+    // master that takes over after the metadata was journaled but before all 
build jobs were submits the rest.
+    private final Map<Long, PendingIndexBuild> pendingIndexBuilds = 
Maps.newConcurrentMap();

Review Comment:
   [P2] Preserve pending build intent in checkpoint images
   
   This map is reconstructed only by replaying the ADD-index journal record, 
but it is absent from image persistence: `Env.saveAlterJob/loadAlterJob` retain 
only the finished `AlterJobV2`, without `buildIndexIds`. A finalized checkpoint 
cutoff can fall after the metadata record and before the partition-job records. 
If the master stops with some jobs still unjournaled, loading that image skips 
the covered metadata record and never reconstructs the missing builds, leaving 
historical data unindexed. Persist and restore the pending intent in 
checkpointed metadata, and cover an image roundtrip at this inter-record 
boundary.



##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -3914,6 +3971,175 @@ private String getCloudClusterName() throws 
UserException {
         return clusterName;
     }
 
+    // How one ADD INDEX runs: LIGHT only changes metadata, so only data 
written afterwards gets the index;
+    // LIGHT_AND_BUILD also builds the existing data of every partition 
through index change jobs;
+    // HEAVY rewrites the existing data in a schema change job.
+    private enum AddIndexPath { LIGHT, LIGHT_AND_BUILD, HEAVY }
+
+    // Resolves the path of every ADD INDEX in alterOps. An index added with 
BUILD DEFERRED keeps the existing
+    // data unindexed, so it can not share a statement with a clause that 
rewrites or changes that data.
+    private static Map<CreateIndexOp, AddIndexPath> 
resolveAddIndexPaths(List<AlterOp> alterOps,
+            OlapTable olapTable, boolean enableAddIndexForNewData) throws 
DdlException {
+        boolean onlyAddIndex = alterOps.stream().allMatch(alterOp -> alterOp 
instanceof CreateIndexOp);
+        boolean sniiTable = olapTable.getInvertedIndexFileStorageFormat() == 
TInvertedIndexFileStorageFormat.SNII;
+        boolean tableHasValuesIndex = 
olapTable.getIndexes().stream().anyMatch(Index::isVariantValuesIndex);
+        // A partition with a storage policy may hold rowsets that have cooled 
to remote storage.
+        boolean mayHaveCooledData = 
olapTable.getPartitionIds().stream().anyMatch(partitionId ->
+                
!Strings.isNullOrEmpty(olapTable.getPartitionInfo().getDataProperty(partitionId).getStoragePolicy()));
+        Map<CreateIndexOp, AddIndexPath> paths = new IdentityHashMap<>();
+        for (AlterOp alterOp : alterOps) {
+            if (alterOp instanceof CreateIndexOp) {
+                CreateIndexOp createIndexOp = (CreateIndexOp) alterOp;
+                Index index = createIndexOp.getIndex();
+                // BUILD INDEX can not build an index on a VARIANT column, see 
the BuildIndexOp branch of process.
+                Optional<Column> variantColumn = 
olapTable.getBaseSchema().stream()
+                        .filter(column -> column.getType().isVariantType())
+                        .filter(column -> 
index.getColumns().stream().anyMatch(column.getName()::equalsIgnoreCase))
+                        .findFirst();
+                paths.put(createIndexOp, resolveAddIndexPath(index, 
createIndexOp.getBuildMode().orElse(null),
+                        enableAddIndexForNewData, sniiTable, onlyAddIndex, 
mayHaveCooledData, tableHasValuesIndex,
+                        variantColumn));
+            }
+        }
+        boolean hasDeferred = paths.keySet().stream()
+                .anyMatch(createIndexOp -> 
createIndexOp.getBuildMode().orElse(null) == BuildMode.DEFERRED);
+        if (hasDeferred && (!onlyAddIndex || 
paths.containsValue(AddIndexPath.HEAVY))) {
+            throw new DdlException("BUILD DEFERRED can not be combined with 
other schema changes or with an index"
+                    + " that rewrites the existing data, please run them in 
separate statements.");
+        }
+        return paths;
+    }
+
+    private static AddIndexPath resolveAddIndexPath(Index index, BuildMode 
buildMode,
+            boolean enableAddIndexForNewData, boolean sniiTable, boolean 
onlyAddIndex, boolean mayHaveCooledData,
+            boolean tableHasValuesIndex, Optional<Column> variantColumn) 
throws DdlException {
+        boolean lightEnabled = Config.enable_light_index_change;
+        if (buildMode == null) {
+            return lightEnabled && 
index.isLightAddIndexSupported(enableAddIndexForNewData)
+                    ? AddIndexPath.LIGHT : AddIndexPath.HEAVY;
+        }
+        if (buildMode == BuildMode.DEFERRED) {
+            if (!lightEnabled) {
+                throw new DdlException("BUILD DEFERRED requires 
enable_light_index_change=true");
+            }
+            if (!index.isLightAddIndexSupported(true)) {
+                throw new DdlException("BUILD DEFERRED is not supported for " 
+ index.getIndexType() + " index "
+                        + index.getIndexName() + " in " + 
(Config.isCloudMode() ? "cloud" : "local") + " mode");
+            }
+            return AddIndexPath.LIGHT;
+        }
+        if (index.isVariantValuesIndex()) {
+            throw new DdlException("VARIANT values index supports only BUILD 
DEFERRED");
+        }
+        // Where adding the index is heavy by default, the heavy schema change 
already indexes the existing data.
+        // Next to other clauses, the statement runs as one heavy schema 
change, which indexes all data as well.
+        // BUILD INDEX builds only local rowsets, so data that may have cooled 
also needs the heavy schema change.
+        if (!lightEnabled || !index.isLightAddIndexSupported(false) || 
!onlyAddIndex || mayHaveCooledData) {
+            // A local heavy schema change links the existing segments unless 
another change forces a rewrite,
+            // because BE does not compare ANN indexes when it picks the 
schema change kind (cloud rowsets are
+            // remote and always rewritten). Linked segments get no ANN index.
+            if (index.getIndexType() == IndexType.ANN && 
Config.isNotCloudMode()) {
+                throw new DdlException("BUILD IMMEDIATE for ANN index " + 
index.getIndexName() + " must run alone,"
+                        + " on a table without a storage policy and with 
enable_light_index_change=true,"
+                        + " because a heavy schema change does not build ANN 
indexes for existing data");
+            }
+            return AddIndexPath.HEAVY;
+        }
+        Preconditions.checkState(index.isBuildIndexSupported(sniiTable), 
index.getIndexName());
+        if (tableHasValuesIndex) {
+            throw new DdlException("BUILD IMMEDIATE is not supported on a 
table with a VARIANT values index,"
+                    + " because BUILD INDEX is not supported on it");
+        }
+        if (variantColumn.isPresent()) {
+            throw new DdlException("BUILD IMMEDIATE is not supported for index 
" + index.getIndexName()
+                    + " on VARIANT column " + variantColumn.get().getName()
+                    + ", because BUILD INDEX can not build it; use BUILD 
DEFERRED instead");
+        }
+        return AddIndexPath.LIGHT_AND_BUILD;
+    }
+
+    // Called with the table write lock held, right after the index metadata 
of a BUILD IMMEDIATE ADD INDEX is
+    // applied, so the entry covers exactly the partitions that the build jobs 
are submitted for.
+    private void recordPendingIndexBuild(long dbId, OlapTable olapTable, 
List<Index> indexes) {
+        Set<String> partitionNames = 
Sets.newConcurrentHashSet(olapTable.getPartitionNames());
+        pendingIndexBuilds.put(olapTable.getId(), new PendingIndexBuild(dbId, 
indexes, partitionNames));

Review Comment:
   [P2] Track outstanding builds per index and partition
   
   After failover, `i1` can remain pending on a NORMAL table. If a client adds 
`i2 BUILD IMMEDIATE` on another column before the recovery daemon runs, this 
`put` replaces `i1`; the `i2` jobs then clear the replacement, so `i1` never 
receives its missing jobs. Clearing has the same missing index dimension: for 
pending `[i1,i2]`, a client `BUILD INDEX i1` removes that partition for both 
indexes because `hasAlterInvertedIndex` matches any overlap. Readiness and 
table locking do not require recovery to run first. Preserve outstanding work 
per index/partition when registering and clearing jobs instead of replacing or 
clearing the whole group.



##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -3914,6 +3971,175 @@ private String getCloudClusterName() throws 
UserException {
         return clusterName;
     }
 
+    // How one ADD INDEX runs: LIGHT only changes metadata, so only data 
written afterwards gets the index;
+    // LIGHT_AND_BUILD also builds the existing data of every partition 
through index change jobs;
+    // HEAVY rewrites the existing data in a schema change job.
+    private enum AddIndexPath { LIGHT, LIGHT_AND_BUILD, HEAVY }
+
+    // Resolves the path of every ADD INDEX in alterOps. An index added with 
BUILD DEFERRED keeps the existing
+    // data unindexed, so it can not share a statement with a clause that 
rewrites or changes that data.
+    private static Map<CreateIndexOp, AddIndexPath> 
resolveAddIndexPaths(List<AlterOp> alterOps,
+            OlapTable olapTable, boolean enableAddIndexForNewData) throws 
DdlException {
+        boolean onlyAddIndex = alterOps.stream().allMatch(alterOp -> alterOp 
instanceof CreateIndexOp);
+        boolean sniiTable = olapTable.getInvertedIndexFileStorageFormat() == 
TInvertedIndexFileStorageFormat.SNII;
+        boolean tableHasValuesIndex = 
olapTable.getIndexes().stream().anyMatch(Index::isVariantValuesIndex);
+        // A partition with a storage policy may hold rowsets that have cooled 
to remote storage.
+        boolean mayHaveCooledData = 
olapTable.getPartitionIds().stream().anyMatch(partitionId ->
+                
!Strings.isNullOrEmpty(olapTable.getPartitionInfo().getDataProperty(partitionId).getStoragePolicy()));
+        Map<CreateIndexOp, AddIndexPath> paths = new IdentityHashMap<>();
+        for (AlterOp alterOp : alterOps) {
+            if (alterOp instanceof CreateIndexOp) {
+                CreateIndexOp createIndexOp = (CreateIndexOp) alterOp;
+                Index index = createIndexOp.getIndex();
+                // BUILD INDEX can not build an index on a VARIANT column, see 
the BuildIndexOp branch of process.
+                Optional<Column> variantColumn = 
olapTable.getBaseSchema().stream()
+                        .filter(column -> column.getType().isVariantType())
+                        .filter(column -> 
index.getColumns().stream().anyMatch(column.getName()::equalsIgnoreCase))
+                        .findFirst();
+                paths.put(createIndexOp, resolveAddIndexPath(index, 
createIndexOp.getBuildMode().orElse(null),
+                        enableAddIndexForNewData, sniiTable, onlyAddIndex, 
mayHaveCooledData, tableHasValuesIndex,
+                        variantColumn));
+            }
+        }
+        boolean hasDeferred = paths.keySet().stream()
+                .anyMatch(createIndexOp -> 
createIndexOp.getBuildMode().orElse(null) == BuildMode.DEFERRED);
+        if (hasDeferred && (!onlyAddIndex || 
paths.containsValue(AddIndexPath.HEAVY))) {
+            throw new DdlException("BUILD DEFERRED can not be combined with 
other schema changes or with an index"
+                    + " that rewrites the existing data, please run them in 
separate statements.");
+        }
+        return paths;
+    }
+
+    private static AddIndexPath resolveAddIndexPath(Index index, BuildMode 
buildMode,
+            boolean enableAddIndexForNewData, boolean sniiTable, boolean 
onlyAddIndex, boolean mayHaveCooledData,
+            boolean tableHasValuesIndex, Optional<Column> variantColumn) 
throws DdlException {
+        boolean lightEnabled = Config.enable_light_index_change;
+        if (buildMode == null) {
+            return lightEnabled && 
index.isLightAddIndexSupported(enableAddIndexForNewData)
+                    ? AddIndexPath.LIGHT : AddIndexPath.HEAVY;
+        }
+        if (buildMode == BuildMode.DEFERRED) {
+            if (!lightEnabled) {
+                throw new DdlException("BUILD DEFERRED requires 
enable_light_index_change=true");
+            }
+            if (!index.isLightAddIndexSupported(true)) {
+                throw new DdlException("BUILD DEFERRED is not supported for " 
+ index.getIndexType() + " index "
+                        + index.getIndexName() + " in " + 
(Config.isCloudMode() ? "cloud" : "local") + " mode");
+            }
+            return AddIndexPath.LIGHT;
+        }
+        if (index.isVariantValuesIndex()) {
+            throw new DdlException("VARIANT values index supports only BUILD 
DEFERRED");
+        }
+        // Where adding the index is heavy by default, the heavy schema change 
already indexes the existing data.
+        // Next to other clauses, the statement runs as one heavy schema 
change, which indexes all data as well.
+        // BUILD INDEX builds only local rowsets, so data that may have cooled 
also needs the heavy schema change.
+        if (!lightEnabled || !index.isLightAddIndexSupported(false) || 
!onlyAddIndex || mayHaveCooledData) {

Review Comment:
   [P2] Resolve the heavy-path interaction before accepting ANN IMMEDIATE
   
   On a local DUP_KEYS table with existing rows, one ALTER adding an ANN index 
with `BUILD IMMEDIATE` and an NGRAM_BF index on another column with `BUILD 
IMMEDIATE` passes this check: `onlyAddIndex` is true, so ANN resolves to 
LIGHT_AND_BUILD while NGRAM resolves to HEAVY. The statement-wide 
`requiresHeavyChange` then suppresses `submitBuildJobs`. BE's 
`has_schema_index_diff` compares ordinary bloom-filter flags and INVERTED 
indexes, neither of which changes for ANN/NGRAM, so unchanged local segments 
take `LinkedSchemaChange` and acquire no ANN index. The statement can finish 
without its promised ANN backfill. Resolve all clauses together and reject this 
combination or force a physical rewrite.



-- 
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