github-actions[bot] commented on code in PR #71000:
URL: https://github.com/apache/doris/pull/71000#discussion_r4690625759


##########
gensrc/thrift/HeartbeatService.thrift:
##########
@@ -68,6 +68,9 @@ struct TBackendInfo {
     10: optional i64 be_mem // The physical memory available for use by BE.
     // Reserved for the Paimon Rust reader and aligned with its branch-4.1 
forward-port.
     11: optional bool supports_paimon_rust_reader
+    12: optional bool supports_fixed_block_sampling_v1

Review Comment:
   [P1] Allocate sampling capabilities after master's existing field 12. 
Current master at 0cb98579f606f6ad83ef2a6446b284c8c3ec3d6a already defines 
TBackendInfo field 12 as supports_native_file_encryption. This declaration 
gives the same optional-bool wire field a different meaning, so backends built 
from one revision can advertise the unrelated capability to FEs built from the 
other. Rebase and allocate unused IDs without reusing the existing master 
allocation, preserving those numbers in picks.



##########
fe/fe-core/src/main/java/org/apache/doris/planner/OlapScanNode.java:
##########
@@ -894,17 +939,312 @@ protected void createScanRangeLocations() throws 
UserException {
         long start = System.currentTimeMillis();
         computeSampleTabletIds();
         computeTabletInfo();
+        if (!(Config.isCloudMode() && Config.enable_cloud_snapshot_version)) {
+            
coordinateSharedKeyRangeSamples(olapTable.getAllBackendsByAllCluster());
+        }
         if (LOG.isDebugEnabled()) {
             LOG.debug("distribution prune cost: {} ms", 
(System.currentTimeMillis() - start));
         }
     }
 
+    private void coordinateSharedKeyRangeSamples(ImmutableMap<Long, Backend> 
allBackends) throws UserException {
+        if (!hasKeyRangeSample() || scanRangeLocations.isEmpty()) {
+            return;
+        }
+        List<Partition> randomPartitions = new ArrayList<>();
+        for (Long partitionId : selectedPartitionIds) {
+            Partition partition = olapTable.getPartition(partitionId);
+            if (partition != null && partition.getDistributionInfo() 
instanceof RandomDistributionInfo) {
+                randomPartitions.add(partition);
+            }
+        }
+        if (randomPartitions.isEmpty()) {
+            return;
+        }
+        Map<Long, TScanRangeLocations> locationsByTablet = 
Maps.newHashMapWithExpectedSize(scanRangeLocations.size());
+        for (TScanRangeLocations loc : scanRangeLocations) {
+            
locationsByTablet.put(loc.getScanRange().getPaloScanRange().getTabletId(), loc);
+        }
+        long timeoutSec = ConnectContext.get() != null ? Math.max(5L, 
ConnectContext.get().getExecTimeoutS()) : 30L;
+
+        record PendingSingleBe(Partition partition, List<TScanRangeLocations> 
partLocations,
+                List<Long> candidateBackendIds, long version,
+                InternalService.PSampleTabletKeyRangesRequest request,
+                Future<InternalService.PSampleTabletKeyRangesResponse> 
firstAttempt, String firstAddr) {
+        }
+
+        List<PendingSingleBe> singleBePending = new ArrayList<>();
+        List<Partition> multiBePartitions = new ArrayList<>();
+        Map<Long, List<TScanRangeLocations>> partLocationsMap = new 
LinkedHashMap<>();
+
+        for (Partition partition : randomPartitions) {
+            MaterializedIndex selectedTable = 
olapTable.getPartitionIndex(partition, selectedIndexId);
+            List<Tablet> allTablets = selectedTable.getTablets();
+            List<TScanRangeLocations> partLocations = new 
ArrayList<>(allTablets.size());
+            List<Long> tabletIds = new ArrayList<>(allTablets.size());
+            for (Tablet tablet : allTablets) {
+                TScanRangeLocations loc = 
locationsByTablet.get(tablet.getId());
+                if (loc != null) {
+                    partLocations.add(loc);
+                    tabletIds.add(tablet.getId());
+                }
+            }
+            if (partLocations.isEmpty()) {
+                continue;
+            }
+            if (partLocations.size() != allTablets.size()) {
+                throw new UserException("KEY_RANGE_BLOCK on RANDOM partition " 
+ partition.getName()
+                        + " requires scanning all partition tablets");
+            }
+            TPaloScanRange firstRange = 
partLocations.get(0).getScanRange().getPaloScanRange();
+            long version = Long.parseLong(firstRange.getVersion());
+            if (version <= Partition.PARTITION_INIT_VERSION) {
+                for (TScanRangeLocations loc : partLocations) {
+                    FixedBlockSampleSpec.applyEmptySharedIntervals(
+                            
loc.getScanRange().getPaloScanRange().getSampleOptions());
+                }
+                continue;
+            }
+            List<Long> fullCoverageBackends = 
findFullCoverageBackends(partLocations, allBackends);
+            if (!fullCoverageBackends.isEmpty()) {
+                TTabletSampleOptions opts = firstRange.getSampleOptions();
+                TKeyRangeBlockSampleParams krParams = 
opts.getKeyRangeBlockParams();
+                InternalService.PSampleTabletKeyRangesRequest request =
+                        
InternalService.PSampleTabletKeyRangesRequest.newBuilder()
+                                .addAllTabletIds(tabletIds)
+                                .setVersion(version)
+                                .setDomainId(partition.getId())
+                                
.setSampleUnitRows(krParams.getSampleUnitRows())
+                                
.setIntraTabletUnitProbability(opts.getIntraTabletUnitProbability())
+                                
.setMaxSampleUnitsPerTablet(krParams.getMaxSampleUnitsPerTablet())
+                                .setSeed(opts.getSeed())
+                                .setReturnBoundaryCuts(false)
+                                .build();
+                Backend firstBe = allBackends.get(fullCoverageBackends.get(0));
+                TNetworkAddress brpcAddr = new 
TNetworkAddress(firstBe.getHost(), firstBe.getBrpcPort());
+                String firstAddr = brpcAddr.getHostname() + ":" + 
brpcAddr.getPort();
+                Future<InternalService.PSampleTabletKeyRangesResponse> 
firstFuture = null;
+                try {
+                    firstFuture = 
BackendServiceProxy.getInstance().sampleTabletKeyRanges(brpcAddr, request);
+                } catch (RpcException e) {
+                    LOG.warn("Failed initial key-range sample RPC to {}", 
firstAddr, e);
+                }
+                singleBePending.add(new PendingSingleBe(partition, 
partLocations, fullCoverageBackends,
+                        version, request, firstFuture, firstAddr));
+            } else {
+                partLocationsMap.put(partition.getId(), partLocations);
+                multiBePartitions.add(partition);
+            }
+        }
+
+        for (PendingSingleBe item : singleBePending) {
+            InternalService.PSampleTabletKeyRangesResponse succeeded = null;
+            String lastError = "no queryable replica";
+            for (int idx = 0; idx < item.candidateBackendIds().size(); idx++) {
+                Backend backend = 
allBackends.get(item.candidateBackendIds().get(idx));
+                if (backend == null) {
+                    continue;
+                }
+                TNetworkAddress brpcAddr = new 
TNetworkAddress(backend.getHost(), backend.getBrpcPort());
+                String addrStr = idx == 0 ? item.firstAddr() : 
brpcAddr.getHostname() + ":" + brpcAddr.getPort();
+                try {
+                    Future<InternalService.PSampleTabletKeyRangesResponse> 
future = idx == 0
+                            ? item.firstAttempt()
+                            : 
BackendServiceProxy.getInstance().sampleTabletKeyRanges(brpcAddr, 
item.request());
+                    if (future == null) {
+                        continue;
+                    }
+                    InternalService.PSampleTabletKeyRangesResponse resp = 
future.get(timeoutSec, TimeUnit.SECONDS);

Review Comment:
   [P1] Move sampling RPC waits outside the planner table locks. This runs 
through PhysicalPlanTranslator -> OlapScanNode.init while 
NereidsPlanner.planWithLock still owns the table read locks. A backend that 
stalls opening segments can therefore block ALTER/DROP/partition DDL for the 
entire statistics timeout (43200 seconds by default). KILL/task cancellation 
does not unblock it: these futures are neither registered with StmtExecutor 
cancellation nor checked against its pending cancel reason. Capture the 
required metadata under the lock, coordinate after releasing it, and 
cancel/bound the futures across both single- and multi-BE paths.



##########
fe/fe-core/src/main/java/org/apache/doris/statistics/analysis/ColumnSampleBatchCollector.java:
##########
@@ -0,0 +1,443 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.statistics.analysis;
+
+import org.apache.doris.analysis.FixedBlockSampleSpec;
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.KeysType;
+import org.apache.doris.catalog.MaterializedIndexMeta;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.common.Config;
+import org.apache.doris.common.Status;
+import org.apache.doris.common.util.SqlUtils;
+import org.apache.doris.qe.AutoCloseConnectContext;
+import org.apache.doris.qe.SessionVariable;
+import org.apache.doris.qe.StmtExecutor;
+import 
org.apache.doris.statistics.analysis.TableStatisticsSqlBuilder.BatchedColumnSpec;
+import org.apache.doris.statistics.repository.ResultRow;
+import org.apache.doris.statistics.sampling.ColumnPhysicalLayout;
+import org.apache.doris.statistics.sampling.RandomAggTabletSamplingMethod;
+import org.apache.doris.statistics.sampling.SampledScanSqlRenderer;
+import org.apache.doris.statistics.sampling.SamplingBudget;
+import org.apache.doris.statistics.sampling.TabletSampleSpec;
+import 
org.apache.doris.statistics.sampling.TabletSampleSpec.EqualProbabilitySamplingSemantics;
+import org.apache.doris.statistics.sampling.TabletSampleSpec.FullScanClause;
+import org.apache.doris.statistics.sampling.TabletSampleSpec.KeyHashScanClause;
+import org.apache.doris.statistics.sampling.TabletSamplingMethod;
+import org.apache.doris.statistics.sampling.TabletSamplingRequest;
+import org.apache.doris.statistics.sampling.TabletSamplingScope;
+import org.apache.doris.statistics.util.StatisticsUtil;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.Lists;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.CancellationException;
+import java.util.stream.Collectors;
+
+/**
+ * Shares a single sampled OLAP scan (MultiCastDataStreamSink CTE) across 
multiple columns of the
+ * same index, avoiding repeated storage scans, key merges, Delete Bitmap 
checks, and key-range RPCs.
+ */
+final class ColumnSampleBatchCollector {
+    private static final Logger LOG = 
LogManager.getLogger(ColumnSampleBatchCollector.class);
+
+    private enum State {
+        PENDING, RUNNING, SUCCEEDED, FALLBACK, CANCELLED
+    }
+
+    private record Target(long jobId, long indexId, Set<String> partitions) {
+    }
+
+    record ColumnSampleOutcome(
+            boolean overLimit,
+            ResultRow row,
+            double sampleProbability,
+            boolean singleNonNullUnique,
+            double domainRate,
+            boolean inSampleBounds,
+            boolean fullScanOfNonNullUniqueKey) {
+    }
+
+    private record PlannedColumn(
+            int ord,
+            String name,
+            Column column,
+            ColumnPhysicalLayout layout,
+            boolean singleUniqueKey,
+            boolean singleNonNullUnique,
+            boolean inSampleBounds) {
+    }
+
+    private final List<Batch> batches = new ArrayList<>();
+
+    ColumnSampleBatchCollector(Collection<? extends BaseAnalysisTask> tasks, 
int batchSize) {
+        if (batchSize <= 1) {
+            return;
+        }
+        Map<Target, Map<String, List<OlapAnalysisTask>>> groups = new 
HashMap<>();
+        for (BaseAnalysisTask task : tasks) {
+            if (!(task instanceof OlapAnalysisTask olapTask) || 
task.tableSample == null
+                    || task.info == null || task.info.rowCount == 0 || 
!(task.tbl instanceof OlapTable)) {
+                continue;
+            }
+            Set<String> partNames = task.info.partitionNames == null ? 
Set.of() : Set.copyOf(task.info.partitionNames);
+            Target target = new Target(task.info.jobId, task.info.indexId, 
partNames);
+            groups.computeIfAbsent(target, key -> new 
TreeMap<>(String.CASE_INSENSITIVE_ORDER))
+                    .computeIfAbsent(task.info.colName, key -> new 
ArrayList<>()).add(olapTask);
+        }
+        groups.forEach((target, byName) -> {
+            for (List<String> names : Lists.partition(new 
ArrayList<>(byName.keySet()), batchSize)) {
+                if (names.size() < 2) {
+                    continue;
+                }
+                List<OlapAnalysisTask> members = names.stream().flatMap(name 
-> byName.get(name).stream())
+                        .collect(Collectors.toList());
+                Batch batch = new Batch(target, names, members);
+                batches.add(batch);
+                members.forEach(task -> task.sampleBatch = batch);
+            }
+        });
+    }
+
+    final class Batch {
+        private final Target target;
+        private final List<String> columns;
+        private final List<OlapAnalysisTask> memberTasks;
+        // All mutable fields are guarded by the collector's monitor.
+        private State state = State.PENDING;
+        private Map<String, ColumnSampleOutcome> outcomes;
+        private StmtExecutor activeExecutor;
+
+        private Batch(Target target, List<String> columns, 
List<OlapAnalysisTask> memberTasks) {
+            this.target = target;
+            this.columns = List.copyOf(columns);
+            this.memberTasks = List.copyOf(memberTasks);
+        }
+
+        ColumnSampleOutcome collect(OlapAnalysisTask caller, OlapTable table, 
long resolvedIndexId,
+                TabletSamplingMethod method, long rows, boolean logicalSample) 
throws InterruptedException {
+            while (true) {
+                synchronized (ColumnSampleBatchCollector.this) {
+                    checkCaller(caller);
+                    if (state == State.FALLBACK) {
+                        return null;
+                    }
+                    if (state == State.SUCCEEDED) {
+                        ColumnSampleOutcome outcome = 
outcomes.get(caller.info.colName);
+                        if (outcome == null) {
+                            return null;
+                        }
+                        return adaptForCaller(outcome, caller);
+                    }
+                    if (state == State.RUNNING) {
+                        ColumnSampleBatchCollector.this.wait();
+                        continue;
+                    }
+                    state = State.RUNNING;
+                }
+                execute(caller, table, resolvedIndexId, method, rows, 
logicalSample);
+            }
+        }
+
+        private ColumnSampleOutcome adaptForCaller(ColumnSampleOutcome 
outcome, OlapAnalysisTask caller) {
+            if (outcome.overLimit()) {
+                return outcome;
+            }
+            List<String> values = new ArrayList<>(outcome.row().getValues());
+            values.set(0, caller.concatColumnStatsId());
+            values.set(5, caller.info.colName);
+            return new ColumnSampleOutcome(false, new ResultRow(values), 
outcome.sampleProbability(),
+                    outcome.singleNonNullUnique(), outcome.domainRate(), 
outcome.inSampleBounds(),
+                    outcome.fullScanOfNonNullUniqueKey());
+        }
+
+        private void checkCaller(OlapAnalysisTask caller) throws 
InterruptedException {
+            caller.checkMinMaxCancelled();
+            if (state == State.CANCELLED) {
+                throw new CancellationException("Sample batch cancelled");
+            }
+            if (Thread.currentThread().isInterrupted()) {
+                throw new InterruptedException("Sample batch interrupted");
+            }
+        }
+
+        private void execute(OlapAnalysisTask caller, OlapTable table, long 
resolvedIndexId,
+                TabletSamplingMethod method, long rows, boolean logicalSample) 
throws InterruptedException {
+            State next = State.PENDING;
+            Map<String, ColumnSampleOutcome> computed = null;
+            try {
+                computed = runBatchQuery(caller, table, resolvedIndexId, 
method, rows, logicalSample);
+                next = computed == null ? State.FALLBACK : State.SUCCEEDED;
+            } catch (AnalyzeSkipException e) {
+                throw e;
+            } catch (RuntimeException e) {
+                synchronized (ColumnSampleBatchCollector.this) {
+                    checkCaller(caller);
+                }
+                if (Throwables.getRootCause(e) instanceof InterruptedException 
interrupted) {
+                    throw interrupted;
+                }
+                if (BaseAnalysisTask.containsSkipMarker(e)) {
+                    next = State.FALLBACK;
+                } else {
+                    LOG.warn("Batch sample scan failed for job {}, index {}, 
columns {}. Falling back to per-column.",
+                            target.jobId, target.indexId, columns, e);
+                    next = State.FALLBACK;
+                }
+            } finally {
+                synchronized (ColumnSampleBatchCollector.this) {
+                    activeExecutor = null;
+                    if (state == State.RUNNING) {
+                        outcomes = computed;
+                        state = next;
+                    }
+                    ColumnSampleBatchCollector.this.notifyAll();
+                }
+            }
+        }
+
+        private Map<String, ColumnSampleOutcome> 
runBatchQuery(OlapAnalysisTask caller, OlapTable table,
+                long resolvedIndexId, TabletSamplingMethod method, long rows, 
boolean logicalSample)
+                throws InterruptedException {
+            List<PlannedColumn> planned = new ArrayList<>(columns.size());
+            List<String> keyColumnNames;
+            boolean retainsPartitionKeys;
+            boolean anyKey = false;
+            boolean anyPartition = false;
+            boolean anyDistribution = false;
+            table.readLock();
+            try {
+                MaterializedIndexMeta meta = 
table.getIndexMetaByIndexId(resolvedIndexId);
+                if (meta == null) {
+                    return null;
+                }
+                retainsPartitionKeys = resolvedIndexId == 
table.getBaseIndexId()
+                        || FixedBlockSampleSpec.retainsPartitionKeys(table, 
meta);
+                keyColumnNames = meta.getKeysType() == KeysType.AGG_KEYS
+                        ? 
meta.getSchema().stream().filter(Column::isKey).map(Column::getName).toList()
+                        : List.of();
+                Set<String> liveNames = new 
TreeMap<>(String.CASE_INSENSITIVE_ORDER).keySet();
+                Map<String, Boolean> seen = new 
TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+                for (OlapAnalysisTask member : memberTasks) {
+                    if (!member.killed && member.info != null) {
+                        seen.put(member.info.colName, Boolean.TRUE);
+                    }
+                }
+                liveNames = seen.keySet();
+                for (String name : columns) {
+                    if (!liveNames.contains(name)) {
+                        continue;
+                    }
+                    Column col = OlapAnalysisTask.resolveColumn(meta, name);
+                    if (col == null) {
+                        continue;
+                    }
+                    ColumnPhysicalLayout layout = 
OlapAnalysisTask.columnLayout(table, meta, col);
+                    boolean singleUnique = layout.singleUniqueKey() && 
retainsPartitionKeys;
+                    boolean singleNonNullUnique = singleUnique && 
!col.isAllowNull();
+                    boolean inSampleBounds = 
OlapAnalysisTask.prefersInSampleBounds(
+                            table, meta, col, resolvedIndexId, caller.info);
+                    anyKey |= layout.key();
+                    anyPartition |= layout.partition();
+                    anyDistribution |= layout.distribution();
+                    planned.add(new PlannedColumn(planned.size(), name, col, 
layout,
+                            singleUnique, singleNonNullUnique, 
inSampleBounds));
+                }
+            } finally {
+                table.readUnlock();
+            }
+            if (planned.size() < 2) {
+                return null;
+            }
+            long population = logicalSample ? rows : 
caller.job.freezeIndexRows(resolvedIndexId, () -> rows);

Review Comment:
   [P2] Defer the population freeze until the sample mode is known. For a 
DUP_KEYS table with at least two collected columns, this freezes the reported 
row count before method.build can choose FullScanClause. If the table reports 
100 rows and another 100 commit before ANALYZE WITH SAMPLE ROWS 1000, the 
batched census measures 200, but publishResultRow -> freezeResultCount replaces 
that with 100 and halves its measured bytes/nulls. With batching disabled the 
census correctly freezes 200. The early freeze also survives batch 
failure/budget fallback. Only prefreeze reported N for a sampled estimate; let 
a census freeze its measured count.



##########
fe/fe-core/src/main/java/org/apache/doris/statistics/sampling/HierarchicalFixedBudgetTabletSamplingMethod.java:
##########
@@ -0,0 +1,315 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.statistics.sampling;
+
+import org.apache.doris.analysis.FixedBlockSampleSpec;
+import org.apache.doris.statistics.analysis.AnalyzeSkipException;
+import 
org.apache.doris.statistics.sampling.TabletSampleSpec.EqualProbabilitySamplingSemantics;
+import 
org.apache.doris.statistics.sampling.TabletSampleSpec.FixedBlockScanClause;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Three-stage sample with a common unconditional inclusion probability for 
every physical block. */
+public final class HierarchicalFixedBudgetTabletSamplingMethod implements 
TabletSamplingMethod {
+    private final FixedBlockSampleSpec.Mode mode;
+
+    public HierarchicalFixedBudgetTabletSamplingMethod() {
+        this(FixedBlockSampleSpec.Mode.FIXED_BLOCK);
+    }
+
+    public 
HierarchicalFixedBudgetTabletSamplingMethod(FixedBlockSampleSpec.Mode mode) {
+        this.mode = mode;
+    }
+
+    private static final long PARTITION = 0x706172746974696fL;
+    private static final long ROUNDING = 0x726f756e64696e67L;
+    private static final long TABLET = 0x7461626c6574L;
+
+    @Override
+    public TabletSampleSpec build(TabletSamplingRequest request) {
+        SamplingBudget budget = request.budget();
+        List<PartitionSampleMeta> partitions = request.scope().partitions();
+        long k = 1 + (budget.targetRows() - 1) / budget.unitRows();
+        Population population = Population.of(partitions, budget.unitRows());
+        if (population.isCensus(budget.targetRows(), budget.unitRows())) {
+            return TabletSampleSpec.fullScan();
+        }
+        long min = population.min();
+        long max = population.max();
+        int tiers = max <= 4.0 * min ? 1 : Math.min(3, 
budget.maxSampleGroups());
+        double step = Math.pow((double) max / min, 1.0 / tiers);
+        double[] boundaries = new double[tiers - 1];
+        for (int h = 0; h < boundaries.length; h++) {
+            boundaries[h] = min * Math.pow(step, h + 1);
+        }
+        int[] counts = new int[tiers];
+        double[] weights = new double[tiers];
+        long[] largest = new long[tiers];
+        long[] largestRows = new long[tiers];
+        List<Cell[]> cells = new ArrayList<>();
+        for (PartitionSampleMeta part : partitions) {
+            Cell[] strata = new Cell[tiers];
+            Arrays.setAll(strata, i -> new Cell());
+            for (TabletSampleMeta t : part.tablets()) {
+                long b = t.blocks(budget.unitRows());
+                int h = 0;
+                while (h < boundaries.length && b >= boundaries[h]) {
+                    h++;
+                }
+                strata[h].ids.add(t.id());
+                counts[h]++;
+                weights[h] += b;
+                largest[h] = Math.max(largest[h], b);
+                largestRows[h] = Math.max(largestRows[h], t.estimatedRows());
+            }
+            cells.add(strata);
+        }
+        int cap = Math.min(budget.maxSelectedTablets(),
+                
SampledScanSqlRenderer.tabletCapacity(budget.maxInternalSqlBytes(), tiers, 
mode));
+        if (cap < 1) {
+            throw new AnalyzeSkipException("Fixed-block SQL budget cannot fit 
one tablet");
+        }
+        int divisor = request.layout().key() || request.layout().partition() 
|| request.layout().distribution()
+                ? 16 : 32;
+        int seats = (int) Math.min(cap, Math.max(1, k / divisor));
+        int m = Math.min(partitions.size(), seats);
+        double alpha = (double) m / partitions.size();
+        // Even if every selected tablet reads all its blocks, equal marginals 
need at least
+        // q * tabletCount seats. Reduce q before water-filling if the nominal 
target is infeasible.
+        long tabletCount = Arrays.stream(counts).asLongStream().sum();
+        double q = Math.min(Math.min(alpha, k / population.blocks()), (double) 
seats / tabletCount);
+        double[] beta = allocate(counts, weights, seats / alpha, q / alpha);
+
+        // Any common offset u < 1 gives floor(worst + u) <= cap when worst <= 
cap.
+        // Evaluate the bound in the same exact units used to draw, before 
consulting the seed.
+        BigInteger[] rates = 
Arrays.stream(beta).mapToObj(SystematicRounding::units).toArray(BigInteger[]::new);
+        BigInteger limit = 
SystematicRounding.units(1.0).multiply(BigInteger.valueOf(cap));
+        BigInteger worst = worstCost(cells, m, rates);
+        if (worst.compareTo(limit) > 0) {
+            q = SystematicRounding.scaleDown(SystematicRounding.units(q), 
limit, worst);
+            for (int h = 0; h < tiers; h++) {
+                beta[h] = SystematicRounding.scaleDown(rates[h], limit, worst);
+                rates[h] = SystematicRounding.units(beta[h]);
+            }
+        }
+        // Division when computing the water-filling floor can round down, 
even without budget scaling.
+        for (int h = 0; h < tiers; h++) {
+            if (counts[h] > 0) {
+                q = Math.min(q, alpha * beta[h]);
+            }
+        }
+        return draw(request, partitions, cells, m, alpha, beta, weights, 
rates, q, largest, largestRows,
+                population.rows());
+    }
+
+    public record Population(long min, long max, double rows, double blocks, 
boolean imputed) {
+        public static Population of(List<PartitionSampleMeta> partitions, long 
unitRows) {
+            long min = Long.MAX_VALUE;
+            long max = 0;
+            double blocks = 0;
+            double rows = 0;
+            boolean imputed = false;
+            for (PartitionSampleMeta part : partitions) {
+                for (TabletSampleMeta t : part.tablets()) {
+                    long b = t.blocks(unitRows);
+                    min = Math.min(min, b);
+                    max = Math.max(max, b);
+                    blocks += b;
+                    rows += t.estimatedRows();
+                    imputed |= t.imputed();
+                }
+            }
+            return new Population(min, max, rows, blocks, imputed);
+        }
+
+        public boolean isCensus(long targetRows, long unitRows) {
+            return !imputed && (rows <= targetRows || 1 + (targetRows - 1) / 
unitRows >= blocks);
+        }
+    }
+
+    private static BigInteger worstCost(List<Cell[]> cells, int m, 
BigInteger[] rates) {
+        return cells.stream().map(strata -> {
+            BigInteger cost = BigInteger.ZERO;
+            for (int h = 0; h < strata.length; h++) {
+                cost = 
cost.add(rates[h].multiply(BigInteger.valueOf(strata[h].ids.size())));
+            }
+            return cost;
+        }).sorted(Comparator.reverseOrder()).limit(m).reduce(BigInteger.ZERO, 
BigInteger::add);
+    }
+
+    // Allocate in proportion to block mass, capping saturated cohorts and 
redistributing their surplus.
+    // The lower bound makes the subsequent conditional block probability 
realizable.
+    private static double[] allocate(int[] counts, double[] weights, double 
seats, double floor) {
+        double[] rates = new double[counts.length];
+        double hi = 0;
+        for (int h = 0; h < counts.length; h++) {
+            if (counts[h] > 0) {
+                hi = Math.max(hi, counts[h] / weights[h]);
+            }
+        }
+        double lo = 0;
+        for (int i = 0; i < 64; i++) {
+            double lambda = (lo + hi) / 2;
+            double total = 0;
+            for (int h = 0; h < counts.length; h++) {
+                rates[h] = counts[h] == 0 ? 0 : Math.max(floor, Math.min(1, 
lambda * weights[h] / counts[h]));
+                total += counts[h] * rates[h];
+            }
+            if (total > seats) {
+                hi = lambda;
+            } else {
+                lo = lambda;
+            }
+        }
+        return rates;
+    }
+
+    private TabletSampleSpec draw(TabletSamplingRequest request, 
List<PartitionSampleMeta> partitions,
+            List<Cell[]> cells, int m, double alpha, double[] beta, double[] 
weights, BigInteger[] rates,
+            double q, long[] largest, long[] largestRows, double 
populationRows) {
+        long seed = request.seed();
+        List<Integer> order = new ArrayList<>();
+        for (int j = 0; j < partitions.size(); j++) {
+            order.add(j);
+        }
+        order.sort(Comparator.comparingLong(j -> hash(seed, PARTITION, 
partitions.get(j).id())));
+        order = order.subList(0, m);
+        order.sort(Comparator.comparingLong(j -> partitions.get(j).id()));
+        List<List<Long>> selected = new ArrayList<>();
+        for (int h = 0; h < beta.length; h++) {
+            selected.add(new ArrayList<>());
+        }
+        SystematicRounding rounding = new SystematicRounding(hash(seed, 
ROUNDING, 0));
+        for (int j : order) {
+            for (int h = 0; h < beta.length; h++) {
+                List<Long> ids = cells.get(j)[h].ids;
+                int take = rounding.take(ids.size(), rates[h]);
+                if (take > 0) {
+                    ids.sort(Comparator.comparingLong(id -> hash(seed, TABLET, 
id)));
+                    selected.get(h).addAll(ids.subList(0, take));
+                }
+            }
+        }
+        int selectedTablets = selected.stream().mapToInt(List::size).sum();
+        long effectiveUnitRows = request.budget().unitRows();
+        if (mode == FixedBlockSampleSpec.Mode.KEY_RANGE_BLOCK && 
selectedTablets > 0) {
+            // Coalesce narrow key units into at most ~32 stratified 
contiguous spans per selected
+            // tablet so overlapping segments do not decompress separate 64 KB 
pages for hundreds of cuts.
+            double expectedRowsPerTablet = (q * populationRows) / 
selectedTablets;
+            long minUnitByTarget = Math.max(1L, (long) 
Math.ceil(expectedRowsPerTablet / 32.0));
+            effectiveUnitRows = Math.max(effectiveUnitRows, minUnitByTarget);
+        }
+        Map<GroupRates, List<Long>> combined = new LinkedHashMap<>();
+        for (int h = 0; h < beta.length; h++) {
+            if (!selected.get(h).isEmpty()) {
+                double pi = alpha * beta[h];
+                double p = q / pi;
+                long maxBlocks = effectiveUnitRows == 
request.budget().unitRows()
+                        ? largest[h]
+                        : (1L + (Math.max(1L, largestRows[h]) - 1L) / 
effectiveUnitRows);
+                // BE rounds per segment. Allow for segment tails and delayed 
tablet reports.
+                long safetyCap = (long) Math.ceil(2 * p * maxBlocks + 64);

Review Comment:
   [P2] Account for per-segment tails when deriving the cap. maxBlocks uses 
ceil(tabletRows/unitRows), but FixedRowIdBlockSampler sums 
ceil(segmentRows/unitRows). For one-tablet partitions with IDs 1 and 2 
reporting 500 and 100000 rows, with the first holding 500 one-row uncompacted 
segments, unit_rows=1024 and targetRows=8192, selecting the first partition 
(e.g. seed 2) yields p=16/99 and cap=65. BE necessarily selects 80 or 81 units 
and rejects this valid, freshly reported layout. Batched and per-column 
fallback reuse the same seed/frame and fail again. Include segment-tail 
fragmentation in the cap or otherwise build a plan that can execute on such 
layouts.



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