airborne12 commented on code in PR #71130:
URL: https://github.com/apache/doris/pull/71130#discussion_r4749822322


##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -3914,6 +3929,92 @@ 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);
+        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, 
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 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.
+        if (!lightEnabled || !index.isLightAddIndexSupported(false) || 
!onlyAddIndex) {
+            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;

Review Comment:
   Update in 3c79c228cb3: this workaround is removed. For this PR we decided 
that BUILD IMMEDIATE keeps exactly the guarantees of a manual `BUILD INDEX` 
where it submits build jobs, and of an ADD INDEX without the clause where it 
runs the heavy schema change, instead of special-casing gaps it inherits from 
them.
   
   The gap here is pre-existing in BUILD INDEX: 
`Tablet::pick_candidate_rowsets_to_build_inverted_index` keeps only local 
rowsets, so a manual `BUILD INDEX` skips cooled rowsets in the same way. It 
will be fixed in BUILD INDEX in a separate PR (first fail the job instead of 
finishing it, then build remote rowsets), which fixes both paths. The 
storage-policy guard and reservation added later for the same reason are 
removed as well, and `Alter` is unchanged by this PR again. 
`testAddIndexBuildImmediateWithStoragePolicyBuildsWithJobs` now asserts build 
jobs on a table with a storage policy.
   



##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -3095,6 +3110,7 @@ public void updatePartitionsProperties(Database db, 
String tableName, List<Strin
             }
         }
         String storagePolicy = 
properties.get(PropertyAnalyzer.PROPERTIES_STORAGE_POLICY);
+        checkNoIndexBuildBeforeStoragePolicy(db.getId(), olapTable, 
storagePolicy);

Review Comment:
   Update in 3c79c228cb3: this workaround is removed. For this PR we decided 
that BUILD IMMEDIATE keeps exactly the guarantees of a manual `BUILD INDEX` 
where it submits build jobs, and of an ADD INDEX without the clause where it 
runs the heavy schema change, instead of special-casing gaps it inherits from 
them.
   
   This race only mattered for the cooled-data routing and the storage-policy 
guard, which are both removed, so `Alter` is unchanged by this PR again and 
there is nothing left to serialize here. Cooled rowsets skipped by BUILD INDEX, 
which a manual `BUILD INDEX` hits in the same way, will be fixed in BUILD INDEX 
in a separate PR.
   



##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -3914,6 +3929,97 @@ 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) {
+            return AddIndexPath.HEAVY;

Review Comment:
   Update in 3c79c228cb3: this workaround is removed. For this PR we decided 
that BUILD IMMEDIATE keeps exactly the guarantees of a manual `BUILD INDEX` 
where it submits build jobs, and of an ADD INDEX without the clause where it 
runs the heavy schema change, instead of special-casing gaps it inherits from 
them.
   
   The gap here is pre-existing in the local heavy schema change: 
`has_schema_index_diff` does not compare ANN indexes, so a heavy schema change 
that only adds an ANN index links the old segments, also for an ADD INDEX 
without the clause. #71134 fixes that on BE. `testAddAnnIndexBuildImmediate` 
now asserts BUILD INDEX jobs when the ANN index is alone, and the heavy schema 
change next to ADD COLUMN or a heavy ADD INDEX, as without the clause.
   



##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -3914,6 +3929,136 @@ 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();
+                // BUILD INDEX builds only the base tablets, also when a 
rollup holds the column.
+                boolean onRollup = 
olapTable.getVisibleIndexIdToMeta().entrySet().stream()
+                        .filter(entry -> entry.getKey() != 
olapTable.getBaseIndexId())
+                        .flatMap(entry -> 
entry.getValue().getSchema().stream())
+                        .anyMatch(column -> 
index.getColumns().stream().anyMatch(column.getName()::equalsIgnoreCase));
+                paths.put(createIndexOp, resolveAddIndexPath(index, 
createIndexOp.getBuildMode().orElse(null),
+                        enableAddIndexForNewData, sniiTable, onlyAddIndex, 
mayHaveCooledData || onRollup,
+                        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.");
+        }
+        // An index that needs the heavy schema change makes the whole 
statement run as one, which builds no ANN
+        // index for existing data (see resolveAddIndexPath), so an ANN index 
that would get BUILD INDEX jobs alone
+        // can not join it.
+        if (paths.containsValue(AddIndexPath.HEAVY)) {
+            Optional<Index> annToBuild = paths.entrySet().stream()
+                    .filter(entry -> entry.getValue() == 
AddIndexPath.LIGHT_AND_BUILD)
+                    .map(entry -> entry.getKey().getIndex())
+                    .filter(index -> index.getIndexType() == IndexType.ANN)
+                    .findFirst();
+            if (annToBuild.isPresent()) {
+                throw annImmediateOnHeavyPath(annToBuild.get());
+            }
+        }
+        return paths;
+    }
+
+    private static DdlException annImmediateOnHeavyPath(Index index) {
+        return new DdlException("BUILD IMMEDIATE for ANN index " + 
index.getIndexName() + " must run alone,"
+                + " on a table without a storage policy or a rollup that holds 
its column and with"
+                + " enable_light_index_change=true, because a heavy schema 
change does not build ANN indexes for"
+                + " existing data");
+    }
+
+    // notBuiltByBuildIndex: some existing data of the index that BUILD INDEX 
does not build, in a partition that may
+    // have cooled to remote storage or in a rollup that holds an index column.
+    private static AddIndexPath resolveAddIndexPath(Index index, BuildMode 
buildMode,
+            boolean enableAddIndexForNewData, boolean sniiTable, boolean 
onlyAddIndex, boolean notBuiltByBuildIndex,
+            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 the local rowsets of the base tablets, so 
data that may have cooled and the data of a
+        // rollup that holds an index column also need the heavy schema change.
+        if (!lightEnabled || !index.isLightAddIndexSupported(false) || 
!onlyAddIndex || notBuiltByBuildIndex) {
+            // A local heavy schema change links the existing segments unless 
another change forces a rewrite,
+            // because BE compares neither ANN nor NGRAM_BF indexes when it 
picks the schema change kind (cloud
+            // rowsets are remote and always rewritten). Linked segments get 
no such index.
+            if (index.getIndexType() == IndexType.ANN && 
Config.isNotCloudMode()) {
+                throw annImmediateOnHeavyPath(index);
+            }
+            if (index.getIndexType() == IndexType.NGRAM_BF && 
Config.isNotCloudMode()) {
+                throw new DdlException("BUILD IMMEDIATE is not supported for 
NGRAM_BF index " + index.getIndexName()
+                        + " in local mode, because a heavy schema change does 
not build NGRAM_BF indexes for"
+                        + " existing data; use BUILD DEFERRED instead");
+            }
+            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;

Review Comment:
   Update in 3c79c228cb3: this workaround is removed. For this PR we decided 
that BUILD IMMEDIATE keeps exactly the guarantees of a manual `BUILD INDEX` 
where it submits build jobs, and of an ADD INDEX without the clause where it 
runs the heavy schema change, instead of special-casing gaps it inherits from 
them.
   
   The gap here is pre-existing in BUILD INDEX: its SNII rewrite drops the path 
indexes of a VARIANT inverted index, so a manual `BUILD INDEX` of any other 
column on such a table hits it today. It will be fixed in BUILD INDEX in a 
separate PR, which fixes both paths. 
`testAddIndexBuildImmediateOnSniiTableWithVariantIndexBuildsWithJobs` now 
asserts build jobs on such a table.
   



##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -2740,6 +2752,9 @@ public int getAsInt() {
                 // For light index changes, directly modify table metadata 
first.
                 modifyTableLightSchemaChange(rawSql, db, olapTable, 
indexSchemaMap, newIndexes,
                         alterIndexes, isDropIndex, jobId, false, propertyMap);
+                if (!indexesToBuild.isEmpty()) {
+                    submitBuildJobs(db, olapTable, indexSchemaMap, 
indexesToBuild);

Review Comment:
   Update: #71137 is on hold. As the PR description states, a master failure 
between the metadata and build-job journal writes leaves the index as if added 
with BUILD DEFERRED, and `BUILD INDEX` completes it. BUILD INDEX jobs 
themselves are not written to the FE image, so a failover can lose them too; 
that will be fixed in BUILD INDEX first, and only then will we decide whether 
BUILD IMMEDIATE still needs the extra bookkeeping of #71137.
   



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