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


##########
be/src/storage/tablet/tablet_manager.cpp:
##########
@@ -1877,4 +1888,24 @@ void TabletManager::get_topn_tablet_delete_bitmap_score(
               << max_base_rowset_delete_bitmap_score_tablet_id << ", 
tablets=[" << ss.str() << "]";
 }
 
+Status TabletManager::record_index_change_job(TTabletId tablet_id, int64_t 
job_id,
+                                              const std::set<int64_t>& 
index_ids) {
+    tablets_shard& shard = _get_tablets_shard(tablet_id);
+    std::lock_guard<std::mutex> lock(shard.lock_for_index_change_jobs);
+    auto& tablet_jobs = shard.index_change_job_ids[tablet_id];
+    for (int64_t index_id : index_ids) {
+        auto it = tablet_jobs.find(index_id);
+        if (it != tablet_jobs.end() && it->second > job_id) {

Review Comment:
   [P1] Reject delayed index tasks for retired replicas
   
   A cancelled DROP can still remove an index after a replica moves away and 
back. Leave DROP queued on BE A before tablet lookup, move the replica to B, 
and let BUILD finish on B. `IndexChangeJob.runWaitingTxnJob` sends BUILD only 
to the current replicas, so A never records it. A later clone from B installs 
the built rowsets on A under the same tablet ID. When the queued DROP runs, 
`process_index_change_task` resolves the replacement by tablet ID and this 
check admits it. Bind the request to the intended replica ID and validate it at 
execution, or transfer the ordering state with the clone.



##########
be/src/storage/task/index_builder.cpp:
##########
@@ -1233,6 +1234,9 @@ Status IndexBuilder::do_build_inverted_index() {
     }
 
     DCHECK(!_alter_index_ids.empty());
+    // A job on an index starts only after the previous one is done, and job 
ids grow, so a
+    // request of a job older than one that already ran here is late and must 
not undo it.
+    RETURN_IF_ERROR(_tablet->record_index_change_job(_job_id, 
_alter_index_ids));

Review Comment:
   [P2] Fence stale builds across index recreation
   
   A cancelled BUILD for index A can already be in flight when a light 
full-table DROP removes A from the catalog. If A's physical cleanup has yet to 
run on this BE, recreating the same definition assigns ID B and BUILD B can 
finish because FE matches conflicts by ID. When the old BUILD A runs, its fence 
checks only A. `update_inverted_index_info` then removes B as a same-definition 
index with a different ID and installs A, undoing the completed BUILD B. Check 
the schema generation or fence every logical index the request can replace.



##########
fe/fe-core/src/test/java/org/apache/doris/alter/SchemaChangeHandlerTest.java:
##########
@@ -1542,6 +1549,87 @@ public void 
testDropIndexRejectedByPendingBuildOfSameIndex() throws Exception {
         }
     }
 
+    @Test
+    public void testCancelledIndexChangeJobSendsNoTask() throws Exception {
+        String tableName = "sc_cancelled_partition_drop";
+        SchemaChangeHandler handler = 
Env.getCurrentEnv().getSchemaChangeHandler();
+        boolean runningUnitTest = FeConstants.runningUnitTest;
+        FeConstants.runningUnitTest = true;
+        try {
+            IndexChangeJob job = runPartitionDropIndexJob(tableName);
+            List<AgentTask> tasks = job.invertedIndexBatchTask.getAllTasks();
+            Assertions.assertEquals(2, tasks.size());
+            Assertions.assertEquals(job.getJobId(), ((AlterInvertedIndexTask) 
tasks.get(0)).toThrift().getJobId());
+
+            // A sender that holds the tasks from before the cancel, like a 
queued batch or a resend.
+            
Assertions.assertTrue(Env.getCurrentSystemInfo().getBackend(tasks.get(0).getBackendId()).isAlive());
+            List<AgentTask> sent = Lists.newArrayList();
+            AgentBatchTask sender = new AgentBatchTask() {
+                @Override
+                protected TAgentTaskRequest toAgentTaskRequest(AgentTask task) 
{
+                    sent.add(task);
+                    return super.toAgentTaskRequest(task);
+                }
+            };
+            tasks.forEach(sender::addTask);
+
+            Assertions.assertTrue(job.cancel("user cancelled"));
+            
Assertions.assertTrue(tasks.stream().noneMatch(AgentTaskQueue::contains));
+            sender.run();
+            Assertions.assertEquals(Collections.emptyList(), sent);
+
+            // BUILD may start at once: it gets a newer job id, and a BE 
rejects a late DROP request of the
+            // cancelled job once the BUILD has run on the tablet.
+            executeNereidsSql("BUILD INDEX idx_v1 ON test." + tableName + " 
PARTITION (p1)");
+            List<IndexChangeJob> buildJobs = 
handler.getIndexChangeJobs().values().stream()
+                    .filter(j -> j.getTableName().equals(tableName) && 
j.getJobId() != job.getJobId())
+                    .collect(Collectors.toList());
+            Assertions.assertEquals(1, buildJobs.size());
+            Assertions.assertTrue(buildJobs.get(0).getJobId() > 
job.getJobId());
+        } finally {
+            FeConstants.runningUnitTest = runningUnitTest;
+            removeIndexChangeJobs(tableName);
+        }
+    }
+
+    // Creates a table whose p1 has two tablets, and runs a DROP INDEX idx_v1 
job on p1 until its tasks are
+    // queued. The job is only registered in indexChangeJobs, so the job 
scheduler does not run it; the
+    // caller sets runningUnitTest so that its tasks are not sent.
+    private IndexChangeJob runPartitionDropIndexJob(String tableName) throws 
Exception {
+        dropTable("test." + tableName, false);
+        createTable("CREATE TABLE test." + tableName + " (k1 INT, v1 STRING, 
INDEX idx_v1 (v1) USING INVERTED)"
+                + " ENGINE=OLAP DUPLICATE KEY(k1)\n"
+                + "PARTITION BY RANGE(k1) (PARTITION p1 VALUES LESS THAN 
(\"10\"),"
+                + " PARTITION p2 VALUES LESS THAN (\"20\"))\n"
+                + "DISTRIBUTED BY HASH(k1) BUCKETS 2\n"
+                + "PROPERTIES ('replication_num' = '1', 'light_schema_change' 
= 'true');");
+        Database db = 
Env.getCurrentInternalCatalog().getDbOrMetaException("test");
+        OlapTable tbl = (OlapTable) db.getTableOrMetaException(tableName, 
Table.TableType.OLAP);
+        MaterializedIndexMeta baseMeta = 
tbl.getIndexMetaByIndexId(tbl.getBaseIndexId());
+        IndexChangeJob job = new 
IndexChangeJob(Env.getCurrentEnv().getNextId(), db.getId(), tbl.getId(),
+                tbl.getName(), 3600 * 1000L, baseMeta.getSchemaVersion(), 
baseMeta.getSchema(true),
+                baseMeta.getIndexes());
+        job.setOriginIndexId(tbl.getBaseIndexId());
+        job.setPartitionId(tbl.getPartition("p1").getId());
+        job.setPartitionName("p1");
+        job.setAlterInvertedIndexInfo(true, 
Lists.newArrayList(tbl.getIndexes()));
+        
Env.getCurrentEnv().getSchemaChangeHandler().getIndexChangeJobs().put(job.getJobId(),
 job);
+        job.run();
+        Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, 
job.getJobState());
+        return job;
+    }
+
+    private void removeIndexChangeJobs(String tableName) {
+        SchemaChangeHandler handler = 
Env.getCurrentEnv().getSchemaChangeHandler();
+        for (IndexChangeJob job : 
Lists.newArrayList(handler.getIndexChangeJobs().values())) {
+            if (job.getTableName().equals(tableName)) {
+                AgentTaskQueue.removeBatchTask(job.invertedIndexBatchTask, 
TTaskType.ALTER_INVERTED_INDEX);

Review Comment:
   [P3] Cancel the scheduled BUILD before removing the test job
   
   The test submits BUILD through the normal scheduler, which still calls 
`IndexChangeJob.run()` in unit-test mode. If it captures the job before this 
cleanup, the test can remove an empty batch and both job entries, then the 
scheduler can populate and enqueue tasks with no owning job. Cancel the job 
through its synchronized `cancel()` method while the test flag is still set, 
then remove it from the maps.



##########
be/src/storage/tablet/tablet_manager.cpp:
##########
@@ -565,22 +565,33 @@ Status TabletManager::_drop_tablet(TTabletId tablet_id, 
TReplicaId replica_id, b
             wlock.lock();
         }
         to_drop_tablet = _get_tablet_unlocked(tablet_id);
-        if (to_drop_tablet == nullptr) {
-            LOG(WARNING) << "fail to drop tablet because it does not exist. "
-                         << "tablet_id=" << tablet_id;
-            return Status::OK();
-        }
+        if (to_drop_tablet != nullptr) {
+            // We should compare replica id to avoid dropping new cloned 
tablet.
+            // Iff request replica id is 0, FE may be an older release, then 
we drop this tablet as before.
+            if (to_drop_tablet->replica_id() != replica_id && replica_id != 0) 
{
+                return Status::Aborted("replica_id not match({} vs {})",
+                                       to_drop_tablet->replica_id(), 
replica_id);
+            }
 
-        // We should compare replica id to avoid dropping new cloned tablet.
-        // Iff request replica id is 0, FE may be an older release, then we 
drop this tablet as before.
-        if (to_drop_tablet->replica_id() != replica_id && replica_id != 0) {
-            return Status::Aborted("replica_id not match({} vs {})", 
to_drop_tablet->replica_id(),
-                                   replica_id);
+            _remove_tablet_from_partition(to_drop_tablet);
+            tablet_map_t& tablet_map = _get_tablet_map(tablet_id);
+            tablet_map.erase(tablet_id);
         }
+    }
 
-        _remove_tablet_from_partition(to_drop_tablet);
-        tablet_map_t& tablet_map = _get_tablet_map(tablet_id);
-        tablet_map.erase(tablet_id);
+    if (is_drop_table_or_partition) {

Review Comment:
   [P2] Reclaim fence entries on former replica hosts
   
   A replica-only drop during rebalance leaves the fence on the old backend. If 
the table is later permanently erased, 
`InternalCatalog.eraseTableDropBackendReplicas` sends the logical drop only to 
current replicas. Partition cleanup and report-based deletion also miss a 
replica that is already gone. The old backend retains an entry for every such 
tablet and its indexes until restart, so repeated rebalance and partition 
expiration can grow this map indefinitely. Give retained records a retirement 
path that reaches former replica hosts, or tie them to a replica generation so 
they can be safely removed when that replica goes away.



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