hello-stephen commented on code in PR #71137:
URL: https://github.com/apache/doris/pull/71137#discussion_r4747028483
##########
fe/fe-core/src/main/java/org/apache/doris/alter/Alter.java:
##########
@@ -709,13 +718,22 @@ public void processAlterTable(AlterTableCommand command)
throws UserException {
OlapTable olapTable = (OlapTable) tableIf;
checkModifyPartitionStoragePolicyResource(
olapTable, partitionNames, properties,
clause.isTempPartition());
- ((SchemaChangeHandler)
schemaChangeHandler).updatePartitionsProperties(
- db, tableName, partitionNames, properties);
- olapTable.writeLockOrDdlException();
+ SchemaChangeHandler handler = (SchemaChangeHandler)
schemaChangeHandler;
+ boolean reserved =
handler.reserveStoragePolicyChange(db.getId(), olapTable,
+
properties.get(PropertyAnalyzer.PROPERTIES_STORAGE_POLICY));
try {
- modifyPartitionsProperty(db, olapTable, partitionNames,
properties, clause.isTempPartition());
+ handler.updatePartitionsProperties(db, tableName,
partitionNames, properties);
+ olapTable.writeLockOrDdlException();
+ try {
+ modifyPartitionsProperty(db, olapTable,
partitionNames, properties,
+ clause.isTempPartition());
+ } finally {
+ olapTable.writeUnlock();
+ }
} finally {
- olapTable.writeUnlock();
+ if (reserved) {
+ handler.releaseStoragePolicyChange(olapTable.getId());
Review Comment:
[P2] Preserve cooldown uncertainty after a partial policy update
A `MODIFY PARTITION (p1,p2) SET ('storage_policy'=...)` can successfully
update p1's tablets and then fail on p2: `updatePartitionProperties` explicitly
allows partial success. The FE metadata update is skipped, but this finally
block removes the reservation. The successful tablets can still receive
cooldown configuration through their reports and cool p1 while FE shows no
policy. A later `ADD INDEX ... BUILD IMMEDIATE` therefore chooses
LIGHT_AND_BUILD; local index building skips remote rowsets and can finish
successfully without indexing that historical data. Preserve/reconcile possible
BE policy application after partial or uncertain failure before accepting light
builds, and cover failed policy update -> IMMEDIATE.
##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -3914,6 +3965,281 @@ 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, boolean
storagePolicyChanging)
+ 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. A table policy, or a
+ // policy change in progress, comes before the partition policies.
+ boolean mayHaveCooledData = storagePolicyChanging ||
!Strings.isNullOrEmpty(olapTable.getStoragePolicy())
+ || olapTable.getPartitionIds().stream().anyMatch(partitionId
-> !Strings.isNullOrEmpty(
+
olapTable.getPartitionInfo().getDataProperty(partitionId).getStoragePolicy()));
+ // A BUILD INDEX rewrite of an SNII container keeps only the indexes
that the rowset schema names, which
+ // leaves out the path indexes of an inverted index on a VARIANT
column.
+ boolean sniiVariantPathIndexes = sniiTable &&
olapTable.getIndexes().stream()
+ .filter(index -> index.getIndexType() == IndexType.INVERTED &&
!index.isVariantValuesIndex())
+ .anyMatch(index -> olapTable.getBaseSchema().stream()
+ .filter(column -> column.getType().isVariantType())
+ .anyMatch(column ->
index.getColumns().stream().anyMatch(column.getName()::equalsIgnoreCase)));
+ 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();
+ Optional<String> rollupWithColumn =
olapTable.getVisibleIndexIdToMeta().entrySet().stream()
+ .filter(entry -> entry.getKey() !=
olapTable.getBaseIndexId())
+ .filter(entry ->
entry.getValue().getSchema().stream().anyMatch(column ->
+
index.getColumns().stream().anyMatch(column.getName()::equalsIgnoreCase)))
+ .map(entry ->
olapTable.getIndexNameById(entry.getKey()))
+ .findFirst();
+ paths.put(createIndexOp, resolveAddIndexPath(index,
createIndexOp.getBuildMode().orElse(null),
+ enableAddIndexForNewData, sniiTable, onlyAddIndex,
mayHaveCooledData || sniiVariantPathIndexes,
+ tableHasValuesIndex, variantColumn, rollupWithColumn));
+ }
+ }
+ 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,"
+ + " with enable_light_index_change=true, on a table without a
storage policy and, if it stores SNII"
+ + " indexes, without an inverted index on a VARIANT column,
because a heavy schema change does not"
+ + " build ANN indexes for existing data");
+ }
+
+ // buildIndexNotEnough: BUILD INDEX can not index the existing data
correctly, because a partition may hold
+ // rowsets that cooled to remote storage, which it skips, or because its
SNII rewrite would drop the path indexes
+ // of an inverted index on a VARIANT column. rollupWithColumn: a rollup
that holds an index column.
+ private static AddIndexPath resolveAddIndexPath(Index index, BuildMode
buildMode,
+ boolean enableAddIndexForNewData, boolean sniiTable, boolean
onlyAddIndex, boolean buildIndexNotEnough,
+ boolean tableHasValuesIndex, Optional<Column> variantColumn,
Optional<String> rollupWithColumn)
+ 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");
+ }
+ // BUILD INDEX builds only the base tablets, and a schema change gives
the rollup tablets no index, so
+ // nothing builds the index for a rollup's existing data.
+ if (rollupWithColumn.isPresent()) {
+ throw new DdlException("BUILD IMMEDIATE is not supported for index
" + index.getIndexName()
+ + ", because rollup " + rollupWithColumn.get() + " holds
its column and neither BUILD INDEX nor"
+ + " a schema change builds the index for a rollup's
existing data; use BUILD DEFERRED instead");
+ }
+ // 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.
+ // Where BUILD INDEX can not index the existing data correctly, the
heavy schema change does it instead.
+ if (!lightEnabled || !index.isLightAddIndexSupported(false) ||
!onlyAddIndex || buildIndexNotEnough) {
+ // 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;
+ }
+
+ // 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 that ended, finished or cancelled, on the master or in
replay, ends the pending build of its indexes
+ // on its partition. Images do not hold build jobs, so the build stays
pending until then.
+ private void clearPendingIndexBuild(IndexChangeJob indexChangeJob) {
+ Database db =
Env.getCurrentInternalCatalog().getDbNullable(indexChangeJob.getDbId());
Review Comment:
[P2] Reconcile pending intent when jobs end on recycled tables
A non-force DROP TABLE is allowed while an IMMEDIATE build runs because the
table remains NORMAL. If the job cancels on the missing table and daemon
cleanup runs before RECOVER, this live-catalog-only lookup leaves
`pendingIndexBuilds` on the recycled object, then removes the runnable job.
RECOVER watches the table again, but `submitPendingIndexBuild` treats its
retained CANCELLED jobs as covering those partitions and consumes the watch
without clearing intent. No later cleanup remains, even after job history
expires, so storage-policy changes keep failing with an instruction to
wait/cancel despite there being no unfinished job. Reconcile terminal cleanup
with recycled metadata or at recovery, and test DROP after submission -> job
cleanup -> RECOVER.
##########
fe/fe-core/src/main/java/org/apache/doris/catalog/OlapTable.java:
##########
@@ -239,6 +240,15 @@ public enum OlapTableState {
@SerializedName(value = "aIncg")
private AutoIncrementGenerator autoIncrementGenerator;
+ // Partition ids, by index id, of indexes added with BUILD IMMEDIATE whose
build job has not ended; null when there
+ // are none. It is table metadata and build jobs are not, so a master that
starts from an image still submits the
+ // build jobs it does not have.
+ // Ids, unlike names, stay the same when a partition or an unpartitioned
table is renamed.
+ // A change replaces the map and never edits it, because serializing the
table (BACKUP copies it under the read
+ // lock only) can read the map while a build job that ends changes the
pending builds.
+ @SerializedName(value = "pib")
+ private volatile Map<Long, Set<Long>> pendingIndexBuilds;
Review Comment:
[P2] Reconcile persisted build intent during backup and restore
BACKUP can copy a NORMAL table while IMMEDIATE builds remain pending, and
`selectiveCopy` serializes this field into the backup. Restoring into a new
table (or atomic replacement) then changes partition IDs in
`resetIdsForRestore` without remapping/clearing `pendingIndexBuilds` or
registering its new table with the handler. On an already running master, its
one-time scan has finished, so old partition IDs remain pending; even a
completed manual BUILD removes only the new IDs. Consequently valid
storage-policy changes remain rejected despite no actual unfinished builds.
Define how backup/restore carries this execution intent, reconcile the
identities and scheduling accordingly, and cover that roundtrip.
##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -2395,12 +2412,18 @@ public int getAsInt() {
throw new
DdlException(PropertyAnalyzer.ROW_TTL_SEQUENCE_COLUMN_CONFLICT);
}
+ // Resolve how each ADD INDEX runs before any clause below touches
table metadata.
+ Map<CreateIndexOp, AddIndexPath> addIndexPaths =
resolveAddIndexPaths(alterOps, olapTable,
Review Comment:
[P3] Preserve the existing-index IF NOT EXISTS no-op
This resolves operational build constraints before `processAddIndex` reaches
its existing-name IF NOT EXISTS return. For example, create an index with
`CREATE INDEX IF NOT EXISTS ... BUILD DEFERRED`, dynamically disable
`enable_light_index_change`, then repeat the identical statement: it now throws
`BUILD DEFERRED requires enable_light_index_change=true` although the index
already exists and no build is needed. Previously the handler's duplicate fast
path returned before table-specific capability checks. Exclude existing-name IF
NOT EXISTS operations before resolving new-build paths so these retries remain
idempotent.
##########
fe/fe-core/src/main/java/org/apache/doris/catalog/OlapTable.java:
##########
@@ -448,6 +458,44 @@ public List<Index> getIndexes() {
return indexes.getIndexes();
}
+ public synchronized void addPendingIndexBuilds(Collection<Long> indexIds,
Collection<Long> partitionIds) {
+ Map<Long, Set<Long>> updated = getPendingIndexBuilds();
+ for (Long indexId : indexIds) {
+ updated.computeIfAbsent(indexId, id -> new
HashSet<>()).addAll(partitionIds);
Review Comment:
[P2] Avoid pending entries when the table has no partitions
A valid local RANGE/auto-partition table can initially have zero partitions.
Adding an INVERTED index with BUILD IMMEDIATE then inserts `{indexId: []}`
here, while job submission creates no jobs. The pending scheduler iterates that
empty set without removing it, and `hasPendingIndexBuilds()` only checks for a
non-null map. Every later non-empty storage-policy change is therefore rejected
although there is nothing to build or cancel; restarting also preserves the
empty entry. Skip empty pending work and normalize an empty state to null, with
a zero-partition ADD IMMEDIATE test.
--
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]