You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "sjvanrossum (via GitHub)" <gi...@apache.org> on 2024/10/31 17:48:54 UTC

[PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

sjvanrossum opened a new pull request, #32986:
URL: https://github.com/apache/beam/pull/32986

   Allows a Kafka consumer to be used for bundled assignments. By decoupling consumers from splits and running them in separate threads the harness thread should be blocked less by the creation of network connections or outstanding polls. The consumer thread may prefetch a batch of records while the harness thread is processing the current record batch. Multiplexing assigned `TopicPartition`s onto a single consumer may improve utilization of the network connection. A follow up PR may introduce consumer pools for cases where a single consumer would become a bottleneck. The state shared between the consumer and harness thread can be retrieved and mutated without locking. The lock-free exchange object of type `TopicPartitionState` fills a 64 byte cache line and should not suffer from false sharing provided that the cache line is 64 bytes long and the object is placed at the start of a cache line.
   
   Benchmarks to follow soon.
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/workflows/Build%20python%20source%20distribution%20and%20wheels/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/workflows/Python%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/workflows/Java%20Tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/workflows/Go%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "sjvanrossum (via GitHub)" <gi...@apache.org>.
sjvanrossum commented on code in PR #32986:
URL: https://github.com/apache/beam/pull/32986#discussion_r1890098337


##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));
+              } else if (!prevAssignment.contains(tp)) {
+                consumer.seek(tp, o);
+              }
+            });
+
+        if (consumer.paused().size() != nextAssignment.size()) {
+          pollResult = consumer.poll(pollDuration.toMillis());
+        }
+
+        nextAssignment.forEach(tp -> positions.put(tp, consumer.position(tp)));
+        return false;
+      } catch (WakeupException e) {
+        if (!this.isTerminated()) {
+          LOG.error("Unexpected wakeup while running", e);
+        }
+      } catch (Exception e) {
+        LOG.error("Exception while reading from Kafka", e);
+      }
+      return true;
+    }
+  }
+
+  ConcurrentConsumer(final Consumer<K, V> consumer, final Duration pollDuration) {
+    this.phaser = new ConsumerPhaser();
+    this.consumer = consumer;
+    this.pollDuration = pollDuration;
+    this.times = AtomicLongMap.create();
+    this.positions = AtomicLongMap.create();
+    this.recordsLagMax =
+        Suppliers.memoize(
+            () ->
+                this.consumer.metrics().values().stream()
+                    .filter(
+                        m ->
+                            "consumer-fetch-manager-metrics".equals(m.metricName().group())
+                                && "records-lag-max".equals(m.metricName().name())
+                                && !m.metricName().tags().containsKey("topic")
+                                && !m.metricName().tags().containsKey("partition"))
+                    .findAny()
+                    .get());
+    this.partitionRecordsLag = new ConcurrentHashMap<>();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  @Override
+  public void close() {
+    this.phaser.forceTermination();
+    try {
+      this.consumer.wakeup();
+      this.consumer.close();
+    } catch (Exception e) {
+      LOG.error("Exception while closing Kafka consumer", e);
+    }
+    this.times.clear();
+    this.positions.clear();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  boolean isClosed() {
+    return this.phaser.isTerminated();
+  }
+
+  Map<MetricName, ? extends Metric> metrics() {
+    return this.consumer.metrics();
+  }
+
+  long currentLagOrMaxLag(final TopicPartition topicPartition) {
+    final Supplier<Metric> metric =
+        this.partitionRecordsLag.getOrDefault(topicPartition, this.recordsLagMax);
+    try {
+      return ((Number) metric.get().metricValue()).longValue();
+    } catch (Exception e) {
+      return 0;
+    }
+  }
+
+  long position(final TopicPartition topicPartition) {
+    return this.positions.get(topicPartition) & Long.MAX_VALUE;

Review Comment:
   Correct, but I don't think we should keep this style of pause/resume bookkeeping since it's the least intuitive way to express it for readers and maintainers. It's unlikely that the representation of partition offsets will ever switch from signed to unsigned integers in a future version of Kafka, but not introducing a dependency on that assumption is also one less thing to worry about in the future.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "sjvanrossum (via GitHub)" <gi...@apache.org>.
sjvanrossum commented on code in PR #32986:
URL: https://github.com/apache/beam/pull/32986#discussion_r1890000062


##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));
+              } else if (!prevAssignment.contains(tp)) {
+                consumer.seek(tp, o);
+              }
+            });
+
+        if (consumer.paused().size() != nextAssignment.size()) {
+          pollResult = consumer.poll(pollDuration.toMillis());
+        }
+
+        nextAssignment.forEach(tp -> positions.put(tp, consumer.position(tp)));
+        return false;
+      } catch (WakeupException e) {
+        if (!this.isTerminated()) {
+          LOG.error("Unexpected wakeup while running", e);
+        }
+      } catch (Exception e) {
+        LOG.error("Exception while reading from Kafka", e);
+      }
+      return true;
+    }
+  }
+
+  ConcurrentConsumer(final Consumer<K, V> consumer, final Duration pollDuration) {
+    this.phaser = new ConsumerPhaser();
+    this.consumer = consumer;
+    this.pollDuration = pollDuration;
+    this.times = AtomicLongMap.create();
+    this.positions = AtomicLongMap.create();
+    this.recordsLagMax =
+        Suppliers.memoize(
+            () ->
+                this.consumer.metrics().values().stream()
+                    .filter(
+                        m ->
+                            "consumer-fetch-manager-metrics".equals(m.metricName().group())
+                                && "records-lag-max".equals(m.metricName().name())
+                                && !m.metricName().tags().containsKey("topic")
+                                && !m.metricName().tags().containsKey("partition"))
+                    .findAny()
+                    .get());
+    this.partitionRecordsLag = new ConcurrentHashMap<>();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  @Override
+  public void close() {
+    this.phaser.forceTermination();
+    try {
+      this.consumer.wakeup();
+      this.consumer.close();
+    } catch (Exception e) {
+      LOG.error("Exception while closing Kafka consumer", e);
+    }
+    this.times.clear();
+    this.positions.clear();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  boolean isClosed() {
+    return this.phaser.isTerminated();
+  }
+
+  Map<MetricName, ? extends Metric> metrics() {
+    return this.consumer.metrics();
+  }
+
+  long currentLagOrMaxLag(final TopicPartition topicPartition) {
+    final Supplier<Metric> metric =
+        this.partitionRecordsLag.getOrDefault(topicPartition, this.recordsLagMax);
+    try {
+      return ((Number) metric.get().metricValue()).longValue();

Review Comment:
   Agreed.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "sjvanrossum (via GitHub)" <gi...@apache.org>.
sjvanrossum commented on code in PR #32986:
URL: https://github.com/apache/beam/pull/32986#discussion_r1890035467


##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ReadFromKafkaDoFn.java:
##########
@@ -215,20 +233,329 @@ private ReadFromKafkaDoFn(
    * must run clean up tasks when {@link #teardown()} is called.
    */
   private static final class SharedStateHolder {
-
-    private static final Map<Long, LoadingCache<KafkaSourceDescriptor, KafkaLatestOffsetEstimator>>
-        OFFSET_ESTIMATOR_CACHE = new ConcurrentHashMap<>();
     private static final Map<Long, LoadingCache<KafkaSourceDescriptor, AverageRecordSize>>
         AVG_RECORD_SIZE_CACHE = new ConcurrentHashMap<>();
+    private static final Map<
+            Long, LoadingCache<Optional<ImmutableSet<String>>, ConsumerExecutionContext>>
+        CONSUMER_EXECUTION_CONTEXT_CACHE = new ConcurrentHashMap<>();
+  }
+
+  static final class TopicPartitionPollState implements AutoCloseable {
+    private static final List<ConsumerRecord<byte[], byte[]>> CLOSED_SENTINEL = Arrays.asList();
+
+    private final AtomicBoolean closed;
+    private final LinkedTransferQueue<List<ConsumerRecord<byte[], byte[]>>> queue;
+    private final TopicPartition topicPartition;
+    private final OffsetRange offsetRange;
+
+    TopicPartitionPollState(final TopicPartition topicPartition, final OffsetRange offsetRange) {
+      this.closed = new AtomicBoolean();
+      this.queue = new LinkedTransferQueue<>();
+      this.topicPartition = topicPartition;
+      this.offsetRange = offsetRange;
+    }
+
+    TopicPartition getTopicPartition() {
+      return this.topicPartition;
+    }
+
+    OffsetRange getOffsetRange() {
+      return this.offsetRange;
+    }
+
+    boolean hasWaitingConsumer() {
+      return !this.closed.get() && queue.hasWaitingConsumer();
+    }
+
+    Optional<List<ConsumerRecord<byte[], byte[]>>> take() throws InterruptedException {

Review Comment:
   I don't think I have a need for a blocking queue between the Kafka consumer and SDF threads at the moment, but I had thought about reusing `CancellableQueue` if that exchange pattern stuck around. πŸ‘ 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "sjvanrossum (via GitHub)" <gi...@apache.org>.
sjvanrossum commented on PR #32986:
URL: https://github.com/apache/beam/pull/32986#issuecomment-2541270102

   Feel free to take a peek @scwhittle! πŸ˜ƒ 
   There's also a separate branch with these changes applied on top of 2.61.0 at https://github.com/sjvanrossum/beam/tree/kafkaio-decoupled-consumer-sdf-2.61.0 if you want to build a pipeline.
   
   I had some inspiration on Sunday and revised the approach to thread-safe sharing of a Kafka consumer after hitting that 1 GiB/s bottleneck. The new `ConcurrentConsumer` wrapper uses a [`Phaser`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html) to synchronize access to the `Consumer`. Registration at the `Phaser` happens when `processElement` is about to enter its poll loop, arrival at the phaser happens at every poll and deregistration happens at every return point or thrown exception. Advancement of the `Phaser` issues a poll on the consumer executed by the thread that last arrived or deregistered.
   
   Kafka's info logs are verbose enough to make out that Kafka consumers on various workers are frequently assigned more than one partition. The image below is from a throughput test using 256-512 cores (n2d-standard-2) to read from 500 partitions that are filled by a producer at ~10 GiB/s and the time mark highlights the moment at which the pipeline had scaled up from 256 to 512 cores. I seem to be hitting a cap at 2.5 GiB/s at the moment when I run this test with a shuffle step as a simple IO sink. This same workload using the unmodified source implementation on Dataflow's Runner V1 reports 2.5-3 GiB/s after scaling up. Without an IO sink both of them are able to process 10 GiB/s with comparable behavior throughout the pipeline's lifetime.
   
   ![image](https://github.com/user-attachments/assets/8bca8ad3-4e5c-4e8b-a1be-a0337deb6ac1)
   
   The `Phaser` does become a bottleneck, as would be expected, when this same workload is packed onto larger machines and that stacks on top of reduced consumer throughput. I've got a few more ideas to reduce the number of forced sync points and to dynamically size the number of consumers per worker, but I'm also open for suggestions if you have any. πŸ‘ 
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "sjvanrossum (via GitHub)" <gi...@apache.org>.
sjvanrossum commented on code in PR #32986:
URL: https://github.com/apache/beam/pull/32986#discussion_r1890030711


##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ReadFromKafkaDoFn.java:
##########
@@ -215,20 +233,329 @@ private ReadFromKafkaDoFn(
    * must run clean up tasks when {@link #teardown()} is called.
    */
   private static final class SharedStateHolder {
-
-    private static final Map<Long, LoadingCache<KafkaSourceDescriptor, KafkaLatestOffsetEstimator>>
-        OFFSET_ESTIMATOR_CACHE = new ConcurrentHashMap<>();
     private static final Map<Long, LoadingCache<KafkaSourceDescriptor, AverageRecordSize>>
         AVG_RECORD_SIZE_CACHE = new ConcurrentHashMap<>();
+    private static final Map<
+            Long, LoadingCache<Optional<ImmutableSet<String>>, ConsumerExecutionContext>>
+        CONSUMER_EXECUTION_CONTEXT_CACHE = new ConcurrentHashMap<>();
+  }
+
+  static final class TopicPartitionPollState implements AutoCloseable {
+    private static final List<ConsumerRecord<byte[], byte[]>> CLOSED_SENTINEL = Arrays.asList();
+
+    private final AtomicBoolean closed;
+    private final LinkedTransferQueue<List<ConsumerRecord<byte[], byte[]>>> queue;
+    private final TopicPartition topicPartition;
+    private final OffsetRange offsetRange;
+
+    TopicPartitionPollState(final TopicPartition topicPartition, final OffsetRange offsetRange) {
+      this.closed = new AtomicBoolean();
+      this.queue = new LinkedTransferQueue<>();
+      this.topicPartition = topicPartition;
+      this.offsetRange = offsetRange;
+    }
+
+    TopicPartition getTopicPartition() {
+      return this.topicPartition;
+    }
+
+    OffsetRange getOffsetRange() {
+      return this.offsetRange;
+    }
+
+    boolean hasWaitingConsumer() {
+      return !this.closed.get() && queue.hasWaitingConsumer();
+    }
+
+    Optional<List<ConsumerRecord<byte[], byte[]>>> take() throws InterruptedException {
+      if (this.closed.get()) {
+        return Optional.empty();
+      }
+      return Optional.of(queue.take()).filter(records -> records != CLOSED_SENTINEL);

Review Comment:
   Resolving since this class has been removed in the redesign.
   If I recall correctly, instances of this class would only be shared between the Kafka consumer thread and the current SDF thread. Setting `closed` to `true` and inserting the sentinel element was intended to unblock queue consumers awaiting the result of `take()`. Sharing `CancellableQueue` would have been my preferred option if this class had stuck around.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "scwhittle (via GitHub)" <gi...@apache.org>.
scwhittle commented on PR #32986:
URL: https://github.com/apache/beam/pull/32986#issuecomment-2512415373

   I'm interested in reviewing since I was looking at performance of this earlier.  Let me know if you'd like me to take a pass in the current state or wait. Thanks! looking forward to these improvements.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "sjvanrossum (via GitHub)" <gi...@apache.org>.
sjvanrossum commented on code in PR #32986:
URL: https://github.com/apache/beam/pull/32986#discussion_r1890188295


##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));

Review Comment:
   `Consumer.pause(Collection<TopicPartition>)` iterates over the input collection, looks up the assignment in its subscription state table and then mutates the state. There's virtually no difference between N invocations of pause/resume for singleton collections or a single invocation for a collection of size N.
   
   I reworked the phaser interaction a bit to deregister when a non-empty list of records for a partition is returned by `Consumer.poll()` so this can be rewritten as `consumer.pause(consumerRecords.partitions())` which returns the set of partitions with available records. That addresses the throughput regression observed on larger machine types along with the rate jumping from ~2.5 GiB/s to ~3.1 GiB/s. I'm looking into a stall at the moment, likely a missed arrive or deregister at the phaser or a missed cache invalidation.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #32986:
URL: https://github.com/apache/beam/pull/32986#issuecomment-2710467859

   This pull request has been marked as stale due to 60 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the dev@beam.apache.org list. Thank you for your contributions.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "scwhittle (via GitHub)" <gi...@apache.org>.
scwhittle commented on code in PR #32986:
URL: https://github.com/apache/beam/pull/32986#discussion_r1866394445


##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ReadFromKafkaDoFn.java:
##########
@@ -215,20 +233,329 @@ private ReadFromKafkaDoFn(
    * must run clean up tasks when {@link #teardown()} is called.
    */
   private static final class SharedStateHolder {
-
-    private static final Map<Long, LoadingCache<KafkaSourceDescriptor, KafkaLatestOffsetEstimator>>
-        OFFSET_ESTIMATOR_CACHE = new ConcurrentHashMap<>();
     private static final Map<Long, LoadingCache<KafkaSourceDescriptor, AverageRecordSize>>
         AVG_RECORD_SIZE_CACHE = new ConcurrentHashMap<>();
+    private static final Map<
+            Long, LoadingCache<Optional<ImmutableSet<String>>, ConsumerExecutionContext>>

Review Comment:
   comment on keys of map and loading cache



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ReadFromKafkaDoFn.java:
##########
@@ -215,20 +233,329 @@ private ReadFromKafkaDoFn(
    * must run clean up tasks when {@link #teardown()} is called.
    */
   private static final class SharedStateHolder {
-
-    private static final Map<Long, LoadingCache<KafkaSourceDescriptor, KafkaLatestOffsetEstimator>>
-        OFFSET_ESTIMATOR_CACHE = new ConcurrentHashMap<>();
     private static final Map<Long, LoadingCache<KafkaSourceDescriptor, AverageRecordSize>>
         AVG_RECORD_SIZE_CACHE = new ConcurrentHashMap<>();
+    private static final Map<
+            Long, LoadingCache<Optional<ImmutableSet<String>>, ConsumerExecutionContext>>
+        CONSUMER_EXECUTION_CONTEXT_CACHE = new ConcurrentHashMap<>();
+  }
+
+  static final class TopicPartitionPollState implements AutoCloseable {
+    private static final List<ConsumerRecord<byte[], byte[]>> CLOSED_SENTINEL = Arrays.asList();
+
+    private final AtomicBoolean closed;
+    private final LinkedTransferQueue<List<ConsumerRecord<byte[], byte[]>>> queue;
+    private final TopicPartition topicPartition;
+    private final OffsetRange offsetRange;
+
+    TopicPartitionPollState(final TopicPartition topicPartition, final OffsetRange offsetRange) {
+      this.closed = new AtomicBoolean();
+      this.queue = new LinkedTransferQueue<>();
+      this.topicPartition = topicPartition;
+      this.offsetRange = offsetRange;
+    }
+
+    TopicPartition getTopicPartition() {
+      return this.topicPartition;
+    }
+
+    OffsetRange getOffsetRange() {
+      return this.offsetRange;
+    }
+
+    boolean hasWaitingConsumer() {
+      return !this.closed.get() && queue.hasWaitingConsumer();
+    }
+
+    Optional<List<ConsumerRecord<byte[], byte[]>>> take() throws InterruptedException {
+      if (this.closed.get()) {
+        return Optional.empty();
+      }
+      return Optional.of(queue.take()).filter(records -> records != CLOSED_SENTINEL);

Review Comment:
   this could block forever if there are multiple threads calling take() as only one would get the sentinel
   
   if that isn't expected usage some comments on usage woudl be good.



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));
+              } else if (!prevAssignment.contains(tp)) {
+                consumer.seek(tp, o);
+              }
+            });
+
+        if (consumer.paused().size() != nextAssignment.size()) {
+          pollResult = consumer.poll(pollDuration.toMillis());
+        }
+
+        nextAssignment.forEach(tp -> positions.put(tp, consumer.position(tp)));
+        return false;
+      } catch (WakeupException e) {
+        if (!this.isTerminated()) {
+          LOG.error("Unexpected wakeup while running", e);
+        }
+      } catch (Exception e) {
+        LOG.error("Exception while reading from Kafka", e);
+      }
+      return true;
+    }
+  }
+
+  ConcurrentConsumer(final Consumer<K, V> consumer, final Duration pollDuration) {
+    this.phaser = new ConsumerPhaser();
+    this.consumer = consumer;
+    this.pollDuration = pollDuration;
+    this.times = AtomicLongMap.create();
+    this.positions = AtomicLongMap.create();
+    this.recordsLagMax =
+        Suppliers.memoize(
+            () ->
+                this.consumer.metrics().values().stream()
+                    .filter(
+                        m ->
+                            "consumer-fetch-manager-metrics".equals(m.metricName().group())
+                                && "records-lag-max".equals(m.metricName().name())
+                                && !m.metricName().tags().containsKey("topic")
+                                && !m.metricName().tags().containsKey("partition"))
+                    .findAny()
+                    .get());
+    this.partitionRecordsLag = new ConcurrentHashMap<>();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  @Override
+  public void close() {
+    this.phaser.forceTermination();
+    try {
+      this.consumer.wakeup();
+      this.consumer.close();
+    } catch (Exception e) {
+      LOG.error("Exception while closing Kafka consumer", e);
+    }
+    this.times.clear();
+    this.positions.clear();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  boolean isClosed() {
+    return this.phaser.isTerminated();
+  }
+
+  Map<MetricName, ? extends Metric> metrics() {
+    return this.consumer.metrics();
+  }
+
+  long currentLagOrMaxLag(final TopicPartition topicPartition) {
+    final Supplier<Metric> metric =
+        this.partitionRecordsLag.getOrDefault(topicPartition, this.recordsLagMax);
+    try {
+      return ((Number) metric.get().metricValue()).longValue();
+    } catch (Exception e) {
+      return 0;
+    }
+  }
+
+  long position(final TopicPartition topicPartition) {
+    return this.positions.get(topicPartition) & Long.MAX_VALUE;
+  }
+
+  long initialOffsetForPartition(final TopicPartition topicPartition) {
+    // Offsets start at 0 and there is no position to advance to beyond Long.MAX_VALUE.
+    // The sign bit indicates that an assignment is paused.
+    checkState(this.phaser.register() >= 0);
+    this.positions.put(topicPartition, Long.MIN_VALUE);
+
+    // Synchronize and throw if the consumer was terminated in between.
+    checkState(this.phaser.arriveAndAwaitAdvance() >= 0);
+
+    // Removal will revoke the assignment when the phase advances.
+    final long result = this.positions.remove(topicPartition);
+
+    // Synchronize and ignore the consumer status since the result is already known.
+    this.phaser.arriveAndDeregister();
+
+    // Since Long.MIN_VALUE only has the sign bit set, this will return 0 as a default value if no
+    // position could be determined.
+    return result & Long.MAX_VALUE;
+  }
+
+  @Nullable
+  OffsetAndTimestamp initialOffsetForTime(final TopicPartition topicPartition, final long time) {
+    // Request the offset closest to the provided time.
+    checkState(this.phaser.register() >= 0);
+    this.times.put(topicPartition, time);
+
+    // Synchronize and throw if the consumer was terminated in between.
+    checkState(this.phaser.arriveAndAwaitAdvance() >= 0);
+    final Map<TopicPartition, OffsetAndTimestamp> result = this.offsetsForTimesResult;
+
+    // Synchronize and ignore the consumer status since the result is already known.
+    this.phaser.arriveAndDeregister();
+
+    return result.get(topicPartition);
+  }
+
+  void assignAndSeek(final TopicPartition topicPartition, final long offset) {
+    checkState(this.phaser.register() >= 0);
+
+    this.positions.put(topicPartition, offset);
+    this.partitionRecordsLag.computeIfAbsent(
+        topicPartition,
+        k ->
+            Suppliers.memoize(

Review Comment:
   similar concern here, what if metrics aren't updated or it is missing on original call?



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));
+              } else if (!prevAssignment.contains(tp)) {
+                consumer.seek(tp, o);
+              }
+            });
+
+        if (consumer.paused().size() != nextAssignment.size()) {
+          pollResult = consumer.poll(pollDuration.toMillis());
+        }
+
+        nextAssignment.forEach(tp -> positions.put(tp, consumer.position(tp)));
+        return false;
+      } catch (WakeupException e) {
+        if (!this.isTerminated()) {
+          LOG.error("Unexpected wakeup while running", e);
+        }
+      } catch (Exception e) {
+        LOG.error("Exception while reading from Kafka", e);
+      }
+      return true;
+    }
+  }
+
+  ConcurrentConsumer(final Consumer<K, V> consumer, final Duration pollDuration) {
+    this.phaser = new ConsumerPhaser();
+    this.consumer = consumer;
+    this.pollDuration = pollDuration;
+    this.times = AtomicLongMap.create();
+    this.positions = AtomicLongMap.create();
+    this.recordsLagMax =
+        Suppliers.memoize(
+            () ->
+                this.consumer.metrics().values().stream()
+                    .filter(
+                        m ->
+                            "consumer-fetch-manager-metrics".equals(m.metricName().group())
+                                && "records-lag-max".equals(m.metricName().name())
+                                && !m.metricName().tags().containsKey("topic")
+                                && !m.metricName().tags().containsKey("partition"))
+                    .findAny()
+                    .get());
+    this.partitionRecordsLag = new ConcurrentHashMap<>();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  @Override
+  public void close() {
+    this.phaser.forceTermination();
+    try {
+      this.consumer.wakeup();
+      this.consumer.close();
+    } catch (Exception e) {
+      LOG.error("Exception while closing Kafka consumer", e);
+    }
+    this.times.clear();
+    this.positions.clear();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  boolean isClosed() {
+    return this.phaser.isTerminated();
+  }
+
+  Map<MetricName, ? extends Metric> metrics() {
+    return this.consumer.metrics();
+  }
+
+  long currentLagOrMaxLag(final TopicPartition topicPartition) {
+    final Supplier<Metric> metric =
+        this.partitionRecordsLag.getOrDefault(topicPartition, this.recordsLagMax);
+    try {
+      return ((Number) metric.get().metricValue()).longValue();

Review Comment:
   handle null explicitly without exception?



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {

Review Comment:
   An overview comment would be helpful



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));
+              } else if (!prevAssignment.contains(tp)) {
+                consumer.seek(tp, o);
+              }
+            });
+
+        if (consumer.paused().size() != nextAssignment.size()) {
+          pollResult = consumer.poll(pollDuration.toMillis());
+        }
+
+        nextAssignment.forEach(tp -> positions.put(tp, consumer.position(tp)));
+        return false;
+      } catch (WakeupException e) {
+        if (!this.isTerminated()) {
+          LOG.error("Unexpected wakeup while running", e);
+        }
+      } catch (Exception e) {
+        LOG.error("Exception while reading from Kafka", e);
+      }
+      return true;
+    }
+  }
+
+  ConcurrentConsumer(final Consumer<K, V> consumer, final Duration pollDuration) {
+    this.phaser = new ConsumerPhaser();
+    this.consumer = consumer;
+    this.pollDuration = pollDuration;
+    this.times = AtomicLongMap.create();
+    this.positions = AtomicLongMap.create();
+    this.recordsLagMax =
+        Suppliers.memoize(

Review Comment:
   I don't see guarantees in kafka interface that same metric object is updated, or about when the metric woudl be created.
   
   Perhaps it woudl be better to have some expiration here? Or at least don't cache a null if we attempt to memoize before the metric has been created in the consumer?



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));
+              } else if (!prevAssignment.contains(tp)) {
+                consumer.seek(tp, o);
+              }
+            });
+
+        if (consumer.paused().size() != nextAssignment.size()) {
+          pollResult = consumer.poll(pollDuration.toMillis());
+        }
+
+        nextAssignment.forEach(tp -> positions.put(tp, consumer.position(tp)));
+        return false;
+      } catch (WakeupException e) {
+        if (!this.isTerminated()) {
+          LOG.error("Unexpected wakeup while running", e);
+        }
+      } catch (Exception e) {
+        LOG.error("Exception while reading from Kafka", e);
+      }
+      return true;
+    }
+  }
+
+  ConcurrentConsumer(final Consumer<K, V> consumer, final Duration pollDuration) {
+    this.phaser = new ConsumerPhaser();
+    this.consumer = consumer;
+    this.pollDuration = pollDuration;
+    this.times = AtomicLongMap.create();
+    this.positions = AtomicLongMap.create();
+    this.recordsLagMax =
+        Suppliers.memoize(
+            () ->
+                this.consumer.metrics().values().stream()
+                    .filter(
+                        m ->
+                            "consumer-fetch-manager-metrics".equals(m.metricName().group())
+                                && "records-lag-max".equals(m.metricName().name())
+                                && !m.metricName().tags().containsKey("topic")
+                                && !m.metricName().tags().containsKey("partition"))
+                    .findAny()
+                    .get());
+    this.partitionRecordsLag = new ConcurrentHashMap<>();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  @Override
+  public void close() {
+    this.phaser.forceTermination();
+    try {
+      this.consumer.wakeup();
+      this.consumer.close();
+    } catch (Exception e) {
+      LOG.error("Exception while closing Kafka consumer", e);
+    }
+    this.times.clear();
+    this.positions.clear();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  boolean isClosed() {
+    return this.phaser.isTerminated();
+  }
+
+  Map<MetricName, ? extends Metric> metrics() {
+    return this.consumer.metrics();
+  }
+
+  long currentLagOrMaxLag(final TopicPartition topicPartition) {
+    final Supplier<Metric> metric =
+        this.partitionRecordsLag.getOrDefault(topicPartition, this.recordsLagMax);
+    try {
+      return ((Number) metric.get().metricValue()).longValue();
+    } catch (Exception e) {
+      return 0;
+    }
+  }
+
+  long position(final TopicPartition topicPartition) {
+    return this.positions.get(topicPartition) & Long.MAX_VALUE;

Review Comment:
   comment on the purpose of &, looks like to protect against exposing negative value?



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;

Review Comment:
   what kind of time? a better variable name could clarify
   
   comment on keys, ditto for positions



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));

Review Comment:
   would it be better to just pause once by building up all partitions you want to pause?



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ReadFromKafkaDoFn.java:
##########
@@ -215,20 +233,329 @@ private ReadFromKafkaDoFn(
    * must run clean up tasks when {@link #teardown()} is called.
    */
   private static final class SharedStateHolder {
-
-    private static final Map<Long, LoadingCache<KafkaSourceDescriptor, KafkaLatestOffsetEstimator>>
-        OFFSET_ESTIMATOR_CACHE = new ConcurrentHashMap<>();
     private static final Map<Long, LoadingCache<KafkaSourceDescriptor, AverageRecordSize>>
         AVG_RECORD_SIZE_CACHE = new ConcurrentHashMap<>();
+    private static final Map<
+            Long, LoadingCache<Optional<ImmutableSet<String>>, ConsumerExecutionContext>>
+        CONSUMER_EXECUTION_CONTEXT_CACHE = new ConcurrentHashMap<>();
+  }
+
+  static final class TopicPartitionPollState implements AutoCloseable {
+    private static final List<ConsumerRecord<byte[], byte[]>> CLOSED_SENTINEL = Arrays.asList();
+
+    private final AtomicBoolean closed;
+    private final LinkedTransferQueue<List<ConsumerRecord<byte[], byte[]>>> queue;
+    private final TopicPartition topicPartition;
+    private final OffsetRange offsetRange;
+
+    TopicPartitionPollState(final TopicPartition topicPartition, final OffsetRange offsetRange) {
+      this.closed = new AtomicBoolean();
+      this.queue = new LinkedTransferQueue<>();
+      this.topicPartition = topicPartition;
+      this.offsetRange = offsetRange;
+    }
+
+    TopicPartition getTopicPartition() {
+      return this.topicPartition;
+    }
+
+    OffsetRange getOffsetRange() {
+      return this.offsetRange;
+    }
+
+    boolean hasWaitingConsumer() {
+      return !this.closed.get() && queue.hasWaitingConsumer();
+    }
+
+    Optional<List<ConsumerRecord<byte[], byte[]>>> take() throws InterruptedException {

Review Comment:
   this looks similar to sdks/java/core/src/main/java/org/apache/beam/sdk/fn/CancellableQueue.java
   
   should we unify?



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ReadFromKafkaDoFn.java:
##########
@@ -215,20 +233,329 @@ private ReadFromKafkaDoFn(
    * must run clean up tasks when {@link #teardown()} is called.
    */
   private static final class SharedStateHolder {
-
-    private static final Map<Long, LoadingCache<KafkaSourceDescriptor, KafkaLatestOffsetEstimator>>
-        OFFSET_ESTIMATOR_CACHE = new ConcurrentHashMap<>();
     private static final Map<Long, LoadingCache<KafkaSourceDescriptor, AverageRecordSize>>
         AVG_RECORD_SIZE_CACHE = new ConcurrentHashMap<>();
+    private static final Map<
+            Long, LoadingCache<Optional<ImmutableSet<String>>, ConsumerExecutionContext>>
+        CONSUMER_EXECUTION_CONTEXT_CACHE = new ConcurrentHashMap<>();
+  }
+
+  static final class TopicPartitionPollState implements AutoCloseable {
+    private static final List<ConsumerRecord<byte[], byte[]>> CLOSED_SENTINEL = Arrays.asList();

Review Comment:
   nit: maybe ImmutableList.of() would be clearer this isn't to be modified



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ReadFromKafkaDoFn.java:
##########
@@ -267,80 +284,121 @@ private static final class SharedStateHolder {
   private static class KafkaLatestOffsetEstimator
       implements GrowableOffsetRangeTracker.RangeEndEstimator {
 
-    private final Consumer<byte[], byte[]> offsetConsumer;
-    private final TopicPartition topicPartition;
-    private final Supplier<Long> memoizedBacklog;
+    private final KafkaSourceDescriptor sourceDescriptor;
+    private final LoadingCache<Optional<ImmutableSet<String>>, ConcurrentConsumer<byte[], byte[]>>
+        consumerExecutionContextCache;
+    private @MonotonicNonNull ConcurrentConsumer<byte[], byte[]> consumerExecutionContextInstance;
 
     KafkaLatestOffsetEstimator(
-        Consumer<byte[], byte[]> offsetConsumer, TopicPartition topicPartition) {
-      this.offsetConsumer = offsetConsumer;
-      this.topicPartition = topicPartition;
-      memoizedBacklog =
-          Suppliers.memoizeWithExpiration(
-              () -> {
-                synchronized (offsetConsumer) {
-                  return Preconditions.checkStateNotNull(
-                      offsetConsumer
-                          .endOffsets(Collections.singleton(topicPartition))
-                          .get(topicPartition),
-                      "No end offset found for partition %s.",
-                      topicPartition);
-                }
-              },
-              1,
-              TimeUnit.SECONDS);
+        final KafkaSourceDescriptor sourceDescriptor,
+        final LoadingCache<Optional<ImmutableSet<String>>, ConcurrentConsumer<byte[], byte[]>>
+            consumerExecutionContextCache) {
+      this.sourceDescriptor = sourceDescriptor;
+      this.consumerExecutionContextCache = consumerExecutionContextCache;
+      this.consumerExecutionContextInstance = null;
     }
 
     @Override
-    protected void finalize() {
+    public long estimate() {
+      Optional<ImmutableSet<String>> consumerExecutionContextKey =
+          Optional.ofNullable(this.sourceDescriptor.getBootStrapServers())
+              .map(ImmutableSet::copyOf);
+      ConcurrentConsumer<byte[], byte[]> consumerExecutionContext;
       try {
-        Closeables.close(offsetConsumer, true);
-        LOG.info("Offset Estimator consumer was closed for {}", topicPartition);
-      } catch (Exception anyException) {
-        LOG.warn("Failed to close offset consumer for {}", topicPartition);
+        consumerExecutionContext =
+            this.consumerExecutionContextCache.get(consumerExecutionContextKey);
+      } catch (ExecutionException ex) {
+        return -1L;
       }
-    }
+      this.consumerExecutionContextInstance = consumerExecutionContext;
 
-    @Override
-    public long estimate() {
-      return memoizedBacklog.get();
+      final long position =
+          this.consumerExecutionContextInstance.position(this.sourceDescriptor.getTopicPartition());

Review Comment:
   use consumerExecutionContext instead of this.consumerExecutionContext



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ReadFromKafkaDoFn.java:
##########
@@ -267,80 +284,121 @@ private static final class SharedStateHolder {
   private static class KafkaLatestOffsetEstimator
       implements GrowableOffsetRangeTracker.RangeEndEstimator {
 
-    private final Consumer<byte[], byte[]> offsetConsumer;
-    private final TopicPartition topicPartition;
-    private final Supplier<Long> memoizedBacklog;
+    private final KafkaSourceDescriptor sourceDescriptor;
+    private final LoadingCache<Optional<ImmutableSet<String>>, ConcurrentConsumer<byte[], byte[]>>
+        consumerExecutionContextCache;
+    private @MonotonicNonNull ConcurrentConsumer<byte[], byte[]> consumerExecutionContextInstance;

Review Comment:
   This doesn't appear to be used to avoid lookups in the cache. Should it be removed or should the logic be changed?



##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));
+              } else if (!prevAssignment.contains(tp)) {
+                consumer.seek(tp, o);
+              }
+            });
+
+        if (consumer.paused().size() != nextAssignment.size()) {
+          pollResult = consumer.poll(pollDuration.toMillis());
+        }
+
+        nextAssignment.forEach(tp -> positions.put(tp, consumer.position(tp)));
+        return false;
+      } catch (WakeupException e) {
+        if (!this.isTerminated()) {
+          LOG.error("Unexpected wakeup while running", e);
+        }
+      } catch (Exception e) {
+        LOG.error("Exception while reading from Kafka", e);
+      }
+      return true;
+    }
+  }
+
+  ConcurrentConsumer(final Consumer<K, V> consumer, final Duration pollDuration) {
+    this.phaser = new ConsumerPhaser();
+    this.consumer = consumer;
+    this.pollDuration = pollDuration;
+    this.times = AtomicLongMap.create();
+    this.positions = AtomicLongMap.create();
+    this.recordsLagMax =
+        Suppliers.memoize(
+            () ->
+                this.consumer.metrics().values().stream()
+                    .filter(
+                        m ->
+                            "consumer-fetch-manager-metrics".equals(m.metricName().group())
+                                && "records-lag-max".equals(m.metricName().name())
+                                && !m.metricName().tags().containsKey("topic")
+                                && !m.metricName().tags().containsKey("partition"))
+                    .findAny()
+                    .get());
+    this.partitionRecordsLag = new ConcurrentHashMap<>();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  @Override
+  public void close() {
+    this.phaser.forceTermination();
+    try {
+      this.consumer.wakeup();
+      this.consumer.close();
+    } catch (Exception e) {
+      LOG.error("Exception while closing Kafka consumer", e);
+    }
+    this.times.clear();
+    this.positions.clear();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  boolean isClosed() {
+    return this.phaser.isTerminated();
+  }
+
+  Map<MetricName, ? extends Metric> metrics() {
+    return this.consumer.metrics();
+  }
+
+  long currentLagOrMaxLag(final TopicPartition topicPartition) {
+    final Supplier<Metric> metric =
+        this.partitionRecordsLag.getOrDefault(topicPartition, this.recordsLagMax);
+    try {
+      return ((Number) metric.get().metricValue()).longValue();
+    } catch (Exception e) {
+      return 0;
+    }
+  }
+
+  long position(final TopicPartition topicPartition) {
+    return this.positions.get(topicPartition) & Long.MAX_VALUE;
+  }
+
+  long initialOffsetForPartition(final TopicPartition topicPartition) {
+    // Offsets start at 0 and there is no position to advance to beyond Long.MAX_VALUE.
+    // The sign bit indicates that an assignment is paused.
+    checkState(this.phaser.register() >= 0);
+    this.positions.put(topicPartition, Long.MIN_VALUE);
+
+    // Synchronize and throw if the consumer was terminated in between.
+    checkState(this.phaser.arriveAndAwaitAdvance() >= 0);
+
+    // Removal will revoke the assignment when the phase advances.
+    final long result = this.positions.remove(topicPartition);
+
+    // Synchronize and ignore the consumer status since the result is already known.
+    this.phaser.arriveAndDeregister();
+
+    // Since Long.MIN_VALUE only has the sign bit set, this will return 0 as a default value if no
+    // position could be determined.
+    return result & Long.MAX_VALUE;
+  }
+
+  @Nullable
+  OffsetAndTimestamp initialOffsetForTime(final TopicPartition topicPartition, final long time) {

Review Comment:
   what is units for time? can Instant be used here and changed to long internally?



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "sjvanrossum (via GitHub)" <gi...@apache.org>.
sjvanrossum commented on code in PR #32986:
URL: https://github.com/apache/beam/pull/32986#discussion_r1890224117


##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ReadFromKafkaDoFn.java:
##########
@@ -267,80 +284,121 @@ private static final class SharedStateHolder {
   private static class KafkaLatestOffsetEstimator
       implements GrowableOffsetRangeTracker.RangeEndEstimator {
 
-    private final Consumer<byte[], byte[]> offsetConsumer;
-    private final TopicPartition topicPartition;
-    private final Supplier<Long> memoizedBacklog;
+    private final KafkaSourceDescriptor sourceDescriptor;
+    private final LoadingCache<Optional<ImmutableSet<String>>, ConcurrentConsumer<byte[], byte[]>>
+        consumerExecutionContextCache;
+    private @MonotonicNonNull ConcurrentConsumer<byte[], byte[]> consumerExecutionContextInstance;

Review Comment:
   The context cache stores values as weak references so it's mainly there to retain a strong reference to a healthy context. The intent is to make a context eligible for eviction from this cache when the last remaining bundle processor referring to this `ReadFromKafkaDoFn` instance has been evicted and eventually collected to minimize unnecessary evictions from the context cache that would result from a time or size based eviction policy.
   
   The use of this field is a mess though so I'll clean that up. πŸ‘ 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #32986:
URL: https://github.com/apache/beam/pull/32986#issuecomment-2729367720

   This pull request has been closed due to lack of activity. If you think that is incorrect, or the pull request requires review, you can revive the PR at any time.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "sjvanrossum (via GitHub)" <gi...@apache.org>.
sjvanrossum commented on code in PR #32986:
URL: https://github.com/apache/beam/pull/32986#discussion_r1889999409


##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {
+  private static final Logger LOG = LoggerFactory.getLogger(ConcurrentConsumer.class);
+
+  private final ConsumerPhaser phaser;
+  private final Consumer<K, V> consumer;
+  private final Duration pollDuration;
+  private final AtomicLongMap<TopicPartition> times;
+  private final AtomicLongMap<TopicPartition> positions;
+  private final Supplier<Metric> recordsLagMax;
+  private final Map<TopicPartition, Supplier<Metric>> partitionRecordsLag;
+  private ConsumerRecords<K, V> pollResult;
+  private Map<TopicPartition, OffsetAndTimestamp> offsetsForTimesResult;
+
+  private final class ConsumerPhaser extends Phaser {
+    @Override
+    protected boolean onAdvance(final int phase, final int registeredParties) {
+      try {
+        final Map<TopicPartition, Long> positionsView = positions.asMap();
+        final Set<TopicPartition> prevAssignment = consumer.assignment();
+        final Set<TopicPartition> nextAssignment = positionsView.keySet();
+
+        if (!times.isEmpty()) {
+          offsetsForTimesResult = consumer.offsetsForTimes(times.asMap());
+          times.clear();
+        }
+
+        if (!prevAssignment.equals(nextAssignment)) {
+          consumer.assign(nextAssignment);
+        }
+
+        positionsView.forEach(
+            (tp, o) -> {
+              if (o == Long.MIN_VALUE) {
+                consumer.pause(Collections.singleton(tp));
+              } else if (!prevAssignment.contains(tp)) {
+                consumer.seek(tp, o);
+              }
+            });
+
+        if (consumer.paused().size() != nextAssignment.size()) {
+          pollResult = consumer.poll(pollDuration.toMillis());
+        }
+
+        nextAssignment.forEach(tp -> positions.put(tp, consumer.position(tp)));
+        return false;
+      } catch (WakeupException e) {
+        if (!this.isTerminated()) {
+          LOG.error("Unexpected wakeup while running", e);
+        }
+      } catch (Exception e) {
+        LOG.error("Exception while reading from Kafka", e);
+      }
+      return true;
+    }
+  }
+
+  ConcurrentConsumer(final Consumer<K, V> consumer, final Duration pollDuration) {
+    this.phaser = new ConsumerPhaser();
+    this.consumer = consumer;
+    this.pollDuration = pollDuration;
+    this.times = AtomicLongMap.create();
+    this.positions = AtomicLongMap.create();
+    this.recordsLagMax =
+        Suppliers.memoize(
+            () ->
+                this.consumer.metrics().values().stream()
+                    .filter(
+                        m ->
+                            "consumer-fetch-manager-metrics".equals(m.metricName().group())
+                                && "records-lag-max".equals(m.metricName().name())
+                                && !m.metricName().tags().containsKey("topic")
+                                && !m.metricName().tags().containsKey("partition"))
+                    .findAny()
+                    .get());
+    this.partitionRecordsLag = new ConcurrentHashMap<>();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  @Override
+  public void close() {
+    this.phaser.forceTermination();
+    try {
+      this.consumer.wakeup();
+      this.consumer.close();
+    } catch (Exception e) {
+      LOG.error("Exception while closing Kafka consumer", e);
+    }
+    this.times.clear();
+    this.positions.clear();
+    this.pollResult = ConsumerRecords.empty();
+    this.offsetsForTimesResult = Collections.emptyMap();
+  }
+
+  boolean isClosed() {
+    return this.phaser.isTerminated();
+  }
+
+  Map<MetricName, ? extends Metric> metrics() {
+    return this.consumer.metrics();
+  }
+
+  long currentLagOrMaxLag(final TopicPartition topicPartition) {
+    final Supplier<Metric> metric =
+        this.partitionRecordsLag.getOrDefault(topicPartition, this.recordsLagMax);
+    try {
+      return ((Number) metric.get().metricValue()).longValue();
+    } catch (Exception e) {
+      return 0;
+    }
+  }
+
+  long position(final TopicPartition topicPartition) {
+    return this.positions.get(topicPartition) & Long.MAX_VALUE;
+  }
+
+  long initialOffsetForPartition(final TopicPartition topicPartition) {
+    // Offsets start at 0 and there is no position to advance to beyond Long.MAX_VALUE.
+    // The sign bit indicates that an assignment is paused.
+    checkState(this.phaser.register() >= 0);
+    this.positions.put(topicPartition, Long.MIN_VALUE);
+
+    // Synchronize and throw if the consumer was terminated in between.
+    checkState(this.phaser.arriveAndAwaitAdvance() >= 0);
+
+    // Removal will revoke the assignment when the phase advances.
+    final long result = this.positions.remove(topicPartition);
+
+    // Synchronize and ignore the consumer status since the result is already known.
+    this.phaser.arriveAndDeregister();
+
+    // Since Long.MIN_VALUE only has the sign bit set, this will return 0 as a default value if no
+    // position could be determined.
+    return result & Long.MAX_VALUE;
+  }
+
+  @Nullable
+  OffsetAndTimestamp initialOffsetForTime(final TopicPartition topicPartition, final long time) {

Review Comment:
   It's in milliseconds, the types requested by the `ConcurrentConsumer` wrapper match the client library where possible: https://kafka.apache.org/38/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html#offsetsForTimes(java.util.Map)



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "sjvanrossum (via GitHub)" <gi...@apache.org>.
sjvanrossum commented on code in PR #32986:
URL: https://github.com/apache/beam/pull/32986#discussion_r1890047785


##########
sdks/java/io/kafka/src/main/java/org/apache/beam/sdk/io/kafka/ConcurrentConsumer.java:
##########
@@ -0,0 +1,231 @@
+/*
+ * 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.beam.sdk.io.kafka;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Phaser;
+import java.util.function.Supplier;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.AtomicLongMap;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
+import org.apache.kafka.common.Metric;
+import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.WakeupException;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class ConcurrentConsumer<K, V> implements AutoCloseable {

Review Comment:
   Agreed, I've been putting off the documentation since I had a few variations of this change running in tandem.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #32986: [KafkaIO] Decouple consumer threads from harness threads
URL: https://github.com/apache/beam/pull/32986


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [KafkaIO] Decouple consumer threads from harness threads [beam]

Posted by "scwhittle (via GitHub)" <gi...@apache.org>.
scwhittle commented on PR #32986:
URL: https://github.com/apache/beam/pull/32986#issuecomment-2579998034

   Hi Steven, I'm back from OOO, let me know when this is ready for another pass. 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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org