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


##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -4099,6 +4372,7 @@ public void replayIndexChangeJob(IndexChangeJob 
indexChangeJob) throws MetaNotFo
             runnableIndexChangeJob.put(indexChangeJob.getJobId(), 
indexChangeJob);
         }
         indexChangeJobs.put(indexChangeJob.getJobId(), indexChangeJob);
+        clearPendingIndexBuild(indexChangeJob);

Review Comment:
   Confirmed and fixed in 646d45da4a3.
   
   A pending build now ends only when a build job for its index and partition 
ends, finished or cancelled: on the master when the job leaves the runnable 
jobs, and in replay when its final state is replayed. Creating or replaying a 
waiting job no longer clears it, so an image taken after the build job records 
still holds the pending builds. The master submits a pending build only for a 
partition that has no build job of that index in any state, so it does not 
submit one twice, while a master restarted from an image without the jobs 
submits them again.
   
   `SchemaChangeHandlerTest#testPendingIndexBuildsKeptUntilBuildJobsEnd` 
replays a waiting p1 job, checks both partitions stay pending, then checks that 
a restarted master (new handler, no jobs) submits p1 and p2 while this master 
submits only p2, and that a finished and a cancelled job each end their 
partition. It failed before the change (`expected {idx=[p1, p2]} but was 
{idx=[p2]}`) and passes now.
   



##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -3914,6 +3960,234 @@ 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.");
+        }
+        // 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 and with 
enable_light_index_change=true,"
+                + " because a heavy schema change does not build ANN indexes 
for existing data");
+    }
+
+    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 annImmediateOnHeavyPath(index);
+            }
+            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 pending partitions are exactly the ones the build jobs 
are submitted for.
+    private void recordPendingIndexBuild(long dbId, OlapTable olapTable, 
List<Index> indexes) {
+        
olapTable.addPendingIndexBuilds(indexes.stream().map(Index::getIndexId).collect(Collectors.toList()),
+                olapTable.getPartitionIds());
+        tablesWithPendingIndexBuilds.put(olapTable.getId(), dbId);
+    }
+
+    // A table recovered from the recycle bin, or one with a recovered 
partition, can hold pending builds that the
+    // master stopped looking at while they were in the recycle bin.
+    public void watchPendingIndexBuilds(long dbId, OlapTable olapTable) {
+        if (olapTable.hasPendingIndexBuilds()) {
+            tablesWithPendingIndexBuilds.put(olapTable.getId(), dbId);
+        }
+    }
+
+    // A build job, submitted or replayed, covers the pending build of its 
indexes on its partition.
+    private void clearPendingIndexBuild(IndexChangeJob indexChangeJob) {
+        Database db = 
Env.getCurrentInternalCatalog().getDbNullable(indexChangeJob.getDbId());
+        Table table = db == null ? null : 
db.getTableNullable(indexChangeJob.getTableId());
+        if (table instanceof OlapTable) {
+            ((OlapTable) 
table).removePendingIndexBuilds(indexChangeJob.getAlterInvertedIndexIds(),
+                    indexChangeJob.getPartitionId());
+        }
+    }
+
+    // Submits the build jobs of BUILD IMMEDIATE whose index metadata a 
previous master journaled, but not the jobs.
+    // Runs on the master only. A failed submission is logged and dropped; 
BUILD INDEX can build the rest.
+    @VisibleForTesting
+    void submitPendingIndexBuilds() {
+        if (!pendingIndexBuildsScanned) {
+            // Tables loaded from an image can hold pending builds that no 
replayed journal record added.
+            for (Database db : Env.getCurrentInternalCatalog().getDbs()) {
+                for (Table table : db.getTables()) {
+                    if (table instanceof OlapTable && ((OlapTable) 
table).hasPendingIndexBuilds()) {
+                        tablesWithPendingIndexBuilds.put(table.getId(), 
db.getId());
+                    }
+                }
+            }
+            pendingIndexBuildsScanned = true;
+        }
+        for (Map.Entry<Long, Long> entry : 
ImmutableList.copyOf(tablesWithPendingIndexBuilds.entrySet())) {
+            long tableId = entry.getKey();
+            Database db = 
Env.getCurrentInternalCatalog().getDbNullable(entry.getValue());
+            Table table = db == null ? null : db.getTableNullable(tableId);
+            if (!(table instanceof OlapTable)) {
+                // The table was dropped.
+                tablesWithPendingIndexBuilds.remove(tableId);
+                continue;
+            }
+            OlapTable olapTable = (OlapTable) table;
+            olapTable.writeLock();

Review Comment:
   Confirmed and fixed in 646d45da4a3.
   
   The master now locks the table with `writeLockIfExist()` and skips a table 
that a DROP TABLE marked dropped after the lookup, leaving its pending builds 
in place; recovering the table watches it again. It also no longer takes the 
pending builds when it visits a table: they end only when their build jobs end, 
so even a job created and later cancelled could not have discarded them 
silently.
   
   `SchemaChangeHandlerTest#testPendingIndexBuildsSkipTableDroppedBeforeLock` 
marks the table dropped while it is still registered (the state after the 
lookup in this interleaving), checks that no build job is created and the 
pending builds stay, then unmarks it, watches it again as RECOVER TABLE does, 
and checks both partitions get their jobs. Before the change, build jobs were 
created on the dropped table.
   



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