You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hudi.apache.org by "fhan688 (via GitHub)" <gi...@apache.org> on 2026/10/02 14:23:02 UTC
[PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
fhan688 opened a new pull request, #20189:
URL: https://github.com/apache/hudi/pull/20189
### Describe the issue this Pull Request addresses
Flink distributes the job-wide `write.rate.limit` across write subtasks using integer division:
```text
rateLimitPerSubtask = write.rate.limit / parallelism
```
When `write.rate.limit` is lower than the write parallelism, the per-subtask value becomes zero. This creates a `RateLimiter` backed by a zero-permit semaphore. Its scheduled refill also releases zero permits, so the first `acquire(1)` blocks indefinitely and the Flink pipeline stops making progress.
In addition, both rate-limited Flink write functions create a scheduled executor during `open()`, but do not stop it during `close()`. Task shutdown, restart, or recovery can therefore leave rate-limiter scheduler threads running.
### Summary and Changelog
Allow positive write rate limits lower than the Flink write parallelism without blocking the pipeline, and reliably release rate-limiter resources.
- Add support for configurable permit refill periods to the common `RateLimiter`.
- Reject zero permits, invalid refill periods, and invalid acquire requests instead of allowing permanently blocked limiters.
- Make `RateLimiter.stop()` thread-safe and idempotent.
- Allow blocked permit acquisition to terminate after the limiter is stopped.
- Preserve the thread interruption status when permit acquisition is interrupted.
- Use a named daemon thread for the rate-limiter scheduler as an additional lifecycle safeguard.
- Add a shared Flink rate-limiter factory to distribute a job-wide rate across subtasks.
- For `write.rate.limit >= parallelism`, preserve the existing per-second permit allocation.
- For `write.rate.limit < parallelism`, allocate one permit per calculated multi-second or sub-second interval instead of creating a zero-permit limiter.
- Stop the limiter from `RowDataToHoodieFunctionWithRateLimit.close()` and `AppendWriteFunctionWithRateLimit.close()`, including when parent resource cleanup throws.
- Add regression tests covering low rate limits, custom refill periods, invalid arguments, blocked acquisition shutdown, repeated closure, and both Flink write paths.
No code was copied from external sources.
### Impact
- Positive `write.rate.limit` values lower than the Flink write parallelism no longer cause the write pipeline to stall permanently.
- The configured job-wide limit remains conservatively distributed across subtasks; this fix does not use a minimum one-per-second allocation that could raise the aggregate rate above the configured value.
- Rate-limiter scheduler threads are terminated when their owning Flink functions close.
- Existing behavior is preserved when the configured rate is greater than or equal to the write parallelism.
- An additive `RateLimiter` factory overload is introduced for configurable refill periods.
- No configuration defaults, storage formats, dependencies, or user-facing method signatures are changed.
### Risk Level
medium
This change modifies the common rate-limiter lifecycle and Flink write throttling behavior.
The following validation was performed using JDK 11 and the Flink 1.20 build profile:
```bash
mvn -pl hudi-common -am \
-DskipITs \
-Dtest=TestRatelimiter \
-DfailIfNoTests=false \
-Dsurefire.failIfNoSpecifiedTests=false \
test-compile surefire:test
```
```bash
mvn -Pflink1.20 \
-pl hudi-flink-datasource/hudi-flink -am \
-DskipITs \
-Dtest=TestFlinkRateLimiterFactory,TestRowDataToHoodieFunctionWithRateLimit,TestAppendWriteFunctionWithRateLimit,TestTransformUtilities,TestAppendWriteFunctionWithBufferSort \
-DfailIfNoTests=false \
-Dsurefire.failIfNoSpecifiedTests=false \
test-compile surefire:test
```
Results:
- `TestRatelimiter`: 5 tests passed.
- Flink rate-limiter and related regression tests: 28 tests passed.
- No failures, errors, or skipped tests.
- Compilation, Checkstyle, and license checks passed.
- `git diff --check` passed.
- The full project test suite was not run.
### Documentation Update
none
This fixes existing rate-limiter behavior without adding or changing user-facing configuration.
### Contributor's checklist
- [ ] Read through [contributor's guide](https://hudi.apache.org/contribute/how-to-contribute)
- [x] Enough context is provided in the sections above
- [x] Adequate tests were added if applicable
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #20189:
URL: https://github.com/apache/hudi/pull/20189#issuecomment-5955010713
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "718820c33938fac4eb5c362500fcae2de12ab9ca",
"status" : "PENDING",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17422",
"triggerID" : "718820c33938fac4eb5c362500fcae2de12ab9ca",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 718820c33938fac4eb5c362500fcae2de12ab9ca Azure: [PENDING](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17422)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot 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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #20189:
URL: https://github.com/apache/hudi/pull/20189#issuecomment-5954886218
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "718820c33938fac4eb5c362500fcae2de12ab9ca",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "718820c33938fac4eb5c362500fcae2de12ab9ca",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 718820c33938fac4eb5c362500fcae2de12ab9ca UNKNOWN
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot 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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "fhan688 (via GitHub)" <gi...@apache.org>.
fhan688 commented on code in PR #20189:
URL: https://github.com/apache/hudi/pull/20189#discussion_r4218874202
##########
hudi-flink-datasource/hudi-flink/src/test/java/org/apache/hudi/sink/utils/TestFlinkRateLimiterFactory.java:
##########
@@ -0,0 +1,58 @@
+/*
+ * 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.hudi.sink.utils;
+
+import org.apache.hudi.common.util.RateLimiter;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class TestFlinkRateLimiterFactory {
+
+ @Test
+ void testRateLimitLowerThanParallelismDoesNotCreateZeroPermitLimiter() {
+ RateLimiter limiter = FlinkRateLimiterFactory.create(1, 4);
+ try {
+ assertTimeoutPreemptively(Duration.ofSeconds(1), () -> assertTrue(limiter.acquire(1)));
Review Comment:
Agreed. This test only consumes the initial permit, so it does not verify that a total rate of 1 with parallelism 4 produces a four-second refill period.
I will separate the rate allocation calculation from limiter construction and add deterministic assertions for the calculated permits and refill period, without relying on real-time waiting.
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "hudi-agent (via GitHub)" <gi...@apache.org>.
hudi-agent commented on code in PR #20189:
URL: https://github.com/apache/hudi/pull/20189#discussion_r4235267799
##########
hudi-common/src/main/java/org/apache/hudi/common/util/RateLimiter.java:
##########
@@ -68,27 +110,71 @@ public boolean tryAcquire(int numPermits) {
}
public boolean acquire(int numOps) {
+ ValidationUtils.checkArgument(numOps > 0 && numOps <= maxPermits,
+ "Number of permits must be between one and the configured maximum");
+ return acquireInternal(numOps);
+ }
+
+ public boolean acquire() {
+ return acquireInternal(1);
+ }
+
+ private boolean acquireInternal(int numOps) {
try {
- while (!semaphore.tryAcquire(numOps)) {
+ while (!stopped && !semaphore.tryAcquire(numOps)) {
+ if (permitWaitCallback != null) {
+ permitWaitCallback.run();
+ }
Thread.sleep(WAIT_BEFORE_NEXT_ACQUIRE_PERMIT_IN_MS);
}
+ ValidationUtils.checkState(!stopped, "Rate limiter is stopped");
log.debug("acquire permits: {}, maxPermits: {}", numOps, maxPermits);
} catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
throw new RuntimeException("Unable to acquire permits", e);
}
return true;
}
- public void stop() {
- scheduler.shutdownNow();
+ public synchronized void stop() {
+ if (stopped) {
+ return;
+ }
+ stopped = true;
+ if (scheduler != null) {
+ scheduler.shutdownNow();
+ }
+ }
+
+ public boolean isStopped() {
+ return stopped;
}
- public void releasePermitsPeriodically() {
- scheduler = Executors.newScheduledThreadPool(SCHEDULER_CORE_THREAD_POOL_SIZE);
- scheduler.scheduleAtFixedRate(() -> {
- log.debug("Release permits: maxPermits: {}, available: {}", maxPermits, semaphore.availablePermits());
- semaphore.release(maxPermits - semaphore.availablePermits());
- }, RELEASE_PERMITS_PERIOD_IN_SECONDS, RELEASE_PERMITS_PERIOD_IN_SECONDS, timePeriod);
+ public synchronized void releasePermitsPeriodically() {
+ ValidationUtils.checkState(!stopped, "Cannot start a stopped rate limiter");
+ if (scheduler != null) {
+ return;
+ }
+ releasePermitsPeriodically(Executors.newScheduledThreadPool(SCHEDULER_CORE_THREAD_POOL_SIZE,
+ new CustomizedThreadFactory("rate-limiter", true)));
+ }
+
+ private synchronized void releasePermitsPeriodically(ScheduledExecutorService scheduler) {
+ ValidationUtils.checkState(!stopped, "Cannot start a stopped rate limiter");
+ if (this.scheduler != null) {
+ return;
+ }
+ this.scheduler = scheduler;
+ try {
+ scheduler.scheduleAtFixedRate(() -> {
+ log.debug("Release permits: maxPermits: {}, available: {}", maxPermits, semaphore.availablePermits());
+ semaphore.release(maxPermits - semaphore.availablePermits());
+ }, releasePermitsPeriod, releasePermitsPeriod, timePeriod);
+ } catch (RuntimeException e) {
+ this.scheduler = null;
+ scheduler.shutdownNow();
+ throw e;
+ }
Review Comment:
🤖 nit: could you drop the trailing blank line before the closing brace of this method?
<sub><i>⚠️ AI-generated; verify before applying. React 👍/👎 to flag quality.</i></sub>
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/utils/FlinkRateLimiterFactory.java:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.hudi.sink.utils;
+
+import org.apache.hudi.common.util.RateLimiter;
+import org.apache.hudi.common.util.ValidationUtils;
+import org.apache.hudi.common.util.VisibleForTesting;
+
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Factory for distributing a job-wide write rate limit across Flink subtasks.
+ */
+public final class FlinkRateLimiterFactory {
+
+ private FlinkRateLimiterFactory() {
+ }
+
+ public static RateLimiter create(long totalRateLimit, int parallelism) {
+ RateLimitConfig rateLimitConfig = resolveRateLimit(totalRateLimit, parallelism);
+ return RateLimiter.create(
+ rateLimitConfig.getPermits(), rateLimitConfig.getReleasePeriod(), rateLimitConfig.getTimeUnit());
+ }
+
+ @VisibleForTesting
+ static RateLimiter create(long totalRateLimit, int parallelism, ScheduledExecutorService scheduler) {
+ RateLimitConfig rateLimitConfig = resolveRateLimit(totalRateLimit, parallelism);
+ return RateLimiter.create(
+ rateLimitConfig.getPermits(), rateLimitConfig.getReleasePeriod(), rateLimitConfig.getTimeUnit(), scheduler);
+ }
+
+ static RateLimitConfig resolveRateLimit(long totalRateLimit, int parallelism) {
+ ValidationUtils.checkArgument(totalRateLimit > 0, "Total rate limit must be greater than zero");
+ ValidationUtils.checkArgument(parallelism > 0, "Parallelism must be greater than zero");
+
+ if (totalRateLimit >= parallelism) {
+ long rateLimitPerSubtask = totalRateLimit / parallelism;
+ ValidationUtils.checkArgument(rateLimitPerSubtask <= Integer.MAX_VALUE,
Review Comment:
🤖 non-blocking: The old `(int) totalLimit / parallelism` capped an oversized `write.rate.limit` at `Integer.MAX_VALUE`, so the job ran effectively unthrottled; this check now throws in `open()`, and such a job would fail and restart in a loop after upgrading. Would it make sense to cap the value instead, e.g. `(int) Math.min(totalRateLimit / parallelism, Integer.MAX_VALUE)`?
<sub><i>⚠️ AI-generated; verify before applying. React 👍/👎 to flag quality.</i></sub>
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/utils/FlinkRateLimiterFactory.java:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.hudi.sink.utils;
+
+import org.apache.hudi.common.util.RateLimiter;
+import org.apache.hudi.common.util.ValidationUtils;
+import org.apache.hudi.common.util.VisibleForTesting;
+
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Factory for distributing a job-wide write rate limit across Flink subtasks.
+ */
+public final class FlinkRateLimiterFactory {
+
+ private FlinkRateLimiterFactory() {
+ }
+
+ public static RateLimiter create(long totalRateLimit, int parallelism) {
+ RateLimitConfig rateLimitConfig = resolveRateLimit(totalRateLimit, parallelism);
+ return RateLimiter.create(
+ rateLimitConfig.getPermits(), rateLimitConfig.getReleasePeriod(), rateLimitConfig.getTimeUnit());
+ }
+
+ @VisibleForTesting
+ static RateLimiter create(long totalRateLimit, int parallelism, ScheduledExecutorService scheduler) {
+ RateLimitConfig rateLimitConfig = resolveRateLimit(totalRateLimit, parallelism);
+ return RateLimiter.create(
+ rateLimitConfig.getPermits(), rateLimitConfig.getReleasePeriod(), rateLimitConfig.getTimeUnit(), scheduler);
+ }
+
+ static RateLimitConfig resolveRateLimit(long totalRateLimit, int parallelism) {
+ ValidationUtils.checkArgument(totalRateLimit > 0, "Total rate limit must be greater than zero");
+ ValidationUtils.checkArgument(parallelism > 0, "Parallelism must be greater than zero");
+
+ if (totalRateLimit >= parallelism) {
+ long rateLimitPerSubtask = totalRateLimit / parallelism;
+ ValidationUtils.checkArgument(rateLimitPerSubtask <= Integer.MAX_VALUE,
+ "Rate limit per subtask exceeds the supported maximum");
+ return new RateLimitConfig((int) rateLimitPerSubtask, 1, TimeUnit.SECONDS);
+ }
+
+ long periodNanos = divideRoundingUp(
Review Comment:
🤖 nit: would it make sense to add a short comment explaining that when the limit is below parallelism we use one permit with a longer release period, since integer division would otherwise give 0 permits?
<sub><i>⚠️ AI-generated; verify before applying. React 👍/👎 to flag quality.</i></sub>
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "fhan688 (via GitHub)" <gi...@apache.org>.
fhan688 commented on code in PR #20189:
URL: https://github.com/apache/hudi/pull/20189#discussion_r4218862634
##########
hudi-common/src/test/java/org/apache/hudi/common/util/TestRatelimiter.java:
##########
@@ -33,25 +41,75 @@ public class TestRatelimiter {
@Test
public void testRateLimiterWithNoThrottling() throws InterruptedException {
RateLimiter limiter = RateLimiter.create(1000, TimeUnit.SECONDS);
- long start = System.currentTimeMillis();
- assertEquals(true, limiter.tryAcquire(1000));
- // Sleep to represent some operation
- Thread.sleep(500);
- long end = System.currentTimeMillis();
- // With a large permit limit, there shouldn't be any throttling of operations
- assertTrue((end - start) < TimeUnit.SECONDS.toMillis(2));
+ try {
+ long start = System.currentTimeMillis();
+ assertEquals(true, limiter.tryAcquire(1000));
+ // Sleep to represent some operation
+ Thread.sleep(500);
+ long end = System.currentTimeMillis();
+ // With a large permit limit, there shouldn't be any throttling of operations
+ assertTrue((end - start) < TimeUnit.SECONDS.toMillis(2));
+ } finally {
+ limiter.stop();
+ }
}
@Test
public void testRateLimiterWithThrottling() throws InterruptedException {
RateLimiter limiter = RateLimiter.create(100, TimeUnit.SECONDS);
- long start = System.currentTimeMillis();
- assertEquals(true, limiter.tryAcquire(400));
- // Sleep to represent some operation
- Thread.sleep(500);
- long end = System.currentTimeMillis();
- // As size of operations is more than the maximum permits per second,
- // whole execution should be greater than 1 second
- assertTrue((end - start) >= TimeUnit.SECONDS.toMillis(2));
+ try {
+ long start = System.currentTimeMillis();
+ assertEquals(true, limiter.tryAcquire(400));
+ // Sleep to represent some operation
+ Thread.sleep(500);
+ long end = System.currentTimeMillis();
+ // As size of operations is more than the maximum permits per second,
+ // whole execution should be greater than 1 second
+ assertTrue((end - start) >= TimeUnit.SECONDS.toMillis(2));
+ } finally {
+ limiter.stop();
+ }
+ }
+
+ @Test
+ public void testCustomReleasePeriod() {
+ RateLimiter limiter = RateLimiter.create(1, 100, TimeUnit.MILLISECONDS);
+ try {
+ assertTrue(limiter.acquire(1));
+ long start = System.nanoTime();
+ assertTimeoutPreemptively(Duration.ofSeconds(1), () -> assertTrue(limiter.acquire(1)));
+ assertTrue(System.nanoTime() - start >= TimeUnit.MILLISECONDS.toNanos(50));
Review Comment:
Good catch. The refill schedule starts when the limiter is created, so the elapsed time measured after the first acquisition depends on the scheduler phase and can make the test flaky.
I will replace the wall-clock assertion with a controllable scheduler, verify the scheduled period directly, and trigger the captured refill task manually.
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "fhan688 (via GitHub)" <gi...@apache.org>.
fhan688 commented on PR #20189:
URL: https://github.com/apache/hudi/pull/20189#issuecomment-6055049324
hi @danny0405 @cshuo , could you please help review this PR when you have time? thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "cshuo (via GitHub)" <gi...@apache.org>.
cshuo commented on code in PR #20189:
URL: https://github.com/apache/hudi/pull/20189#discussion_r4217157774
##########
hudi-common/src/test/java/org/apache/hudi/common/util/TestRatelimiter.java:
##########
@@ -33,25 +41,75 @@ public class TestRatelimiter {
@Test
public void testRateLimiterWithNoThrottling() throws InterruptedException {
RateLimiter limiter = RateLimiter.create(1000, TimeUnit.SECONDS);
- long start = System.currentTimeMillis();
- assertEquals(true, limiter.tryAcquire(1000));
- // Sleep to represent some operation
- Thread.sleep(500);
- long end = System.currentTimeMillis();
- // With a large permit limit, there shouldn't be any throttling of operations
- assertTrue((end - start) < TimeUnit.SECONDS.toMillis(2));
+ try {
+ long start = System.currentTimeMillis();
+ assertEquals(true, limiter.tryAcquire(1000));
+ // Sleep to represent some operation
+ Thread.sleep(500);
+ long end = System.currentTimeMillis();
+ // With a large permit limit, there shouldn't be any throttling of operations
+ assertTrue((end - start) < TimeUnit.SECONDS.toMillis(2));
+ } finally {
+ limiter.stop();
+ }
}
@Test
public void testRateLimiterWithThrottling() throws InterruptedException {
RateLimiter limiter = RateLimiter.create(100, TimeUnit.SECONDS);
- long start = System.currentTimeMillis();
- assertEquals(true, limiter.tryAcquire(400));
- // Sleep to represent some operation
- Thread.sleep(500);
- long end = System.currentTimeMillis();
- // As size of operations is more than the maximum permits per second,
- // whole execution should be greater than 1 second
- assertTrue((end - start) >= TimeUnit.SECONDS.toMillis(2));
+ try {
+ long start = System.currentTimeMillis();
+ assertEquals(true, limiter.tryAcquire(400));
+ // Sleep to represent some operation
+ Thread.sleep(500);
+ long end = System.currentTimeMillis();
+ // As size of operations is more than the maximum permits per second,
+ // whole execution should be greater than 1 second
+ assertTrue((end - start) >= TimeUnit.SECONDS.toMillis(2));
+ } finally {
+ limiter.stop();
+ }
+ }
+
+ @Test
+ public void testCustomReleasePeriod() {
+ RateLimiter limiter = RateLimiter.create(1, 100, TimeUnit.MILLISECONDS);
+ try {
+ assertTrue(limiter.acquire(1));
+ long start = System.nanoTime();
+ assertTimeoutPreemptively(Duration.ofSeconds(1), () -> assertTrue(limiter.acquire(1)));
+ assertTrue(System.nanoTime() - start >= TimeUnit.MILLISECONDS.toNanos(50));
Review Comment:
Refills are timed from `create()`, not `acquire()`. If the first acquisition occurs 70 ms after creation, the next refill takes only ~30 ms, so this assertion fails despite correct behavior. Could we use a controllable scheduler to avoid this timing assumption?
##########
hudi-flink-datasource/hudi-flink/src/test/java/org/apache/hudi/sink/utils/TestFlinkRateLimiterFactory.java:
##########
@@ -0,0 +1,58 @@
+/*
+ * 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.hudi.sink.utils;
+
+import org.apache.hudi.common.util.RateLimiter;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class TestFlinkRateLimiterFactory {
+
+ @Test
+ void testRateLimitLowerThanParallelismDoesNotCreateZeroPermitLimiter() {
+ RateLimiter limiter = FlinkRateLimiterFactory.create(1, 4);
+ try {
+ assertTimeoutPreemptively(Duration.ofSeconds(1), () -> assertTrue(limiter.acquire(1)));
Review Comment:
This consumes only the initial permit, so an incorrect refill period of one second instead of four would still pass. Could we consume another permit and check the expected refill interval, ideally with a controllable scheduler?
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #20189:
URL: https://github.com/apache/hudi/pull/20189#issuecomment-5955088373
## [Codecov](https://app.codecov.io/gh/apache/hudi/pull/20189?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `0%` with `23 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 80.45%. Comparing base ([`4e08176`](https://app.codecov.io/gh/apache/hudi/commit/4e0817680ea8b2f54bf03ecd32e4048c904a5df5?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`718820c`](https://app.codecov.io/gh/apache/hudi/commit/718820c33938fac4eb5c362500fcae2de12ab9ca?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 1 commits behind head on master.
| [Files with missing lines](https://app.codecov.io/gh/apache/hudi/pull/20189?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [.../java/org/apache/hudi/common/util/RateLimiter.java](https://app.codecov.io/gh/apache/hudi/pull/20189?src=pr&el=tree&filepath=hudi-common%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fhudi%2Fcommon%2Futil%2FRateLimiter.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aHVkaS1jb21tb24vc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2h1ZGkvY29tbW9uL3V0aWwvUmF0ZUxpbWl0ZXIuamF2YQ==) | 0.00% | [23 Missing :warning: ](https://app.codecov.io/gh/apache/hudi/pull/20189?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #20189 +/- ##
============================================
- Coverage 80.46% 80.45% -0.02%
+ Complexity 34942 34937 -5
============================================
Files 2549 2549
Lines 143053 143066 +13
Branches 17391 17397 +6
============================================
- Hits 115111 115106 -5
- Misses 20039 20057 +18
Partials 7903 7903
```
| [Components](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=components&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [hudi-common](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `83.91% <0.00%> (-0.06%)` | :arrow_down: |
| [hudi-client](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `83.48% <ø> (ø)` | |
| [hudi-flink](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `85.99% <ø> (+0.01%)` | :arrow_up: |
| [hudi-spark-datasource](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `73.85% <ø> (ø)` | |
| [hudi-utilities](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `78.14% <ø> (ø)` | |
| [hudi-cli](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `70.78% <ø> (ø)` | |
| [hudi-hadoop](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `70.98% <ø> (ø)` | |
| [hudi-sync](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `76.25% <ø> (ø)` | |
| [hudi-io](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `81.40% <ø> (ø)` | |
| [hudi-timeline-service](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `83.06% <ø> (ø)` | |
| [hudi-cloud](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `81.00% <ø> (ø)` | |
| [hudi-kafka-connect](https://app.codecov.io/gh/apache/hudi/pull/20189/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `53.96% <ø> (ø)` | |
| [Flag](https://app.codecov.io/gh/apache/hudi/pull/20189/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [hadoop-mr-java-client](https://app.codecov.io/gh/apache/hudi/pull/20189/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `43.97% <0.00%> (+<0.01%)` | :arrow_up: |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Files with missing lines](https://app.codecov.io/gh/apache/hudi/pull/20189?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [.../sink/append/AppendWriteFunctionWithRateLimit.java](https://app.codecov.io/gh/apache/hudi/pull/20189?src=pr&el=tree&filepath=hudi-flink-datasource%2Fhudi-flink%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fhudi%2Fsink%2Fappend%2FAppendWriteFunctionWithRateLimit.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aHVkaS1mbGluay1kYXRhc291cmNlL2h1ZGktZmxpbmsvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2h1ZGkvc2luay9hcHBlbmQvQXBwZW5kV3JpdGVGdW5jdGlvbldpdGhSYXRlTGltaXQuamF2YQ==) | `0.00% <ø> (ø)` | |
| [...ransform/RowDataToHoodieFunctionWithRateLimit.java](https://app.codecov.io/gh/apache/hudi/pull/20189?src=pr&el=tree&filepath=hudi-flink-datasource%2Fhudi-flink%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fhudi%2Fsink%2Ftransform%2FRowDataToHoodieFunctionWithRateLimit.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aHVkaS1mbGluay1kYXRhc291cmNlL2h1ZGktZmxpbmsvc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2h1ZGkvc2luay90cmFuc2Zvcm0vUm93RGF0YVRvSG9vZGllRnVuY3Rpb25XaXRoUmF0ZUxpbWl0LmphdmE=) | `42.85% <ø> (+9.52%)` | :arrow_up: |
| [.../java/org/apache/hudi/common/util/RateLimiter.java](https://app.codecov.io/gh/apache/hudi/pull/20189?src=pr&el=tree&filepath=hudi-common%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fhudi%2Fcommon%2Futil%2FRateLimiter.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-aHVkaS1jb21tb24vc3JjL21haW4vamF2YS9vcmcvYXBhY2hlL2h1ZGkvY29tbW9uL3V0aWwvUmF0ZUxpbWl0ZXIuamF2YQ==) | `41.66% <0.00%> (-38.98%)` | :arrow_down: |
</details>
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "fhan688 (via GitHub)" <gi...@apache.org>.
fhan688 commented on code in PR #20189:
URL: https://github.com/apache/hudi/pull/20189#discussion_r4229322363
##########
hudi-common/src/main/java/org/apache/hudi/common/util/RateLimiter.java:
##########
@@ -68,27 +94,67 @@ public boolean tryAcquire(int numPermits) {
}
public boolean acquire(int numOps) {
+ ValidationUtils.checkArgument(numOps > 0 && numOps <= maxPermits,
+ "Number of permits must be between one and the configured maximum");
+ return acquireInternal(numOps);
+ }
+
+ public boolean acquire() {
+ return acquireInternal(1);
+ }
+
+ private boolean acquireInternal(int numOps) {
try {
- while (!semaphore.tryAcquire(numOps)) {
+ while (!stopped.get() && !semaphore.tryAcquire(numOps)) {
Thread.sleep(WAIT_BEFORE_NEXT_ACQUIRE_PERMIT_IN_MS);
}
+ ValidationUtils.checkState(!stopped.get(), "Rate limiter is stopped");
log.debug("acquire permits: {}, maxPermits: {}", numOps, maxPermits);
} catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
throw new RuntimeException("Unable to acquire permits", e);
}
return true;
}
- public void stop() {
- scheduler.shutdownNow();
+ public synchronized void stop() {
+ if (stopped.compareAndSet(false, true)) {
Review Comment:
Thanks for the suggestion. I’ve simplified the synchronization by replacing `AtomicBoolean` with a `volatile boolean`, keeping `stop()` and scheduler initialization synchronized, and removing the unnecessary volatile modifier and local snapshot for the scheduler. This preserves the required visibility while making the lifecycle logic clearer.
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "fhan688 (via GitHub)" <gi...@apache.org>.
fhan688 commented on code in PR #20189:
URL: https://github.com/apache/hudi/pull/20189#discussion_r4229313730
##########
hudi-common/src/test/java/org/apache/hudi/common/util/TestRatelimiter.java:
##########
@@ -33,25 +44,91 @@ public class TestRatelimiter {
@Test
public void testRateLimiterWithNoThrottling() throws InterruptedException {
RateLimiter limiter = RateLimiter.create(1000, TimeUnit.SECONDS);
- long start = System.currentTimeMillis();
- assertEquals(true, limiter.tryAcquire(1000));
- // Sleep to represent some operation
- Thread.sleep(500);
- long end = System.currentTimeMillis();
- // With a large permit limit, there shouldn't be any throttling of operations
- assertTrue((end - start) < TimeUnit.SECONDS.toMillis(2));
+ try {
+ long start = System.currentTimeMillis();
+ assertEquals(true, limiter.tryAcquire(1000));
+ // Sleep to represent some operation
+ Thread.sleep(500);
+ long end = System.currentTimeMillis();
+ // With a large permit limit, there shouldn't be any throttling of operations
+ assertTrue((end - start) < TimeUnit.SECONDS.toMillis(2));
+ } finally {
+ limiter.stop();
+ }
}
@Test
public void testRateLimiterWithThrottling() throws InterruptedException {
RateLimiter limiter = RateLimiter.create(100, TimeUnit.SECONDS);
- long start = System.currentTimeMillis();
- assertEquals(true, limiter.tryAcquire(400));
- // Sleep to represent some operation
- Thread.sleep(500);
- long end = System.currentTimeMillis();
- // As size of operations is more than the maximum permits per second,
- // whole execution should be greater than 1 second
- assertTrue((end - start) >= TimeUnit.SECONDS.toMillis(2));
+ try {
+ long start = System.currentTimeMillis();
+ assertEquals(true, limiter.tryAcquire(400));
+ // Sleep to represent some operation
+ Thread.sleep(500);
+ long end = System.currentTimeMillis();
+ // As size of operations is more than the maximum permits per second,
+ // whole execution should be greater than 1 second
+ assertTrue((end - start) >= TimeUnit.SECONDS.toMillis(2));
+ } finally {
+ limiter.stop();
+ }
+ }
+
+ @Test
+ public void testCustomReleasePeriod() {
+ ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
+
+ RateLimiter limiter = RateLimiter.create(1, 100, TimeUnit.MILLISECONDS, scheduler);
+ ArgumentCaptor<Runnable> refillTask = ArgumentCaptor.forClass(Runnable.class);
+ try {
+ verify(scheduler).scheduleAtFixedRate(
+ refillTask.capture(), eq(100L), eq(100L), eq(TimeUnit.MILLISECONDS));
+ assertTrue(limiter.acquire());
+ refillTask.getValue().run();
+ assertTrue(limiter.acquire());
+ } finally {
+ limiter.stop();
+ }
+ verify(scheduler).shutdownNow();
+ }
+
+ @Test
+ public void testInvalidConfigurationIsRejected() {
+ assertThrows(IllegalArgumentException.class, () -> RateLimiter.create(0, TimeUnit.SECONDS));
+ assertThrows(IllegalArgumentException.class, () -> RateLimiter.create(1, 0, TimeUnit.SECONDS));
+ assertThrows(IllegalArgumentException.class, () -> RateLimiter.create(1, 1, null));
+ }
+
+ @Test
+ public void testInvalidAcquireRequestIsRejected() {
+ RateLimiter limiter = RateLimiter.create(1, 1, TimeUnit.DAYS);
+ try {
+ assertThrows(IllegalArgumentException.class, () -> limiter.acquire(0));
+ assertThrows(IllegalArgumentException.class, () -> limiter.acquire(2));
+ } finally {
+ limiter.stop();
+ }
+ }
+
+ @Test
+ public void testStopIsIdempotentAndUnblocksAcquire() throws Exception {
+ RateLimiter limiter = RateLimiter.create(1, 1, TimeUnit.DAYS);
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ assertTrue(limiter.acquire());
+ Future<Boolean> blockedAcquire = executor.submit(() -> limiter.acquire());
+
+ limiter.stop();
Review Comment:
Thanks for pointing this out. I’ve made the test deterministic by adding a test-only callback that signals a `CountDownLatch` after the permit acquisition fails and enters the waiting path. The test now waits for this signal before calling `stop()`, ensuring it actually verifies that `stop()` unblocks an ongoing `acquire()`.
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "fhan688 (via GitHub)" <gi...@apache.org>.
fhan688 commented on code in PR #20189:
URL: https://github.com/apache/hudi/pull/20189#discussion_r4226438292
##########
hudi-common/src/main/java/org/apache/hudi/common/util/RateLimiter.java:
##########
@@ -68,27 +94,59 @@ public boolean tryAcquire(int numPermits) {
}
public boolean acquire(int numOps) {
+ ValidationUtils.checkArgument(numOps > 0 && numOps <= maxPermits,
Review Comment:
Good point. I’ll add a no-argument `acquire()` backed by a private unchecked single-permit acquisition path, while keeping argument validation in `acquire(int)`. Both Flink per-record call sites will be updated to use the new overload, with tests covering the no-argument path and the existing validation behavior.
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "danny0405 (via GitHub)" <gi...@apache.org>.
danny0405 commented on code in PR #20189:
URL: https://github.com/apache/hudi/pull/20189#discussion_r4228513724
##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/utils/FlinkRateLimiterFactory.java:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.hudi.sink.utils;
+
+import org.apache.hudi.common.util.RateLimiter;
+import org.apache.hudi.common.util.ValidationUtils;
+import org.apache.hudi.common.util.VisibleForTesting;
+
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Factory for distributing a job-wide write rate limit across Flink subtasks.
+ */
+public final class FlinkRateLimiterFactory {
+
+ private FlinkRateLimiterFactory() {
+ }
+
+ public static RateLimiter create(long totalRateLimit, int parallelism) {
+ RateLimitConfig rateLimitConfig = resolveRateLimit(totalRateLimit, parallelism);
+ return RateLimiter.create(
+ rateLimitConfig.getPermits(), rateLimitConfig.getReleasePeriod(), rateLimitConfig.getTimeUnit());
+ }
+
+ @VisibleForTesting
+ static RateLimiter create(long totalRateLimit, int parallelism, ScheduledExecutorService scheduler) {
+ RateLimitConfig rateLimitConfig = resolveRateLimit(totalRateLimit, parallelism);
+ return RateLimiter.create(
+ rateLimitConfig.getPermits(), rateLimitConfig.getReleasePeriod(), rateLimitConfig.getTimeUnit(), scheduler);
+ }
+
+ static RateLimitConfig resolveRateLimit(long totalRateLimit, int parallelism) {
+ ValidationUtils.checkArgument(totalRateLimit > 0, "Total rate limit must be greater than zero");
+ ValidationUtils.checkArgument(parallelism > 0, "Parallelism must be greater than zero");
+
+ if (totalRateLimit >= parallelism) {
+ long rateLimitPerSubtask = totalRateLimit / parallelism;
+ ValidationUtils.checkArgument(rateLimitPerSubtask <= Integer.MAX_VALUE,
+ "Rate limit per subtask exceeds the supported maximum");
+ return new RateLimitConfig((int) rateLimitPerSubtask, 1, TimeUnit.SECONDS);
+ }
+
+ long periodNanos = divideRoundingUp(
+ Math.multiplyExact(TimeUnit.SECONDS.toNanos(1), parallelism), totalRateLimit);
+ return new RateLimitConfig(1, periodNanos, TimeUnit.NANOSECONDS);
Review Comment:
Could we clarify in the PR description that this conservatively limits the long-run average, while allowing bursts? Each subtask starts with one available permit, so `write.rate.limit=1` with parallelism `4` lets four records through immediately, followed by four-second refill intervals. I reproduced the initial burst. This seems consistent with the existing bucket-style limiter, but the statement that the aggregate rate cannot exceed the configured value is too strong if read as a per-second guarantee.
##########
hudi-common/src/main/java/org/apache/hudi/common/util/RateLimiter.java:
##########
@@ -68,27 +94,67 @@ public boolean tryAcquire(int numPermits) {
}
public boolean acquire(int numOps) {
+ ValidationUtils.checkArgument(numOps > 0 && numOps <= maxPermits,
+ "Number of permits must be between one and the configured maximum");
+ return acquireInternal(numOps);
+ }
+
+ public boolean acquire() {
+ return acquireInternal(1);
+ }
+
+ private boolean acquireInternal(int numOps) {
try {
- while (!semaphore.tryAcquire(numOps)) {
+ while (!stopped.get() && !semaphore.tryAcquire(numOps)) {
Thread.sleep(WAIT_BEFORE_NEXT_ACQUIRE_PERMIT_IN_MS);
}
+ ValidationUtils.checkState(!stopped.get(), "Rate limiter is stopped");
log.debug("acquire permits: {}, maxPermits: {}", numOps, maxPermits);
} catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
throw new RuntimeException("Unable to acquire permits", e);
}
return true;
}
- public void stop() {
- scheduler.shutdownNow();
+ public synchronized void stop() {
+ if (stopped.compareAndSet(false, true)) {
Review Comment:
Could we simplify the synchronization here? `stop()` and both scheduler-initialization methods already synchronize on the same instance, and `stop()` is the only writer of `stopped`. A `volatile boolean stopped` with an ordinary check/set under this monitor should be sufficient; CAS is redundant. Likewise, all accesses to `scheduler` are under that monitor, so its `volatile` modifier and the local `currentScheduler` snapshot are unnecessary. Keep `stopped` volatile because acquisition and `isStopped()` read it without taking the monitor.
##########
hudi-common/src/test/java/org/apache/hudi/common/util/TestRatelimiter.java:
##########
@@ -33,25 +44,91 @@ public class TestRatelimiter {
@Test
public void testRateLimiterWithNoThrottling() throws InterruptedException {
RateLimiter limiter = RateLimiter.create(1000, TimeUnit.SECONDS);
- long start = System.currentTimeMillis();
- assertEquals(true, limiter.tryAcquire(1000));
- // Sleep to represent some operation
- Thread.sleep(500);
- long end = System.currentTimeMillis();
- // With a large permit limit, there shouldn't be any throttling of operations
- assertTrue((end - start) < TimeUnit.SECONDS.toMillis(2));
+ try {
+ long start = System.currentTimeMillis();
+ assertEquals(true, limiter.tryAcquire(1000));
+ // Sleep to represent some operation
+ Thread.sleep(500);
+ long end = System.currentTimeMillis();
+ // With a large permit limit, there shouldn't be any throttling of operations
+ assertTrue((end - start) < TimeUnit.SECONDS.toMillis(2));
+ } finally {
+ limiter.stop();
+ }
}
@Test
public void testRateLimiterWithThrottling() throws InterruptedException {
RateLimiter limiter = RateLimiter.create(100, TimeUnit.SECONDS);
- long start = System.currentTimeMillis();
- assertEquals(true, limiter.tryAcquire(400));
- // Sleep to represent some operation
- Thread.sleep(500);
- long end = System.currentTimeMillis();
- // As size of operations is more than the maximum permits per second,
- // whole execution should be greater than 1 second
- assertTrue((end - start) >= TimeUnit.SECONDS.toMillis(2));
+ try {
+ long start = System.currentTimeMillis();
+ assertEquals(true, limiter.tryAcquire(400));
+ // Sleep to represent some operation
+ Thread.sleep(500);
+ long end = System.currentTimeMillis();
+ // As size of operations is more than the maximum permits per second,
+ // whole execution should be greater than 1 second
+ assertTrue((end - start) >= TimeUnit.SECONDS.toMillis(2));
+ } finally {
+ limiter.stop();
+ }
+ }
+
+ @Test
+ public void testCustomReleasePeriod() {
+ ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class);
+
+ RateLimiter limiter = RateLimiter.create(1, 100, TimeUnit.MILLISECONDS, scheduler);
+ ArgumentCaptor<Runnable> refillTask = ArgumentCaptor.forClass(Runnable.class);
+ try {
+ verify(scheduler).scheduleAtFixedRate(
+ refillTask.capture(), eq(100L), eq(100L), eq(TimeUnit.MILLISECONDS));
+ assertTrue(limiter.acquire());
+ refillTask.getValue().run();
+ assertTrue(limiter.acquire());
+ } finally {
+ limiter.stop();
+ }
+ verify(scheduler).shutdownNow();
+ }
+
+ @Test
+ public void testInvalidConfigurationIsRejected() {
+ assertThrows(IllegalArgumentException.class, () -> RateLimiter.create(0, TimeUnit.SECONDS));
+ assertThrows(IllegalArgumentException.class, () -> RateLimiter.create(1, 0, TimeUnit.SECONDS));
+ assertThrows(IllegalArgumentException.class, () -> RateLimiter.create(1, 1, null));
+ }
+
+ @Test
+ public void testInvalidAcquireRequestIsRejected() {
+ RateLimiter limiter = RateLimiter.create(1, 1, TimeUnit.DAYS);
+ try {
+ assertThrows(IllegalArgumentException.class, () -> limiter.acquire(0));
+ assertThrows(IllegalArgumentException.class, () -> limiter.acquire(2));
+ } finally {
+ limiter.stop();
+ }
+ }
+
+ @Test
+ public void testStopIsIdempotentAndUnblocksAcquire() throws Exception {
+ RateLimiter limiter = RateLimiter.create(1, 1, TimeUnit.DAYS);
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ assertTrue(limiter.acquire());
+ Future<Boolean> blockedAcquire = executor.submit(() -> limiter.acquire());
+
+ limiter.stop();
Review Comment:
Could we ensure the worker has actually reached the permit-waiting path before calling `stop()`? `submit()` does not guarantee that the task has started, so this test can pass by exercising only an acquisition that begins after shutdown. A deterministic signal from the waiting path would let the test distinguish those cases. I separately verified that the current implementation does unblock an already-waiting acquisition; this is a regression-coverage gap.
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "hudi-bot (via GitHub)" <gi...@apache.org>.
hudi-bot commented on PR #20189:
URL: https://github.com/apache/hudi/pull/20189#issuecomment-5956967023
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "718820c33938fac4eb5c362500fcae2de12ab9ca",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17422",
"triggerID" : "718820c33938fac4eb5c362500fcae2de12ab9ca",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 718820c33938fac4eb5c362500fcae2de12ab9ca Azure: [SUCCESS](https://dev.azure.com/apachehudi/a1a51da7-8592-47d4-88dc-fd67bed336bb/_build/results?buildId=17422)
<details>
<summary>Bot commands</summary>
@hudi-bot supports the following commands:
- `@hudi-bot 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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "danny0405 (via GitHub)" <gi...@apache.org>.
danny0405 merged PR #20189:
URL: https://github.com/apache/hudi/pull/20189
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "fhan688 (via GitHub)" <gi...@apache.org>.
fhan688 closed pull request #20189: fix(flink): prevent write rate limiter stalls and thread leaks
URL: https://github.com/apache/hudi/pull/20189
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] fix(flink): prevent write rate limiter stalls and thread leaks [hudi]
Posted by "cshuo (via GitHub)" <gi...@apache.org>.
cshuo commented on code in PR #20189:
URL: https://github.com/apache/hudi/pull/20189#discussion_r4225921206
##########
hudi-common/src/main/java/org/apache/hudi/common/util/RateLimiter.java:
##########
@@ -68,27 +94,59 @@ public boolean tryAcquire(int numPermits) {
}
public boolean acquire(int numOps) {
+ ValidationUtils.checkArgument(numOps > 0 && numOps <= maxPermits,
Review Comment:
Since both Flink callers invoke `acquire(1)` for every record, could we add a no-argument `acquire()` that skips argument validation? Construction already guarantees `maxPermits > 0`, so a single-permit request is always valid. We can keep the checks in `acquire(int)` for variable-sized requests.
--
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@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org