You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by "kfaraz (via GitHub)" <gi...@apache.org> on 2025/08/14 06:50:57 UTC
[PR] Add catalog templates to power cascading compaction (druid)
kfaraz opened a new pull request, #18402:
URL: https://github.com/apache/druid/pull/18402
### Summary
- Add batch indexing templates that live in the Druid catalog.
- These templates can be used to perform a variety of batch indexing operations
such as compaction, export, batch ingestion, or any ETL in general.
- Templates allow easy reuse of logic with all the niceties of Druid catalog.
- Add batch indexing supervisor as a base supervisor for managing batch tasks (analogous to `SeekableStreamSupervisor`)
- `CompactionSupervisor` now implements `BatchIndexingSupervisor` and is powered by
`CompactionJobTemplates`.
- Using templates instead of the `DataSourceCompactionConfig` makes the logic much more extensible.
- In the future, we can have `ScheduledBatchSupervisor` also implement `BatchIndexingSupervisor`
### Major changes
- Add `BatchIndexingJob` which may contain exactly one of:
- a `Task` (as a `ClientTaskQuery`)
- OR an MSQ SQL (as a `ClientSqlQuery`)
- Add `BatchIndexingJobTemplate`
- `List<BatchIndexingJob> createJobs(InputSource source, OutputDestination destination, JobParams params)`
- Add `BatchIndexingSupervisor<J, P>`
- `List<J> createJobs(P params)`
- Implement `BatchIndexingSupervisor` with `CompactionSupervisor`
- Extend `BatchIndexingJob` with `CompactionJob` to contain additional info such as `CompactionCandidate` and `compactionInterval`
#### Supported template types
|Type|Class|Function|
|-----|-----|---------|
|`compactInline`|`InlineCompactionJobTemplate`|Simple template to define a `segmentGranularity`, `partitionsSpec` etc. to use in a compaction job. Can be used directly inside a cascading template or stored in the Druid catalog.|
|`compactCatalog`|`CatalogCompactionJobTemplate`|Template which references to a delegate template stored in the Druid catalog. The referenced template can currently only be an `InlineCompactionJobTemplate`.|
|`compactCascade`|`CascadingCompactionTemplate`|Template used by compaction supervisor for period-based cascading compaction.|
#### Catalog changes
- Add a new schema `index_template`
- Register a new table definition `IndexingTemplateDefn` which can currently contain only one property `payload`
- Technically, the indexing template does not fit the bill for a `TableDefn`, but rather `ObjectDefn`
- But since a template is flexible enough, it can be thought of as a table creator
- And owing to the flexible model of the catalog `TableSpec`, treating the templates as a table definition seemed
like the cleanest approach
Please leave feedback on whether there is a better/cleaner alternative.
### Pending changes
- Add a basic MSQ template
- Handle some minor corner cases
- Fill timeline gaps due to misaligned granularities in cascading compaction
### Release note
TODO
<hr>
This PR has:
- [ ] 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.
- [ ] 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)
- [ ] added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
- [ ] 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.
- [ ] 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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on PR #18402:
URL: https://github.com/apache/druid/pull/18402#issuecomment-3467692348
Since there is a lack of clarity on how the catalog would be used to persist compaction templates, the catalog bits have been removed from this PR for the time being.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2361762785
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CatalogCompactionJobTemplate.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JacksonInject;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.catalog.MetadataCatalog;
+import org.apache.druid.catalog.model.ResolvedTable;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.table.IndexingTemplateDefn;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.indexing.template.BatchIndexingJobTemplate;
+import org.apache.druid.java.util.common.granularity.Granularity;
+
+import javax.annotation.Nullable;
+import java.util.List;
+
+/**
+ * Compaction template that delegates job creation to a template stored in the
+ * Druid catalog.
+ */
+public class CatalogCompactionJobTemplate implements CompactionJobTemplate
+{
+ public static final String TYPE = "compactCatalog";
+
+ private final String templateId;
+
+ private final TableId tableId;
+ private final MetadataCatalog catalog;
+
+ @JsonCreator
+ public CatalogCompactionJobTemplate(
+ @JsonProperty("templateId") String templateId,
+ @JacksonInject MetadataCatalog catalog
+ )
+ {
+ this.templateId = templateId;
+ this.catalog = catalog;
+ this.tableId = TableId.of(TableId.INDEXING_TEMPLATE_SCHEMA, templateId);
+ }
+
+ @JsonProperty
+ public String getTemplateId()
+ {
+ return templateId;
+ }
+
+ @Nullable
+ @Override
+ public Granularity getSegmentGranularity()
+ {
+ final CompactionJobTemplate delegate = getDelegate();
+ return delegate == null ? null : delegate.getSegmentGranularity();
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams params
+ )
+ {
+ final CompactionJobTemplate delegate = getDelegate();
+ if (delegate == null) {
+ return List.of();
+ } else {
+ return delegate.createCompactionJobs(source, params);
+ }
+ }
+
+ @Nullable
+ private CompactionJobTemplate getDelegate()
+ {
+ final ResolvedTable resolvedTable = catalog.resolveTable(tableId);
+ if (resolvedTable == null) {
+ return null;
+ }
+
+ final BatchIndexingJobTemplate delegate
+ = resolvedTable.decodeProperty(IndexingTemplateDefn.PROPERTY_PAYLOAD);
+ if (delegate instanceof CompactionJobTemplate) {
+ return (CompactionJobTemplate) delegate;
+ } else {
Review Comment:
Yes, this felt hacky to me too. Unfortunately, the Druid catalog currently only understands a "table" as the top-level object. So, I just stuck to that model for the time being. I have also put in some relevant points in the PR descrioption under "Open questions".
@clintropolis , do you have any suggestions on what would be the preferred approach to store an indexing/compaction template in the catalog?
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "capistrant (via GitHub)" <gi...@apache.org>.
capistrant commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2475543524
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/MSQCompactionJobTemplate.java:
##########
@@ -0,0 +1,191 @@
+/*
Review Comment:
when I was playing with this on my local I accidentally got into a state where I had defined an expected granularity of MONTH, but the query in the template was DAY. It looked like it just went into an infinite compact loop. Could we force the templated query to honor segment granularity from the state matcher by injecting it? I guess this forces everyone creating a rule to select a segment gran though, which is probably not desired.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2465834418
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionJobParams.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.druid.indexing.compact;
+
+import org.apache.druid.indexing.template.JobParams;
+import org.apache.druid.server.compaction.CompactionSnapshotBuilder;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.timeline.SegmentTimeline;
+import org.joda.time.DateTime;
+
+/**
+ * Parameters used while creating a {@link CompactionJob} using a {@link CompactionJobTemplate}.
+ */
+public class CompactionJobParams implements JobParams
Review Comment:
The search interval seemed like a better fit for the `InputSource` since it defines the time range of the data that is the input for a job template.
But I guess we can also include it in `CompactionJobParams` so that the templates may filter out any jobs outside of the search interval.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2476620120
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/MSQCompactionJobTemplate.java:
##########
@@ -0,0 +1,191 @@
+/*
Review Comment:
Allowing the state matcher to be distinct from the query is by design as it allows us to make improvements the query without worrying about all the intervals being recompacted when not desired.
For the time being, it is upto the user to ensure that the state matcher and the query are compatible with each other.
In future versions, we will include some kind of template validation.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2476627399
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionStateMatcher.java:
##########
@@ -0,0 +1,183 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.data.input.impl.AggregateProjectionSpec;
+import org.apache.druid.data.input.impl.DimensionsSpec;
+import org.apache.druid.indexer.partitions.PartitionsSpec;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.query.aggregation.AggregatorFactory;
+import org.apache.druid.segment.IndexSpec;
+import org.apache.druid.segment.transform.CompactionTransformSpec;
+import org.apache.druid.server.coordinator.UserCompactionTaskGranularityConfig;
+
+import javax.annotation.Nullable;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Target compacted state of segments used to determine if compaction is needed
+ * for an interval. An explicitly defined target state helps avoid superfluous
+ * compaction when only the job definition has changed.
+ * <p>
+ * This class is mostly a duplicate of {@code CompactionState} but is kept
+ * separate to allow:
+ * <ul>
+ * <li>fields to be nullable so that only non-null fields are used for matching</li>
+ * <li>legacy "compaction-incompatible" fields to be removed</li>
Review Comment:
Updated the javadoc to clarify this point. But it mostly refers to things like the `transformSpec` which can filter out data or even the `dimensionsSpec` where we may choose to drop some dimensions and thus cause an irreversible aggregation of the data.
(Side note: the more desirable way to achieve this pre-aggregation to improve query perf would be to use projections).
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2465834418
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionJobParams.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.druid.indexing.compact;
+
+import org.apache.druid.indexing.template.JobParams;
+import org.apache.druid.server.compaction.CompactionSnapshotBuilder;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.timeline.SegmentTimeline;
+import org.joda.time.DateTime;
+
+/**
+ * Parameters used while creating a {@link CompactionJob} using a {@link CompactionJobTemplate}.
+ */
+public class CompactionJobParams implements JobParams
Review Comment:
The search interval seemed like a better fit for the `InputSource` since it defines the time range of the data that is the input for a job template.
It seemed redundant to include it in `CompactionJobParams` too since the passed `DruidInputSource` already contains the search interval.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "capistrant (via GitHub)" <gi...@apache.org>.
capistrant commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2475534268
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/MSQCompactionJobTemplate.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.query.http.ClientSqlQuery;
+import org.apache.druid.server.compaction.CompactionCandidate;
+import org.apache.druid.server.compaction.CompactionSlotManager;
+import org.apache.druid.server.compaction.DataSourceCompactibleSegmentIterator;
+import org.apache.druid.server.coordinator.duty.CompactSegments;
+import org.joda.time.Interval;
+import org.joda.time.format.DateTimeFormat;
+import org.joda.time.format.DateTimeFormatter;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Compaction template that creates MSQ SQL jobs using a templatized SQL with
+ * variables of the format {@code ${variableName}} for fields such as datasource
+ * name and start timestamp.
+ * <p>
+ * Compaction is triggered for an interval only if the current compaction state
+ * of the underlying segments DOES NOT match with the {@link #targetState}.
+ */
+public class MSQCompactionJobTemplate implements CompactionJobTemplate
+{
+ public static final String TYPE = "compactMsq";
+
+ public static final String VAR_DATASOURCE = "${dataSource}";
+ public static final String VAR_START_TIMESTAMP = "${startTimestamp}";
+ public static final String VAR_END_TIMESTAMP = "${endTimestamp}";
+
+ private static final DateTimeFormatter TIMESTAMP_FORMATTER =
+ DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
+
+ private final ClientSqlQuery sqlTemplate;
+ private final CompactionStateMatcher targetState;
+
+ @JsonCreator
+ public MSQCompactionJobTemplate(
+ @JsonProperty("sqlTemplate") ClientSqlQuery sqlTemplate,
+ @JsonProperty("targetState") CompactionStateMatcher targetState
+ )
+ {
+ this.sqlTemplate = sqlTemplate;
+ this.targetState = targetState;
+ }
+
+ @JsonProperty
+ public ClientSqlQuery getSqlTemplate()
+ {
+ return sqlTemplate;
+ }
+
+ @JsonProperty
+ public CompactionStateMatcher getTargetState()
+ {
+ return targetState;
+ }
+
+ @Nullable
+ @Override
+ public Granularity getSegmentGranularity()
+ {
+ return targetState.getSegmentGranularity();
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams jobParams
+ )
+ {
+ final String dataSource = source.getDataSource();
+
+ // Identify the compactible candidate segments
+ final CompactionConfigBasedJobTemplate delegate =
+ CompactionConfigBasedJobTemplate.create(dataSource, targetState);
+ final DataSourceCompactibleSegmentIterator candidateIterator =
+ delegate.getCompactibleCandidates(source, jobParams);
+
+ // Create MSQ jobs for each candidate by interpolating the template variables
+ final List<CompactionJob> jobs = new ArrayList<>();
+ while (candidateIterator.hasNext()) {
+ final CompactionCandidate candidate = candidateIterator.next();
+ jobs.add(
+ new CompactionJob(
+ createQueryForJob(dataSource, candidate.getCompactionInterval()),
+ candidate,
+ CompactionSlotManager.getMaxTaskSlotsForMSQCompactionTask(sqlTemplate.getContext())
+ )
+ );
+ }
+
+ return jobs;
+ }
+
+ private ClientSqlQuery createQueryForJob(String dataSource, Interval compactionInterval)
Review Comment:
I guess since this is just inline, the filter could be defined inline. But if someone changed the query after it existed for some time that filter wouldn't be re-applied to already compacted segments since it is not persisted in the target state.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2464654523
##########
server/src/test/java/org/apache/druid/server/metrics/LatchableEmitter.java:
##########
@@ -260,12 +262,11 @@
}
/**
- * Matches an event only if it has a metric value equal to or greater than
- * the given value.
+ * Matches an event only if the metric value satisfies the given matcher.
*/
- public EventMatcher hasValueAtLeast(long metricValue)
+ public EventMatcher hasValue(Matcher<Long> valueMatcher)
{
- this.metricValue = metricValue;
+ this.valueMatcher = valueMatcher;
Review Comment:
## Confusing overloading of methods
Method EventMatcher.hasDimension(..) could be confused with overloaded method [hasDimension](1), since dispatch depends on static types.
[Show more details](https://github.com/apache/druid/security/code-scanning/10232)
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2275711471
##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/BatchIndexingSupervisor.java:
##########
@@ -0,0 +1,48 @@
+/*
+ * 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.druid.indexing.overlord.supervisor;
+
+import org.apache.druid.indexing.template.BatchIndexingJob;
+import org.apache.druid.indexing.template.JobParams;
+
+import java.util.List;
+
+/**
+ * Supervisor to perform batch ingestion using {@link BatchIndexingJob}.
+ */
+public interface BatchIndexingSupervisor
+ <J extends BatchIndexingJob, P extends JobParams> extends Supervisor
+{
+ /**
+ * Checks if this supervisor is ready to create jobs in the current run.
+ *
+ * @param jobParams Parameters for the current run of the scheduler.
+ */
+ boolean shouldCreateJobs(P jobParams);
Review Comment:
## Useless parameter
The parameter 'jobParams' is never used.
[Show more details](https://github.com/apache/druid/security/code-scanning/10178)
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionJobQueue.java:
##########
@@ -0,0 +1,281 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.client.DataSourcesSnapshot;
+import org.apache.druid.client.indexing.ClientCompactionTaskQuery;
+import org.apache.druid.client.indexing.ClientTaskQuery;
+import org.apache.druid.common.guava.FutureUtils;
+import org.apache.druid.indexing.common.actions.TaskActionClientFactory;
+import org.apache.druid.indexing.common.task.Task;
+import org.apache.druid.indexing.overlord.GlobalTaskLockbox;
+import org.apache.druid.indexing.template.BatchIndexingJob;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.apache.druid.rpc.indexing.OverlordClient;
+import org.apache.druid.server.compaction.CompactionCandidate;
+import org.apache.druid.server.compaction.CompactionCandidateSearchPolicy;
+import org.apache.druid.server.compaction.CompactionSlotManager;
+import org.apache.druid.server.compaction.CompactionSnapshotBuilder;
+import org.apache.druid.server.compaction.CompactionStatus;
+import org.apache.druid.server.compaction.CompactionStatusTracker;
+import org.apache.druid.server.coordinator.AutoCompactionSnapshot;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.server.coordinator.CompactionConfigValidationResult;
+import org.apache.druid.server.coordinator.stats.CoordinatorRunStats;
+import org.apache.druid.server.coordinator.stats.Dimension;
+import org.apache.druid.server.coordinator.stats.RowKey;
+import org.apache.druid.server.coordinator.stats.Stats;
+
+import java.util.Map;
+import java.util.Objects;
+import java.util.PriorityQueue;
+
+/**
+ * Iterates over all eligible compaction jobs in order of their priority.
+ * A fresh instance of this class must be used in every run of the
+ * {@link CompactionScheduler}.
+ */
+public class CompactionJobQueue
+{
+ private static final Logger log = new Logger(CompactionJobQueue.class);
+
+ private final CompactionJobParams jobParams;
+ private final CompactionCandidateSearchPolicy searchPolicy;
+
+ private final ObjectMapper objectMapper;
+ private final CompactionStatusTracker statusTracker;
+ private final TaskActionClientFactory taskActionClientFactory;
+ private final OverlordClient overlordClient;
+ private final GlobalTaskLockbox taskLockbox;
+
+ private final CompactionSnapshotBuilder snapshotBuilder;
+ private final PriorityQueue<CompactionJob> queue;
+ private final CoordinatorRunStats runStats;
+
+ private final CompactionSlotManager slotManager;
+
+ public CompactionJobQueue(
+ DataSourcesSnapshot dataSourcesSnapshot,
+ ClusterCompactionConfig clusterCompactionConfig,
+ CompactionStatusTracker statusTracker,
+ TaskActionClientFactory taskActionClientFactory,
+ GlobalTaskLockbox taskLockbox,
+ OverlordClient overlordClient,
+ ObjectMapper objectMapper
+ )
+ {
+ this.searchPolicy = clusterCompactionConfig.getCompactionPolicy();
+ this.queue = new PriorityQueue<>(
+ (o1, o2) -> searchPolicy.compareCandidates(o1.getCandidate(), o2.getCandidate())
+ );
+ this.jobParams = new CompactionJobParams(
+ DateTimes.nowUtc(),
+ objectMapper,
+ dataSourcesSnapshot.getUsedSegmentsTimelinesPerDataSource()::get
+ );
+ this.slotManager = new CompactionSlotManager(
+ overlordClient,
+ statusTracker,
+ clusterCompactionConfig
+ );
+
+ this.runStats = new CoordinatorRunStats();
+ this.snapshotBuilder = new CompactionSnapshotBuilder(runStats);
+ this.taskActionClientFactory = taskActionClientFactory;
+ this.overlordClient = overlordClient;
+ this.statusTracker = statusTracker;
+ this.objectMapper = objectMapper;
+ this.taskLockbox = taskLockbox;
+
+ computeAvailableTaskSlots();
+ }
+
+ /**
+ * Adds a job to this queue.
+ */
+ public void add(CompactionJob job)
+ {
+ queue.add(job);
+ }
+
+ /**
+ * Creates jobs for the given {@link CompactionSupervisor} and adds them to
+ * the job queue.
+ */
+ public void createAndEnqueueJobs(CompactionSupervisor supervisor)
+ {
+ final String supervisorId = supervisor.getSpec().getId();
+ try {
+ if (supervisor.shouldCreateJobs(jobParams)) {
+ queue.addAll(supervisor.createJobs(jobParams));
+ } else {
+ log.debug("Skipping job creation for supervisor[%s]", supervisorId);
+ }
+ }
+ catch (Exception e) {
+ log.error(e, "Error while creating jobs for supervisor[%s]", supervisorId);
+ }
+ }
+
+ /**
+ * Submits jobs which are ready to either the Overlord or a Broker (if it is
+ * an MSQ SQL job).
+ */
+ public void runReadyJobs()
+ {
+ while (!queue.isEmpty()) {
+ final CompactionJob job = queue.poll();
+ final ClientTaskQuery task = Objects.requireNonNull(job.getNonNullTask());
+
+ if (startJobIfPendingAndReady(job, searchPolicy)) {
+ statusTracker.onTaskSubmitted(task.getId(), job.getCandidate());
+ runStats.add(Stats.Compaction.SUBMITTED_TASKS, RowKey.of(Dimension.DATASOURCE, task.getDataSource()), 1);
+ }
+ }
+ }
+
+ /**
+ * Builds and returns the compaction snapshots for all the datasources being
+ * tracked in this queue. Must be called after {@link #runReadyJobs()}.
+ */
+ public Map<String, AutoCompactionSnapshot> getCompactionSnapshots()
+ {
+ return snapshotBuilder.build();
+ }
+
+ public CoordinatorRunStats getRunStats()
+ {
+ return runStats;
+ }
+
+ private void computeAvailableTaskSlots()
+ {
+ // Do not cancel any currently running compaction tasks to be valid
+ // Future iterations can cancel a job if it doesn't match the given template
+ for (ClientCompactionTaskQuery task : slotManager.fetchRunningCompactionTasks()) {
+ slotManager.reserveTaskSlots(task);
+ }
+ }
+
+ /**
+ * Starts a job if it is ready and is not already in progress.
+ *
+ * @return true if the job was submitted successfully for execution
+ */
+ private boolean startJobIfPendingAndReady(CompactionJob job, CompactionCandidateSearchPolicy policy)
+ {
+ // Check if the job is a valid compaction job
+ final CompactionCandidate candidate = job.getCandidate();
+ final CompactionConfigValidationResult validationResult = validateCompactionJob(job);
+ if (!validationResult.isValid()) {
+ log.error("Compaction job[%s] is invalid due to reason[%s].", job, validationResult.getReason());
+ snapshotBuilder.addToSkipped(candidate);
+ return false;
+ }
+
+ // Check if the job is already running, completed or skipped
+ final CompactionStatus compactionStatus = getCurrentStatusForJob(job, policy);
+ switch (compactionStatus.getState()) {
Review Comment:
## Missing enum case in switch
Switch statement does not have a case for [PENDING](1).
[Show more details](https://github.com/apache/druid/security/code-scanning/10180)
##########
server/src/main/java/org/apache/druid/server/coordinator/duty/CompactSegments.java:
##########
@@ -271,333 +213,168 @@
}
}
- /**
- * Queries the Overlord for the status of all tasks that were submitted
- * recently but are not active anymore. The statuses are then updated in the
- * {@link #statusTracker}.
- */
- private void trackStatusOfCompletedTasks(Set<String> activeTaskIds)
- {
- final Set<String> finishedTaskIds = new HashSet<>(statusTracker.getSubmittedTaskIds());
- finishedTaskIds.removeAll(activeTaskIds);
-
- if (finishedTaskIds.isEmpty()) {
- return;
- }
-
- final Map<String, TaskStatus> taskStatusMap
- = FutureUtils.getUnchecked(overlordClient.taskStatuses(finishedTaskIds), true);
- for (String taskId : finishedTaskIds) {
- // Assume unknown task to have finished successfully
- final TaskStatus taskStatus = taskStatusMap.getOrDefault(taskId, TaskStatus.success(taskId));
- if (taskStatus.isComplete()) {
- statusTracker.onTaskFinished(taskId, taskStatus);
- }
- }
- }
-
- /**
- * Cancels a currently running compaction task if the segment granularity
- * for this datasource has changed in the compaction config.
- *
- * @return true if the task was canceled, false otherwise.
- */
- private boolean cancelTaskIfGranularityChanged(
- ClientCompactionTaskQuery compactionTaskQuery,
- DataSourceCompactionConfig dataSourceCompactionConfig
- )
- {
- if (dataSourceCompactionConfig == null
- || dataSourceCompactionConfig.getGranularitySpec() == null
- || compactionTaskQuery.getGranularitySpec() == null) {
- return false;
- }
-
- Granularity configuredSegmentGranularity = dataSourceCompactionConfig.getGranularitySpec()
- .getSegmentGranularity();
- Granularity taskSegmentGranularity = compactionTaskQuery.getGranularitySpec().getSegmentGranularity();
- if (configuredSegmentGranularity == null || configuredSegmentGranularity.equals(taskSegmentGranularity)) {
- return false;
- }
-
- LOG.info(
- "Cancelling task[%s] as task segmentGranularity[%s] differs from compaction config segmentGranularity[%s].",
- compactionTaskQuery.getId(), taskSegmentGranularity, configuredSegmentGranularity
- );
- overlordClient.cancelTask(compactionTaskQuery.getId());
- return true;
- }
-
- /**
- * Gets a List of Intervals locked by higher priority tasks for each datasource.
- * However, when using a REPLACE lock for compaction, intervals locked with any APPEND lock will not be returned
- * Since compaction tasks submitted for these Intervals would have to wait anyway,
- * we skip these Intervals until the next compaction run.
- * <p>
- * For now, Segment Locks are being treated the same as Time Chunk Locks even
- * though they lock only a Segment and not the entire Interval. Thus,
- * a compaction task will not be submitted for an Interval if
- * <ul>
- * <li>either the whole Interval is locked by a higher priority Task with an incompatible lock type</li>
- * <li>or there is atleast one Segment in the Interval that is locked by a
- * higher priority Task</li>
- * </ul>
- */
- private Map<String, List<Interval>> getLockedIntervals(
- List<DataSourceCompactionConfig> compactionConfigs
- )
- {
- final List<LockFilterPolicy> lockFilterPolicies = compactionConfigs
- .stream()
- .map(config ->
- new LockFilterPolicy(config.getDataSource(), config.getTaskPriority(), null, config.getTaskContext()))
- .collect(Collectors.toList());
- final Map<String, List<Interval>> datasourceToLockedIntervals =
- new HashMap<>(FutureUtils.getUnchecked(overlordClient.findLockedIntervals(lockFilterPolicies), true));
- LOG.debug(
- "Skipping the following intervals for Compaction as they are currently locked: %s",
- datasourceToLockedIntervals
- );
-
- return datasourceToLockedIntervals;
- }
-
- /**
- * Returns the maximum number of task slots used by one native compaction task at any time when the task is
- * issued with the given tuningConfig.
- */
- public static int findMaxNumTaskSlotsUsedByOneNativeCompactionTask(
- @Nullable ClientCompactionTaskQueryTuningConfig tuningConfig
- )
- {
- if (isParallelMode(tuningConfig)) {
- @Nullable
- Integer maxNumConcurrentSubTasks = tuningConfig.getMaxNumConcurrentSubTasks();
- // Max number of task slots used in parallel mode = maxNumConcurrentSubTasks + 1 (supervisor task)
- return (maxNumConcurrentSubTasks == null ? 1 : maxNumConcurrentSubTasks) + 1;
- } else {
- return 1;
- }
- }
-
- /**
- * Returns the maximum number of task slots used by one MSQ compaction task at any time when the task is
- * issued with the given context.
- */
- static int findMaxNumTaskSlotsUsedByOneMsqCompactionTask(@Nullable Map<String, Object> context)
- {
- return context == null
- ? ClientMSQContext.DEFAULT_MAX_NUM_TASKS
- : (int) context.getOrDefault(ClientMSQContext.CTX_MAX_NUM_TASKS, ClientMSQContext.DEFAULT_MAX_NUM_TASKS);
- }
-
-
- /**
- * Returns true if the compaction task can run in the parallel mode with the given tuningConfig.
- * This method should be synchronized with ParallelIndexSupervisorTask.isParallelMode(InputSource, ParallelIndexTuningConfig).
- */
- @VisibleForTesting
- static boolean isParallelMode(@Nullable ClientCompactionTaskQueryTuningConfig tuningConfig)
- {
- if (null == tuningConfig) {
- return false;
- }
- boolean useRangePartitions = useRangePartitions(tuningConfig);
- int minRequiredNumConcurrentSubTasks = useRangePartitions ? 1 : 2;
- return tuningConfig.getMaxNumConcurrentSubTasks() != null
- && tuningConfig.getMaxNumConcurrentSubTasks() >= minRequiredNumConcurrentSubTasks;
- }
-
- private static boolean useRangePartitions(ClientCompactionTaskQueryTuningConfig tuningConfig)
- {
- // dynamic partitionsSpec will be used if getPartitionsSpec() returns null
- return tuningConfig.getPartitionsSpec() instanceof DimensionRangePartitionsSpec;
- }
-
- private int getCompactionTaskCapacity(DruidCompactionConfig dynamicConfig)
- {
- int totalWorkerCapacity = CoordinatorDutyUtils.getTotalWorkerCapacity(overlordClient);
-
- return Math.min(
- (int) (totalWorkerCapacity * dynamicConfig.getCompactionTaskSlotRatio()),
- dynamicConfig.getMaxCompactionTaskSlots()
- );
- }
-
- private int getAvailableCompactionTaskSlots(int compactionTaskCapacity, int busyCompactionTaskSlots)
- {
- final int availableCompactionTaskSlots;
- if (busyCompactionTaskSlots > 0) {
- availableCompactionTaskSlots = Math.max(0, compactionTaskCapacity - busyCompactionTaskSlots);
- } else {
- // compactionTaskCapacity might be 0 if totalWorkerCapacity is low.
- // This guarantees that at least one slot is available if
- // compaction is enabled and estimatedIncompleteCompactionTasks is 0.
- availableCompactionTaskSlots = Math.max(1, compactionTaskCapacity);
- }
- LOG.debug(
- "Found [%d] available task slots for compaction out of max compaction task capacity [%d]",
- availableCompactionTaskSlots, compactionTaskCapacity
- );
-
- return availableCompactionTaskSlots;
- }
-
/**
* Submits compaction tasks to the Overlord. Returns total number of tasks submitted.
*/
private int submitCompactionTasks(
Map<String, DataSourceCompactionConfig> compactionConfigs,
- Map<String, AutoCompactionSnapshot.Builder> currentRunAutoCompactionSnapshotBuilders,
- int numAvailableCompactionTaskSlots,
+ CompactionSnapshotBuilder snapshotBuilder,
+ CompactionSlotManager slotManager,
CompactionSegmentIterator iterator,
+ CompactionCandidateSearchPolicy policy,
CompactionEngine defaultEngine
)
{
- if (numAvailableCompactionTaskSlots <= 0) {
+ if (slotManager.getNumAvailableTaskSlots() <= 0) {
return 0;
}
int numSubmittedTasks = 0;
int totalTaskSlotsAssigned = 0;
- while (iterator.hasNext() && totalTaskSlotsAssigned < numAvailableCompactionTaskSlots) {
+ while (iterator.hasNext() && totalTaskSlotsAssigned < slotManager.getNumAvailableTaskSlots()) {
final CompactionCandidate entry = iterator.next();
final String dataSourceName = entry.getDataSource();
+ final DataSourceCompactionConfig config = compactionConfigs.get(dataSourceName);
- // As these segments will be compacted, we will aggregate the statistic to the Compacted statistics
- currentRunAutoCompactionSnapshotBuilders
- .computeIfAbsent(dataSourceName, AutoCompactionSnapshot::builder)
- .incrementCompactedStats(entry.getStats());
+ final CompactionStatus compactionStatus =
+ statusTracker.computeCompactionStatus(entry, policy);
+ final CompactionCandidate candidatesWithStatus = entry.withCurrentStatus(compactionStatus);
+ statusTracker.onCompactionStatusComputed(candidatesWithStatus, config);
- final DataSourceCompactionConfig config = compactionConfigs.get(dataSourceName);
- final List<DataSegment> segmentsToCompact = entry.getSegments();
-
- // Create granularitySpec to send to compaction task
- Granularity segmentGranularityToUse = null;
- if (config.getGranularitySpec() == null || config.getGranularitySpec().getSegmentGranularity() == null) {
- // Determines segmentGranularity from the segmentsToCompact
- // Each batch of segmentToCompact from CompactionSegmentIterator will contain the same interval as
- // segmentGranularity is not set in the compaction config
- Interval interval = segmentsToCompact.get(0).getInterval();
- if (segmentsToCompact.stream().allMatch(segment -> interval.overlaps(segment.getInterval()))) {
- try {
- segmentGranularityToUse = GranularityType.fromPeriod(interval.toPeriod()).getDefaultGranularity();
- }
- catch (IllegalArgumentException iae) {
- // This case can happen if the existing segment interval result in complicated periods.
- // Fall back to setting segmentGranularity as null
- LOG.warn("Cannot determine segmentGranularity from interval[%s].", interval);
- }
- } else {
- LOG.warn(
- "Not setting 'segmentGranularity' for auto-compaction task as"
- + " the segments to compact do not have the same interval."
- );
- }
+ if (compactionStatus.isComplete()) {
+ snapshotBuilder.addToComplete(candidatesWithStatus);
+ } else if (compactionStatus.isSkipped()) {
+ snapshotBuilder.addToSkipped(candidatesWithStatus);
} else {
- segmentGranularityToUse = config.getGranularitySpec().getSegmentGranularity();
+ // As these segments will be compacted, we will aggregate the statistic to the Compacted statistics
+ snapshotBuilder.addToComplete(entry);
}
- final ClientCompactionTaskGranularitySpec granularitySpec = new ClientCompactionTaskGranularitySpec(
- segmentGranularityToUse,
- config.getGranularitySpec() != null ? config.getGranularitySpec().getQueryGranularity() : null,
- config.getGranularitySpec() != null ? config.getGranularitySpec().isRollup() : null
- );
- // Create dimensionsSpec to send to compaction task
- final ClientCompactionTaskDimensionsSpec dimensionsSpec;
- if (config.getDimensionsSpec() != null) {
- dimensionsSpec = new ClientCompactionTaskDimensionsSpec(
- config.getDimensionsSpec().getDimensions()
- );
- } else {
- dimensionsSpec = null;
- }
+ final ClientCompactionTaskQuery taskPayload = createCompactionTask(entry, config, defaultEngine);
- Boolean dropExisting = null;
- if (config.getIoConfig() != null) {
- dropExisting = config.getIoConfig().isDropExisting();
- }
+ final String taskId = taskPayload.getId();
+ FutureUtils.getUnchecked(overlordClient.runTask(taskId, taskPayload), true);
+ statusTracker.onTaskSubmitted(taskId, entry);
- // If all the segments found to be compacted are tombstones then dropExisting
- // needs to be forced to true. This forcing needs to happen in the case that
- // the flag is null, or it is false. It is needed when it is null to avoid the
- // possibility of the code deciding to default it to false later.
- // Forcing the flag to true will enable the task ingestion code to generate new, compacted, tombstones to
- // cover the tombstones found to be compacted as well as to mark them
- // as compacted (update their lastCompactionState). If we don't force the
- // flag then every time this compact duty runs it will find the same tombstones
- // in the interval since their lastCompactionState
- // was not set repeating this over and over and the duty will not make progress; it
- // will become stuck on this set of tombstones.
- // This forcing code should be revised
- // when/if the autocompaction code policy to decide which segments to compact changes
- if (dropExisting == null || !dropExisting) {
- if (segmentsToCompact.stream().allMatch(DataSegment::isTombstone)) {
- dropExisting = true;
- LOG.info("Forcing dropExisting to true since all segments to compact are tombstones.");
- }
- }
+ LOG.debug(
+ "Submitted a compaction task[%s] for [%d] segments in datasource[%s], umbrella interval[%s].",
+ taskId, entry.numSegments(), dataSourceName, entry.getUmbrellaInterval()
+ );
+ LOG.debugSegments(entry.getSegments(), "Compacting segments");
+ numSubmittedTasks++;
+ totalTaskSlotsAssigned += slotManager.computeSlotsRequiredForTask(taskPayload, config);
+ }
- final CompactionEngine compactionEngine = config.getEngine() == null ? defaultEngine : config.getEngine();
- final Map<String, Object> autoCompactionContext = newAutoCompactionContext(config.getTaskContext());
- int slotsRequiredForCurrentTask;
-
- if (compactionEngine == CompactionEngine.MSQ) {
- if (autoCompactionContext.containsKey(ClientMSQContext.CTX_MAX_NUM_TASKS)) {
- slotsRequiredForCurrentTask = (int) autoCompactionContext.get(ClientMSQContext.CTX_MAX_NUM_TASKS);
- } else {
- // Since MSQ needs all task slots for the calculated #tasks to be available upfront, allot all available
- // compaction slots (upto a max of MAX_TASK_SLOTS_FOR_MSQ_COMPACTION) to current compaction task to avoid
- // stalling. Setting "taskAssignment" to "auto" has the problem of not being able to determine the actual
- // count, which is required for subsequent tasks.
- slotsRequiredForCurrentTask = Math.min(
- // Update the slots to 2 (min required for MSQ) if only 1 slot is available.
- numAvailableCompactionTaskSlots == 1 ? 2 : numAvailableCompactionTaskSlots,
- ClientMSQContext.MAX_TASK_SLOTS_FOR_MSQ_COMPACTION_TASK
- );
- autoCompactionContext.put(ClientMSQContext.CTX_MAX_NUM_TASKS, slotsRequiredForCurrentTask);
+ LOG.info("Submitted a total of [%d] compaction tasks.", numSubmittedTasks);
+ return numSubmittedTasks;
+ }
+
+ /**
+ * Creates a {@link ClientCompactionTaskQuery} which can be submitted to an
+ * {@link OverlordClient} to start a compaction task.
+ */
+ public static ClientCompactionTaskQuery createCompactionTask(
+ CompactionCandidate candidate,
+ DataSourceCompactionConfig config,
+ CompactionEngine defaultEngine
+ )
+ {
+ final List<DataSegment> segmentsToCompact = candidate.getSegments();
+
+ // Create granularitySpec to send to compaction task
+ Granularity segmentGranularityToUse = null;
+ if (config.getGranularitySpec() == null || config.getGranularitySpec().getSegmentGranularity() == null) {
+ // Determines segmentGranularity from the segmentsToCompact
+ // Each batch of segmentToCompact from CompactionSegmentIterator will contain the same interval as
+ // segmentGranularity is not set in the compaction config
+ Interval interval = segmentsToCompact.get(0).getInterval();
+ if (segmentsToCompact.stream().allMatch(segment -> interval.overlaps(segment.getInterval()))) {
+ try {
+ segmentGranularityToUse = GranularityType.fromPeriod(interval.toPeriod()).getDefaultGranularity();
+ }
+ catch (IllegalArgumentException iae) {
+ // This case can happen if the existing segment interval result in complicated periods.
+ // Fall back to setting segmentGranularity as null
+ LOG.warn("Cannot determine segmentGranularity from interval[%s].", interval);
}
} else {
- slotsRequiredForCurrentTask = findMaxNumTaskSlotsUsedByOneNativeCompactionTask(config.getTuningConfig());
+ LOG.warn(
+ "Not setting 'segmentGranularity' for auto-compaction task as"
+ + " the segments to compact do not have the same interval."
+ );
}
+ } else {
+ segmentGranularityToUse = config.getGranularitySpec().getSegmentGranularity();
+ }
+ final ClientCompactionTaskGranularitySpec granularitySpec = new ClientCompactionTaskGranularitySpec(
+ segmentGranularityToUse,
+ config.getGranularitySpec() != null ? config.getGranularitySpec().getQueryGranularity() : null,
+ config.getGranularitySpec() != null ? config.getGranularitySpec().isRollup() : null
+ );
+
+ // Create dimensionsSpec to send to compaction task
+ final ClientCompactionTaskDimensionsSpec dimensionsSpec;
+ if (config.getDimensionsSpec() != null) {
+ dimensionsSpec = new ClientCompactionTaskDimensionsSpec(
+ config.getDimensionsSpec().getDimensions()
+ );
+ } else {
+ dimensionsSpec = null;
+ }
- if (entry.getCurrentStatus() != null) {
- autoCompactionContext.put(COMPACTION_REASON_KEY, entry.getCurrentStatus().getReason());
+ Boolean dropExisting = null;
+ if (config.getIoConfig() != null) {
+ dropExisting = config.getIoConfig().isDropExisting();
+ }
+
+ // If all the segments found to be compacted are tombstones then dropExisting
+ // needs to be forced to true. This forcing needs to happen in the case that
+ // the flag is null, or it is false. It is needed when it is null to avoid the
+ // possibility of the code deciding to default it to false later.
+ // Forcing the flag to true will enable the task ingestion code to generate new, compacted, tombstones to
+ // cover the tombstones found to be compacted as well as to mark them
+ // as compacted (update their lastCompactionState). If we don't force the
+ // flag then every time this compact duty runs it will find the same tombstones
+ // in the interval since their lastCompactionState
+ // was not set repeating this over and over and the duty will not make progress; it
+ // will become stuck on this set of tombstones.
+ // This forcing code should be revised
+ // when/if the autocompaction code policy to decide which segments to compact changes
+ if (dropExisting == null || !dropExisting) {
+ if (segmentsToCompact.stream().allMatch(DataSegment::isTombstone)) {
+ dropExisting = true;
+ LOG.info("Forcing dropExisting to true since all segments to compact are tombstones.");
}
+ }
- final String taskId = compactSegments(
- entry,
- config.getTaskPriority(),
- ClientCompactionTaskQueryTuningConfig.from(
- config.getTuningConfig(),
- config.getMaxRowsPerSegment(),
- config.getMetricsSpec() != null
- ),
- granularitySpec,
- dimensionsSpec,
- config.getMetricsSpec(),
- config.getTransformSpec(),
- config.getProjections(),
- dropExisting,
- autoCompactionContext,
- new ClientCompactionRunnerInfo(compactionEngine)
- );
+ final CompactionEngine compactionEngine = config.getEngine() == null ? defaultEngine : config.getEngine();
+ final Map<String, Object> autoCompactionContext = newAutoCompactionContext(config.getTaskContext());
- LOG.debug(
- "Submitted a compaction task[%s] for [%d] segments in datasource[%s], umbrella interval[%s].",
- taskId, segmentsToCompact.size(), dataSourceName, entry.getUmbrellaInterval()
- );
- LOG.debugSegments(segmentsToCompact, "Compacting segments");
- numSubmittedTasks++;
- totalTaskSlotsAssigned += slotsRequiredForCurrentTask;
+ if (candidate.getCurrentStatus() != null) {
+ autoCompactionContext.put(COMPACTION_REASON_KEY, candidate.getCurrentStatus().getReason());
}
- LOG.info("Submitted a total of [%d] compaction tasks.", numSubmittedTasks);
- return numSubmittedTasks;
+ return compactSegments(
+ candidate,
+ config.getTaskPriority(),
+ ClientCompactionTaskQueryTuningConfig.from(
+ config.getTuningConfig(),
+ config.getMaxRowsPerSegment(),
Review Comment:
## Deprecated method or constructor invocation
Invoking [DataSourceCompactionConfig.getMaxRowsPerSegment](1) should be avoided because it has been deprecated.
[Show more details](https://github.com/apache/druid/security/code-scanning/10179)
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "imply-cheddar (via GitHub)" <gi...@apache.org>.
imply-cheddar commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2344651752
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CatalogCompactionJobTemplate.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JacksonInject;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.catalog.MetadataCatalog;
+import org.apache.druid.catalog.model.ResolvedTable;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.table.IndexingTemplateDefn;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.indexing.template.BatchIndexingJobTemplate;
+import org.apache.druid.java.util.common.granularity.Granularity;
+
+import javax.annotation.Nullable;
+import java.util.List;
+
+/**
+ * Compaction template that delegates job creation to a template stored in the
+ * Druid catalog.
+ */
+public class CatalogCompactionJobTemplate implements CompactionJobTemplate
+{
+ public static final String TYPE = "compactCatalog";
+
+ private final String templateId;
+
+ private final TableId tableId;
+ private final MetadataCatalog catalog;
+
+ @JsonCreator
+ public CatalogCompactionJobTemplate(
+ @JsonProperty("templateId") String templateId,
+ @JacksonInject MetadataCatalog catalog
+ )
+ {
+ this.templateId = templateId;
+ this.catalog = catalog;
+ this.tableId = TableId.of(TableId.INDEXING_TEMPLATE_SCHEMA, templateId);
+ }
+
+ @JsonProperty
+ public String getTemplateId()
+ {
+ return templateId;
+ }
+
+ @Nullable
+ @Override
+ public Granularity getSegmentGranularity()
+ {
+ final CompactionJobTemplate delegate = getDelegate();
+ return delegate == null ? null : delegate.getSegmentGranularity();
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams params
+ )
+ {
+ final CompactionJobTemplate delegate = getDelegate();
+ if (delegate == null) {
+ return List.of();
Review Comment:
This would mean that the table doesn't actually exist right? Should we offer some sort of indication that there is a reference to a table that doesn't exist? an exception? a log line? Something that can help figure out that there's an issue with how things are setup?
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionJobParams.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.druid.indexing.compact;
+
+import org.apache.druid.indexing.template.JobParams;
+import org.apache.druid.server.compaction.CompactionSnapshotBuilder;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.timeline.SegmentTimeline;
+import org.joda.time.DateTime;
+
+/**
+ * Parameters used while creating a {@link CompactionJob} using a {@link CompactionJobTemplate}.
+ */
+public class CompactionJobParams implements JobParams
Review Comment:
In some other code, you are adjsuting the input with a searchInterval in order to limit the time interval seen. When I initially read that, I wondered "isn't that a param? why isn't it on the param object". After seeing this class, I still don't have a good answer, why isn't that a param on the param object?
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CatalogCompactionJobTemplate.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JacksonInject;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.catalog.MetadataCatalog;
+import org.apache.druid.catalog.model.ResolvedTable;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.table.IndexingTemplateDefn;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.indexing.template.BatchIndexingJobTemplate;
+import org.apache.druid.java.util.common.granularity.Granularity;
+
+import javax.annotation.Nullable;
+import java.util.List;
+
+/**
+ * Compaction template that delegates job creation to a template stored in the
+ * Druid catalog.
+ */
+public class CatalogCompactionJobTemplate implements CompactionJobTemplate
+{
+ public static final String TYPE = "compactCatalog";
+
+ private final String templateId;
+
+ private final TableId tableId;
+ private final MetadataCatalog catalog;
+
+ @JsonCreator
+ public CatalogCompactionJobTemplate(
+ @JsonProperty("templateId") String templateId,
+ @JacksonInject MetadataCatalog catalog
+ )
+ {
+ this.templateId = templateId;
+ this.catalog = catalog;
+ this.tableId = TableId.of(TableId.INDEXING_TEMPLATE_SCHEMA, templateId);
+ }
+
+ @JsonProperty
+ public String getTemplateId()
+ {
+ return templateId;
+ }
+
+ @Nullable
+ @Override
+ public Granularity getSegmentGranularity()
+ {
+ final CompactionJobTemplate delegate = getDelegate();
+ return delegate == null ? null : delegate.getSegmentGranularity();
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams params
+ )
+ {
+ final CompactionJobTemplate delegate = getDelegate();
+ if (delegate == null) {
+ return List.of();
+ } else {
+ return delegate.createCompactionJobs(source, params);
+ }
+ }
+
+ @Nullable
+ private CompactionJobTemplate getDelegate()
+ {
+ final ResolvedTable resolvedTable = catalog.resolveTable(tableId);
+ if (resolvedTable == null) {
+ return null;
+ }
+
+ final BatchIndexingJobTemplate delegate
+ = resolvedTable.decodeProperty(IndexingTemplateDefn.PROPERTY_PAYLOAD);
+ if (delegate instanceof CompactionJobTemplate) {
+ return (CompactionJobTemplate) delegate;
+ } else {
Review Comment:
Perhaps this is an established pattern. But I would never have thought that you are supposed to get the table from the catalog and then pass a magical parameter to "decodeProperty" in order to get it to become an object that is a template.
Why isn't there a method that's like `asJobTemplate()` or `as()` or something like that? What's `PROPERTY_PAYLOAD` and why is it special? Will a decoded property always generate a `BatchIndexingJobTemplate`? What does "decode property" have to do with generating a `BatchIndexingJobTemplate`?
Maybe as I read more of the code I'll understand, but only reading the usage-side of this is not very intuitive.
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionJobQueue.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.client.DataSourcesSnapshot;
+import org.apache.druid.client.broker.BrokerClient;
+import org.apache.druid.client.indexing.ClientCompactionTaskQuery;
+import org.apache.druid.client.indexing.ClientTaskQuery;
+import org.apache.druid.common.guava.FutureUtils;
+import org.apache.druid.indexing.common.actions.TaskActionClientFactory;
+import org.apache.druid.indexing.common.task.Task;
+import org.apache.druid.indexing.input.DruidDatasourceDestination;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.indexing.overlord.GlobalTaskLockbox;
+import org.apache.druid.indexing.template.BatchIndexingJob;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.apache.druid.rpc.indexing.OverlordClient;
+import org.apache.druid.server.compaction.CompactionCandidate;
+import org.apache.druid.server.compaction.CompactionCandidateSearchPolicy;
+import org.apache.druid.server.compaction.CompactionSlotManager;
+import org.apache.druid.server.compaction.CompactionSnapshotBuilder;
+import org.apache.druid.server.compaction.CompactionStatus;
+import org.apache.druid.server.compaction.CompactionStatusTracker;
+import org.apache.druid.server.coordinator.AutoCompactionSnapshot;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.server.coordinator.CompactionConfigValidationResult;
+import org.apache.druid.server.coordinator.stats.CoordinatorRunStats;
+import org.apache.druid.server.coordinator.stats.Dimension;
+import org.apache.druid.server.coordinator.stats.RowKey;
+import org.apache.druid.server.coordinator.stats.Stats;
+
+import javax.annotation.Nullable;
+import java.util.Map;
+import java.util.PriorityQueue;
+
+/**
+ * Iterates over all eligible compaction jobs in order of their priority.
+ * A fresh instance of this class must be used in every run of the
+ * {@link CompactionScheduler}.
+ */
Review Comment:
What's the scale of compaction jobs? Like, how many do we expect this to be iterating at any point in time?
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionConfigBasedJobTemplate.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.druid.indexing.compact;
+
+import org.apache.druid.client.indexing.ClientCompactionTaskQuery;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexing.input.DruidDatasourceDestination;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.server.compaction.CompactionCandidate;
+import org.apache.druid.server.compaction.CompactionSlotManager;
+import org.apache.druid.server.compaction.DataSourceCompactibleSegmentIterator;
+import org.apache.druid.server.compaction.NewestSegmentFirstPolicy;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.InlineSchemaDataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.duty.CompactSegments;
+import org.apache.druid.timeline.SegmentTimeline;
+import org.joda.time.Interval;
+import org.joda.time.Period;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * This template never needs to be deserialized as a {@code BatchIndexingJobTemplate}.
+ * It is just a delegating template that uses a {@link DataSourceCompactionConfig}
+ * to create compaction jobs.
+ */
+public class CompactionConfigBasedJobTemplate implements CompactionJobTemplate
+{
+ private final DataSourceCompactionConfig config;
+
+ public CompactionConfigBasedJobTemplate(DataSourceCompactionConfig config)
+ {
+ this.config = config;
+ }
+
+ public static CompactionConfigBasedJobTemplate create(String dataSource, CompactionStateMatcher stateMatcher)
+ {
+ return new CompactionConfigBasedJobTemplate(
+ InlineSchemaDataSourceCompactionConfig
+ .builder()
+ .forDataSource(dataSource)
+ .withSkipOffsetFromLatest(Period.ZERO)
+ .withTransformSpec(stateMatcher.getTransformSpec())
+ .withProjections(stateMatcher.getProjections())
+ .withMetricsSpec(stateMatcher.getMetricsSpec())
+ .withGranularitySpec(stateMatcher.getGranularitySpec())
+ .build()
+ );
+ }
+
+ @Nullable
+ @Override
+ public Granularity getSegmentGranularity()
+ {
+ return config.getSegmentGranularity();
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams params
+ )
+ {
+ final DataSourceCompactibleSegmentIterator segmentIterator = getCompactibleCandidates(source, params);
+
+ final List<CompactionJob> jobs = new ArrayList<>();
+
+ // Create a job for each CompactionCandidate
+ while (segmentIterator.hasNext()) {
+ final CompactionCandidate candidate = segmentIterator.next();
+
+ ClientCompactionTaskQuery taskPayload
+ = CompactSegments.createCompactionTask(candidate, config, params.getClusterCompactionConfig().getEngine());
+ jobs.add(
+ new CompactionJob(
+ taskPayload,
+ candidate,
+ CompactionSlotManager.getMaxTaskSlotsForNativeCompactionTask(taskPayload.getTuningConfig())
+ )
+ );
+ }
+
+ return jobs;
+ }
+
+ @Override
+ public String getType()
+ {
+ throw new UnsupportedOperationException("This template type cannot be serialized");
+ }
Review Comment:
What is someone supposed to do if this exception gets thrown? Why would it have happened? Are there any hints that can be provided to the developer who sees this and needs to fix it? Also, it should probably be either a `DruidException.defensive()` or a `NotYetImplemented` exception.
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/OverlordCompactionScheduler.java:
##########
@@ -107,43 +121,57 @@ public class OverlordCompactionScheduler implements CompactionScheduler
private final AtomicBoolean isLeader = new AtomicBoolean(false);
private final AtomicBoolean started = new AtomicBoolean(false);
- private final CompactSegments duty;
/**
* The scheduler should enable/disable polling of segments only if the Overlord
* is running in standalone mode, otherwise this is handled by the DruidCoordinator
* class itself.
*/
private final boolean shouldPollSegments;
+ private final long schedulePeriodMillis;
private final Stopwatch sinceStatsEmitted = Stopwatch.createUnstarted();
@Inject
public OverlordCompactionScheduler(
TaskMaster taskMaster,
+ GlobalTaskLockbox taskLockbox,
TaskQueryTool taskQueryTool,
SegmentsMetadataManager segmentManager,
+ SegmentsMetadataManagerConfig segmentManagerConfig,
Supplier<DruidCompactionConfig> compactionConfigSupplier,
CompactionStatusTracker statusTracker,
CoordinatorOverlordServiceConfig coordinatorOverlordServiceConfig,
+ TaskActionClientFactory taskActionClientFactory,
+ DruidInputSourceFactory druidInputSourceFactory,
ScheduledExecutorFactory executorFactory,
+ BrokerClient brokerClient,
ServiceEmitter emitter,
ObjectMapper objectMapper
)
{
+ final long segmentPollPeriodSeconds =
+ segmentManagerConfig.getPollDuration().toStandardDuration().getMillis();
+ this.schedulePeriodMillis = Math.min(5_000, segmentPollPeriodSeconds);
Review Comment:
A 5 second poll is pretty rapid, what's the logic behind the need for such a rapid poll and why it won't be a significant resource burden?
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CascadingCompactionTemplate.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.data.input.impl.AggregateProjectionSpec;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexer.CompactionEngine;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.query.aggregation.AggregatorFactory;
+import org.apache.druid.segment.transform.CompactionTransformSpec;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskDimensionsConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskGranularityConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskIOConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskQueryTuningConfig;
+import org.joda.time.DateTime;
+import org.joda.time.Interval;
+import org.joda.time.Period;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Template to perform period-based cascading compaction. Contains a list of
+ * {@link CompactionRule} which divide the segment timeline into compactible
+ * intervals. Each rule specifies a period relative to the current time which is
+ * used to determine its applicable interval:
+ * <ul>
+ * <li>Rule 1: range = [now - p1, +inf)</li>
+ * <li>Rule 2: range = [now - p2, now - p1)</li>
+ * <li>...</li>
+ * <li>Rule n: range = (-inf, now - p(n - 1))</li>
+ * </ul>
+ *
+ * If two adjacent rules explicitly specify a segment granularity, the boundary
+ * between them may be {@linkplain CompactionRule#computeStartTime adjusted}
+ * to ensure that there are no uncompacted gaps in the timeline.
+ * <p>
+ * This template never needs to be deserialized as a {@code BatchIndexingJobTemplate},
+ * only as a {@link DataSourceCompactionConfig} in {@link CompactionSupervisorSpec}.
+ */
+public class CascadingCompactionTemplate implements CompactionJobTemplate, DataSourceCompactionConfig
+{
+ public static final String TYPE = "compactCascade";
+
+ private final String dataSource;
+ private final List<CompactionRule> rules;
+
+ @JsonCreator
+ public CascadingCompactionTemplate(
+ @JsonProperty("dataSource") String dataSource,
+ @JsonProperty("rules") List<CompactionRule> rules
+ )
+ {
+ this.rules = rules;
+ this.dataSource = Objects.requireNonNull(dataSource, "'dataSource' cannot be null");
+
+ InvalidInput.conditionalException(rules != null && !rules.isEmpty(), "'rules' cannot be empty");
+ }
+
+ @Override
+ @JsonProperty
+ public String getDataSource()
+ {
+ return dataSource;
+ }
+
+ @JsonProperty
+ public List<CompactionRule> getRules()
+ {
+ return rules;
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams jobParams
+ )
+ {
+ final List<CompactionJob> allJobs = new ArrayList<>();
+
+ // Include future dates in the first rule
+ final DateTime currentTime = jobParams.getScheduleStartTime();
+ DateTime previousRuleStartTime = DateTimes.MAX;
+ for (int i = 0; i < rules.size() - 1; ++i) {
+ final CompactionRule rule = rules.get(i);
+ final DateTime ruleStartTime = rule.computeStartTime(currentTime, rules.get(i + 1));
+ final Interval ruleInterval = new Interval(ruleStartTime, previousRuleStartTime);
+
+ allJobs.addAll(
+ createJobsForSearchInterval(rule.getTemplate(), ruleInterval, source, jobParams)
+ );
+
+ previousRuleStartTime = ruleStartTime;
+ }
+
+ // Include past dates in the last rule
+ final CompactionRule lastRule = rules.get(rules.size() - 1);
+ final Interval lastRuleInterval = new Interval(DateTimes.MIN, previousRuleStartTime);
+ allJobs.addAll(
+ createJobsForSearchInterval(lastRule.getTemplate(), lastRuleInterval, source, jobParams)
+ );
+
+ return allJobs;
+ }
+
+ private List<CompactionJob> createJobsForSearchInterval(
+ CompactionJobTemplate template,
+ Interval searchInterval,
+ DruidInputSource inputSource,
+ CompactionJobParams jobParams
+ )
+ {
+ final List<CompactionJob> allJobs = template.createCompactionJobs(
+ inputSource.withInterval(searchInterval),
+ jobParams
+ );
+
+ // Filter out jobs if they are outside the search interval
+ final List<CompactionJob> validJobs = new ArrayList<>();
+ for (CompactionJob job : allJobs) {
+ final Interval compactionInterval = job.getCandidate().getCompactionInterval();
+ if (searchInterval.contains(compactionInterval)) {
+ validJobs.add(job);
+ }
+ }
Review Comment:
Why would you get jobs outside of the interval? That seems like a problem with the contract or the specific implementation rather than a concern that everybody who ever calls the method needs to apply?
##########
server/src/main/java/org/apache/druid/indexing/template/JobParams.java:
##########
@@ -0,0 +1,30 @@
+/*
+ * 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.druid.indexing.template;
+
+import org.joda.time.DateTime;
+
+/**
+ * Provides parameters required to create a {@link BatchIndexingJob}.
+ */
+public interface JobParams
Review Comment:
Why interface instead of class? It seems like this interface is very likely to only ever carry `getters` and it's unclear to me why it's important that different classes can implement this instead of just having a reference to one of these lying around.
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionJobParams.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.druid.indexing.compact;
+
+import org.apache.druid.indexing.template.JobParams;
+import org.apache.druid.server.compaction.CompactionSnapshotBuilder;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.timeline.SegmentTimeline;
+import org.joda.time.DateTime;
+
+/**
+ * Parameters used while creating a {@link CompactionJob} using a {@link CompactionJobTemplate}.
+ */
+public class CompactionJobParams implements JobParams
+{
+ private final DateTime scheduleStartTime;
+ private final TimelineProvider timelineProvider;
+ private final ClusterCompactionConfig clusterCompactionConfig;
+ private final CompactionSnapshotBuilder snapshotBuilder;
+
+ public CompactionJobParams(
+ DateTime scheduleStartTime,
+ ClusterCompactionConfig clusterCompactionConfig,
+ TimelineProvider timelineProvider,
+ CompactionSnapshotBuilder snapshotBuilder
+ )
+ {
+ this.scheduleStartTime = scheduleStartTime;
+ this.clusterCompactionConfig = clusterCompactionConfig;
+ this.timelineProvider = timelineProvider;
+ this.snapshotBuilder = snapshotBuilder;
+ }
+
+ @Override
+ public DateTime getScheduleStartTime()
+ {
+ return scheduleStartTime;
+ }
+
+ public ClusterCompactionConfig getClusterCompactionConfig()
+ {
+ return clusterCompactionConfig;
+ }
+
+ public SegmentTimeline getTimeline(String dataSource)
+ {
+ return timelineProvider.getTimelineForDataSource(dataSource);
+ }
+
+ public CompactionSnapshotBuilder getSnapshotBuilder()
+ {
+ return snapshotBuilder;
+ }
Review Comment:
Where is the right place to find the contract of what these objects are and what they do and why they exist? If I'm just a lowly developer trying to create a new CompactionTask thingie and I'm passing in a `CompactionJobParams` how do I go about figuring out what the semantics of the things that were given to me are and what I need to do with them?
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2476622734
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/MSQCompactionJobTemplate.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.query.http.ClientSqlQuery;
+import org.apache.druid.server.compaction.CompactionCandidate;
+import org.apache.druid.server.compaction.CompactionSlotManager;
+import org.apache.druid.server.compaction.DataSourceCompactibleSegmentIterator;
+import org.apache.druid.server.coordinator.duty.CompactSegments;
+import org.joda.time.Interval;
+import org.joda.time.format.DateTimeFormat;
+import org.joda.time.format.DateTimeFormatter;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Compaction template that creates MSQ SQL jobs using a templatized SQL with
+ * variables of the format {@code ${variableName}} for fields such as datasource
+ * name and start timestamp.
+ * <p>
+ * Compaction is triggered for an interval only if the current compaction state
+ * of the underlying segments DOES NOT match with the {@link #targetState}.
+ */
+public class MSQCompactionJobTemplate implements CompactionJobTemplate
+{
+ public static final String TYPE = "compactMsq";
+
+ public static final String VAR_DATASOURCE = "${dataSource}";
+ public static final String VAR_START_TIMESTAMP = "${startTimestamp}";
+ public static final String VAR_END_TIMESTAMP = "${endTimestamp}";
+
+ private static final DateTimeFormatter TIMESTAMP_FORMATTER =
+ DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
+
+ private final ClientSqlQuery sqlTemplate;
+ private final CompactionStateMatcher targetState;
+
+ @JsonCreator
+ public MSQCompactionJobTemplate(
+ @JsonProperty("sqlTemplate") ClientSqlQuery sqlTemplate,
+ @JsonProperty("targetState") CompactionStateMatcher targetState
+ )
+ {
+ this.sqlTemplate = sqlTemplate;
+ this.targetState = targetState;
+ }
+
+ @JsonProperty
+ public ClientSqlQuery getSqlTemplate()
+ {
+ return sqlTemplate;
+ }
+
+ @JsonProperty
+ public CompactionStateMatcher getTargetState()
+ {
+ return targetState;
+ }
+
+ @Nullable
+ @Override
+ public Granularity getSegmentGranularity()
+ {
+ return targetState.getSegmentGranularity();
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams jobParams
+ )
+ {
+ final String dataSource = source.getDataSource();
+
+ // Identify the compactible candidate segments
+ final CompactionConfigBasedJobTemplate delegate =
+ CompactionConfigBasedJobTemplate.create(dataSource, targetState);
+ final DataSourceCompactibleSegmentIterator candidateIterator =
+ delegate.getCompactibleCandidates(source, jobParams);
+
+ // Create MSQ jobs for each candidate by interpolating the template variables
+ final List<CompactionJob> jobs = new ArrayList<>();
+ while (candidateIterator.hasNext()) {
+ final CompactionCandidate candidate = candidateIterator.next();
+ jobs.add(
+ new CompactionJob(
+ createQueryForJob(dataSource, candidate.getCompactionInterval()),
+ candidate,
+ CompactionSlotManager.getMaxTaskSlotsForMSQCompactionTask(sqlTemplate.getContext())
+ )
+ );
+ }
+
+ return jobs;
+ }
+
+ private ClientSqlQuery createQueryForJob(String dataSource, Interval compactionInterval)
Review Comment:
Yes, the filter can simply be included in the SQL.
> But if someone changed the query after it existed for some time that filter wouldn't be re-applied to already compacted segments since it is not persisted in the target state.
Yes, that is by design. We don't want compaction to be triggered as long as the compaction state has not changed.
This ensures that every minor tweak made to the SQL query does not end up recompacting everything.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2280845188
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionSupervisor.java:
##########
@@ -51,6 +54,32 @@
this.dataSource = supervisorSpec.getSpec().getDataSource();
}
+ public CompactionSupervisorSpec getSpec()
+ {
+ return supervisorSpec;
+ }
+
+ /**
+ * Checks if this supervisor is ready to create jobs in the current run of the
+ * scheduler.
+ */
+ public boolean shouldCreateJobs()
+ {
+ return !supervisorSpec.isSuspended();
+ }
+
+ /**
+ * Creates compaction jobs for this supervisor.
+ */
+ public List<CompactionJob> createJobs(
+ DruidInputSource inputSource,
+ DruidDatasourceDestination destination,
Review Comment:
## Useless parameter
The parameter 'destination' is never used.
[Show more details](https://github.com/apache/druid/security/code-scanning/10231)
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2464602160
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CatalogCompactionJobTemplate.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JacksonInject;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.catalog.MetadataCatalog;
+import org.apache.druid.catalog.model.ResolvedTable;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.table.IndexingTemplateDefn;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.indexing.template.BatchIndexingJobTemplate;
+import org.apache.druid.java.util.common.granularity.Granularity;
+
+import javax.annotation.Nullable;
+import java.util.List;
+
+/**
+ * Compaction template that delegates job creation to a template stored in the
+ * Druid catalog.
+ */
+public class CatalogCompactionJobTemplate implements CompactionJobTemplate
+{
+ public static final String TYPE = "compactCatalog";
+
+ private final String templateId;
+
+ private final TableId tableId;
+ private final MetadataCatalog catalog;
+
+ @JsonCreator
+ public CatalogCompactionJobTemplate(
+ @JsonProperty("templateId") String templateId,
+ @JacksonInject MetadataCatalog catalog
+ )
+ {
+ this.templateId = templateId;
+ this.catalog = catalog;
+ this.tableId = TableId.of(TableId.INDEXING_TEMPLATE_SCHEMA, templateId);
+ }
+
+ @JsonProperty
+ public String getTemplateId()
+ {
+ return templateId;
+ }
+
+ @Nullable
+ @Override
+ public Granularity getSegmentGranularity()
+ {
+ final CompactionJobTemplate delegate = getDelegate();
+ return delegate == null ? null : delegate.getSegmentGranularity();
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams params
+ )
+ {
+ final CompactionJobTemplate delegate = getDelegate();
+ if (delegate == null) {
+ return List.of();
Review Comment:
Fixed to throw a `NotFound` exception with the proper error message.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2280726201
##########
embedded-tests/src/test/java/org/apache/druid/testing/embedded/compact/CompactionSupervisorTest.java:
##########
@@ -0,0 +1,354 @@
+/*
+ * 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.druid.testing.embedded.compact;
+
+import org.apache.druid.catalog.guice.CatalogClientModule;
+import org.apache.druid.catalog.guice.CatalogCoordinatorModule;
+import org.apache.druid.catalog.model.ResolvedTable;
+import org.apache.druid.catalog.model.TableId;
+import org.apache.druid.catalog.model.TableSpec;
+import org.apache.druid.catalog.model.table.IndexingTemplateDefn;
+import org.apache.druid.catalog.sync.CatalogClient;
+import org.apache.druid.common.utils.IdUtils;
+import org.apache.druid.indexing.common.task.IndexTask;
+import org.apache.druid.indexing.compact.CascadingCompactionTemplate;
+import org.apache.druid.indexing.compact.CatalogCompactionJobTemplate;
+import org.apache.druid.indexing.compact.CompactionJobTemplate;
+import org.apache.druid.indexing.compact.CompactionRule;
+import org.apache.druid.indexing.compact.CompactionStateMatcher;
+import org.apache.druid.indexing.compact.CompactionSupervisorSpec;
+import org.apache.druid.indexing.compact.InlineCompactionJobTemplate;
+import org.apache.druid.indexing.compact.MSQCompactionJobTemplate;
+import org.apache.druid.indexing.overlord.Segments;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.granularity.Granularities;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.msq.guice.IndexerMemoryManagementModule;
+import org.apache.druid.msq.guice.MSQDurableStorageModule;
+import org.apache.druid.msq.guice.MSQIndexingModule;
+import org.apache.druid.msq.guice.MSQSqlModule;
+import org.apache.druid.msq.guice.SqlTaskModule;
+import org.apache.druid.query.DruidMetrics;
+import org.apache.druid.query.http.ClientSqlQuery;
+import org.apache.druid.rpc.UpdateResponse;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.InlineSchemaDataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskGranularityConfig;
+import org.apache.druid.testing.embedded.EmbeddedBroker;
+import org.apache.druid.testing.embedded.EmbeddedCoordinator;
+import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
+import org.apache.druid.testing.embedded.EmbeddedHistorical;
+import org.apache.druid.testing.embedded.EmbeddedIndexer;
+import org.apache.druid.testing.embedded.EmbeddedOverlord;
+import org.apache.druid.testing.embedded.EmbeddedRouter;
+import org.apache.druid.testing.embedded.indexing.MoreResources;
+import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
+import org.joda.time.DateTime;
+import org.joda.time.Period;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+public class CompactionSupervisorTest extends EmbeddedClusterTestBase
+{
+ private final EmbeddedBroker broker = new EmbeddedBroker();
+ private final EmbeddedIndexer indexer = new EmbeddedIndexer()
+ .setServerMemory(4_000_000_000L)
+ .addProperty("druid.worker.capacity", "8");
+ private final EmbeddedOverlord overlord = new EmbeddedOverlord()
+ .addProperty("druid.manager.segments.pollDuration", "PT1s")
+ .addProperty("druid.manager.segments.useIncrementalCache", "always");
+ private final EmbeddedHistorical historical = new EmbeddedHistorical();
+ private final EmbeddedCoordinator coordinator = new EmbeddedCoordinator()
+ .addProperty("druid.manager.segments.useIncrementalCache", "always");
+
+ @Override
+ public EmbeddedDruidCluster createCluster()
+ {
+ return EmbeddedDruidCluster.withEmbeddedDerbyAndZookeeper()
+ .useLatchableEmitter()
+ .addExtensions(
+ CatalogClientModule.class,
+ CatalogCoordinatorModule.class,
+ IndexerMemoryManagementModule.class,
+ MSQDurableStorageModule.class,
+ MSQIndexingModule.class,
+ MSQSqlModule.class,
+ SqlTaskModule.class
+ )
+ .addServer(coordinator)
+ .addServer(overlord)
+ .addServer(indexer)
+ .addServer(historical)
+ .addServer(broker)
+ .addServer(new EmbeddedRouter());
+ }
+
+ @BeforeAll
+ public void enableCompactionSupervisors()
+ {
+ final UpdateResponse updateResponse = cluster.callApi().onLeaderOverlord(
+ o -> o.updateClusterCompactionConfig(new ClusterCompactionConfig(1.0, 10, null, true, null))
+ );
+ Assertions.assertTrue(updateResponse.isSuccess());
+ }
+
+ @Test
+ public void test_ingestDayGranularity_andCompactToMonthGranularity_withInlineConfig()
+ {
+ // Ingest data at DAY granularity and verify
+ runIngestionAtGranularity(
+ "DAY",
+ "2025-06-01T00:00:00.000Z,shirt,105"
+ + "\n2025-06-02T00:00:00.000Z,trousers,210"
+ + "\n2025-06-03T00:00:00.000Z,jeans,150"
+ );
+ Assertions.assertEquals(3, getNumSegmentsWith(Granularities.DAY));
+
+ // Create a compaction config with MONTH granularity
+ InlineSchemaDataSourceCompactionConfig compactionConfig =
+ InlineSchemaDataSourceCompactionConfig
+ .builder()
+ .forDataSource(dataSource)
+ .withSkipOffsetFromLatest(Period.seconds(0))
+ .withGranularitySpec(
+ new UserCompactionTaskGranularityConfig(Granularities.MONTH, null, null)
+ )
+ .build();
+
+ runCompactionWithSpec(compactionConfig);
+ waitForCompactionTasksToFinish("compact", 1);
+
+ Assertions.assertEquals(0, getNumSegmentsWith(Granularities.DAY));
+ Assertions.assertEquals(1, getNumSegmentsWith(Granularities.MONTH));
+ }
+
+ @Test
+ public void test_ingestHourGranularity_andCompactToDayAndMonth_withInlineTemplates()
+ {
+ // Create a cascading template with DAY and MONTH granularity
+ CascadingCompactionTemplate cascadingTemplate = new CascadingCompactionTemplate(
+ dataSource,
+ List.of(
+ new CompactionRule(Period.days(1), new InlineCompactionJobTemplate(createMatcher(Granularities.DAY))),
+ new CompactionRule(Period.days(50), new InlineCompactionJobTemplate(createMatcher(Granularities.MONTH)))
+ )
+ );
+
+ ingestSegments(1200, "HOUR");
+ runCompactionWithSpec(cascadingTemplate);
+ waitForCompactionTasksToFinish("compact", 3);
+
+ Assertions.assertEquals(0, getNumSegmentsWith(Granularities.HOUR));
+ Assertions.assertTrue(getNumSegmentsWith(Granularities.DAY) >= 1);
+ Assertions.assertTrue(getNumSegmentsWith(Granularities.MONTH) >= 1);
+ }
+
+ @Test
+ public void test_ingestHourGranularity_andCompactToDayAndMonth_withCatalogTemplates()
+ {
+ ingestSegments(1200, "HOUR");
+
+ // Add compaction templates to catalog
+ final String dayGranularityTemplateId = saveTemplateToCatalog(
+ new InlineCompactionJobTemplate(createMatcher(Granularities.DAY))
+ );
+ final String monthGranularityTemplateId = saveTemplateToCatalog(
+ new InlineCompactionJobTemplate(createMatcher(Granularities.MONTH))
+ );
+
+ // Create a cascading template with DAY and MONTH granularity
+ CascadingCompactionTemplate cascadingTemplate = new CascadingCompactionTemplate(
+ dataSource,
+ List.of(
+ new CompactionRule(Period.days(1), new CatalogCompactionJobTemplate(dayGranularityTemplateId, null)),
+ new CompactionRule(Period.days(50), new CatalogCompactionJobTemplate(monthGranularityTemplateId, null))
+ )
+ );
+
+ runCompactionWithSpec(cascadingTemplate);
+ waitForCompactionTasksToFinish("compact", 3);
+
+ Assertions.assertEquals(0, getNumSegmentsWith(Granularities.HOUR));
+ Assertions.assertTrue(getNumSegmentsWith(Granularities.DAY) >= 1);
+ Assertions.assertTrue(getNumSegmentsWith(Granularities.MONTH) >= 1);
+ }
+
+ @Test
+ public void test_ingestHourGranularity_andCompactToDayAndMonth_withCatalogMSQTemplates()
+ {
+ ingestSegments(1200, "HOUR");
+
+ // Add compaction templates to catalog
+ final String sqlDayGranularity =
+ "REPLACE INTO ${dataSource}"
+ + " OVERWRITE WHERE __time >= TIMESTAMP '${startTimestamp}' AND __time < TIMESTAMP '${endTimestamp}'"
+ + " SELECT * FROM ${dataSource}"
+ + " WHERE __time BETWEEN '${startTimestamp}' AND '${endTimestamp}'"
+ + " PARTITIONED BY DAY";
+ final String dayGranularityTemplateId = saveTemplateToCatalog(
+ new MSQCompactionJobTemplate(
+ new ClientSqlQuery(sqlDayGranularity, null, false, false, false, null, null),
+ createMatcher(Granularities.DAY)
+ )
+ );
+ final String sqlMonthGranularity =
+ "REPLACE INTO ${dataSource}"
+ + " OVERWRITE WHERE __time >= TIMESTAMP '${startTimestamp}' AND __time < TIMESTAMP '${endTimestamp}'"
+ + " SELECT * FROM ${dataSource}"
+ + " WHERE __time >= TIMESTAMP '${startTimestamp}' AND __time < TIMESTAMP '${endTimestamp}'"
+ + " PARTITIONED BY MONTH";
+ final String monthGranularityTemplateId = saveTemplateToCatalog(
+ new MSQCompactionJobTemplate(
+ new ClientSqlQuery(sqlMonthGranularity, null, false, false, false, null, null),
+ createMatcher(Granularities.MONTH)
+ )
+ );
+
+ // Create a cascading template with DAY and MONTH granularity
+ CascadingCompactionTemplate cascadingTemplate = new CascadingCompactionTemplate(
+ dataSource,
+ List.of(
+ new CompactionRule(Period.days(1), new CatalogCompactionJobTemplate(dayGranularityTemplateId, null)),
+ new CompactionRule(Period.days(50), new CatalogCompactionJobTemplate(monthGranularityTemplateId, null))
+ )
+ );
+
+ runCompactionWithSpec(cascadingTemplate);
+ waitForCompactionTasksToFinish("query_controller", 3);
+
+ Assertions.assertEquals(0, getNumSegmentsWith(Granularities.HOUR));
+ Assertions.assertTrue(getNumSegmentsWith(Granularities.DAY) >= 1);
+ Assertions.assertTrue(getNumSegmentsWith(Granularities.MONTH) >= 1);
+ }
+
+ private void ingestSegments(int numSegments, String granularityName)
+ {
+ runIngestionAtGranularity(
+ granularityName,
+ createHourlyInlineDataCsv(DateTimes.nowUtc(), numSegments)
+ );
+ }
+
+ private void runCompactionWithSpec(DataSourceCompactionConfig config)
+ {
+ final CompactionSupervisorSpec compactionSupervisor
+ = new CompactionSupervisorSpec(config, false, null);
+ cluster.callApi().postSupervisor(compactionSupervisor);
+ }
+
+ private void waitForCompactionTasksToFinish(String taskType, int expectedCount)
Review Comment:
## Useless parameter
The parameter 'expectedCount' is never used.
[Show more details](https://github.com/apache/druid/security/code-scanning/10229)
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2280310791
##########
server/src/main/java/org/apache/druid/server/compaction/CompactionStatus.java:
##########
@@ -204,22 +208,29 @@
*/
static CompactionStatus compute(
CompactionCandidate candidateSegments,
- DataSourceCompactionConfig config,
- ObjectMapper objectMapper
+ DataSourceCompactionConfig config
)
{
- final Evaluator evaluator = new Evaluator(candidateSegments, config, objectMapper);
+ final Evaluator evaluator = new Evaluator(candidateSegments, config);
return CHECKS.stream().map(f -> f.apply(evaluator))
.filter(status -> !status.isComplete())
.findFirst().orElse(COMPLETE);
}
+ @Nullable
static PartitionsSpec findPartitionsSpecFromConfig(ClientCompactionTaskQueryTuningConfig tuningConfig)
{
final PartitionsSpec partitionsSpecFromTuningConfig = tuningConfig.getPartitionsSpec();
if (partitionsSpecFromTuningConfig == null) {
- final long maxTotalRows = Configs.valueOrDefault(tuningConfig.getMaxTotalRows(), Long.MAX_VALUE);
- return new DynamicPartitionsSpec(tuningConfig.getMaxRowsPerSegment(), maxTotalRows);
+ final Long maxTotalRows = tuningConfig.getMaxTotalRows();
+ final Integer maxRowsPerSegment = tuningConfig.getMaxRowsPerSegment();
Review Comment:
## Deprecated method or constructor invocation
Invoking [ClientCompactionTaskQueryTuningConfig.getMaxRowsPerSegment](1) should be avoided because it has been deprecated.
[Show more details](https://github.com/apache/druid/security/code-scanning/10223)
##########
server/src/main/java/org/apache/druid/server/compaction/CompactionStatus.java:
##########
@@ -204,22 +208,29 @@
*/
static CompactionStatus compute(
CompactionCandidate candidateSegments,
- DataSourceCompactionConfig config,
- ObjectMapper objectMapper
+ DataSourceCompactionConfig config
)
{
- final Evaluator evaluator = new Evaluator(candidateSegments, config, objectMapper);
+ final Evaluator evaluator = new Evaluator(candidateSegments, config);
return CHECKS.stream().map(f -> f.apply(evaluator))
.filter(status -> !status.isComplete())
.findFirst().orElse(COMPLETE);
}
+ @Nullable
static PartitionsSpec findPartitionsSpecFromConfig(ClientCompactionTaskQueryTuningConfig tuningConfig)
{
final PartitionsSpec partitionsSpecFromTuningConfig = tuningConfig.getPartitionsSpec();
if (partitionsSpecFromTuningConfig == null) {
- final long maxTotalRows = Configs.valueOrDefault(tuningConfig.getMaxTotalRows(), Long.MAX_VALUE);
- return new DynamicPartitionsSpec(tuningConfig.getMaxRowsPerSegment(), maxTotalRows);
+ final Long maxTotalRows = tuningConfig.getMaxTotalRows();
Review Comment:
## Deprecated method or constructor invocation
Invoking [ClientCompactionTaskQueryTuningConfig.getMaxTotalRows](1) should be avoided because it has been deprecated.
[Show more details](https://github.com/apache/druid/security/code-scanning/10222)
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2464600404
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionConfigBasedJobTemplate.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.druid.indexing.compact;
+
+import org.apache.druid.client.indexing.ClientCompactionTaskQuery;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexing.input.DruidDatasourceDestination;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.java.util.common.Intervals;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.server.compaction.CompactionCandidate;
+import org.apache.druid.server.compaction.CompactionSlotManager;
+import org.apache.druid.server.compaction.DataSourceCompactibleSegmentIterator;
+import org.apache.druid.server.compaction.NewestSegmentFirstPolicy;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.InlineSchemaDataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.duty.CompactSegments;
+import org.apache.druid.timeline.SegmentTimeline;
+import org.joda.time.Interval;
+import org.joda.time.Period;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * This template never needs to be deserialized as a {@code BatchIndexingJobTemplate}.
+ * It is just a delegating template that uses a {@link DataSourceCompactionConfig}
+ * to create compaction jobs.
+ */
+public class CompactionConfigBasedJobTemplate implements CompactionJobTemplate
+{
+ private final DataSourceCompactionConfig config;
+
+ public CompactionConfigBasedJobTemplate(DataSourceCompactionConfig config)
+ {
+ this.config = config;
+ }
+
+ public static CompactionConfigBasedJobTemplate create(String dataSource, CompactionStateMatcher stateMatcher)
+ {
+ return new CompactionConfigBasedJobTemplate(
+ InlineSchemaDataSourceCompactionConfig
+ .builder()
+ .forDataSource(dataSource)
+ .withSkipOffsetFromLatest(Period.ZERO)
+ .withTransformSpec(stateMatcher.getTransformSpec())
+ .withProjections(stateMatcher.getProjections())
+ .withMetricsSpec(stateMatcher.getMetricsSpec())
+ .withGranularitySpec(stateMatcher.getGranularitySpec())
+ .build()
+ );
+ }
+
+ @Nullable
+ @Override
+ public Granularity getSegmentGranularity()
+ {
+ return config.getSegmentGranularity();
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams params
+ )
+ {
+ final DataSourceCompactibleSegmentIterator segmentIterator = getCompactibleCandidates(source, params);
+
+ final List<CompactionJob> jobs = new ArrayList<>();
+
+ // Create a job for each CompactionCandidate
+ while (segmentIterator.hasNext()) {
+ final CompactionCandidate candidate = segmentIterator.next();
+
+ ClientCompactionTaskQuery taskPayload
+ = CompactSegments.createCompactionTask(candidate, config, params.getClusterCompactionConfig().getEngine());
+ jobs.add(
+ new CompactionJob(
+ taskPayload,
+ candidate,
+ CompactionSlotManager.getMaxTaskSlotsForNativeCompactionTask(taskPayload.getTuningConfig())
+ )
+ );
+ }
+
+ return jobs;
+ }
+
+ @Override
+ public String getType()
+ {
+ throw new UnsupportedOperationException("This template type cannot be serialized");
+ }
Review Comment:
Converted to a defensive exception with a better error message.
--
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] Add compaction templates and `CompactionJobQueue` (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on PR #18402:
URL: https://github.com/apache/druid/pull/18402#issuecomment-3471029150
Thanks for the reviews, @capistrant , @gianm , @uds5501 , @cheddar !
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "uds5501 (via GitHub)" <gi...@apache.org>.
uds5501 commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2288571666
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CascadingCompactionTemplate.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.data.input.impl.AggregateProjectionSpec;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexer.CompactionEngine;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.query.aggregation.AggregatorFactory;
+import org.apache.druid.segment.transform.CompactionTransformSpec;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskDimensionsConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskGranularityConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskIOConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskQueryTuningConfig;
+import org.joda.time.DateTime;
+import org.joda.time.Interval;
+import org.joda.time.Period;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Template to perform period-based cascading compaction. Contains a list of
+ * {@link CompactionRule} which divide the segment timeline into compactible
+ * intervals. Each rule specifies a period relative to the current time which is
+ * used to determine its applicable interval:
+ * <ul>
+ * <li>Rule 1: range = [now - p1, +inf)</li>
+ * <li>Rule 2: range = [now - p2, now - p1)</li>
+ * <li>...</li>
+ * <li>Rule n: range = (-inf, now - p(n - 1))</li>
+ * </ul>
+ *
+ * If two adjacent rules explicitly specify a segment granularity, the boundary
+ * between them may be {@linkplain CompactionRule#computeStartTime adjusted}
+ * to ensure that there are no uncompacted gaps in the timeline.
+ * <p>
+ * This template never needs to be deserialized as a {@code BatchIndexingJobTemplate},
+ * only as a {@link DataSourceCompactionConfig} in {@link CompactionSupervisorSpec}.
+ */
+public class CascadingCompactionTemplate implements CompactionJobTemplate, DataSourceCompactionConfig
+{
+ public static final String TYPE = "compactCascade";
+
+ private final String dataSource;
+ private final List<CompactionRule> rules;
+
+ @JsonCreator
+ public CascadingCompactionTemplate(
+ @JsonProperty("dataSource") String dataSource,
+ @JsonProperty("rules") List<CompactionRule> rules
+ )
+ {
+ this.rules = rules;
+ this.dataSource = Objects.requireNonNull(dataSource, "'dataSource' cannot be null");
+
+ InvalidInput.conditionalException(rules != null && !rules.isEmpty(), "'rules' cannot be empty");
+ }
+
+ @Override
+ @JsonProperty
+ public String getDataSource()
+ {
+ return dataSource;
+ }
+
+ @JsonProperty
+ public List<CompactionRule> getRules()
+ {
+ return rules;
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams jobParams
+ )
+ {
+ final List<CompactionJob> allJobs = new ArrayList<>();
+
+ // Include future dates in the first rule
+ final DateTime currentTime = jobParams.getScheduleStartTime();
+ DateTime previousRuleStartTime = DateTimes.MAX;
+ for (int i = 0; i < rules.size() - 1; ++i) {
+ final CompactionRule rule = rules.get(i);
+ final DateTime ruleStartTime = rule.computeStartTime(currentTime, rules.get(i + 1));
Review Comment:
Q: considering the signature of the method `computeStartTime(DateTime referenceTime, CompactionRule beforeRule)`, adding a `rules.get(i+1)` as `beforeRule` sounds a bit counter-intuitive.
Does it mean that the list of rules being passed here is meant to be executed in reverse?
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2464599391
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionJobParams.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.druid.indexing.compact;
+
+import org.apache.druid.indexing.template.JobParams;
+import org.apache.druid.server.compaction.CompactionSnapshotBuilder;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.timeline.SegmentTimeline;
+import org.joda.time.DateTime;
+
+/**
+ * Parameters used while creating a {@link CompactionJob} using a {@link CompactionJobTemplate}.
+ */
+public class CompactionJobParams implements JobParams
+{
+ private final DateTime scheduleStartTime;
+ private final TimelineProvider timelineProvider;
+ private final ClusterCompactionConfig clusterCompactionConfig;
+ private final CompactionSnapshotBuilder snapshotBuilder;
+
+ public CompactionJobParams(
+ DateTime scheduleStartTime,
+ ClusterCompactionConfig clusterCompactionConfig,
+ TimelineProvider timelineProvider,
+ CompactionSnapshotBuilder snapshotBuilder
+ )
+ {
+ this.scheduleStartTime = scheduleStartTime;
+ this.clusterCompactionConfig = clusterCompactionConfig;
+ this.timelineProvider = timelineProvider;
+ this.snapshotBuilder = snapshotBuilder;
+ }
+
+ @Override
+ public DateTime getScheduleStartTime()
+ {
+ return scheduleStartTime;
+ }
+
+ public ClusterCompactionConfig getClusterCompactionConfig()
+ {
+ return clusterCompactionConfig;
+ }
+
+ public SegmentTimeline getTimeline(String dataSource)
+ {
+ return timelineProvider.getTimelineForDataSource(dataSource);
+ }
+
+ public CompactionSnapshotBuilder getSnapshotBuilder()
+ {
+ return snapshotBuilder;
+ }
Review Comment:
Added javadocs for these methods. Please let me know if they do not seem adequate.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2464598113
##########
server/src/main/java/org/apache/druid/indexing/template/JobParams.java:
##########
@@ -0,0 +1,30 @@
+/*
+ * 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.druid.indexing.template;
+
+import org.joda.time.DateTime;
+
+/**
+ * Provides parameters required to create a {@link BatchIndexingJob}.
+ */
+public interface JobParams
Review Comment:
Fixed, made `JobParams` a concrete class.
We would still need to have a `CompactionJobParams` which extends `JobParams` since compaction job templates use some extra stuff like `CompactionSnapshotBuilder` and `ClusterCompactionConfig`.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2465776914
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/OverlordCompactionScheduler.java:
##########
@@ -107,43 +121,57 @@ public class OverlordCompactionScheduler implements CompactionScheduler
private final AtomicBoolean isLeader = new AtomicBoolean(false);
private final AtomicBoolean started = new AtomicBoolean(false);
- private final CompactSegments duty;
/**
* The scheduler should enable/disable polling of segments only if the Overlord
* is running in standalone mode, otherwise this is handled by the DruidCoordinator
* class itself.
*/
private final boolean shouldPollSegments;
+ private final long schedulePeriodMillis;
private final Stopwatch sinceStatsEmitted = Stopwatch.createUnstarted();
@Inject
public OverlordCompactionScheduler(
TaskMaster taskMaster,
+ GlobalTaskLockbox taskLockbox,
TaskQueryTool taskQueryTool,
SegmentsMetadataManager segmentManager,
+ SegmentsMetadataManagerConfig segmentManagerConfig,
Supplier<DruidCompactionConfig> compactionConfigSupplier,
CompactionStatusTracker statusTracker,
CoordinatorOverlordServiceConfig coordinatorOverlordServiceConfig,
+ TaskActionClientFactory taskActionClientFactory,
+ DruidInputSourceFactory druidInputSourceFactory,
ScheduledExecutorFactory executorFactory,
+ BrokerClient brokerClient,
ServiceEmitter emitter,
ObjectMapper objectMapper
)
{
+ final long segmentPollPeriodSeconds =
+ segmentManagerConfig.getPollDuration().toStandardDuration().getMillis();
+ this.schedulePeriodMillis = Math.min(5_000, segmentPollPeriodSeconds);
Review Comment:
Yes, this value has been carried over from the original iteration of the `OverlordCompactionScheduler`.
I had intended the scheduler to be able to pick up compaction jobs as soon as compaction task slots become available but it is wasteful to recompute the entire queue for that, especially since on large clusters, recomputation of the entire queue may take up to a couple of minutes (seen from `coordinator/time` metric on large clusters).
We can do the following instead:
- Keep the schedule period as 5 minutes (or may be even higher?)
- When the scheduler kicks in, reset the job queue.
- We already receive a callback whenever a task completes.
- When a task completes and slots become available, check if there is any pending job still in the queue from the last scheduled run. If there is a pending job, launch that.
Please let me know if this makes sense.
--
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] Add compaction templates and `CompactionJobQueue` (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz merged PR #18402:
URL: https://github.com/apache/druid/pull/18402
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2288857033
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CascadingCompactionTemplate.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.data.input.impl.AggregateProjectionSpec;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexer.CompactionEngine;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.query.aggregation.AggregatorFactory;
+import org.apache.druid.segment.transform.CompactionTransformSpec;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskDimensionsConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskGranularityConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskIOConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskQueryTuningConfig;
+import org.joda.time.DateTime;
+import org.joda.time.Interval;
+import org.joda.time.Period;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Template to perform period-based cascading compaction. Contains a list of
+ * {@link CompactionRule} which divide the segment timeline into compactible
+ * intervals. Each rule specifies a period relative to the current time which is
+ * used to determine its applicable interval:
+ * <ul>
+ * <li>Rule 1: range = [now - p1, +inf)</li>
+ * <li>Rule 2: range = [now - p2, now - p1)</li>
+ * <li>...</li>
+ * <li>Rule n: range = (-inf, now - p(n - 1))</li>
+ * </ul>
+ *
+ * If two adjacent rules explicitly specify a segment granularity, the boundary
+ * between them may be {@linkplain CompactionRule#computeStartTime adjusted}
+ * to ensure that there are no uncompacted gaps in the timeline.
+ * <p>
+ * This template never needs to be deserialized as a {@code BatchIndexingJobTemplate},
+ * only as a {@link DataSourceCompactionConfig} in {@link CompactionSupervisorSpec}.
+ */
+public class CascadingCompactionTemplate implements CompactionJobTemplate, DataSourceCompactionConfig
+{
+ public static final String TYPE = "compactCascade";
+
+ private final String dataSource;
+ private final List<CompactionRule> rules;
+
+ @JsonCreator
+ public CascadingCompactionTemplate(
+ @JsonProperty("dataSource") String dataSource,
+ @JsonProperty("rules") List<CompactionRule> rules
+ )
+ {
+ this.rules = rules;
+ this.dataSource = Objects.requireNonNull(dataSource, "'dataSource' cannot be null");
+
+ InvalidInput.conditionalException(rules != null && !rules.isEmpty(), "'rules' cannot be empty");
+ }
+
+ @Override
+ @JsonProperty
+ public String getDataSource()
+ {
+ return dataSource;
+ }
+
+ @JsonProperty
+ public List<CompactionRule> getRules()
+ {
+ return rules;
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams jobParams
+ )
+ {
+ final List<CompactionJob> allJobs = new ArrayList<>();
+
+ // Include future dates in the first rule
+ final DateTime currentTime = jobParams.getScheduleStartTime();
+ DateTime previousRuleStartTime = DateTimes.MAX;
+ for (int i = 0; i < rules.size() - 1; ++i) {
+ final CompactionRule rule = rules.get(i);
+ final DateTime ruleStartTime = rule.computeStartTime(currentTime, rules.get(i + 1));
Review Comment:
Yes, the `beforeRule` name is explained in the javadoc of the `computeStartTime` method.
It comes before the current rule in the segment timeline.
But the rules can be evaluated in any order really, since the time chunks of two rules are mutually exclusive.
The rule with the latest time period comes first in the list since that is how we typically think of compaction,
and also how we define load rules in Druid. It keeps the rule definitions intuitive and straightforward.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2476633181
##########
server/src/main/java/org/apache/druid/server/compaction/CompactionSlotManager.java:
##########
@@ -0,0 +1,358 @@
+/*
+ * 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.druid.server.compaction;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.apache.druid.client.indexing.ClientCompactionTaskQuery;
+import org.apache.druid.client.indexing.ClientCompactionTaskQueryTuningConfig;
+import org.apache.druid.client.indexing.ClientMSQContext;
+import org.apache.druid.client.indexing.TaskPayloadResponse;
+import org.apache.druid.common.guava.FutureUtils;
+import org.apache.druid.indexer.CompactionEngine;
+import org.apache.druid.indexer.TaskStatus;
+import org.apache.druid.indexer.TaskStatusPlus;
+import org.apache.druid.indexer.partitions.DimensionRangePartitionsSpec;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.apache.druid.metadata.LockFilterPolicy;
+import org.apache.druid.rpc.indexing.OverlordClient;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.duty.CoordinatorDutyUtils;
+import org.joda.time.Interval;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * Fetches running compaction tasks from the Overlord and tracks their compaction
+ * intervals and task slots.
+ */
+public class CompactionSlotManager
+{
+ /**
+ * Task type for native compaction tasks.
+ */
+ public static final String COMPACTION_TASK_TYPE = "compact";
+
+ private static final Logger log = new Logger(CompactionSlotManager.class);
+
+ private final OverlordClient overlordClient;
+ private final CompactionStatusTracker statusTracker;
+
+ private final Map<String, List<Interval>> intervalsToSkipCompaction;
+
+ private int numAvailableTaskSlots;
+
+ public CompactionSlotManager(
+ OverlordClient overlordClient,
+ CompactionStatusTracker statusTracker,
+ ClusterCompactionConfig clusterCompactionConfig
+ )
+ {
+ this.overlordClient = overlordClient;
+ this.statusTracker = statusTracker;
+ this.numAvailableTaskSlots = getCompactionTaskCapacity(clusterCompactionConfig);
+ this.intervalsToSkipCompaction = new HashMap<>();
+ }
+
+ public int getNumAvailableTaskSlots()
+ {
+ return numAvailableTaskSlots;
+ }
+
+ public Map<String, List<Interval>> getDatasourceIntervalsToSkipCompaction()
+ {
+ return intervalsToSkipCompaction;
+ }
+
+ public void reserveTaskSlots(int numSlotsToReserve)
+ {
+ numAvailableTaskSlots -= numSlotsToReserve;
+ }
+
+ /**
+ * Reserves task slots for the given task from the overall compaction task capacity.
+ */
+ public void reserveTaskSlots(ClientCompactionTaskQuery compactionTaskQuery)
+ {
+ // Note: The default compactionRunnerType used here should match the default runner used in CompactionTask when
+ // no runner is provided there.
+ CompactionEngine compactionRunnerType = compactionTaskQuery.getCompactionRunner() == null
+ ? CompactionEngine.NATIVE
+ : compactionTaskQuery.getCompactionRunner().getType();
+ if (compactionRunnerType == CompactionEngine.NATIVE) {
+ numAvailableTaskSlots -=
+ getMaxTaskSlotsForNativeCompactionTask(compactionTaskQuery.getTuningConfig());
+ } else {
+ numAvailableTaskSlots -=
+ getMaxTaskSlotsForMSQCompactionTask(compactionTaskQuery.getContext());
+ }
+ }
+
+ /**
+ * Retrieves currently running tasks of type {@link #COMPACTION_TASK_TYPE} from
+ * the Overlord.
+ * <p>
+ * Also queries the Overlord for the status of all tasks that were submitted
+ * recently but are not active anymore. The statuses are then updated in the
+ * {@link CompactionStatusTracker}.
+ */
+ public List<ClientCompactionTaskQuery> fetchRunningCompactionTasks()
+ {
+ // Fetch currently running compaction tasks
+ final List<TaskStatusPlus> compactionTasks = CoordinatorDutyUtils.getStatusOfActiveTasks(
+ overlordClient,
+ status -> status != null && COMPACTION_TASK_TYPE.equals(status.getType())
+ );
+
+ final Set<String> activeTaskIds
+ = compactionTasks.stream().map(TaskStatusPlus::getId).collect(Collectors.toSet());
+ trackStatusOfCompletedTasks(activeTaskIds);
+
+ final List<ClientCompactionTaskQuery> runningCompactTasks = new ArrayList<>();
+ for (TaskStatusPlus status : compactionTasks) {
+ final TaskPayloadResponse response =
+ FutureUtils.getUnchecked(overlordClient.taskPayload(status.getId()), true);
+ if (response == null) {
+ throw new ISE("Could not find payload for active compaction task[%s]", status.getId());
+ } else if (!COMPACTION_TASK_TYPE.equals(response.getPayload().getType())) {
+ throw new ISE(
+ "Payload of active compaction task[%s] is of invalid type[%s]",
+ status.getId(), response.getPayload().getType()
+ );
+ }
+
+ runningCompactTasks.add((ClientCompactionTaskQuery) response.getPayload());
+ }
+
+ return runningCompactTasks;
+ }
+
+ /**
+ * Cancels a currently running compaction task only if the segment granularity
+ * has changed in the datasource compaction config. Otherwise, the task is
+ * retained and its intervals are skipped from the current round of compaction.
+ *
+ * @return true if the task was canceled, false otherwise.
+ */
+ public boolean cancelTaskOnlyIfGranularityChanged(
+ ClientCompactionTaskQuery compactionTaskQuery,
+ DataSourceCompactionConfig dataSourceCompactionConfig
+ )
+ {
+ if (dataSourceCompactionConfig == null
+ || dataSourceCompactionConfig.getGranularitySpec() == null
+ || compactionTaskQuery.getGranularitySpec() == null) {
+ skipTaskInterval(compactionTaskQuery);
+ reserveTaskSlots(compactionTaskQuery);
+ return false;
+ }
+
+ Granularity configuredSegmentGranularity = dataSourceCompactionConfig.getGranularitySpec()
+ .getSegmentGranularity();
+ Granularity taskSegmentGranularity = compactionTaskQuery.getGranularitySpec().getSegmentGranularity();
+ if (configuredSegmentGranularity == null || configuredSegmentGranularity.equals(taskSegmentGranularity)) {
+ skipTaskInterval(compactionTaskQuery);
+ reserveTaskSlots(compactionTaskQuery);
+ return false;
+ }
+
+ log.info(
+ "Cancelling task[%s] as task segmentGranularity[%s] differs from compaction config segmentGranularity[%s].",
+ compactionTaskQuery.getId(), taskSegmentGranularity, configuredSegmentGranularity
+ );
+ overlordClient.cancelTask(compactionTaskQuery.getId());
+ return true;
+ }
+
+ /**
+ * Retrieves the list of intervals locked by higher priority tasks for each datasource.
+ * Since compaction tasks submitted for these Intervals would have to wait anyway,
+ * we skip these Intervals until the next compaction run by adding them to
+ * {@link #intervalsToSkipCompaction}.
+ * <p>
+ */
+ public void skipLockedIntervals(List<DataSourceCompactionConfig> compactionConfigs)
+ {
+ final List<LockFilterPolicy> lockFilterPolicies = compactionConfigs
+ .stream()
+ .map(config ->
+ new LockFilterPolicy(config.getDataSource(), config.getTaskPriority(), null, config.getTaskContext()))
+ .collect(Collectors.toList());
+ final Map<String, List<Interval>> datasourceToLockedIntervals =
+ new HashMap<>(FutureUtils.getUnchecked(overlordClient.findLockedIntervals(lockFilterPolicies), true));
+ log.debug(
+ "Skipping the following intervals for Compaction as they are currently locked: %s",
+ datasourceToLockedIntervals
+ );
+
+ // Skip all the intervals locked by higher priority tasks for each datasource
+ // This must be done after the invalid compaction tasks are cancelled
Review Comment:
updated, thanks for the suggestion!
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "capistrant (via GitHub)" <gi...@apache.org>.
capistrant commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2470832205
##########
server/src/main/java/org/apache/druid/server/compaction/CompactionStatusTracker.java:
##########
@@ -86,50 +75,46 @@ public Set<String> getSubmittedTaskIds()
return submittedTaskIdToSegments.keySet();
}
+ /**
+ * Checks if compaction can be started for the given {@link CompactionCandidate}.
+ * This method assumes that the given candidate is eligible for compaction
+ * based on the current compaction config/supervisor of the datasource.
+ */
public CompactionStatus computeCompactionStatus(
CompactionCandidate candidate,
- DataSourceCompactionConfig config,
CompactionCandidateSearchPolicy searchPolicy
)
{
- final CompactionStatus compactionStatus = CompactionStatus.compute(candidate, config, objectMapper);
- if (compactionStatus.isComplete()) {
- return compactionStatus;
- }
-
- // Skip intervals that violate max allowed input segment size
- final long inputSegmentSize = config.getInputSegmentSizeBytes();
- if (candidate.getTotalBytes() > inputSegmentSize) {
- return CompactionStatus.skipped(
- "'inputSegmentSize' exceeded: Total segment size[%d] is larger than allowed inputSegmentSize[%d]",
- candidate.getTotalBytes(), inputSegmentSize
- );
- }
+ final CompactionStatus pendingStatus = CompactionStatus.pending("not compacted yet");
Review Comment:
nit: renaming this status to pending when there is an actual status called pending that may not be the final status we return feels odd. I didn't mind the previous name or maybe something like `computedStatus`, not sure. Big scheme, not a big deal and up to you if you just want to leave it as is.
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionStateMatcher.java:
##########
@@ -0,0 +1,183 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.data.input.impl.AggregateProjectionSpec;
+import org.apache.druid.data.input.impl.DimensionsSpec;
+import org.apache.druid.indexer.partitions.PartitionsSpec;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.query.aggregation.AggregatorFactory;
+import org.apache.druid.segment.IndexSpec;
+import org.apache.druid.segment.transform.CompactionTransformSpec;
+import org.apache.druid.server.coordinator.UserCompactionTaskGranularityConfig;
+
+import javax.annotation.Nullable;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Target compacted state of segments used to determine if compaction is needed
+ * for an interval. An explicitly defined target state helps avoid superfluous
+ * compaction when only the job definition has changed.
+ * <p>
+ * This class is mostly a duplicate of {@code CompactionState} but is kept
+ * separate to allow:
+ * <ul>
+ * <li>fields to be nullable so that only non-null fields are used for matching</li>
+ * <li>legacy "compaction-incompatible" fields to be removed</li>
Review Comment:
I think this may be me coming late to the party on compaction. For my sake, could you elaborate on this list item to get me up to speed. I guess I'm unclear on what you refer to as compaction-incompatible fields
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/MSQCompactionJobTemplate.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.query.http.ClientSqlQuery;
+import org.apache.druid.server.compaction.CompactionCandidate;
+import org.apache.druid.server.compaction.CompactionSlotManager;
+import org.apache.druid.server.compaction.DataSourceCompactibleSegmentIterator;
+import org.apache.druid.server.coordinator.duty.CompactSegments;
+import org.joda.time.Interval;
+import org.joda.time.format.DateTimeFormat;
+import org.joda.time.format.DateTimeFormatter;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Compaction template that creates MSQ SQL jobs using a templatized SQL with
+ * variables of the format {@code ${variableName}} for fields such as datasource
+ * name and start timestamp.
+ * <p>
+ * Compaction is triggered for an interval only if the current compaction state
+ * of the underlying segments DOES NOT match with the {@link #targetState}.
+ */
+public class MSQCompactionJobTemplate implements CompactionJobTemplate
+{
+ public static final String TYPE = "compactMsq";
+
+ public static final String VAR_DATASOURCE = "${dataSource}";
+ public static final String VAR_START_TIMESTAMP = "${startTimestamp}";
+ public static final String VAR_END_TIMESTAMP = "${endTimestamp}";
+
+ private static final DateTimeFormatter TIMESTAMP_FORMATTER =
+ DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
+
+ private final ClientSqlQuery sqlTemplate;
+ private final CompactionStateMatcher targetState;
+
+ @JsonCreator
+ public MSQCompactionJobTemplate(
+ @JsonProperty("sqlTemplate") ClientSqlQuery sqlTemplate,
+ @JsonProperty("targetState") CompactionStateMatcher targetState
+ )
+ {
+ this.sqlTemplate = sqlTemplate;
+ this.targetState = targetState;
+ }
+
+ @JsonProperty
+ public ClientSqlQuery getSqlTemplate()
+ {
+ return sqlTemplate;
+ }
+
+ @JsonProperty
+ public CompactionStateMatcher getTargetState()
+ {
+ return targetState;
+ }
+
+ @Nullable
+ @Override
+ public Granularity getSegmentGranularity()
+ {
+ return targetState.getSegmentGranularity();
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams jobParams
+ )
+ {
+ final String dataSource = source.getDataSource();
+
+ // Identify the compactible candidate segments
+ final CompactionConfigBasedJobTemplate delegate =
+ CompactionConfigBasedJobTemplate.create(dataSource, targetState);
+ final DataSourceCompactibleSegmentIterator candidateIterator =
+ delegate.getCompactibleCandidates(source, jobParams);
+
+ // Create MSQ jobs for each candidate by interpolating the template variables
+ final List<CompactionJob> jobs = new ArrayList<>();
+ while (candidateIterator.hasNext()) {
+ final CompactionCandidate candidate = candidateIterator.next();
+ jobs.add(
+ new CompactionJob(
+ createQueryForJob(dataSource, candidate.getCompactionInterval()),
+ candidate,
+ CompactionSlotManager.getMaxTaskSlotsForMSQCompactionTask(sqlTemplate.getContext())
+ )
+ );
+ }
+
+ return jobs;
+ }
+
+ private ClientSqlQuery createQueryForJob(String dataSource, Interval compactionInterval)
Review Comment:
wondering aloud on if there is a way to make the query and formatting more flexible/extensible if folks want to use more than these standard format vars. Perhaps if someone wanted to do some filtering during compaction? Or would you suggest that if a person desires that, that it would be in some custom template type that they roll on their own?
##########
server/src/main/java/org/apache/druid/server/compaction/CompactionSlotManager.java:
##########
@@ -0,0 +1,358 @@
+/*
+ * 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.druid.server.compaction;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.apache.druid.client.indexing.ClientCompactionTaskQuery;
+import org.apache.druid.client.indexing.ClientCompactionTaskQueryTuningConfig;
+import org.apache.druid.client.indexing.ClientMSQContext;
+import org.apache.druid.client.indexing.TaskPayloadResponse;
+import org.apache.druid.common.guava.FutureUtils;
+import org.apache.druid.indexer.CompactionEngine;
+import org.apache.druid.indexer.TaskStatus;
+import org.apache.druid.indexer.TaskStatusPlus;
+import org.apache.druid.indexer.partitions.DimensionRangePartitionsSpec;
+import org.apache.druid.java.util.common.ISE;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.apache.druid.metadata.LockFilterPolicy;
+import org.apache.druid.rpc.indexing.OverlordClient;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.duty.CoordinatorDutyUtils;
+import org.joda.time.Interval;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * Fetches running compaction tasks from the Overlord and tracks their compaction
+ * intervals and task slots.
+ */
+public class CompactionSlotManager
+{
+ /**
+ * Task type for native compaction tasks.
+ */
+ public static final String COMPACTION_TASK_TYPE = "compact";
+
+ private static final Logger log = new Logger(CompactionSlotManager.class);
+
+ private final OverlordClient overlordClient;
+ private final CompactionStatusTracker statusTracker;
+
+ private final Map<String, List<Interval>> intervalsToSkipCompaction;
+
+ private int numAvailableTaskSlots;
+
+ public CompactionSlotManager(
+ OverlordClient overlordClient,
+ CompactionStatusTracker statusTracker,
+ ClusterCompactionConfig clusterCompactionConfig
+ )
+ {
+ this.overlordClient = overlordClient;
+ this.statusTracker = statusTracker;
+ this.numAvailableTaskSlots = getCompactionTaskCapacity(clusterCompactionConfig);
+ this.intervalsToSkipCompaction = new HashMap<>();
+ }
+
+ public int getNumAvailableTaskSlots()
+ {
+ return numAvailableTaskSlots;
+ }
+
+ public Map<String, List<Interval>> getDatasourceIntervalsToSkipCompaction()
+ {
+ return intervalsToSkipCompaction;
+ }
+
+ public void reserveTaskSlots(int numSlotsToReserve)
+ {
+ numAvailableTaskSlots -= numSlotsToReserve;
+ }
+
+ /**
+ * Reserves task slots for the given task from the overall compaction task capacity.
+ */
+ public void reserveTaskSlots(ClientCompactionTaskQuery compactionTaskQuery)
+ {
+ // Note: The default compactionRunnerType used here should match the default runner used in CompactionTask when
+ // no runner is provided there.
+ CompactionEngine compactionRunnerType = compactionTaskQuery.getCompactionRunner() == null
+ ? CompactionEngine.NATIVE
+ : compactionTaskQuery.getCompactionRunner().getType();
+ if (compactionRunnerType == CompactionEngine.NATIVE) {
+ numAvailableTaskSlots -=
+ getMaxTaskSlotsForNativeCompactionTask(compactionTaskQuery.getTuningConfig());
+ } else {
+ numAvailableTaskSlots -=
+ getMaxTaskSlotsForMSQCompactionTask(compactionTaskQuery.getContext());
+ }
+ }
+
+ /**
+ * Retrieves currently running tasks of type {@link #COMPACTION_TASK_TYPE} from
+ * the Overlord.
+ * <p>
+ * Also queries the Overlord for the status of all tasks that were submitted
+ * recently but are not active anymore. The statuses are then updated in the
+ * {@link CompactionStatusTracker}.
+ */
+ public List<ClientCompactionTaskQuery> fetchRunningCompactionTasks()
+ {
+ // Fetch currently running compaction tasks
+ final List<TaskStatusPlus> compactionTasks = CoordinatorDutyUtils.getStatusOfActiveTasks(
+ overlordClient,
+ status -> status != null && COMPACTION_TASK_TYPE.equals(status.getType())
+ );
+
+ final Set<String> activeTaskIds
+ = compactionTasks.stream().map(TaskStatusPlus::getId).collect(Collectors.toSet());
+ trackStatusOfCompletedTasks(activeTaskIds);
+
+ final List<ClientCompactionTaskQuery> runningCompactTasks = new ArrayList<>();
+ for (TaskStatusPlus status : compactionTasks) {
+ final TaskPayloadResponse response =
+ FutureUtils.getUnchecked(overlordClient.taskPayload(status.getId()), true);
+ if (response == null) {
+ throw new ISE("Could not find payload for active compaction task[%s]", status.getId());
+ } else if (!COMPACTION_TASK_TYPE.equals(response.getPayload().getType())) {
+ throw new ISE(
+ "Payload of active compaction task[%s] is of invalid type[%s]",
+ status.getId(), response.getPayload().getType()
+ );
+ }
+
+ runningCompactTasks.add((ClientCompactionTaskQuery) response.getPayload());
+ }
+
+ return runningCompactTasks;
+ }
+
+ /**
+ * Cancels a currently running compaction task only if the segment granularity
+ * has changed in the datasource compaction config. Otherwise, the task is
+ * retained and its intervals are skipped from the current round of compaction.
+ *
+ * @return true if the task was canceled, false otherwise.
+ */
+ public boolean cancelTaskOnlyIfGranularityChanged(
+ ClientCompactionTaskQuery compactionTaskQuery,
+ DataSourceCompactionConfig dataSourceCompactionConfig
+ )
+ {
+ if (dataSourceCompactionConfig == null
+ || dataSourceCompactionConfig.getGranularitySpec() == null
+ || compactionTaskQuery.getGranularitySpec() == null) {
+ skipTaskInterval(compactionTaskQuery);
+ reserveTaskSlots(compactionTaskQuery);
+ return false;
+ }
+
+ Granularity configuredSegmentGranularity = dataSourceCompactionConfig.getGranularitySpec()
+ .getSegmentGranularity();
+ Granularity taskSegmentGranularity = compactionTaskQuery.getGranularitySpec().getSegmentGranularity();
+ if (configuredSegmentGranularity == null || configuredSegmentGranularity.equals(taskSegmentGranularity)) {
+ skipTaskInterval(compactionTaskQuery);
+ reserveTaskSlots(compactionTaskQuery);
+ return false;
+ }
+
+ log.info(
+ "Cancelling task[%s] as task segmentGranularity[%s] differs from compaction config segmentGranularity[%s].",
+ compactionTaskQuery.getId(), taskSegmentGranularity, configuredSegmentGranularity
+ );
+ overlordClient.cancelTask(compactionTaskQuery.getId());
+ return true;
+ }
+
+ /**
+ * Retrieves the list of intervals locked by higher priority tasks for each datasource.
+ * Since compaction tasks submitted for these Intervals would have to wait anyway,
+ * we skip these Intervals until the next compaction run by adding them to
+ * {@link #intervalsToSkipCompaction}.
+ * <p>
+ */
+ public void skipLockedIntervals(List<DataSourceCompactionConfig> compactionConfigs)
+ {
+ final List<LockFilterPolicy> lockFilterPolicies = compactionConfigs
+ .stream()
+ .map(config ->
+ new LockFilterPolicy(config.getDataSource(), config.getTaskPriority(), null, config.getTaskContext()))
+ .collect(Collectors.toList());
+ final Map<String, List<Interval>> datasourceToLockedIntervals =
+ new HashMap<>(FutureUtils.getUnchecked(overlordClient.findLockedIntervals(lockFilterPolicies), true));
+ log.debug(
+ "Skipping the following intervals for Compaction as they are currently locked: %s",
+ datasourceToLockedIntervals
+ );
+
+ // Skip all the intervals locked by higher priority tasks for each datasource
+ // This must be done after the invalid compaction tasks are cancelled
Review Comment:
should this suggestion/requirement be in the javadoc instead of a normal code comment?
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionSupervisor.java:
##########
@@ -51,6 +54,32 @@
this.dataSource = supervisorSpec.getSpec().getDataSource();
}
+ public CompactionSupervisorSpec getSpec()
+ {
+ return supervisorSpec;
+ }
+
+ /**
+ * Checks if this supervisor is ready to create jobs in the current run of the
+ * scheduler.
+ */
+ public boolean shouldCreateJobs()
+ {
+ return !supervisorSpec.isSuspended();
+ }
+
+ /**
+ * Creates compaction jobs for this supervisor.
+ */
+ public List<CompactionJob> createJobs(
+ DruidInputSource inputSource,
+ DruidDatasourceDestination destination,
Review Comment:
bumping this notice for awareness. seems like signature needs refactor
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2465869282
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CascadingCompactionTemplate.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.druid.data.input.impl.AggregateProjectionSpec;
+import org.apache.druid.error.InvalidInput;
+import org.apache.druid.indexer.CompactionEngine;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.granularity.Granularity;
+import org.apache.druid.query.aggregation.AggregatorFactory;
+import org.apache.druid.segment.transform.CompactionTransformSpec;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskDimensionsConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskGranularityConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskIOConfig;
+import org.apache.druid.server.coordinator.UserCompactionTaskQueryTuningConfig;
+import org.joda.time.DateTime;
+import org.joda.time.Interval;
+import org.joda.time.Period;
+
+import javax.annotation.Nullable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Template to perform period-based cascading compaction. Contains a list of
+ * {@link CompactionRule} which divide the segment timeline into compactible
+ * intervals. Each rule specifies a period relative to the current time which is
+ * used to determine its applicable interval:
+ * <ul>
+ * <li>Rule 1: range = [now - p1, +inf)</li>
+ * <li>Rule 2: range = [now - p2, now - p1)</li>
+ * <li>...</li>
+ * <li>Rule n: range = (-inf, now - p(n - 1))</li>
+ * </ul>
+ *
+ * If two adjacent rules explicitly specify a segment granularity, the boundary
+ * between them may be {@linkplain CompactionRule#computeStartTime adjusted}
+ * to ensure that there are no uncompacted gaps in the timeline.
+ * <p>
+ * This template never needs to be deserialized as a {@code BatchIndexingJobTemplate},
+ * only as a {@link DataSourceCompactionConfig} in {@link CompactionSupervisorSpec}.
+ */
+public class CascadingCompactionTemplate implements CompactionJobTemplate, DataSourceCompactionConfig
+{
+ public static final String TYPE = "compactCascade";
+
+ private final String dataSource;
+ private final List<CompactionRule> rules;
+
+ @JsonCreator
+ public CascadingCompactionTemplate(
+ @JsonProperty("dataSource") String dataSource,
+ @JsonProperty("rules") List<CompactionRule> rules
+ )
+ {
+ this.rules = rules;
+ this.dataSource = Objects.requireNonNull(dataSource, "'dataSource' cannot be null");
+
+ InvalidInput.conditionalException(rules != null && !rules.isEmpty(), "'rules' cannot be empty");
+ }
+
+ @Override
+ @JsonProperty
+ public String getDataSource()
+ {
+ return dataSource;
+ }
+
+ @JsonProperty
+ public List<CompactionRule> getRules()
+ {
+ return rules;
+ }
+
+ @Override
+ public List<CompactionJob> createCompactionJobs(
+ DruidInputSource source,
+ CompactionJobParams jobParams
+ )
+ {
+ final List<CompactionJob> allJobs = new ArrayList<>();
+
+ // Include future dates in the first rule
+ final DateTime currentTime = jobParams.getScheduleStartTime();
+ DateTime previousRuleStartTime = DateTimes.MAX;
+ for (int i = 0; i < rules.size() - 1; ++i) {
+ final CompactionRule rule = rules.get(i);
+ final DateTime ruleStartTime = rule.computeStartTime(currentTime, rules.get(i + 1));
+ final Interval ruleInterval = new Interval(ruleStartTime, previousRuleStartTime);
+
+ allJobs.addAll(
+ createJobsForSearchInterval(rule.getTemplate(), ruleInterval, source, jobParams)
+ );
+
+ previousRuleStartTime = ruleStartTime;
+ }
+
+ // Include past dates in the last rule
+ final CompactionRule lastRule = rules.get(rules.size() - 1);
+ final Interval lastRuleInterval = new Interval(DateTimes.MIN, previousRuleStartTime);
+ allJobs.addAll(
+ createJobsForSearchInterval(lastRule.getTemplate(), lastRuleInterval, source, jobParams)
+ );
+
+ return allJobs;
+ }
+
+ private List<CompactionJob> createJobsForSearchInterval(
+ CompactionJobTemplate template,
+ Interval searchInterval,
+ DruidInputSource inputSource,
+ CompactionJobParams jobParams
+ )
+ {
+ final List<CompactionJob> allJobs = template.createCompactionJobs(
+ inputSource.withInterval(searchInterval),
+ jobParams
+ );
+
+ // Filter out jobs if they are outside the search interval
+ final List<CompactionJob> validJobs = new ArrayList<>();
+ for (CompactionJob job : allJobs) {
+ final Interval compactionInterval = job.getCandidate().getCompactionInterval();
+ if (searchInterval.contains(compactionInterval)) {
+ validJobs.add(job);
+ }
+ }
Review Comment:
Thanks for catching this. This should not be needed anymore.
--
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] Add catalog templates to power cascading compaction (druid)
Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #18402:
URL: https://github.com/apache/druid/pull/18402#discussion_r2465759121
##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CompactionJobQueue.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * 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.druid.indexing.compact;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.client.DataSourcesSnapshot;
+import org.apache.druid.client.broker.BrokerClient;
+import org.apache.druid.client.indexing.ClientCompactionTaskQuery;
+import org.apache.druid.client.indexing.ClientTaskQuery;
+import org.apache.druid.common.guava.FutureUtils;
+import org.apache.druid.indexing.common.actions.TaskActionClientFactory;
+import org.apache.druid.indexing.common.task.Task;
+import org.apache.druid.indexing.input.DruidDatasourceDestination;
+import org.apache.druid.indexing.input.DruidInputSource;
+import org.apache.druid.indexing.overlord.GlobalTaskLockbox;
+import org.apache.druid.indexing.template.BatchIndexingJob;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.apache.druid.rpc.indexing.OverlordClient;
+import org.apache.druid.server.compaction.CompactionCandidate;
+import org.apache.druid.server.compaction.CompactionCandidateSearchPolicy;
+import org.apache.druid.server.compaction.CompactionSlotManager;
+import org.apache.druid.server.compaction.CompactionSnapshotBuilder;
+import org.apache.druid.server.compaction.CompactionStatus;
+import org.apache.druid.server.compaction.CompactionStatusTracker;
+import org.apache.druid.server.coordinator.AutoCompactionSnapshot;
+import org.apache.druid.server.coordinator.ClusterCompactionConfig;
+import org.apache.druid.server.coordinator.CompactionConfigValidationResult;
+import org.apache.druid.server.coordinator.stats.CoordinatorRunStats;
+import org.apache.druid.server.coordinator.stats.Dimension;
+import org.apache.druid.server.coordinator.stats.RowKey;
+import org.apache.druid.server.coordinator.stats.Stats;
+
+import javax.annotation.Nullable;
+import java.util.Map;
+import java.util.PriorityQueue;
+
+/**
+ * Iterates over all eligible compaction jobs in order of their priority.
+ * A fresh instance of this class must be used in every run of the
+ * {@link CompactionScheduler}.
+ */
Review Comment:
Each time chunk (using the target segment granularity) of each datasource would translate to a single compaction job.
On a large cluster with say 1 year of hourly segment data for 10 datasources, this number could easily be 365 * 24 * 10 = ~80k.
Every time the queue is reset, we re-create all of the jobs and check which ones are already done and which ones need to be queued up.
Some of the work is wasteful and we may optimize it in follow up PRs to simply not re-create jobs for intervals which we know to be already compacted.
I have added some metrics to easily monitor the size of the job queue.
--
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