You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by "AmatyaAvadhanula (via GitHub)" <gi...@apache.org> on 2024/10/26 05:38:27 UTC
[PR] Faster batch segment allocation by reducing metadata IO (druid)
AmatyaAvadhanula opened a new pull request, #17420:
URL: https://github.com/apache/druid/pull/17420
### Problem
Metadata IO is the main bottleneck for segment allocation times, which can contribute to lag significantly.
Currently, the metadata call to fetch used segments limits the allocation rate, and contributes to allocation wait time which can grow quite quickly. The sum of allocation times is a direct contributor to lag.
### Idea
Segment allocation with `time chunk locking` requires only the segment ids and the number of core partitions to determine the next id.
We can issue a much less expensive call to fetch segmentIds instead of segments if the segment payloads are significantly large due to the dimensions and metrics.
The core partitions do not change for a given (datasource, interval, version) and we can fetch exactly one segment by id for such combinations and reduce the load on the metadata store, and also reduce the time taken to build the DataSegment object on the Overlord.
### Usage
Adds a new feature flag
`druid.indexer.tasklock.segmentAllocationReduceMetadataIO` with default value `false`
Setting this flag to true allows segment allocation to fetch only the required segmentIds and fewer segment payloads from the metadata store.
At present, this flag is only applicable for TimeChunk locking with batch segment allocation.
This PR has:
- [x] been self-reviewed.
- [ ] using the [concurrency checklist](https://github.com/apache/druid/blob/master/dev/code-review/concurrency.md) (Remove this item if the PR doesn't have any relation to concurrency.)
- [ ] added documentation for new or modified features or behaviors.
- [ ] a release note entry in the PR description.
- [x] added Javadocs for most classes and all non-trivial methods. Linked related entities via Javadoc links.
- [ ] added or updated version, license, or notice information in [licenses.yaml](https://github.com/apache/druid/blob/master/dev/license.md)
- [x] added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
- [x] added unit tests or modified existing tests to cover new code paths, ensuring the threshold for [code coverage](https://github.com/apache/druid/blob/master/dev/code-review/code-coverage.md) is met.
- [ ] added integration tests.
- [x] been tested in a test Druid cluster.
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "AmatyaAvadhanula (via GitHub)" <gi...@apache.org>.
AmatyaAvadhanula commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821514854
##########
server/src/main/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinator.java:
##########
@@ -2900,6 +2929,70 @@ public int removeDataSourceMetadataOlderThan(long timestamp, @NotNull Set<String
);
}
+ @VisibleForTesting
+ Set<DataSegment> retrieveUsedSegmentsForAllocation(
+ final Handle handle,
+ final String dataSource,
+ final Interval interval
+ )
+ {
+ final Set<SegmentId> overlappingSegmentIds = SqlSegmentsMetadataQuery.forHandle(handle, connector, dbTables, jsonMapper)
+ .retrieveUsedSegmentIds(
+ dataSource,
+ interval
+ );
+ // Map from version -> interval -> segmentId with the smallest partitionNum
+ Map<String, Map<Interval, SegmentId>> versionIntervalToSmallestSegmentId = new HashMap<>();
+ for (SegmentId segmentId : overlappingSegmentIds) {
+ final Map<Interval, SegmentId> map
+ = versionIntervalToSmallestSegmentId.computeIfAbsent(segmentId.getVersion(), v -> new HashMap<>());
+ final SegmentId value = map.get(segmentId.getInterval());
+ if (value == null || value.getPartitionNum() > segmentId.getPartitionNum()) {
+ map.put(interval, segmentId);
+ }
+ }
+
+ // Retrieve the segments for the ids stored in the map to get the numCorePartitions
+ final Set<String> segmentIdsToRetrieve = new HashSet<>();
+ for (Map<Interval, SegmentId> itvlMap : versionIntervalToSmallestSegmentId.values()) {
Review Comment:
The idea was so that we get a consistent result irrespective of the order in which the metadata store returns results
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1817695838
##########
indexing-service/src/test/java/org/apache/druid/indexing/common/actions/SegmentAllocationQueueTest.java:
##########
@@ -99,6 +121,133 @@
emitter.flush();
}
+ @Test
+ @Ignore
+ public void testLongQueue() throws Exception
+ {
+ allocationQueue.start();
+ allocationQueue.becomeLeader();
+ final Task task = NoopTask.create();
+ taskActionTestKit.getTaskLockbox().add(task);
+
+ final Interval startInterval = Intervals.of("2024-01-01/PT1H");
+ final long hourToMillis = 1000L * 60L * 60L;
+ final long numHours = 48;
+ List<Interval> intervals = new ArrayList<>();
+ for (long hour = 0; hour < numHours; hour++) {
+ intervals.add(
+ new Interval(
+ startInterval.getStartMillis() + hourToMillis * hour,
+ startInterval.getStartMillis() + hourToMillis * hour + hourToMillis,
+ DateTimeZone.UTC
+ )
+ );
+ }
+
+ final IndexerSQLMetadataStorageCoordinator coordinator =
+ (IndexerSQLMetadataStorageCoordinator) taskActionTestKit.getMetadataStorageCoordinator();
+
+ final List<String> dimensions = new ArrayList<>();
+ for (int i = 0; i < 1000; i++) {
+ dimensions.add("dimension_" + i);
+ }
+ final Set<DataSegment> segments = new HashSet<>();
+ final int numUsedSegmentsPerInterval = 2000;
+ int version = 0;
+ for (Interval interval : intervals) {
+ for (int i = 0; i < numUsedSegmentsPerInterval; i++) {
+ segments.add(
+ DataSegment.builder()
+ .dataSource(task.getDataSource())
+ .interval(interval)
+ .version("version" + version)
+ .shardSpec(new NumberedShardSpec(i, numUsedSegmentsPerInterval))
+ .dimensions(dimensions)
+ .size(100)
+ .build()
+ );
+ }
+ coordinator.commitSegments(segments, null);
+ segments.clear();
+ version = (version + 1) % 10;
+ }
+
+
+ final int numAllocations = 10;
+ final int replicas = 2;
+ Map<String, List<Future<SegmentIdWithShardSpec>>> sequenceNameAndPrevIdToFutures = new HashMap<>();
+ for (int i = 0; i < numAllocations; i++) {
+ for (int j = 0; j < numHours; j++) {
+ final int id = numUsedSegmentsPerInterval + i / replicas;
+ final String sequenceId = j + "-sequence" + id;
+ final String prevSequenceId = j + "-sequence" + (id - 1);
+ sequenceNameAndPrevIdToFutures.computeIfAbsent(
+ sequenceId + "|" + prevSequenceId,
+ k -> new ArrayList<>()
+ ).add(
+ allocationQueue.add(
+ new SegmentAllocateRequest(
+ task,
+ new SegmentAllocateAction(
+ task.getDataSource(),
+ intervals.get(j).getStart(),
+ Granularities.NONE,
+ Granularities.HOUR,
+ sequenceId,
+ prevSequenceId,
+ false,
+ NumberedPartialShardSpec.instance(),
+ LockGranularity.TIME_CHUNK,
+ TaskLockType.APPEND
+ ),
+ 10
+ )
+ )
+ );
+ }
+ }
+ executor.finishAllPendingTasks();
+
+ final Set<SegmentIdWithShardSpec> allocatedIds = new HashSet<>();
+ for (List<Future<SegmentIdWithShardSpec>> sameIds : sequenceNameAndPrevIdToFutures.values()) {
+ if (sameIds.isEmpty()) {
+ return;
+ }
+ final SegmentIdWithShardSpec id = sameIds.get(0).get();
+ Assert.assertNotNull(id);
+ for (int i = 1; i < sameIds.size(); i++) {
+ Assert.assertEquals(id, sameIds.get(i).get());
+ }
+ Assert.assertFalse(allocatedIds.contains(id));
+ allocatedIds.add(id);
+ }
+ Assert.assertEquals(numHours * numAllocations, allocatedIds.size() * replicas);
Review Comment:
## Result of multiplication cast to wider type
Potential overflow in [int multiplication](1) before it is converted to long by use in an invocation context.
[Show more details](https://github.com/apache/druid/security/code-scanning/8435)
##########
server/src/main/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinator.java:
##########
@@ -2900,6 +2929,70 @@
);
}
+ @VisibleForTesting
+ Set<DataSegment> retrieveUsedSegmentsForAllocation(
+ final Handle handle,
+ final String dataSource,
+ final Interval interval
+ )
+ {
+ final Set<SegmentId> overlappingSegmentIds = SqlSegmentsMetadataQuery.forHandle(handle, connector, dbTables, jsonMapper)
+ .retrieveUsedSegmentIds(
+ dataSource,
+ interval
+ );
+ // Map from version -> interval -> segmentId with the smallest partitionNum
+ Map<String, Map<Interval, SegmentId>> versionIntervalToSmallestSegmentId = new HashMap<>();
+ for (SegmentId segmentId : overlappingSegmentIds) {
+ final Map<Interval, SegmentId> map
+ = versionIntervalToSmallestSegmentId.computeIfAbsent(segmentId.getVersion(), v -> new HashMap<>());
+ final SegmentId value = map.get(segmentId.getInterval());
+ if (value == null || value.getPartitionNum() > segmentId.getPartitionNum()) {
+ map.put(interval, segmentId);
+ }
+ }
+
+ // Retrieve the segments for the ids stored in the map to get the numCorePartitions
+ final Set<String> segmentIdsToRetrieve = new HashSet<>();
+ for (Map<Interval, SegmentId> itvlMap : versionIntervalToSmallestSegmentId.values()) {
+ segmentIdsToRetrieve.addAll(itvlMap.values().stream().map(SegmentId::toString).collect(Collectors.toList()));
+ }
+ final Set<DataSegment> dataSegments = retrieveSegmentsById(dataSource, segmentIdsToRetrieve);
+ final Set<String> retrievedIds = new HashSet<>();
+ final Map<String, Map<Interval, Integer>> versionIntervalToNumCorePartitions = new HashMap<>();
+ for (DataSegment segment : dataSegments) {
+ versionIntervalToNumCorePartitions.computeIfAbsent(segment.getVersion(), v -> new HashMap<>())
+ .put(segment.getInterval(), segment.getShardSpec().getNumCorePartitions());
+ retrievedIds.add(segment.getId().toString());
+ }
+ if (!retrievedIds.equals(segmentIdsToRetrieve)) {
+ throw DruidException.defensive(
+ "Cannot create DataSegments for segment allocations."
+ + "The used segments may have changed for dataSource[%s] and interval[%s].",
Review Comment:
## Missing space in string literal
This string appears to be missing a space after 'allocations.'.
[Show more details](https://github.com/apache/druid/security/code-scanning/8436)
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz closed pull request #17420: Faster batch segment allocation by reducing metadata IO
URL: https://github.com/apache/druid/pull/17420
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "maytasm (via GitHub)" <gi...@apache.org>.
maytasm commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821529186
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -242,6 +245,69 @@ public CloseableIterator<DataSegmentPlus> retrieveUnusedSegmentsPlus(
);
}
+ public Set<SegmentId> retrieveUsedSegmentIds(
+ final String dataSource,
+ final Interval interval
+ )
+ {
+ return retrieveSegmentIds(dataSource, Collections.singletonList(interval));
+ }
+
+ private Set<SegmentId> retrieveSegmentIds(
Review Comment:
should this also be called retrieveUsedSegmentIds?
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "maytasm (via GitHub)" <gi...@apache.org>.
maytasm commented on PR #17420:
URL: https://github.com/apache/druid/pull/17420#issuecomment-2576064363
> @maytasm , I am currently working on caching segment metadata on the Overlord to speed up segment allocations. I plan to publish that PR some time this week. Once that is in place, we shouldn't need any separate caching mechanism at the `TaskLockPosse` level.
Is it this PR, https://github.com/apache/druid/pull/17390 ? Thanks!
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "maytasm (via GitHub)" <gi...@apache.org>.
maytasm commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821538435
##########
server/src/main/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinator.java:
##########
@@ -2900,6 +2929,70 @@ public int removeDataSourceMetadataOlderThan(long timestamp, @NotNull Set<String
);
}
+ @VisibleForTesting
+ Set<DataSegment> retrieveUsedSegmentsForAllocation(
+ final Handle handle,
+ final String dataSource,
+ final Interval interval
+ )
+ {
+ final Set<SegmentId> overlappingSegmentIds = SqlSegmentsMetadataQuery.forHandle(handle, connector, dbTables, jsonMapper)
+ .retrieveUsedSegmentIds(
+ dataSource,
+ interval
+ );
+ // Map from version -> interval -> segmentId with the smallest partitionNum
+ Map<String, Map<Interval, SegmentId>> versionIntervalToSmallestSegmentId = new HashMap<>();
+ for (SegmentId segmentId : overlappingSegmentIds) {
+ final Map<Interval, SegmentId> map
+ = versionIntervalToSmallestSegmentId.computeIfAbsent(segmentId.getVersion(), v -> new HashMap<>());
+ final SegmentId value = map.get(segmentId.getInterval());
+ if (value == null || value.getPartitionNum() > segmentId.getPartitionNum()) {
+ map.put(interval, segmentId);
+ }
+ }
+
+ // Retrieve the segments for the ids stored in the map to get the numCorePartitions
+ final Set<String> segmentIdsToRetrieve = new HashSet<>();
+ for (Map<Interval, SegmentId> itvlMap : versionIntervalToSmallestSegmentId.values()) {
Review Comment:
can you add as comment on the use of Smallest. Thanks
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "maytasm (via GitHub)" <gi...@apache.org>.
maytasm commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821480405
##########
indexing-service/src/main/java/org/apache/druid/indexing/common/actions/SegmentAllocationQueue.java:
##########
@@ -380,13 +383,11 @@ private boolean processBatch(AllocateRequestBatch requestBatch)
private Set<DataSegment> retrieveUsedSegments(AllocateRequestKey key)
{
- return new HashSet<>(
- metadataStorage.retrieveUsedSegmentsForInterval(
- key.dataSource,
- key.preferredAllocationInterval,
- Segments.ONLY_VISIBLE
- )
- );
+ return metadataStorage.getSegmentTimelineForAllocation(
Review Comment:
Is it inefficient here if skipSegmentPayloadFetchForAllocation is true? We are getting segments from retrieveUsedSegmentsForAllocation then creating a timeline via SegmentTimeline.forSegments and then getting segments back again via findNonOvershadowedObjectsInInterval. Why do we even need to create a timeline?
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "AmatyaAvadhanula (via GitHub)" <gi...@apache.org>.
AmatyaAvadhanula commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821533588
##########
indexing-service/src/test/java/org/apache/druid/indexing/common/actions/SegmentAllocationQueueTest.java:
##########
@@ -73,6 +89,12 @@ public long getBatchAllocationWaitTime()
{
return 0;
}
+
+ @Override
+ public boolean isSegmentAllocationReduceMetadataIO()
+ {
+ return true;
Review Comment:
Will do this
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on PR #17420:
URL: https://github.com/apache/druid/pull/17420#issuecomment-2652632056
Closing this PR as #17653 and #17496 have already been merged.
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "maytasm (via GitHub)" <gi...@apache.org>.
maytasm commented on PR #17420:
URL: https://github.com/apache/druid/pull/17420#issuecomment-2569976600
Do we have plan to implement TaskLockPosse level cache for segment allocations too? @AmatyaAvadhanula @kfaraz
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "AmatyaAvadhanula (via GitHub)" <gi...@apache.org>.
AmatyaAvadhanula commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821493037
##########
indexing-service/src/main/java/org/apache/druid/indexing/common/actions/SegmentAllocationQueue.java:
##########
@@ -380,13 +383,11 @@ private boolean processBatch(AllocateRequestBatch requestBatch)
private Set<DataSegment> retrieveUsedSegments(AllocateRequestKey key)
{
- return new HashSet<>(
- metadataStorage.retrieveUsedSegmentsForInterval(
- key.dataSource,
- key.preferredAllocationInterval,
- Segments.ONLY_VISIBLE
- )
- );
+ return metadataStorage.getSegmentTimelineForAllocation(
Review Comment:
Do you mean when it is false?
If it is true, we are simply getting all the used ids in the retrieval call, so we'd have to create a SegmentTimeline as we're interested only in the visible segment set
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1820125029
##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/TaskLockbox.java:
##########
@@ -702,12 +711,12 @@ private TaskLockPosse createNewTaskLockPosse(LockRequest request)
* for the given requests. Updates the holder with the allocated segment if
* the allocation succeeds, otherwise marks it as failed.
*/
- @VisibleForTesting
- void allocateSegmentIds(
+ private void allocateSegmentIds(
String dataSource,
Interval interval,
boolean skipSegmentLineageCheck,
- Collection<SegmentAllocationHolder> holders
+ Collection<SegmentAllocationHolder> holders,
+ boolean skipSegmentPayloadFetchForAllocation
Review Comment:
Please rename this argument everywhere.
You can either call it `reduceMetadataIO` same as the config or `fetchRequiredSegmentsOnly` or something.
```suggestion
boolean reduceMetadataIO
```
##########
indexing-service/src/test/java/org/apache/druid/indexing/common/actions/SegmentAllocationQueueTest.java:
##########
@@ -73,6 +89,12 @@ public long getBatchAllocationWaitTime()
{
return 0;
}
+
+ @Override
+ public boolean isSegmentAllocationReduceMetadataIO()
+ {
+ return true;
Review Comment:
Would be nice to run the tests in this class for both true and false and not just true.
##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/config/TaskLockConfig.java:
##########
@@ -36,6 +36,9 @@ public class TaskLockConfig
@JsonProperty
private long batchAllocationWaitTime = 0L;
+ @JsonProperty
+ private boolean segmentAllocationReduceMetadataIO = false;
Review Comment:
This is used only for batch segment allocation, IIUC. Let's rename it to `batchAllocationReduceMetadataIO`.
Once this has been tested thoroughly, we can remove the flag altogether and use the new approach for both regular and batch allocation.
##########
indexing-service/src/main/java/org/apache/druid/indexing/common/actions/SegmentAllocationQueue.java:
##########
@@ -87,6 +87,8 @@ public class SegmentAllocationQueue
private final ConcurrentHashMap<AllocateRequestKey, AllocateRequestBatch> keyToBatch = new ConcurrentHashMap<>();
private final BlockingDeque<AllocateRequestBatch> processingQueue = new LinkedBlockingDeque<>(MAX_QUEUE_SIZE);
+ private final boolean skipSegmentPayloadFetchForAllocation;
Review Comment:
Please rename as suggested.
##########
indexing-service/src/test/java/org/apache/druid/indexing/common/actions/SegmentAllocationQueueTest.java:
##########
@@ -99,6 +121,133 @@ public void tearDown()
emitter.flush();
}
+ @Test
+ @Ignore
Review Comment:
Let's remove this test if we are not running it as a UT. If it is meant to be a benchmark, please put it in a `Benchmark` class and share the details of a some sample run in the PR description.
##########
server/src/main/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinator.java:
##########
@@ -2900,6 +2929,70 @@ public int removeDataSourceMetadataOlderThan(long timestamp, @NotNull Set<String
);
}
+ @VisibleForTesting
+ Set<DataSegment> retrieveUsedSegmentsForAllocation(
+ final Handle handle,
+ final String dataSource,
+ final Interval interval
+ )
+ {
+ final Set<SegmentId> overlappingSegmentIds = SqlSegmentsMetadataQuery.forHandle(handle, connector, dbTables, jsonMapper)
+ .retrieveUsedSegmentIds(
+ dataSource,
+ interval
+ );
+ // Map from version -> interval -> segmentId with the smallest partitionNum
+ Map<String, Map<Interval, SegmentId>> versionIntervalToSmallestSegmentId = new HashMap<>();
+ for (SegmentId segmentId : overlappingSegmentIds) {
+ final Map<Interval, SegmentId> map
+ = versionIntervalToSmallestSegmentId.computeIfAbsent(segmentId.getVersion(), v -> new HashMap<>());
+ final SegmentId value = map.get(segmentId.getInterval());
+ if (value == null || value.getPartitionNum() > segmentId.getPartitionNum()) {
+ map.put(interval, segmentId);
+ }
+ }
+
+ // Retrieve the segments for the ids stored in the map to get the numCorePartitions
+ final Set<String> segmentIdsToRetrieve = new HashSet<>();
+ for (Map<Interval, SegmentId> itvlMap : versionIntervalToSmallestSegmentId.values()) {
+ segmentIdsToRetrieve.addAll(itvlMap.values().stream().map(SegmentId::toString).collect(Collectors.toList()));
+ }
+ final Set<DataSegment> dataSegments = retrieveSegmentsById(dataSource, segmentIdsToRetrieve);
+ final Set<String> retrievedIds = new HashSet<>();
+ final Map<String, Map<Interval, Integer>> versionIntervalToNumCorePartitions = new HashMap<>();
+ for (DataSegment segment : dataSegments) {
+ versionIntervalToNumCorePartitions.computeIfAbsent(segment.getVersion(), v -> new HashMap<>())
+ .put(segment.getInterval(), segment.getShardSpec().getNumCorePartitions());
+ retrievedIds.add(segment.getId().toString());
+ }
+ if (!retrievedIds.equals(segmentIdsToRetrieve)) {
+ throw DruidException.defensive(
+ "Cannot create DataSegments for segment allocations."
+ + "The used segments may have changed for dataSource[%s] and interval[%s].",
+ dataSource, interval
+ );
+ }
+
+ // Populate the required segment info
Review Comment:
```suggestion
// Create dummy segments for each segmentId with only the shard spec populated
```
##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/TaskLockbox.java:
##########
@@ -702,12 +711,12 @@ private TaskLockPosse createNewTaskLockPosse(LockRequest request)
* for the given requests. Updates the holder with the allocated segment if
* the allocation succeeds, otherwise marks it as failed.
*/
- @VisibleForTesting
- void allocateSegmentIds(
Review Comment:
thanks!
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on PR #17420:
URL: https://github.com/apache/druid/pull/17420#issuecomment-2454201410
@AmatyaAvadhanula , caching the segment state seems like a good idea.
But it would be better to limit this PR to have only the `reduceMetadataIO` changes which fetch only the segment IDs and not all the payloads. That change has already been tested on some clusters and it is best to keep it as a separate patch from other experimental changes.
The caching changes can be done as a follow up to this PR.
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on PR #17420:
URL: https://github.com/apache/druid/pull/17420#issuecomment-2572300939
@maytasm , I am currently working on caching segment metadata on the Overlord to speed up segment allocations.
I plan to publish that PR some time this week. Once that is in place, we shouldn't need any separate caching mechanism at the `TaskLockPosse` level.
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "AmatyaAvadhanula (via GitHub)" <gi...@apache.org>.
AmatyaAvadhanula commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821534953
##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/config/TaskLockConfig.java:
##########
@@ -36,6 +36,9 @@ public class TaskLockConfig
@JsonProperty
private long batchAllocationWaitTime = 0L;
+ @JsonProperty
+ private boolean segmentAllocationReduceMetadataIO = false;
Review Comment:
Are you against its usage in the normal flow with the same feature flag?
It's behind a flag anyway so I don't think there's a need to not make the changes there.
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "AmatyaAvadhanula (via GitHub)" <gi...@apache.org>.
AmatyaAvadhanula commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821533849
##########
indexing-service/src/test/java/org/apache/druid/indexing/common/actions/SegmentAllocationQueueTest.java:
##########
@@ -99,6 +121,133 @@ public void tearDown()
emitter.flush();
}
+ @Test
+ @Ignore
Review Comment:
Understood, will remove it.
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "maytasm (via GitHub)" <gi...@apache.org>.
maytasm commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821513030
##########
server/src/main/java/org/apache/druid/metadata/IndexerSQLMetadataStorageCoordinator.java:
##########
@@ -2900,6 +2929,70 @@ public int removeDataSourceMetadataOlderThan(long timestamp, @NotNull Set<String
);
}
+ @VisibleForTesting
+ Set<DataSegment> retrieveUsedSegmentsForAllocation(
+ final Handle handle,
+ final String dataSource,
+ final Interval interval
+ )
+ {
+ final Set<SegmentId> overlappingSegmentIds = SqlSegmentsMetadataQuery.forHandle(handle, connector, dbTables, jsonMapper)
+ .retrieveUsedSegmentIds(
+ dataSource,
+ interval
+ );
+ // Map from version -> interval -> segmentId with the smallest partitionNum
+ Map<String, Map<Interval, SegmentId>> versionIntervalToSmallestSegmentId = new HashMap<>();
+ for (SegmentId segmentId : overlappingSegmentIds) {
+ final Map<Interval, SegmentId> map
+ = versionIntervalToSmallestSegmentId.computeIfAbsent(segmentId.getVersion(), v -> new HashMap<>());
+ final SegmentId value = map.get(segmentId.getInterval());
+ if (value == null || value.getPartitionNum() > segmentId.getPartitionNum()) {
+ map.put(interval, segmentId);
+ }
+ }
+
+ // Retrieve the segments for the ids stored in the map to get the numCorePartitions
+ final Set<String> segmentIdsToRetrieve = new HashSet<>();
+ for (Map<Interval, SegmentId> itvlMap : versionIntervalToSmallestSegmentId.values()) {
Review Comment:
Why do we want/use the Smallest here?
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "AmatyaAvadhanula (via GitHub)" <gi...@apache.org>.
AmatyaAvadhanula commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821530769
##########
server/src/main/java/org/apache/druid/metadata/SqlSegmentsMetadataQuery.java:
##########
@@ -242,6 +245,69 @@ public CloseableIterator<DataSegmentPlus> retrieveUnusedSegmentsPlus(
);
}
+ public Set<SegmentId> retrieveUsedSegmentIds(
+ final String dataSource,
+ final Interval interval
+ )
+ {
+ return retrieveSegmentIds(dataSource, Collections.singletonList(interval));
+ }
+
+ private Set<SegmentId> retrieveSegmentIds(
Review Comment:
Yes, it should. Thanks, I'll make the change.
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #17420:
URL: https://github.com/apache/druid/pull/17420#discussion_r1821679094
##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/TaskLockbox.java:
##########
@@ -452,6 +463,232 @@
}
}
+ public void cacheSegmentPublishResults(Task task, Collection<DataSegment> segments)
+ {
+ if (!segmentAllocationReduceMetadataIO) {
+ return;
+ }
+ Map<Interval, DataSegment> intervalToMaxSegment = new HashMap<>();
+ for (DataSegment segment : segments) {
+ final Interval interval = segment.getInterval();
+ if (intervalToMaxSegment.get(interval) == null
+ || intervalToMaxSegment.get(interval).getId().getPartitionNum() < segment.getId().getPartitionNum()) {
+ intervalToMaxSegment.put(interval, segment);
+ }
+ }
+ for (Map.Entry<Interval, DataSegment> entry : intervalToMaxSegment.entrySet()) {
+ final Interval interval = entry.getKey();
+ for (TaskLockPosse posse : findLockPossesOverlapsInterval(task.getDataSource(), interval)) {
+ if (posse.containsTask(task)) {
+ if (posse.getTaskLock().getInterval().equals(interval) && posse.visibleSegmentState != null) {
+ posse.visibleSegmentState.updateMaxSegment(entry.getValue());
+ }
+ }
+ }
+ }
+ }
+
+ public boolean canAllocateSegmentWithReducedMetadataIO(final LockGranularity granularity, final TaskLockType lockType)
+ {
+ return segmentAllocationReduceMetadataIO
+ && granularity == LockGranularity.TIME_CHUNK
+ && (lockType == TaskLockType.EXCLUSIVE || lockType == TaskLockType.SHARED);
+ }
+
+ public LockResult allocateSegmentWithReducedMetadataIO(
+ final Task task,
+ final TaskLockType lockType,
+ final DateTime timestamp,
+ final Granularity queryGranularity,
+ final Granularity preferredSegmentGranularity,
+ final String sequenceName,
+ final String previousSegmentId,
+ final boolean skipSegmentLineageCheck,
+ final PartialShardSpec partialShardSpec
+ )
+ {
+ giant.lock();
+
+ try {
+ final Interval rowInterval = queryGranularity.bucket(timestamp).withChronology(ISOChronology.getInstanceUTC());
+
+ for (Granularity segmentGranularity : Granularity.granularitiesFinerThan(preferredSegmentGranularity)) {
+ final Interval segmentInterval = segmentGranularity.bucket(timestamp)
+ .withChronology(ISOChronology.getInstanceUTC());
+ if (!segmentInterval.contains(rowInterval)) {
+ break;
+ }
+ final VisibleSegmentState visibleSegmentState = determineVisibleSegmentState(task, segmentInterval);
+ if (visibleSegmentState == null) {
+ continue;
+ }
+
+ if (!visibleSegmentState.interval.contains(rowInterval)) {
+ continue;
+ }
+
+ if (visibleSegmentState.committedVersion == null && !visibleSegmentState.interval.equals(segmentInterval)) {
+ continue;
+ }
+
+ final TimeChunkLockRequest lockRequest
+ = new TimeChunkLockRequest(lockType, task, visibleSegmentState.interval, null);
+
+ final TaskLockPosse lockPosse = createOrFindLockPosse(lockRequest, task, true);
+
+ if (lockPosse.getTaskLock().isRevoked()) {
+ log.warn("Lock[%s] is revoked.", lockPosse.getTaskLock());
+ return LockResult.revoked(lockPosse.getTaskLock());
+ }
+
+ if (!lockPosse.getTaskLock().getInterval().equals(visibleSegmentState.interval)) {
+ log.warn(
+ "Interval[%s] of existing segments for datasource[%s] does not match the lock interval[%s]",
+ visibleSegmentState.interval, task.getDataSource(), lockPosse.taskLock.getInterval()
+ );
+ unlock(task, lockPosse.getTaskLock().getInterval());
+ continue;
+ }
+
+ if (lockPosse.visibleSegmentState == null) {
+ lockPosse.visibleSegmentState = visibleSegmentState;
+ } else if (!lockPosse.visibleSegmentState.equals(visibleSegmentState)) {
+ throw DruidException.defensive("VisibleSegmentState mismatch for lock[%s]", lockPosse.getTaskLock());
+ }
+
+ final String allocatorId = ((PendingSegmentAllocatingTask) task).getTaskAllocatorId();
+ SegmentIdWithShardSpec allocatedId = ((IndexerSQLMetadataStorageCoordinator) metadataStorageCoordinator)
+ .findOrInsertPendingSegmentRecord(
+ task.getDataSource(),
+ visibleSegmentState.interval,
+ visibleSegmentState.committedVersion,
+ visibleSegmentState.getVersion(lockPosse.taskLock.getVersion()),
+ visibleSegmentState.getMaxId(),
+ visibleSegmentState.numCorePartitions,
+ partialShardSpec,
+ sequenceName,
+ previousSegmentId,
+ skipSegmentLineageCheck,
+ allocatorId
+ );
+
+ if (allocatedId != null) {
+ visibleSegmentState.addPendingSegment(
+ new PendingSegmentRecord(allocatedId, sequenceName, previousSegmentId, null, allocatorId)
+ );
+ }
+ log.info("Found or Allocated pendingSegment[%s].", allocatedId.asSegmentId());
Review Comment:
## Dereferenced variable may be null
Variable [allocatedId](1) may be null at this access as suggested by [this](2) null guard.
[Show more details](https://github.com/apache/druid/security/code-scanning/8440)
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org
Re: [PR] Faster batch segment allocation by reducing metadata IO (druid)
Posted by "AmatyaAvadhanula (via GitHub)" <gi...@apache.org>.
AmatyaAvadhanula commented on PR #17420:
URL: https://github.com/apache/druid/pull/17420#issuecomment-2445525099
I've added a TaskLockPosse level cache for segment allocations with the idea that the used segment set and pending segments are covered by an appending lock and cannot change unless altered by tasks holding these locks.
There are 24 intervals, each with 2000 datasegments, each with 1000 dimensions.
With with a batching of 5, and 128 allocations (2 replicas)
Here are the results using a simple unit test:
- Batch segment allocation with the flag turned off
```
INFO [main] org.apache.druid.indexing.common.actions.SegmentAllocateActionTest - Total time taken for [3072] allocations is [653233] ms.
```
- Batch segment allocation with the flag turned on : `3x Improvement`
```
INFO [main] org.apache.druid.indexing.common.actions.SegmentAllocateActionTest - Total time taken for [3072] allocations is [236854] ms.
```
- Normal segment allocation with the mentioned caching with the flag: `100x improvement`
```
INFO [main] org.apache.druid.indexing.common.actions.SegmentAllocateActionTest - Total time taken for [3072] allocations is [6302] ms.
```
`TLDR` : Turning the flag on gives a 3x boost over batch segment allocation, while using the cache gives about 100x.
--
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: commits-unsubscribe@druid.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org