You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "zoudan (via GitHub)" <gi...@apache.org> on 2023/12/01 07:23:04 UTC
[PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
zoudan opened a new pull request, #23849:
URL: https://github.com/apache/flink/pull/23849
## What is the purpose of the change
Support plan cache for DQL in SQL Gateway, so that we could reuse the plan and save time on SQL parsing, validation, and optimization.
## Brief change log
- Add a PlanCacheManager to save the cached plan.
- Gateway may reuse the plan in PlanCacheManager when execute a DQL.
## Verifying this change
This change added tests and can be verified as follows:
- Add test cases in SqlGatewayServiceStatementITCase, and all these new DQL will execute for twice with plan cache enabled to ensure that plan cache works well.
## Does this pull request potentially affect one of the following parts:
- Dependencies (does it add or upgrade a dependency): (no)
- The public API, i.e., is any changed class annotated with `@Public(Evolving)`: (no)
- The serializers: (no)
- The runtime per-record code paths (performance sensitive): (no)
- Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Kubernetes/Yarn, ZooKeeper: (no)
- The S3 file system connector: (no)
## Documentation
- Does this pull request introduce a new feature? (yes)
- If yes, how is the feature documented? (JavaDocs)
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "zoudan (via GitHub)" <gi...@apache.org>.
zoudan commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1415242114
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/ResultProvider.java:
##########
@@ -59,4 +59,7 @@ public interface ResultProvider {
* {@link CloseableIterator#next()} method returns a row.
*/
boolean isFirstRowReady();
+
+ /** Reset this ResultProvider to the origin state when we create it. */
+ default void reset() {}
Review Comment:
You are right, but the problem is that Flink creates the `ResultProvider` while translating `ModifyOperation` into `Transformation`(in DynamicSinkUtils#convertCollectToRel, and we will not call this when hit a plan cache). I find it hard to recreate a new one here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "zoudan (via GitHub)" <gi...@apache.org>.
zoudan commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1416945039
##########
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/service/SqlGatewayServiceStatementITCase.java:
##########
@@ -52,18 +59,49 @@
/** Test {@link SqlGatewayService}#executeStatement. */
public class SqlGatewayServiceStatementITCase extends AbstractSqlGatewayStatementITCase {
- private final SessionEnvironment defaultSessionEnvironment =
+ private static final SessionEnvironment DEFAULT_SESSION_ENVIRONMENT =
+ SessionEnvironment.newBuilder()
+ .setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .build();
+
+ private static final SessionEnvironment SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED =
SessionEnvironment.newBuilder()
.setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .addSessionConfig(
+ Collections.singletonMap(
+ SQL_GATEWAY_SESSION_PLAN_CACHE_ENABLED.key(), "true"))
.build();
private SessionHandle sessionHandle;
+ @Parameters(name = "parameters={0}")
+ public static List<TestParameters> parameters() throws Exception {
+ return listFlinkSqlTests().stream()
+ .map(path -> new StatementTestParameters(path, path.endsWith("repeated_dql.q")))
+ .collect(Collectors.toList());
+ }
+
@BeforeEach
@Override
public void before(@TempDir Path temporaryFolder) throws Exception {
super.before(temporaryFolder);
- sessionHandle = service.openSession(defaultSessionEnvironment);
+ SessionEnvironment sessionEnvironment =
+ isPlanCacheEnabled()
+ ? SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED
+ : DEFAULT_SESSION_ENVIRONMENT;
+ sessionHandle = service.openSession(sessionEnvironment);
+ }
+
+ @AfterEach
+ public void after() {
+ if (isPlanCacheEnabled()) {
+ CacheStats cacheStats =
+ ((SqlGatewayServiceImpl) service)
+ .getSession(sessionHandle)
+ .getPlanCacheManager()
+ .getCacheStats();
+ assertThat(cacheStats).isEqualTo(new CacheStats(4, 14, 0, 0, 0, 0));
Review Comment:
This assertion affects `repeated_dql.q` as we only enable plan cache for it. So we only have to modify the expected value when we change the queries in `repeated_dql.q`.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "libenchao (via GitHub)" <gi...@apache.org>.
libenchao closed pull request #23849: [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway
URL: https://github.com/apache/flink/pull/23849
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "flinkbot (via GitHub)" <gi...@apache.org>.
flinkbot commented on PR #23849:
URL: https://github.com/apache/flink/pull/23849#issuecomment-1835607763
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "ef24fc5d7376102ac47fe8e4f12fef9af7a53682",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "ef24fc5d7376102ac47fe8e4f12fef9af7a53682",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* ef24fc5d7376102ac47fe8e4f12fef9af7a53682 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "zoudan (via GitHub)" <gi...@apache.org>.
zoudan commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1415242114
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/ResultProvider.java:
##########
@@ -59,4 +59,7 @@ public interface ResultProvider {
* {@link CloseableIterator#next()} method returns a row.
*/
boolean isFirstRowReady();
+
+ /** Reset this ResultProvider to the origin state when we create it. */
+ default void reset() {}
Review Comment:
You are right, but the problem is that Flink creates the `ResultProvider` while translating `ModifyOperation` into `Transformation`(in DynamicSinkUtils#convertCollectToRel, and we will not call this when hit a plan cache). I find it hard to recreate a new one here(As we could not include dependencies on flink-table-planner).
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "zoudan (via GitHub)" <gi...@apache.org>.
zoudan commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1416588553
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/ResultProvider.java:
##########
@@ -59,4 +59,7 @@ public interface ResultProvider {
* {@link CloseableIterator#next()} method returns a row.
*/
boolean isFirstRowReady();
+
+ /** Reset this ResultProvider to the origin state when we create it. */
+ default void reset() {}
Review Comment:
`CollectResultProvider` uses a field `iterator` of Outer class `CollectDynamicSink`, and it is **lazily created** in DataStreamSinkProvider#consumeDataStream(which is called when translate `DynamicTableSink` into a Transformation). So it is hard to recreate a new `CollectResultProvider` when we hit a plan cache as our caches store Transformations and will not create new Transformations.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "zoudan (via GitHub)" <gi...@apache.org>.
zoudan commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1416588553
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/ResultProvider.java:
##########
@@ -59,4 +59,7 @@ public interface ResultProvider {
* {@link CloseableIterator#next()} method returns a row.
*/
boolean isFirstRowReady();
+
+ /** Reset this ResultProvider to the origin state when we create it. */
+ default void reset() {}
Review Comment:
`CollectResultProvider` used a field `iterator` of Outer class `CollectDynamicSink`, and it is **lazily created** in DataStreamSinkProvider#consumeDataStream(which is called when translate `DynamicTableSink` into a Transformation). So it is hard to recreate a new `CollectResultProvider` when we hit a plan cache as our caches store Transformations and will not create new Transformations.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "libenchao (via GitHub)" <gi...@apache.org>.
libenchao commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1416754135
##########
flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/service/context/SessionContext.java:
##########
@@ -136,6 +158,10 @@ public URLClassLoader getUserClassloader() {
return userClassloader;
}
+ public PlanCacheManager getPlanCacheManager() {
Review Comment:
`@Nullable`
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/TableConfig.java:
##########
@@ -475,4 +476,23 @@ public void setRootConfiguration(ReadableConfig rootConfiguration) {
public static TableConfig getDefault() {
return new TableConfig();
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ TableConfig that = (TableConfig) o;
+ return Objects.equals(plannerConfig, that.plannerConfig)
+ && Objects.equals(configuration, that.configuration)
+ && Objects.equals(rootConfiguration, that.rootConfiguration);
+ }
+
+ @Override
+ public int hashCode() {
Review Comment:
Then changes in `TableConfig` can be reverted now.
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/TableResultImpl.java:
##########
@@ -224,13 +234,23 @@ public Builder setPrintStyle(PrintStyle printStyle) {
return this;
}
+ /**
+ * Specifies cached plan which associates the submitted Flink job.
+ *
+ * @param cachedPlan a {@link CachedPlan} for the submitted Flink job.
+ */
+ public Builder setPlanValue(CachedPlan cachedPlan) {
Review Comment:
`setCachedPlan` is better?
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/TableEnvironmentImpl.java:
##########
@@ -1064,6 +1076,8 @@ private TableResultInternal executeQueryOperation(QueryOperation operation) {
try {
JobClient jobClient = execEnv.executeAsync(pipeline);
ResultProvider resultProvider = sinkOperation.getSelectResultProvider();
+ // We must reset resultProvider as we have to reuse it between different jobs.
Review Comment:
```suggestion
// We must reset resultProvider as we might reuse it between different jobs.
```
##########
docs/content/docs/dev/table/olap_quickstart.md:
##########
@@ -151,10 +151,11 @@ In OLAP scenario, appropriate configurations that can greatly help users improve
#### SQL&Table Options
-| Parameters | Default | Recommended |
-|:---------------------------------------------------------------------------------------------------------------|:--------|:------------|
-| [table.optimizer.join-reorder-enabled]({{<ref "docs/dev/table/config#table-optimizer-join-reorder-enabled">}}) | false | true |
-| [pipeline.object-reuse]({{< ref "docs/deployment/config#pipeline-object-reuse" >}}) | false | true |
+| Parameters | Default | Recommended |
+|:-----------------------------------------------------------------------------------------------------------------------------------|:----------|:------------|
+| [table.optimizer.join-reorder-enabled]({{<ref "docs/dev/table/config#table-optimizer-join-reorder-enabled">}}) | false | true |
+| [pipeline.object-reuse]({{< ref "docs/deployment/config#pipeline-object-reuse" >}}) | false | true |
+| [sql-gateway.session.plan-cache.enabled]({{<ref "docs/dev/table/sql-gateway/overview/#sql-gateway-session-plan-cache-enabled">}}) | false | true |
Review Comment:
```suggestion
| [sql-gateway.session.plan-cache.enabled]({{<ref "docs/dev/table/sql-gateway/overview#sql-gateway-session-plan-cache-enabled">}}) | false | true |
```
##########
docs/content/docs/dev/table/sql-gateway/overview.md:
##########
@@ -190,6 +190,24 @@ $ ./sql-gateway -Dkey=value
<td>Integer</td>
<td>The maximum number of the active session for sql gateway service.</td>
</tr>
+ <tr>
+ <td><h5>sql-gateway.session.plan-cache.enabled</h5></td>
+ <td style="word-wrap: break-word;">false</td>
+ <td>Boolean</td>
+ <td>When it is true, sql gateway will cache and reuse plans for queries.</td>
Review Comment:
```suggestion
<td>When it is true, sql gateway will cache and reuse plans for queries per session.</td>
```
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/PlanCacheManager.java:
##########
@@ -0,0 +1,63 @@
+/*
+ * 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.flink.table.api.internal;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.flink.shaded.guava31.com.google.common.cache.Cache;
+import org.apache.flink.shaded.guava31.com.google.common.cache.CacheBuilder;
+import org.apache.flink.shaded.guava31.com.google.common.cache.CacheStats;
+
+import java.time.Duration;
+import java.util.Optional;
+
+/** This manages all the plan caches. */
+@Internal
+public class PlanCacheManager {
+
+ private final Cache<String, CachedPlan> planCache;
+
+ public PlanCacheManager(long maximumCapacity, Duration ttl) {
+ planCache =
+ CacheBuilder.newBuilder()
+ .maximumSize(maximumCapacity)
+ .expireAfterWrite(ttl)
+ .recordStats()
+ .build();
+ }
+
+ public Optional<CachedPlan> getPlan(String query) {
+ CachedPlan cachedPlan = planCache.getIfPresent(query);
+ return Optional.ofNullable(cachedPlan);
+ }
+
+ public void putPlan(String query, CachedPlan cachedPlan) {
+ Preconditions.checkNotNull(query, "query can not be null");
+ Preconditions.checkNotNull(cachedPlan, "cachedPlan can not be null");
+ planCache.put(query, cachedPlan);
+ }
+
+ public void invalidateAll() {
+ planCache.invalidateAll();
+ }
+
+ public CacheStats getCacheStats() {
Review Comment:
It seems that this is only used in tests, please add `@VisibleForTesting` annotation.
##########
flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/service/session/Session.java:
##########
@@ -74,6 +75,10 @@ public OperationExecutor createExecutor(Configuration executionConfig) {
return sessionContext.createOperationExecutor(executionConfig);
}
+ public PlanCacheManager getPlanCacheManager() {
Review Comment:
`@Nullable`
##########
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/service/SqlGatewayServiceStatementITCase.java:
##########
@@ -52,18 +59,49 @@
/** Test {@link SqlGatewayService}#executeStatement. */
public class SqlGatewayServiceStatementITCase extends AbstractSqlGatewayStatementITCase {
- private final SessionEnvironment defaultSessionEnvironment =
+ private static final SessionEnvironment DEFAULT_SESSION_ENVIRONMENT =
+ SessionEnvironment.newBuilder()
+ .setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .build();
+
+ private static final SessionEnvironment SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED =
SessionEnvironment.newBuilder()
.setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .addSessionConfig(
+ Collections.singletonMap(
+ SQL_GATEWAY_SESSION_PLAN_CACHE_ENABLED.key(), "true"))
.build();
private SessionHandle sessionHandle;
+ @Parameters(name = "parameters={0}")
+ public static List<TestParameters> parameters() throws Exception {
+ return listFlinkSqlTests().stream()
+ .map(path -> new StatementTestParameters(path, path.endsWith("repeated_dql.q")))
+ .collect(Collectors.toList());
+ }
+
@BeforeEach
@Override
public void before(@TempDir Path temporaryFolder) throws Exception {
super.before(temporaryFolder);
- sessionHandle = service.openSession(defaultSessionEnvironment);
+ SessionEnvironment sessionEnvironment =
+ isPlanCacheEnabled()
+ ? SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED
+ : DEFAULT_SESSION_ENVIRONMENT;
+ sessionHandle = service.openSession(sessionEnvironment);
+ }
+
+ @AfterEach
+ public void after() {
+ if (isPlanCacheEnabled()) {
+ CacheStats cacheStats =
+ ((SqlGatewayServiceImpl) service)
+ .getSession(sessionHandle)
+ .getPlanCacheManager()
+ .getCacheStats();
+ assertThat(cacheStats).isEqualTo(new CacheStats(4, 14, 0, 0, 0, 0));
Review Comment:
The design of this test is very fragile, since adding more tests in `*.iq` will all break this test, and they would be forced to change this test expectation as well. I'll think again about how we can test it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "zoudan (via GitHub)" <gi...@apache.org>.
zoudan commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1416957349
##########
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/service/SqlGatewayServiceStatementITCase.java:
##########
@@ -52,18 +59,49 @@
/** Test {@link SqlGatewayService}#executeStatement. */
public class SqlGatewayServiceStatementITCase extends AbstractSqlGatewayStatementITCase {
- private final SessionEnvironment defaultSessionEnvironment =
+ private static final SessionEnvironment DEFAULT_SESSION_ENVIRONMENT =
+ SessionEnvironment.newBuilder()
+ .setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .build();
+
+ private static final SessionEnvironment SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED =
SessionEnvironment.newBuilder()
.setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .addSessionConfig(
+ Collections.singletonMap(
+ SQL_GATEWAY_SESSION_PLAN_CACHE_ENABLED.key(), "true"))
.build();
private SessionHandle sessionHandle;
+ @Parameters(name = "parameters={0}")
+ public static List<TestParameters> parameters() throws Exception {
+ return listFlinkSqlTests().stream()
+ .map(path -> new StatementTestParameters(path, path.endsWith("repeated_dql.q")))
+ .collect(Collectors.toList());
+ }
+
@BeforeEach
@Override
public void before(@TempDir Path temporaryFolder) throws Exception {
super.before(temporaryFolder);
- sessionHandle = service.openSession(defaultSessionEnvironment);
+ SessionEnvironment sessionEnvironment =
+ isPlanCacheEnabled()
+ ? SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED
+ : DEFAULT_SESSION_ENVIRONMENT;
+ sessionHandle = service.openSession(sessionEnvironment);
+ }
+
+ @AfterEach
+ public void after() {
+ if (isPlanCacheEnabled()) {
+ CacheStats cacheStats =
+ ((SqlGatewayServiceImpl) service)
+ .getSession(sessionHandle)
+ .getPlanCacheManager()
+ .getCacheStats();
+ assertThat(cacheStats).isEqualTo(new CacheStats(4, 14, 0, 0, 0, 0));
Review Comment:
How about we just check the value of hitCount? Then we only have to modify the expected value when we add/delete/modify a query which has an impact on cache hits.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "libenchao (via GitHub)" <gi...@apache.org>.
libenchao commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1416954073
##########
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/service/SqlGatewayServiceStatementITCase.java:
##########
@@ -52,18 +59,49 @@
/** Test {@link SqlGatewayService}#executeStatement. */
public class SqlGatewayServiceStatementITCase extends AbstractSqlGatewayStatementITCase {
- private final SessionEnvironment defaultSessionEnvironment =
+ private static final SessionEnvironment DEFAULT_SESSION_ENVIRONMENT =
+ SessionEnvironment.newBuilder()
+ .setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .build();
+
+ private static final SessionEnvironment SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED =
SessionEnvironment.newBuilder()
.setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .addSessionConfig(
+ Collections.singletonMap(
+ SQL_GATEWAY_SESSION_PLAN_CACHE_ENABLED.key(), "true"))
.build();
private SessionHandle sessionHandle;
+ @Parameters(name = "parameters={0}")
+ public static List<TestParameters> parameters() throws Exception {
+ return listFlinkSqlTests().stream()
+ .map(path -> new StatementTestParameters(path, path.endsWith("repeated_dql.q")))
+ .collect(Collectors.toList());
+ }
+
@BeforeEach
@Override
public void before(@TempDir Path temporaryFolder) throws Exception {
super.before(temporaryFolder);
- sessionHandle = service.openSession(defaultSessionEnvironment);
+ SessionEnvironment sessionEnvironment =
+ isPlanCacheEnabled()
+ ? SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED
+ : DEFAULT_SESSION_ENVIRONMENT;
+ sessionHandle = service.openSession(sessionEnvironment);
+ }
+
+ @AfterEach
+ public void after() {
+ if (isPlanCacheEnabled()) {
+ CacheStats cacheStats =
+ ((SqlGatewayServiceImpl) service)
+ .getSession(sessionHandle)
+ .getPlanCacheManager()
+ .getCacheStats();
+ assertThat(cacheStats).isEqualTo(new CacheStats(4, 14, 0, 0, 0, 0));
Review Comment:
That sounds good, then let's keep it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "libenchao (via GitHub)" <gi...@apache.org>.
libenchao commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1414825282
##########
flink-table/flink-sql-gateway/src/test/resources/sql/repeated_dql.q:
##########
@@ -0,0 +1,220 @@
+# statement-set.q - BEGIN STATEMENT SET, END
Review Comment:
You forgot to change it to current filename.
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/OptimizerConfigOptions.java:
##########
@@ -274,6 +276,33 @@ public class OptimizerConfigOptions {
+ "such as causing the output of certain non-deterministic expressions to not meet expectations(see FLINK-20887).")
.build());
+ @Documentation.TableOption(execMode = Documentation.ExecMode.BATCH_STREAMING)
+ public static final ConfigOption<Boolean> TABLE_OPTIMIZER_PLAN_CACHE_ENABLED =
+ key("table.optimizer.plan-cache.enabled")
Review Comment:
Since this is dedicated for sql-gateway for now, how about move these configs to `SqlGatewayServiceConfigOptions`?
Besides, if it's not enabled by default, I would suggest to add it to "flink olap quickstart" doc too.
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/TableConfig.java:
##########
@@ -475,4 +476,23 @@ public void setRootConfiguration(ReadableConfig rootConfiguration) {
public static TableConfig getDefault() {
return new TableConfig();
}
+
+ @Override
+ public boolean equals(Object o) {
Review Comment:
Actually using a mutable object as a map key is not a good practice. I'm wondering if there is another way to implement the plan cache, such as invalidating the cache when config is changed?
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/CachedPlan.java:
##########
@@ -0,0 +1,29 @@
+/*
+ * 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.flink.table.api.internal;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.operations.Operation;
+
+/** SQL execution plan cache. */
+@Internal
+public interface CachedPlan {
+ /** Return the origin operation parsed from the origin statement. */
Review Comment:
```suggestion
/** Return the cached operation parsed from the statement. */
```
##########
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/service/SqlGatewayServiceStatementITCase.java:
##########
@@ -52,18 +56,39 @@
/** Test {@link SqlGatewayService}#executeStatement. */
public class SqlGatewayServiceStatementITCase extends AbstractSqlGatewayStatementITCase {
- private final SessionEnvironment defaultSessionEnvironment =
+ private static final SessionEnvironment DEFAULT_SESSION_ENVIRONMENT =
SessionEnvironment.newBuilder()
.setSessionEndpointVersion(MockedEndpointVersion.V1)
.build();
+ private static final SessionEnvironment SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED =
+ SessionEnvironment.newBuilder()
+ .setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .addSessionConfig(
+ Collections.singletonMap(
+ TABLE_OPTIMIZER_PLAN_CACHE_ENABLED.key(), "true"))
+ .build();
+
private SessionHandle sessionHandle;
+ @Parameters(name = "parameters={0}")
+ public static List<TestParameters> parameters() throws Exception {
+ return listFlinkSqlTests().stream()
+ .map(path -> new StatementTestParameters(path, path.endsWith("repeated_dql.q")))
+ .collect(Collectors.toList());
+ }
+
@BeforeEach
@Override
public void before(@TempDir Path temporaryFolder) throws Exception {
super.before(temporaryFolder);
- sessionHandle = service.openSession(defaultSessionEnvironment);
+ boolean planCacheEnabled =
Review Comment:
The test you added actually cannot tell whether cached feature is used or not. This test can only show that if cache is enabled, the `SqlGatewayService}#executeStatement` works fine.
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/ResultProvider.java:
##########
@@ -59,4 +59,7 @@ public interface ResultProvider {
* {@link CloseableIterator#next()} method returns a row.
*/
boolean isFirstRowReady();
+
+ /** Reset this ResultProvider to the origin state when we create it. */
+ default void reset() {}
Review Comment:
Adding a `reset` contract is fragile to break, I'm trying to understand the rational behind. If I'm not mistaken, the reason is `ResultProvider` is also cached, if we can make it bind only to a real job instance, then we'll don't need to reset it, do you think it's doable?
##########
flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/service/context/SessionContext.java:
##########
@@ -85,14 +86,17 @@ public class SessionContext {
private boolean isStatementSetState;
private final List<ModifyOperation> statementSetOperations;
+ private final PlanCacheManager planCacheManager;
Review Comment:
Annotate it `Nulllable` if it's nullable, see: https://flink.apache.org/how-to-contribute/code-style-and-quality-java/#java-optional
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/CachedPlan.java:
##########
@@ -0,0 +1,29 @@
+/*
+ * 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.flink.table.api.internal;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.operations.Operation;
+
+/** SQL execution plan cache. */
+@Internal
+public interface CachedPlan {
+ /** Return the origin operation parsed from the origin statement. */
+ Operation getOriginOperation();
Review Comment:
I think `getOperation` is sufficient.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "libenchao (via GitHub)" <gi...@apache.org>.
libenchao commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1416956966
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/PlanCacheManager.java:
##########
@@ -0,0 +1,63 @@
+/*
+ * 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.flink.table.api.internal;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.flink.shaded.guava31.com.google.common.cache.Cache;
+import org.apache.flink.shaded.guava31.com.google.common.cache.CacheBuilder;
+import org.apache.flink.shaded.guava31.com.google.common.cache.CacheStats;
+
+import java.time.Duration;
+import java.util.Optional;
+
+/** This manages all the plan caches. */
+@Internal
+public class PlanCacheManager {
+
+ private final Cache<String, CachedPlan> planCache;
+
+ public PlanCacheManager(long maximumCapacity, Duration ttl) {
+ planCache =
+ CacheBuilder.newBuilder()
+ .maximumSize(maximumCapacity)
+ .expireAfterWrite(ttl)
+ .recordStats()
+ .build();
+ }
+
+ public Optional<CachedPlan> getPlan(String query) {
+ CachedPlan cachedPlan = planCache.getIfPresent(query);
+ return Optional.ofNullable(cachedPlan);
+ }
+
+ public void putPlan(String query, CachedPlan cachedPlan) {
+ Preconditions.checkNotNull(query, "query can not be null");
+ Preconditions.checkNotNull(cachedPlan, "cachedPlan can not be null");
+ planCache.put(query, cachedPlan);
+ }
+
+ public void invalidateAll() {
+ planCache.invalidateAll();
+ }
+
+ public CacheStats getCacheStats() {
Review Comment:
Then we can remove it when it's really used other than tests.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "libenchao (via GitHub)" <gi...@apache.org>.
libenchao commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1416960738
##########
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/service/SqlGatewayServiceStatementITCase.java:
##########
@@ -52,18 +59,49 @@
/** Test {@link SqlGatewayService}#executeStatement. */
public class SqlGatewayServiceStatementITCase extends AbstractSqlGatewayStatementITCase {
- private final SessionEnvironment defaultSessionEnvironment =
+ private static final SessionEnvironment DEFAULT_SESSION_ENVIRONMENT =
+ SessionEnvironment.newBuilder()
+ .setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .build();
+
+ private static final SessionEnvironment SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED =
SessionEnvironment.newBuilder()
.setSessionEndpointVersion(MockedEndpointVersion.V1)
+ .addSessionConfig(
+ Collections.singletonMap(
+ SQL_GATEWAY_SESSION_PLAN_CACHE_ENABLED.key(), "true"))
.build();
private SessionHandle sessionHandle;
+ @Parameters(name = "parameters={0}")
+ public static List<TestParameters> parameters() throws Exception {
+ return listFlinkSqlTests().stream()
+ .map(path -> new StatementTestParameters(path, path.endsWith("repeated_dql.q")))
+ .collect(Collectors.toList());
+ }
+
@BeforeEach
@Override
public void before(@TempDir Path temporaryFolder) throws Exception {
super.before(temporaryFolder);
- sessionHandle = service.openSession(defaultSessionEnvironment);
+ SessionEnvironment sessionEnvironment =
+ isPlanCacheEnabled()
+ ? SESSION_ENVIRONMENT_WITH_PLAN_CACHE_ENABLED
+ : DEFAULT_SESSION_ENVIRONMENT;
+ sessionHandle = service.openSession(sessionEnvironment);
+ }
+
+ @AfterEach
+ public void after() {
+ if (isPlanCacheEnabled()) {
+ CacheStats cacheStats =
+ ((SqlGatewayServiceImpl) service)
+ .getSession(sessionHandle)
+ .getPlanCacheManager()
+ .getCacheStats();
+ assertThat(cacheStats).isEqualTo(new CacheStats(4, 14, 0, 0, 0, 0));
Review Comment:
I don't have a strong opinion on it, `repeated_dql.iq` is a dedicated test for verifying cache, so it's ok to bind it with the test expectation.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-33266][sql-gateway] Support plan cache for DQL in SQL Gateway [flink]
Posted by "zoudan (via GitHub)" <gi...@apache.org>.
zoudan commented on code in PR #23849:
URL: https://github.com/apache/flink/pull/23849#discussion_r1416948569
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/PlanCacheManager.java:
##########
@@ -0,0 +1,63 @@
+/*
+ * 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.flink.table.api.internal;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.flink.shaded.guava31.com.google.common.cache.Cache;
+import org.apache.flink.shaded.guava31.com.google.common.cache.CacheBuilder;
+import org.apache.flink.shaded.guava31.com.google.common.cache.CacheStats;
+
+import java.time.Duration;
+import java.util.Optional;
+
+/** This manages all the plan caches. */
+@Internal
+public class PlanCacheManager {
+
+ private final Cache<String, CachedPlan> planCache;
+
+ public PlanCacheManager(long maximumCapacity, Duration ttl) {
+ planCache =
+ CacheBuilder.newBuilder()
+ .maximumSize(maximumCapacity)
+ .expireAfterWrite(ttl)
+ .recordStats()
+ .build();
+ }
+
+ public Optional<CachedPlan> getPlan(String query) {
+ CachedPlan cachedPlan = planCache.getIfPresent(query);
+ return Optional.ofNullable(cachedPlan);
+ }
+
+ public void putPlan(String query, CachedPlan cachedPlan) {
+ Preconditions.checkNotNull(query, "query can not be null");
+ Preconditions.checkNotNull(cachedPlan, "cachedPlan can not be null");
+ planCache.put(query, cachedPlan);
+ }
+
+ public void invalidateAll() {
+ planCache.invalidateAll();
+ }
+
+ public CacheStats getCacheStats() {
Review Comment:
It only used in tests for now, but may be used in other case, e.g. monitor the cache stats. I am not sure wether we should add `@ VisibleForTesting` for now.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org