You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "m-trieu (via GitHub)" <gi...@apache.org> on 2024/04/30 11:40:59 UTC

[PR] add computation state cache, config loaders, and status pages [beam]

m-trieu opened a new pull request, #31133:
URL: https://github.com/apache/beam/pull/31133

   Add computation state cache and config loaders that load the computation state cache
   move status pages out of StreamingDataflowWorker file
   
   R: @scwhittle 
   ------------------------
   
   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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1594374204


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertFalse(computationState.isPresent());
+  }
+
+  @Test
+  public void testGet_usesUserTransformToStateFamilyNameIfNotEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, userTransformToStateFamilyName, ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_defaultsToStateNameMapWhenUserTransformToStateFamilyNameEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, ImmutableMap.of(), ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(computationStateCache.getGlobalUsernameToStateFamilyNameMap());
+  }
+
+  @Test
+  public void testGet_buildsStateNameMap() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> stateNameMap = ImmutableMap.of("stateName1", "stateName");
+    ComputationConfig computationConfig = ComputationConfig.create(mapTask, null, stateNameMap);
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    assertThat(computationStateCache.getGlobalUsernameToStateFamilyNameMap())
+        .containsExactlyEntriesIn(stateNameMap);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.getIfPresent(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateNotCached() {
+    Optional<ComputationState> computationState =
+        computationStateCache.getIfPresent("computationId");
+    assertFalse(computationState.isPresent());
+    verifyNoInteractions(configFetcher);
+  }
+
+  @Test
+  public void testGetAllComputations() {
+    String computationId1 = "computationId1";
+    String computationId2 = "computationId2";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId1))).thenReturn(Optional.of(computationConfig));
+    when(configFetcher.fetchConfig(eq(computationId2))).thenReturn(Optional.of(computationConfig));
+
+    computationStateCache.get(computationId1);
+    computationStateCache.get(computationId2);
+    Set<String> computationIds = ImmutableSet.of(computationId1, computationId2);
+    computationStateCache
+        .getAllPresentComputations()
+        .forEach(
+            computationState -> {
+              assertThat(computationIds).contains(computationState.getComputationId());
+              assertThat(computationState.getMapTask()).isEqualTo(mapTask);
+              assertThat(computationState.getTransformUserNameToStateFamily())
+                  .isEqualTo(userTransformToStateFamilyName);
+            });
+  }
+
+  @Test
+  public void testTotalCurrentActiveGetWorkBudget() {

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1594544458


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),
+        onPipelineConfig);
+  }
+
+  @After
+  public void cleanUp() {
+    streamingEngineConfigFetcher.stop();
+  }
+
+  @Test
+  public void testStart_requiresInitialConfig() throws IOException, InterruptedException {
+    WorkItem initialConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    CountDownLatch waitForInitialConfig = new CountDownLatch(1);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(initialConfig));
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            0,
+            config -> {
+              try {
+                receivedPipelineConfig.add(config);
+                waitForInitialConfig.await();
+              } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+              }
+            });
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    waitForInitialConfig.countDown();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    initialConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testStart_startsPeriodicConfigRequests() throws IOException, InterruptedException {
+    WorkItem firstConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    WorkItem secondConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(15L));
+    WorkItem thirdConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(100L));
+    CountDownLatch numExpectedRefreshes = new CountDownLatch(3);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(firstConfig))
+        .thenReturn(Optional.of(secondConfig))
+        .thenReturn(Optional.of(thirdConfig));
+
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            Duration.millis(100).getMillis(),
+            config -> {
+              receivedPipelineConfig.add(config);
+              numExpectedRefreshes.countDown();
+            });
+
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    numExpectedRefreshes.await();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    firstConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build(),
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    secondConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build(),
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    thirdConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testGetComputationConfig() throws IOException {
+    streamingEngineConfigFetcher =
+        createConfigLoader(/* waitForInitialConfig= */ false, 0, ignored -> {});
+    String computationId = "computationId";
+    String stageName = "stageName";
+    String systemName = "systemName";
+    StreamingComputationConfig pipelineConfig =
+        new StreamingComputationConfig()
+            .setComputationId(computationId)
+            .setStageName(stageName)
+            .setSystemName(systemName)
+            .setInstructions(ImmutableList.of());
+
+    WorkItem workItem =
+        new WorkItem()
+            .setStreamingConfigTask(
+                new StreamingConfigTask()
+                    .setStreamingComputationConfigs(ImmutableList.of(pipelineConfig)));
+
+    when(mockDataflowServiceClient.getStreamingConfigWorkItem(anyString()))
+        .thenReturn(Optional.of(workItem));
+    Optional<ComputationConfig> actualPipelineConfig =
+        streamingEngineConfigFetcher.fetchConfig(computationId);
+
+    assertTrue(actualPipelineConfig.isPresent());
+    assertThat(actualPipelineConfig.get())
+        .isEqualTo(
+            ComputationConfig.create(
+                StreamingEngineComputationConfigFetcher.createMapTask(pipelineConfig),
+                ImmutableMap.of(),
+                ImmutableMap.of()));
+  }
+
+  @Test
+  public void testGetComputationConfig_noComputationPresent() throws IOException {

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1591858198


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCache.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static java.util.stream.Collectors.toConcurrentMap;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList.toImmutableList;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.PrintWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Function;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.apiary.FixMultiOutputInfosOnParDoInstructions;
+import org.apache.beam.runners.dataflow.worker.status.StatusDataProvider;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.fn.IdGenerator;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheBuilder;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheLoader;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.LoadingCache;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Cache of {@link String} computationId to {@link ComputationState}. */
+@Internal
+@ThreadSafe
+public final class ComputationStateCache implements StatusDataProvider {
+
+  private static final Logger LOG = LoggerFactory.getLogger(ComputationStateCache.class);
+
+  private final LoadingCache<String, ComputationState> computationCache;
+
+  /**
+   * Fix up MapTask representation because MultiOutputInfos are missing from system generated
+   * ParDoInstructions.
+   */
+  private final Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions;
+
+  private ComputationStateCache(
+      LoadingCache<String, ComputationState> computationCache,
+      Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions) {
+    this.computationCache = computationCache;
+    this.fixMultiOutputInfosOnParDoInstructions = fixMultiOutputInfosOnParDoInstructions;
+  }
+
+  public static ComputationStateCache create(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      IdGenerator idGenerator) {
+    Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions =
+        new FixMultiOutputInfosOnParDoInstructions(idGenerator);
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
+    return new ComputationStateCache(
+        CacheBuilder.newBuilder()
+            .build(
+                newComputationStateCacheLoader(
+                    computationConfigFetcher,
+                    workUnitExecutor,
+                    perComputationStateCacheViewFactory,
+                    fixMultiOutputInfosOnParDoInstructions,
+                    stateNameMap)),
+        fixMultiOutputInfosOnParDoInstructions);
+  }
+
+  @VisibleForTesting
+  public static ComputationStateCache forTesting(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      IdGenerator idGenerator,
+      ConcurrentMap<String, String> stateNameMap) {
+    Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions =
+        new FixMultiOutputInfosOnParDoInstructions(idGenerator);
+    return new ComputationStateCache(
+        CacheBuilder.newBuilder()
+            .build(
+                newComputationStateCacheLoader(
+                    computationConfigFetcher,
+                    workUnitExecutor,
+                    perComputationStateCacheViewFactory,
+                    fixMultiOutputInfosOnParDoInstructions,
+                    stateNameMap)),
+        fixMultiOutputInfosOnParDoInstructions);
+  }
+
+  private static CacheLoader<String, ComputationState> newComputationStateCacheLoader(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions,
+      ConcurrentMap<String, String> stateNameMap) {
+    return new CacheLoader<String, ComputationState>() {
+      @Override
+      public ComputationState load(String computationId) {
+        // LoadingCache load(K key) will throw an exception if we return null here,
+        // throw ComputationStateNotFoundException to represent semantics better.
+        ComputationConfig computationConfig =
+            computationConfigFetcher
+                .getConfig(computationId)
+                .orElseThrow(() -> new ComputationStateNotFoundException(computationId));
+        stateNameMap.putAll(computationConfig.stateNameMap());
+        return new ComputationState(
+            computationId,
+            fixMultiOutputInfosOnParDoInstructions.apply(computationConfig.mapTask()),
+            workUnitExecutor,
+            !computationConfig.userTransformToStateFamilyName().isEmpty()
+                ? computationConfig.userTransformToStateFamilyName()
+                : stateNameMap,
+            perComputationStateCacheViewFactory.apply(computationId));
+      }
+    };
+  }
+
+  /**
+   * Returns the {@link ComputationState} associated with the given computationId. May perform IO if
+   * a value is not present, and it is possible that after IO is performed there is no value
+   * correlated with that computationId.
+   */
+  public Optional<ComputationState> get(String computationId) {
+    try {
+      return Optional.ofNullable(computationCache.get(computationId));
+    } catch (ExecutionException | ComputationStateNotFoundException e) {
+      if (e.getCause() instanceof ComputationStateNotFoundException) {
+        LOG.error(
+            "Trying to fetch unknown computation={}, known computations are {}.",
+            computationId,
+            ImmutableSet.copyOf(computationCache.asMap().keySet()));
+      } else {
+        LOG.warn("Error occurred fetching computation for computationId={}", computationId, e);
+      }
+    }
+
+    return Optional.empty();
+  }
+
+  public Optional<ComputationState> getIfPresent(String computationId) {
+    return Optional.ofNullable(computationCache.getIfPresent(computationId));
+  }
+
+  /** Returns a read-only view of all computations. */
+  public ImmutableList<ComputationState> getAllComputations() {

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCache.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static java.util.stream.Collectors.toConcurrentMap;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList.toImmutableList;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.PrintWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Function;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.apiary.FixMultiOutputInfosOnParDoInstructions;
+import org.apache.beam.runners.dataflow.worker.status.StatusDataProvider;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.fn.IdGenerator;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheBuilder;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheLoader;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.LoadingCache;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Cache of {@link String} computationId to {@link ComputationState}. */
+@Internal
+@ThreadSafe
+public final class ComputationStateCache implements StatusDataProvider {
+
+  private static final Logger LOG = LoggerFactory.getLogger(ComputationStateCache.class);
+
+  private final LoadingCache<String, ComputationState> computationCache;
+
+  /**
+   * Fix up MapTask representation because MultiOutputInfos are missing from system generated
+   * ParDoInstructions.
+   */
+  private final Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions;
+
+  private ComputationStateCache(
+      LoadingCache<String, ComputationState> computationCache,
+      Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions) {
+    this.computationCache = computationCache;
+    this.fixMultiOutputInfosOnParDoInstructions = fixMultiOutputInfosOnParDoInstructions;
+  }
+
+  public static ComputationStateCache create(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      IdGenerator idGenerator) {
+    Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions =
+        new FixMultiOutputInfosOnParDoInstructions(idGenerator);
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
+    return new ComputationStateCache(
+        CacheBuilder.newBuilder()
+            .build(
+                newComputationStateCacheLoader(
+                    computationConfigFetcher,
+                    workUnitExecutor,
+                    perComputationStateCacheViewFactory,
+                    fixMultiOutputInfosOnParDoInstructions,
+                    stateNameMap)),
+        fixMultiOutputInfosOnParDoInstructions);
+  }
+
+  @VisibleForTesting
+  public static ComputationStateCache forTesting(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      IdGenerator idGenerator,
+      ConcurrentMap<String, String> stateNameMap) {
+    Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions =
+        new FixMultiOutputInfosOnParDoInstructions(idGenerator);
+    return new ComputationStateCache(

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1591859391


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -718,100 +834,27 @@ int numCommitThreads() {
   public void start() {
     running.set(true);
 
-    if (windmillServiceEnabled) {
-      // Schedule the background getConfig thread. Blocks until windmillServer stub is ready.
-      schedulePeriodicGlobalConfigRequests();
-    }
+    configFetcher.start();
 
     memoryMonitorThread.start();
     dispatchThread.start();
     sampler.start();
 
-    if (options.getPeriodicStatusPageOutputDirectory() != null) {
-      ScheduledExecutorService statusPageTimer = executorSupplier.apply("DumpStatusPages");
-      statusPageTimer.scheduleWithFixedDelay(
-          () -> {
-            Collection<Capturable> pages = statusPages.getDebugCapturePages();
-            if (pages.isEmpty()) {
-              LOG.warn("No captured status pages.");
-            }
-            long timestamp = clock.get().getMillis();
-            for (Capturable page : pages) {
-              PrintWriter writer = null;
-              try {
-                File outputFile =
-                    new File(
-                        options.getPeriodicStatusPageOutputDirectory(),
-                        ("StreamingDataflowWorker"
-                                + options.getWorkerId()
-                                + "_"
-                                + page.pageName()
-                                + timestamp
-                                + ".html")
-                            .replaceAll("/", "_"));
-                writer = new PrintWriter(outputFile, UTF_8.name());
-                page.captureData(writer);
-              } catch (IOException e) {
-                LOG.warn("Error dumping status page.", e);
-              } finally {
-                if (writer != null) {
-                  writer.close();
-                }
-              }
-            }
-          },
-          60,
-          60,
-          TimeUnit.SECONDS);
-      scheduledExecutors.add(statusPageTimer);
-    }
     workCommitter.start();
     workerStatusReporter.start();
     activeWorkRefresher.start();
   }
 
   public void startStatusPages() {

Review Comment:
   added



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1588506484


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceConfigFetcher.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap.toImmutableMap;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse.NameMapEntry;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.HashBasedTable;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Table;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Fetches computation config from Streaming Appliance. */
+@Internal
+@ThreadSafe
+public final class StreamingApplianceConfigFetcher implements ComputationConfig.Fetcher {
+
+  private static final Logger LOG = LoggerFactory.getLogger(StreamingApplianceConfigFetcher.class);
+
+  private final WindmillServerStub windmillServer;
+  private final Consumer<StreamingPipelineConfig> onPipelineConfig;
+  private final ConcurrentHashMap<String, String> systemNameToComputationIdMap;
+  private final Function<MapTask, MapTask> fixMapTaskMultiOutputInfoFn;
+
+  public StreamingApplianceConfigFetcher(
+      WindmillServerStub windmillServer,
+      Consumer<StreamingPipelineConfig> onPipelineConfig,
+      Function<MapTask, MapTask> fixMapTaskMultiOutputInfoFn) {
+    this.windmillServer = windmillServer;
+    this.onPipelineConfig = onPipelineConfig;

Review Comment:
   done and moved
   
   changed it to be a member instead of static since we need the static global id generator from StreamingDataflowWorker. 



-- 
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] add computation state cache, config loaders, and status pages [beam]

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

   Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment `assign set of reviewers`


-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1591858355


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -1114,9 +1092,12 @@ private void process(
                 streamingCounters.pendingDeltaCounters(),
                 computationId,
                 readerCache,
-                !computationState.getTransformUserNameToStateFamily().isEmpty()
-                    ? computationState.getTransformUserNameToStateFamily()
-                    : stateNameMap,
+                //                !computationState.getTransformUserNameToStateFamily().isEmpty()

Review Comment:
   removed



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585964743


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                true,
+                options.getGlobalConfigRefreshPeriod().getMillis(),
+                dataflowServiceClient,
+                executorSupplier,
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS,
+                config ->
+                    onPipelineConfig(
+                        config,
+                        stateNameMap,
+                        windmillServer::setWindmillServiceEndpoints,
+                        maxWorkItemCommitBytes))
+            : new StreamingApplianceConfigFetcher(
+                windmillServer,
+                config -> consumeUserStepToStateFamilyName(config, stateNameMap),
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS);
+    ComputationStateCache computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, windmillStateCache::forComputation);
+    if (windmillServer instanceof GrpcWindmillServer) {

Review Comment:
   done
   i changed the way this was created, still not super clean but much better than before.
   
   I wonder if we can make `GrpcWindmillServer` not implement `WindmillServerStub`.  Not sure it currently makes sense to group together Appliance and Engine client implementations and leads to wonky situtations like above.



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1593188468


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {

Review Comment:
   moved



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1594450657


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),

Review Comment:
   this needs to be available for the executor supplier in `StreamingDataflowWorkerTest`



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1598853279


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -3203,12 +3145,21 @@ public void testExceptionInvalidatesCache() throws Exception {
                 WindowingStrategy.globalDefault()),
             makeSinkInstruction(StringUtf8Coder.of(), 1, GlobalWindow.Coder.INSTANCE));
 
+    defaultWorkerParams()

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

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


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(

Review Comment:
   forTesting isn't a good name if this is in the regular path



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingPipelineConfig.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.auto.value.AutoValue;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+
+/** Pipeline configuration for jobs running w/ Streaming Engine. */
+@AutoValue
+@Internal
+public abstract class StreamingPipelineConfig {
+
+  private static final long DEFAULT_MAX_WORK_ITEM_COMMIT_BYTES = 180 << 20;
+
+  public static StreamingPipelineConfig.Builder builder() {
+    return new AutoValue_StreamingPipelineConfig.Builder()
+        .setMaxWorkItemCommitBytes(DEFAULT_MAX_WORK_ITEM_COMMIT_BYTES)
+        .setComputationConfig(null)
+        .setUserStepToStateFamilyNameMap(new HashMap<>())
+        .setWindmillServiceEndpoints(ImmutableSet.of());
+  }
+
+  public static StreamingPipelineConfig forAppliance(

Review Comment:
   can we just get rid of this and have the appliance config use builder() and set these?



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                true,

Review Comment:
   rm param if hard-coded



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -373,10 +350,39 @@ private StreamingDataflowWorker(
             clock,
             options.getActiveWorkRefreshPeriodMillis(),
             stuckCommitDurationMillis,
-            () -> Collections.unmodifiableCollection(computationMap.values()),
+            computationStateCache::getAllComputations,
             sampler,
             metricTrackingWindmillServer::refreshActiveWork,
             executorSupplier.apply("RefreshWork"));
+
+    WorkerStatusPages workerStatusPages =
+        WorkerStatusPages.create(DEFAULT_STATUS_PORT, memoryMonitor, () -> true);

Review Comment:
   can this last parameter be made optional via overload? or at least add a comment here



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                true,
+                options.getGlobalConfigRefreshPeriod().getMillis(),
+                dataflowServiceClient,
+                executorSupplier,
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS,
+                config ->
+                    onPipelineConfig(
+                        config,
+                        stateNameMap,
+                        windmillServer::setWindmillServiceEndpoints,
+                        maxWorkItemCommitBytes))
+            : new StreamingApplianceConfigFetcher(
+                windmillServer,
+                config -> consumeUserStepToStateFamilyName(config, stateNameMap),
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS);
+    ComputationStateCache computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, windmillStateCache::forComputation);
+    if (windmillServer instanceof GrpcWindmillServer) {

Review Comment:
   this cast and lazy initialization is kind of gross
   
   one idea could be to remove the windmillserver from the appliance config fetcher, it could just construct it's own channel and sync stub directly.
   and then have a separate start method on the configfetcher taking the function to consume responses.  Then you can make sure to call that after everything is initialized.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                true,
+                options.getGlobalConfigRefreshPeriod().getMillis(),
+                dataflowServiceClient,
+                executorSupplier,
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS,
+                config ->
+                    onPipelineConfig(
+                        config,
+                        stateNameMap,
+                        windmillServer::setWindmillServiceEndpoints,
+                        maxWorkItemCommitBytes))
+            : new StreamingApplianceConfigFetcher(
+                windmillServer,
+                config -> consumeUserStepToStateFamilyName(config, stateNameMap),

Review Comment:
   seems like the consuming the config method could be the same for both SE and appliance, where unset fields are just ignored



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -373,10 +350,39 @@ private StreamingDataflowWorker(
             clock,
             options.getActiveWorkRefreshPeriodMillis(),
             stuckCommitDurationMillis,
-            () -> Collections.unmodifiableCollection(computationMap.values()),
+            computationStateCache::getAllComputations,
             sampler,
             metricTrackingWindmillServer::refreshActiveWork,
             executorSupplier.apply("RefreshWork"));
+
+    WorkerStatusPages workerStatusPages =
+        WorkerStatusPages.create(DEFAULT_STATUS_PORT, memoryMonitor, () -> true);
+    this.statusPages =
+        windmillServiceEnabled
+            ? StreamingWorkerStatusPages.forStreamingEngine(

Review Comment:
   would a builder pattern be better than the separate forStreamingEngine and forAppliance factory methods?
   
   There seem to be a lot of common things.



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585820350


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -373,10 +350,39 @@ private StreamingDataflowWorker(
             clock,
             options.getActiveWorkRefreshPeriodMillis(),
             stuckCommitDurationMillis,
-            () -> Collections.unmodifiableCollection(computationMap.values()),
+            computationStateCache::getAllComputations,
             sampler,
             metricTrackingWindmillServer::refreshActiveWork,
             executorSupplier.apply("RefreshWork"));
+
+    WorkerStatusPages workerStatusPages =
+        WorkerStatusPages.create(DEFAULT_STATUS_PORT, memoryMonitor, () -> true);

Review Comment:
   done. overloaded 



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1588478357


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -471,10 +548,38 @@ static StreamingDataflowWorker forTesting(
       Function<String, ScheduledExecutorService> executorSupplier,
       int localRetryTimeoutMs) {
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
     BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
     WindmillStateCache stateCache = WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
-    computationMap.putAll(
-        createComputationMapForTesting(mapTasks, workExecutor, stateCache::forComputation));
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                /* hasReceivedGlobalConfig= */ true,
+                options.getGlobalConfigRefreshPeriod().getMillis(),
+                workUnitClient,
+                executorSupplier,
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS,
+                config ->
+                    onPipelineConfig(
+                        config,
+                        stateNameMap,
+                        windmillServer::setWindmillServiceEndpoints,
+                        maxWorkItemCommitBytes))
+            : new StreamingApplianceConfigFetcher(
+                windmillServer,
+                config ->
+                    onPipelineConfig(config, stateNameMap, ignored -> {}, maxWorkItemCommitBytes),
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS);
+    ComputationStateCache computationStateCache =
+        ComputationStateCache.create(configFetcher, workExecutor, stateCache::forComputation);
+    computationStateCache.loadCacheForTesting(
+        mapTasks.stream()
+            .map(FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS)
+            .collect(Collectors.toList()),
+        workExecutor,
+        stateCache::forComputation);
+    computationStateCacheRef.set(computationStateCache);

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585824700


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                true,
+                options.getGlobalConfigRefreshPeriod().getMillis(),
+                dataflowServiceClient,
+                executorSupplier,
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS,
+                config ->
+                    onPipelineConfig(
+                        config,
+                        stateNameMap,
+                        windmillServer::setWindmillServiceEndpoints,
+                        maxWorkItemCommitBytes))
+            : new StreamingApplianceConfigFetcher(
+                windmillServer,
+                config -> consumeUserStepToStateFamilyName(config, stateNameMap),
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS);
+    ComputationStateCache computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, windmillStateCache::forComputation);
+    if (windmillServer instanceof GrpcWindmillServer) {

Review Comment:
   sgtm 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] add computation state cache, config loaders, and status pages [beam]

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


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -718,100 +834,27 @@ int numCommitThreads() {
   public void start() {
     running.set(true);
 
-    if (windmillServiceEnabled) {
-      // Schedule the background getConfig thread. Blocks until windmillServer stub is ready.
-      schedulePeriodicGlobalConfigRequests();
-    }
+    configFetcher.start();
 
     memoryMonitorThread.start();
     dispatchThread.start();
     sampler.start();
 
-    if (options.getPeriodicStatusPageOutputDirectory() != null) {
-      ScheduledExecutorService statusPageTimer = executorSupplier.apply("DumpStatusPages");
-      statusPageTimer.scheduleWithFixedDelay(
-          () -> {
-            Collection<Capturable> pages = statusPages.getDebugCapturePages();
-            if (pages.isEmpty()) {
-              LOG.warn("No captured status pages.");
-            }
-            long timestamp = clock.get().getMillis();
-            for (Capturable page : pages) {
-              PrintWriter writer = null;
-              try {
-                File outputFile =
-                    new File(
-                        options.getPeriodicStatusPageOutputDirectory(),
-                        ("StreamingDataflowWorker"
-                                + options.getWorkerId()
-                                + "_"
-                                + page.pageName()
-                                + timestamp
-                                + ".html")
-                            .replaceAll("/", "_"));
-                writer = new PrintWriter(outputFile, UTF_8.name());
-                page.captureData(writer);
-              } catch (IOException e) {
-                LOG.warn("Error dumping status page.", e);
-              } finally {
-                if (writer != null) {
-                  writer.close();
-                }
-              }
-            }
-          },
-          60,
-          60,
-          TimeUnit.SECONDS);
-      scheduledExecutors.add(statusPageTimer);
-    }
     workCommitter.start();
     workerStatusReporter.start();
     activeWorkRefresher.start();
   }
 
   public void startStatusPages() {

Review Comment:
   can this be inlined into start() and removed?



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -471,10 +548,38 @@ static StreamingDataflowWorker forTesting(
       Function<String, ScheduledExecutorService> executorSupplier,
       int localRetryTimeoutMs) {
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
     BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
     WindmillStateCache stateCache = WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
-    computationMap.putAll(
-        createComputationMapForTesting(mapTasks, workExecutor, stateCache::forComputation));
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                /* hasReceivedGlobalConfig= */ true,
+                options.getGlobalConfigRefreshPeriod().getMillis(),
+                workUnitClient,
+                executorSupplier,
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS,
+                config ->
+                    onPipelineConfig(
+                        config,
+                        stateNameMap,
+                        windmillServer::setWindmillServiceEndpoints,
+                        maxWorkItemCommitBytes))
+            : new StreamingApplianceConfigFetcher(
+                windmillServer,
+                config ->
+                    onPipelineConfig(config, stateNameMap, ignored -> {}, maxWorkItemCommitBytes),
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS);
+    ComputationStateCache computationStateCache =
+        ComputationStateCache.create(configFetcher, workExecutor, stateCache::forComputation);
+    computationStateCache.loadCacheForTesting(
+        mapTasks.stream()
+            .map(FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS)
+            .collect(Collectors.toList()),
+        workExecutor,
+        stateCache::forComputation);
+    computationStateCacheRef.set(computationStateCache);

Review Comment:
   how about a VisibleForTesting annotated method to access the ComputationStateCache instead?  Seems convoluted to pass in atomic ref to assign to.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -931,15 +941,19 @@ void streamingDispatchLoop() {
                   Instant inputDataWatermark,
                   Instant synchronizedProcessingTime,
                   Windmill.WorkItem workItem,
-                  Collection<LatencyAttribution> getWorkStreamLatencies) -> {
-                memoryMonitor.waitForResources("GetWork");
-                scheduleWorkItem(
-                    getComputationState(computation),
-                    inputDataWatermark,
-                    synchronizedProcessingTime,
-                    workItem,
-                    getWorkStreamLatencies);
-              });
+                  Collection<LatencyAttribution> getWorkStreamLatencies) ->
+                  computationStateCache
+                      .get(computation)
+                      .ifPresent(

Review Comment:
   what happened before on missing computation? In either case it seems like we should throw exception or log error as otherwise we're just dropping the work item silently which will be confusing.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceConfigFetcher.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap.toImmutableMap;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse.NameMapEntry;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.HashBasedTable;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Table;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Fetches computation config from Streaming Appliance. */
+@Internal
+@ThreadSafe
+public final class StreamingApplianceConfigFetcher implements ComputationConfig.Fetcher {
+
+  private static final Logger LOG = LoggerFactory.getLogger(StreamingApplianceConfigFetcher.class);
+
+  private final WindmillServerStub windmillServer;
+  private final Consumer<StreamingPipelineConfig> onPipelineConfig;
+  private final ConcurrentHashMap<String, String> systemNameToComputationIdMap;
+  private final Function<MapTask, MapTask> fixMapTaskMultiOutputInfoFn;
+
+  public StreamingApplianceConfigFetcher(
+      WindmillServerStub windmillServer,
+      Consumer<StreamingPipelineConfig> onPipelineConfig,
+      Function<MapTask, MapTask> fixMapTaskMultiOutputInfoFn) {
+    this.windmillServer = windmillServer;
+    this.onPipelineConfig = onPipelineConfig;

Review Comment:
   seems odd to have this listener hidden in the fetcher
   
   Maybe instead the listener should be on whatever is driving the fetching. I think that woudl be the cache.
   
   Additionally I think that the FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS could move into the cache where fetches are being performed.  As is it is injected into all teh fetchers and applied to the testing generated configs.  That would let you just do it once and possibly coudl remove from StreamingDataflowWorker to the cache



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceConfigFetcher.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap.toImmutableMap;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse.NameMapEntry;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.HashBasedTable;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Table;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Fetches computation config from Streaming Appliance. */
+@Internal
+@ThreadSafe
+public final class StreamingApplianceConfigFetcher implements ComputationConfig.Fetcher {

Review Comment:
   should this be StreamingApplianceComputationConfigFetcher? ditto with SE



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1591858956


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);
+          break;
+        }
+        LOG.info("Haven't received initial global configuration, will retry in 5 seconds");
+        sleepUninterruptibly(5, TimeUnit.SECONDS);
+      }
+    }
+    LOG.info("Initial global configuration received, harness is now ready");
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getComputationConfigInternal(
+      String computationId) {
+    Optional<StreamingEnginePipelineConfig> streamingConfig = getConfigInternal(computationId);
+    streamingConfig.ifPresent(onStreamingConfig);
+    return streamingConfig;
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getGlobalConfig() {
+    return getConfigInternal(null);
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getConfigInternal(@Nullable String computation) {

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/ComputationConfig.java:
##########
@@ -0,0 +1,59 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.auto.value.AutoValue;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+
+@Internal
+@AutoValue
+public abstract class ComputationConfig {
+
+  public static ComputationConfig create(
+      MapTask mapTask,
+      @Nullable Map<String, String> userTransformToStateFamilyName,
+      Map<String, String> stateNameMap) {
+    return new AutoValue_ComputationConfig(
+        mapTask,
+        Optional.ofNullable(userTransformToStateFamilyName)
+            .map(ImmutableMap::copyOf)
+            .orElseGet(ImmutableMap::of),
+        ImmutableMap.copyOf(stateNameMap));
+  }
+
+  public abstract MapTask mapTask();
+
+  public abstract ImmutableMap<String, String> userTransformToStateFamilyName();
+
+  public abstract ImmutableMap<String, String> stateNameMap();
+
+  /** Interface to fetch configurations for a specific computation. */
+  @FunctionalInterface
+  public interface Fetcher {
+    default void start() {}
+
+    default void stop() {}
+
+    Optional<ComputationConfig> getConfig(String computationId);

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1598852745


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -800,110 +805,39 @@ private DataflowWorkerHarnessOptions createTestingPipelineOptions(String... args
   }
 
   private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      Supplier<Instant> clock,
-      Function<String, ScheduledExecutorService> executorSupplier,
-      int localRetryTimeoutMs) {
-    return makeWorker(
-        ImmutableMap.of(),
-        instructions,
-        options,
-        publishCounters,
-        clock,
-        executorSupplier,
-        localRetryTimeoutMs);
-  }
-
-  private StreamingDataflowWorker makeWorker(
-      Map<String, String> stateNameMappings,
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      Supplier<Instant> clock,
-      Function<String, ScheduledExecutorService> executorSupplier,
-      int localRetryTimeoutMs) {
-    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
-    stateNameMap.putAll(stateNameMappings);
-    stateNameMap.putAll(ImmutableMap.of(DEFAULT_PARDO_USER_NAME, DEFAULT_PARDO_STATE_FAMILY));
+      StreamingDataflowWorkerTestParams streamingDataflowWorkerTestParams) {
     StreamingDataflowWorker worker =
         StreamingDataflowWorker.forTesting(
-            stateNameMap,
+            streamingDataflowWorkerTestParams.stateNameMappings(),
             server,
-            Collections.singletonList(defaultMapTask(instructions)),
+            Collections.singletonList(
+                defaultMapTask(streamingDataflowWorkerTestParams.instructions())),
             IntrinsicMapTaskExecutorFactory.defaultFactory(),
             mockWorkUnitClient,
-            options,
-            publishCounters,
+            streamingDataflowWorkerTestParams.options(),
+            streamingDataflowWorkerTestParams.publishCounters(),
             hotKeyLogger,
-            clock,
-            executorSupplier,
-            localRetryTimeoutMs);
+            streamingDataflowWorkerTestParams.clock(),
+            streamingDataflowWorkerTestParams.executorSupplier(),
+            streamingDataflowWorkerTestParams.localRetryTimeoutMs(),
+            streamingDataflowWorkerTestParams.maxWorkItemCommitBytes());
     this.computationStateCache = worker.getComputationStateCache();
     return worker;
   }
 
-  private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      Supplier<Instant> clock,
-      Function<String, ScheduledExecutorService> executorSupplier) {
-    return makeWorker(instructions, options, publishCounters, clock, executorSupplier, -1);
-  }
-
-  private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters) {
-    return makeWorker(
-        instructions,
-        options,
-        publishCounters,
-        Instant::now,
-        (threadName) -> Executors.newSingleThreadScheduledExecutor(),
-        -1);
-  }
-
-  private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      Map<String, String> stateNameMap) {
-    return makeWorker(
-        stateNameMap,
-        instructions,
-        options,
-        publishCounters,
-        Instant::now,
-        (threadName) -> Executors.newSingleThreadScheduledExecutor(),
-        -1);
-  }
-
-  private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      int localRetryTimeoutMs) {
-    return makeWorker(
-        instructions,
-        options,
-        publishCounters,
-        Instant::now,
-        (threadName) -> Executors.newSingleThreadScheduledExecutor(),
-        localRetryTimeoutMs);
-  }
-
   @Test
   public void testBasicHarness() throws Exception {
     List<ParallelInstruction> instructions =
         Arrays.asList(
             makeSourceInstruction(StringUtf8Coder.of()),
             makeSinkInstruction(StringUtf8Coder.of(), 0));
-
     StreamingDataflowWorker worker =
-        makeWorker(instructions, createTestingPipelineOptions(), true /* publishCounters */);
+        makeWorker(
+            defaultWorkerParams()
+                .setInstructions(instructions)
+                .publishCounters()
+                .setOptions(createTestingPipelineOptions())

Review Comment:
   removed



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1593187217


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCache.java:
##########
@@ -54,6 +56,7 @@ public final class ComputationStateCache implements StatusDataProvider {
 
   private static final Logger LOG = LoggerFactory.getLogger(ComputationStateCache.class);
 
+  private final ConcurrentMap<String, String> globalUsernameToStateFamilyNameMap;

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1594447162


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static java.util.stream.Collectors.toMap;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingApplianceComputationConfigFetcherTest {
+  private final WindmillServerStub mockWindmillServer = mock(WindmillServerStub.class);
+
+  @Test
+  public void testGetComputationConfig() throws IOException {
+    List<Windmill.GetConfigResponse.NameMapEntry> nameMapEntries =
+        ImmutableList.of(
+            Windmill.GetConfigResponse.NameMapEntry.newBuilder()
+                .setUserName("userName1")
+                .setSystemName("systemName1")
+                .build(),
+            Windmill.GetConfigResponse.NameMapEntry.newBuilder()
+                .setUserName("userName2")
+                .setSystemName("userName2")
+                .build());
+    String serializedMapTask =
+        Transport.getJsonFactory()
+            .toString(
+                new MapTask()
+                    .setSystemName("systemName")
+                    .setStageName("stageName")
+                    .setInstructions(ImmutableList.of()));
+    Windmill.GetConfigResponse getConfigResponse =
+        Windmill.GetConfigResponse.newBuilder()
+            .addAllNameMap(nameMapEntries)
+            .addComputationConfigMap(
+                Windmill.GetConfigResponse.ComputationConfigMapEntry.newBuilder()
+                    .setComputationId("systemName")
+                    .setComputationConfig(
+                        Windmill.ComputationConfig.newBuilder()
+                            .addTransformUserNameToStateFamily(
+                                Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                                    .newBuilder()
+                                    .setStateFamily("stateFamilyName")
+                                    .setTransformUserName("transformUserName")
+                                    .build())
+                            .build())
+                    .build())
+            .addCloudWorks(serializedMapTask)
+            .build();
+    ComputationConfig expectedConfig =
+        ComputationConfig.create(
+            Transport.getJsonFactory().fromString(serializedMapTask, MapTask.class),
+            getConfigResponse.getComputationConfigMapList().stream()
+                .map(Windmill.GetConfigResponse.ComputationConfigMapEntry::getComputationConfig)
+                .flatMap(
+                    computationConfig ->
+                        computationConfig.getTransformUserNameToStateFamilyList().stream())
+                .collect(
+                    toMap(
+                        Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                            ::getTransformUserName,
+                        Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                            ::getStateFamily)),
+            nameMapEntries.stream()
+                .collect(
+                    toMap(
+                        Windmill.GetConfigResponse.NameMapEntry::getUserName,
+                        Windmill.GetConfigResponse.NameMapEntry::getSystemName)));
+    StreamingApplianceComputationConfigFetcher configLoader =
+        createStreamingApplianceConfigLoader();
+    when(mockWindmillServer.getConfig(any())).thenReturn(getConfigResponse);
+    Optional<ComputationConfig> config = configLoader.fetchConfig("someComputationId");
+    assertTrue(config.isPresent());
+    assertThat(config.get()).isEqualTo(expectedConfig);
+  }
+
+  @Test
+  public void testGetComputationConfig_whenNoConfigReturned() {
+    StreamingApplianceComputationConfigFetcher configLoader =
+        createStreamingApplianceConfigLoader();
+    when(mockWindmillServer.getConfig(any())).thenReturn(null);
+    Optional<ComputationConfig> configResponse = configLoader.fetchConfig("someComputationId");
+    assertFalse(configResponse.isPresent());
+  }
+

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static java.util.stream.Collectors.toMap;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingApplianceComputationConfigFetcherTest {
+  private final WindmillServerStub mockWindmillServer = mock(WindmillServerStub.class);
+
+  @Test
+  public void testGetComputationConfig() throws IOException {
+    List<Windmill.GetConfigResponse.NameMapEntry> nameMapEntries =
+        ImmutableList.of(
+            Windmill.GetConfigResponse.NameMapEntry.newBuilder()
+                .setUserName("userName1")
+                .setSystemName("systemName1")
+                .build(),
+            Windmill.GetConfigResponse.NameMapEntry.newBuilder()
+                .setUserName("userName2")
+                .setSystemName("userName2")
+                .build());
+    String serializedMapTask =
+        Transport.getJsonFactory()
+            .toString(
+                new MapTask()
+                    .setSystemName("systemName")
+                    .setStageName("stageName")
+                    .setInstructions(ImmutableList.of()));
+    Windmill.GetConfigResponse getConfigResponse =
+        Windmill.GetConfigResponse.newBuilder()
+            .addAllNameMap(nameMapEntries)
+            .addComputationConfigMap(
+                Windmill.GetConfigResponse.ComputationConfigMapEntry.newBuilder()
+                    .setComputationId("systemName")
+                    .setComputationConfig(
+                        Windmill.ComputationConfig.newBuilder()
+                            .addTransformUserNameToStateFamily(
+                                Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                                    .newBuilder()
+                                    .setStateFamily("stateFamilyName")
+                                    .setTransformUserName("transformUserName")
+                                    .build())
+                            .build())
+                    .build())
+            .addCloudWorks(serializedMapTask)
+            .build();
+    ComputationConfig expectedConfig =
+        ComputationConfig.create(
+            Transport.getJsonFactory().fromString(serializedMapTask, MapTask.class),
+            getConfigResponse.getComputationConfigMapList().stream()
+                .map(Windmill.GetConfigResponse.ComputationConfigMapEntry::getComputationConfig)
+                .flatMap(
+                    computationConfig ->
+                        computationConfig.getTransformUserNameToStateFamilyList().stream())
+                .collect(
+                    toMap(
+                        Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                            ::getTransformUserName,
+                        Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                            ::getStateFamily)),
+            nameMapEntries.stream()
+                .collect(
+                    toMap(
+                        Windmill.GetConfigResponse.NameMapEntry::getUserName,
+                        Windmill.GetConfigResponse.NameMapEntry::getSystemName)));
+    StreamingApplianceComputationConfigFetcher configLoader =
+        createStreamingApplianceConfigLoader();
+    when(mockWindmillServer.getConfig(any())).thenReturn(getConfigResponse);
+    Optional<ComputationConfig> config = configLoader.fetchConfig("someComputationId");
+    assertTrue(config.isPresent());
+    assertThat(config.get()).isEqualTo(expectedConfig);
+  }
+
+  @Test
+  public void testGetComputationConfig_whenNoConfigReturned() {
+    StreamingApplianceComputationConfigFetcher configLoader =
+        createStreamingApplianceConfigLoader();
+    when(mockWindmillServer.getConfig(any())).thenReturn(null);
+    Optional<ComputationConfig> configResponse = configLoader.fetchConfig("someComputationId");
+    assertFalse(configResponse.isPresent());
+  }
+

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585833306


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                true,
+                options.getGlobalConfigRefreshPeriod().getMillis(),
+                dataflowServiceClient,
+                executorSupplier,
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS,
+                config ->
+                    onPipelineConfig(
+                        config,
+                        stateNameMap,
+                        windmillServer::setWindmillServiceEndpoints,
+                        maxWorkItemCommitBytes))
+            : new StreamingApplianceConfigFetcher(
+                windmillServer,
+                config -> consumeUserStepToStateFamilyName(config, stateNameMap),
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS);
+    ComputationStateCache computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, windmillStateCache::forComputation);
+    if (windmillServer instanceof GrpcWindmillServer) {

Review Comment:
   i think the issue would be if it is using the `WindmillServerBase` implementation of WindmillServerStub, which uses JNI
   
   i will try to find a way around this



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

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


Re: [PR] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1599094241


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -3368,7 +3318,13 @@ public void testActiveWorkRefresh() throws Exception {
 
     DataflowWorkerHarnessOptions options = createTestingPipelineOptions();
     options.setActiveWorkRefreshPeriodMillis(100);
-    StreamingDataflowWorker worker = makeWorker(instructions, options, true /* publishCounters */);
+    StreamingDataflowWorker worker =
+        makeWorker(
+            defaultWorkerParams()

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

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


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -1114,9 +1092,12 @@ private void process(
                 streamingCounters.pendingDeltaCounters(),
                 computationId,
                 readerCache,
-                !computationState.getTransformUserNameToStateFamily().isEmpty()
-                    ? computationState.getTransformUserNameToStateFamily()
-                    : stateNameMap,
+                //                !computationState.getTransformUserNameToStateFamily().isEmpty()

Review Comment:
   rm comments



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCache.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static java.util.stream.Collectors.toConcurrentMap;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList.toImmutableList;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.PrintWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Function;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.apiary.FixMultiOutputInfosOnParDoInstructions;
+import org.apache.beam.runners.dataflow.worker.status.StatusDataProvider;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.fn.IdGenerator;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheBuilder;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheLoader;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.LoadingCache;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Cache of {@link String} computationId to {@link ComputationState}. */
+@Internal
+@ThreadSafe
+public final class ComputationStateCache implements StatusDataProvider {
+
+  private static final Logger LOG = LoggerFactory.getLogger(ComputationStateCache.class);
+
+  private final LoadingCache<String, ComputationState> computationCache;
+
+  /**
+   * Fix up MapTask representation because MultiOutputInfos are missing from system generated
+   * ParDoInstructions.
+   */
+  private final Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions;
+
+  private ComputationStateCache(
+      LoadingCache<String, ComputationState> computationCache,
+      Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions) {
+    this.computationCache = computationCache;
+    this.fixMultiOutputInfosOnParDoInstructions = fixMultiOutputInfosOnParDoInstructions;
+  }
+
+  public static ComputationStateCache create(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      IdGenerator idGenerator) {
+    Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions =
+        new FixMultiOutputInfosOnParDoInstructions(idGenerator);
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
+    return new ComputationStateCache(
+        CacheBuilder.newBuilder()
+            .build(
+                newComputationStateCacheLoader(
+                    computationConfigFetcher,
+                    workUnitExecutor,
+                    perComputationStateCacheViewFactory,
+                    fixMultiOutputInfosOnParDoInstructions,
+                    stateNameMap)),
+        fixMultiOutputInfosOnParDoInstructions);
+  }
+
+  @VisibleForTesting
+  public static ComputationStateCache forTesting(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      IdGenerator idGenerator,
+      ConcurrentMap<String, String> stateNameMap) {
+    Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions =
+        new FixMultiOutputInfosOnParDoInstructions(idGenerator);
+    return new ComputationStateCache(

Review Comment:
   Could this instead just use create and then poke in to add initial state name map values?
   via
   cache = create(...);
   cache.stateNameMap.addAll(stateNameMap);
   
   It's a fair bit of setup to duplicate and it coudl drift meaning we're not testing the main code-path.
   
   Or you could further reduce duplication of the parameters the create/forTesting methods and just expose a visiblefortesting method for the statenamemap and the current caller of this method could use that directly.
   



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceComputationConfigFetcher.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap.toImmutableMap;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse.NameMapEntry;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.HashBasedTable;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Table;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Fetches computation config from Streaming Appliance. */
+@Internal
+@ThreadSafe
+public final class StreamingApplianceComputationConfigFetcher implements ComputationConfig.Fetcher {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingApplianceComputationConfigFetcher.class);
+
+  private final WindmillServerStub windmillServer;
+  private final ConcurrentHashMap<String, String> systemNameToComputationIdMap;
+
+  public StreamingApplianceComputationConfigFetcher(WindmillServerStub windmillServer) {
+    this.windmillServer = windmillServer;
+    this.systemNameToComputationIdMap = new ConcurrentHashMap<>();
+  }
+
+  private static Table<String, String, String> transformUserNameToStateFamilyByComputationId(
+      Windmill.GetConfigResponse response) {
+    // a row in the table is <ComputationId, TransformUserName, StateFamilyName>
+    Table<String, String, String> computationIdTransformUserNameStateFamilyNameTable =
+        HashBasedTable.create();
+    for (Windmill.GetConfigResponse.ComputationConfigMapEntry computationConfig :
+        response.getComputationConfigMapList()) {
+      for (Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry entry :
+          computationConfig.getComputationConfig().getTransformUserNameToStateFamilyList()) {
+        computationIdTransformUserNameStateFamilyNameTable.put(
+            computationConfig.getComputationId(),
+            entry.getTransformUserName(),
+            entry.getStateFamily());
+      }
+    }
+
+    return computationIdTransformUserNameStateFamilyNameTable;
+  }
+
+  /** Deserialize {@link MapTask} and populate MultiOutputInfos in MapTask. */
+  private Optional<MapTask> deserializeAndFixMapTask(String serializedMapTask) {
+    try {
+      return Optional.of(Transport.getJsonFactory().fromString(serializedMapTask, MapTask.class));
+    } catch (IOException e) {
+      LOG.warn("Parsing MapTask failed: {}", serializedMapTask, e);
+    }
+    return Optional.empty();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+
+    GetConfigResponse response =
+        windmillServer.getConfig(

Review Comment:
   instead of taking in WindmillServer can you take in a functional interface matching this method?
   
   That will help show that the full class isn't used and could simplify testing. It could help in the future break up windmillServer if we get rid of the jni class keeping it all tied together ATM.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceComputationConfigFetcher.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap.toImmutableMap;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse.NameMapEntry;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.HashBasedTable;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Table;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Fetches computation config from Streaming Appliance. */
+@Internal
+@ThreadSafe
+public final class StreamingApplianceComputationConfigFetcher implements ComputationConfig.Fetcher {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingApplianceComputationConfigFetcher.class);
+
+  private final WindmillServerStub windmillServer;
+  private final ConcurrentHashMap<String, String> systemNameToComputationIdMap;
+
+  public StreamingApplianceComputationConfigFetcher(WindmillServerStub windmillServer) {
+    this.windmillServer = windmillServer;
+    this.systemNameToComputationIdMap = new ConcurrentHashMap<>();
+  }
+
+  private static Table<String, String, String> transformUserNameToStateFamilyByComputationId(
+      Windmill.GetConfigResponse response) {
+    // a row in the table is <ComputationId, TransformUserName, StateFamilyName>

Review Comment:
   move to method comment?



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(

Review Comment:
   visiblefortesting



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);
+          break;
+        }
+        LOG.info("Haven't received initial global configuration, will retry in 5 seconds");
+        sleepUninterruptibly(5, TimeUnit.SECONDS);
+      }
+    }
+    LOG.info("Initial global configuration received, harness is now ready");
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getComputationConfigInternal(
+      String computationId) {
+    Optional<StreamingEnginePipelineConfig> streamingConfig = getConfigInternal(computationId);
+    streamingConfig.ifPresent(onStreamingConfig);
+    return streamingConfig;
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getGlobalConfig() {
+    return getConfigInternal(null);
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getConfigInternal(@Nullable String computation) {

Review Comment:
   ditto for the methods in this class, prefer fetch to get



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";

Review Comment:
   add thread_name to variable? maybe shorten then as well



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {

Review Comment:
   nit: seemsl ike you could move !hasReceivedGlobalConfig to the while condition instead
   
   removes some nesting and if we did have multiple callers calling fetchInitialPipelineGlobalConfig it could speed things up.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/ComputationConfig.java:
##########
@@ -0,0 +1,59 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.auto.value.AutoValue;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+
+@Internal
+@AutoValue
+public abstract class ComputationConfig {
+
+  public static ComputationConfig create(
+      MapTask mapTask,
+      @Nullable Map<String, String> userTransformToStateFamilyName,
+      Map<String, String> stateNameMap) {
+    return new AutoValue_ComputationConfig(
+        mapTask,
+        Optional.ofNullable(userTransformToStateFamilyName)
+            .map(ImmutableMap::copyOf)
+            .orElseGet(ImmutableMap::of),
+        ImmutableMap.copyOf(stateNameMap));
+  }
+
+  public abstract MapTask mapTask();
+
+  public abstract ImmutableMap<String, String> userTransformToStateFamilyName();
+
+  public abstract ImmutableMap<String, String> stateNameMap();
+
+  /** Interface to fetch configurations for a specific computation. */
+  @FunctionalInterface
+  public interface Fetcher {
+    default void start() {}
+
+    default void stop() {}
+
+    Optional<ComputationConfig> getConfig(String computationId);

Review Comment:
   let's call this fetchConfig, it makes it clearer that it is likely an rpc (and matches class name)



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEnginePipelineConfig.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.auto.value.AutoValue;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+
+@AutoValue
+@Internal
+public abstract class StreamingEnginePipelineConfig {
+
+  private static final long DEFAULT_MAX_WORK_ITEM_COMMIT_BYTES = 180 << 20;
+
+  public static StreamingEnginePipelineConfig.Builder builder() {
+    return new AutoValue_StreamingEnginePipelineConfig.Builder()
+        .setMaxWorkItemCommitBytes(DEFAULT_MAX_WORK_ITEM_COMMIT_BYTES)
+        .setComputationConfig(null)
+        .setUserStepToStateFamilyNameMap(new HashMap<>())
+        .setWindmillServiceEndpoints(ImmutableSet.of());
+  }
+
+  public abstract long maxWorkItemCommitBytes();
+
+  public abstract Map<String, String> userStepToStateFamilyNameMap();
+
+  public abstract Optional<StreamingComputationConfig> computationConfig();

Review Comment:
   see other comment, I think this class should just be for the global config, not related to a computation.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);
+          break;
+        }
+        LOG.info("Haven't received initial global configuration, will retry in 5 seconds");
+        sleepUninterruptibly(5, TimeUnit.SECONDS);
+      }
+    }
+    LOG.info("Initial global configuration received, harness is now ready");
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getComputationConfigInternal(
+      String computationId) {
+    Optional<StreamingEnginePipelineConfig> streamingConfig = getConfigInternal(computationId);
+    streamingConfig.ifPresent(onStreamingConfig);

Review Comment:
   can we remove this listening from the computation config fetching?  It seems like it should just be the global config from the background thread that runs onStreamingConfig.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);
+          break;
+        }
+        LOG.info("Haven't received initial global configuration, will retry in 5 seconds");
+        sleepUninterruptibly(5, TimeUnit.SECONDS);
+      }
+    }
+    LOG.info("Initial global configuration received, harness is now ready");
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getComputationConfigInternal(

Review Comment:
   I think this should just return the computationconfig not full StreamingEnginePipelineConfig.  I think that StreamingEnginePipelineConfig can have the computation config removed from it, as we don't care about listening to computations as they are fetched.
   
   That will then make it clearer that we only want the listener to trigger on the periodic background fetching, not the computation fetching driven by the cache.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);
+          break;
+        }
+        LOG.info("Haven't received initial global configuration, will retry in 5 seconds");
+        sleepUninterruptibly(5, TimeUnit.SECONDS);
+      }
+    }
+    LOG.info("Initial global configuration received, harness is now ready");
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getComputationConfigInternal(
+      String computationId) {
+    Optional<StreamingEnginePipelineConfig> streamingConfig = getConfigInternal(computationId);
+    streamingConfig.ifPresent(onStreamingConfig);
+    return streamingConfig;
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getGlobalConfig() {
+    return getConfigInternal(null);
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getConfigInternal(@Nullable String computation) {

Review Comment:
   probably need to change this to some template if we're returnign different types for global or per-computation config



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -718,100 +834,27 @@ int numCommitThreads() {
   public void start() {
     running.set(true);
 
-    if (windmillServiceEnabled) {
-      // Schedule the background getConfig thread. Blocks until windmillServer stub is ready.
-      schedulePeriodicGlobalConfigRequests();
-    }
+    configFetcher.start();
 
     memoryMonitorThread.start();
     dispatchThread.start();
     sampler.start();
 
-    if (options.getPeriodicStatusPageOutputDirectory() != null) {
-      ScheduledExecutorService statusPageTimer = executorSupplier.apply("DumpStatusPages");
-      statusPageTimer.scheduleWithFixedDelay(
-          () -> {
-            Collection<Capturable> pages = statusPages.getDebugCapturePages();
-            if (pages.isEmpty()) {
-              LOG.warn("No captured status pages.");
-            }
-            long timestamp = clock.get().getMillis();
-            for (Capturable page : pages) {
-              PrintWriter writer = null;
-              try {
-                File outputFile =
-                    new File(
-                        options.getPeriodicStatusPageOutputDirectory(),
-                        ("StreamingDataflowWorker"
-                                + options.getWorkerId()
-                                + "_"
-                                + page.pageName()
-                                + timestamp
-                                + ".html")
-                            .replaceAll("/", "_"));
-                writer = new PrintWriter(outputFile, UTF_8.name());
-                page.captureData(writer);
-              } catch (IOException e) {
-                LOG.warn("Error dumping status page.", e);
-              } finally {
-                if (writer != null) {
-                  writer.close();
-                }
-              }
-            }
-          },
-          60,
-          60,
-          TimeUnit.SECONDS);
-      scheduledExecutors.add(statusPageTimer);
-    }
     workCommitter.start();
     workerStatusReporter.start();
     activeWorkRefresher.start();
   }
 
   public void startStatusPages() {

Review Comment:
   Add a comment that this may be omitted for lighterweight testing?
   



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);

Review Comment:
   just set it true, no need for the compare



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {

Review Comment:
   could be static



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCache.java:
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static java.util.stream.Collectors.toConcurrentMap;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList.toImmutableList;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.PrintWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Function;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.apiary.FixMultiOutputInfosOnParDoInstructions;
+import org.apache.beam.runners.dataflow.worker.status.StatusDataProvider;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.fn.IdGenerator;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheBuilder;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.CacheLoader;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.cache.LoadingCache;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Cache of {@link String} computationId to {@link ComputationState}. */
+@Internal
+@ThreadSafe
+public final class ComputationStateCache implements StatusDataProvider {
+
+  private static final Logger LOG = LoggerFactory.getLogger(ComputationStateCache.class);
+
+  private final LoadingCache<String, ComputationState> computationCache;
+
+  /**
+   * Fix up MapTask representation because MultiOutputInfos are missing from system generated
+   * ParDoInstructions.
+   */
+  private final Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions;
+
+  private ComputationStateCache(
+      LoadingCache<String, ComputationState> computationCache,
+      Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions) {
+    this.computationCache = computationCache;
+    this.fixMultiOutputInfosOnParDoInstructions = fixMultiOutputInfosOnParDoInstructions;
+  }
+
+  public static ComputationStateCache create(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      IdGenerator idGenerator) {
+    Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions =
+        new FixMultiOutputInfosOnParDoInstructions(idGenerator);
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
+    return new ComputationStateCache(
+        CacheBuilder.newBuilder()
+            .build(
+                newComputationStateCacheLoader(
+                    computationConfigFetcher,
+                    workUnitExecutor,
+                    perComputationStateCacheViewFactory,
+                    fixMultiOutputInfosOnParDoInstructions,
+                    stateNameMap)),
+        fixMultiOutputInfosOnParDoInstructions);
+  }
+
+  @VisibleForTesting
+  public static ComputationStateCache forTesting(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      IdGenerator idGenerator,
+      ConcurrentMap<String, String> stateNameMap) {
+    Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions =
+        new FixMultiOutputInfosOnParDoInstructions(idGenerator);
+    return new ComputationStateCache(
+        CacheBuilder.newBuilder()
+            .build(
+                newComputationStateCacheLoader(
+                    computationConfigFetcher,
+                    workUnitExecutor,
+                    perComputationStateCacheViewFactory,
+                    fixMultiOutputInfosOnParDoInstructions,
+                    stateNameMap)),
+        fixMultiOutputInfosOnParDoInstructions);
+  }
+
+  private static CacheLoader<String, ComputationState> newComputationStateCacheLoader(
+      ComputationConfig.Fetcher computationConfigFetcher,
+      BoundedQueueExecutor workUnitExecutor,
+      Function<String, WindmillStateCache.ForComputation> perComputationStateCacheViewFactory,
+      Function<MapTask, MapTask> fixMultiOutputInfosOnParDoInstructions,
+      ConcurrentMap<String, String> stateNameMap) {
+    return new CacheLoader<String, ComputationState>() {
+      @Override
+      public ComputationState load(String computationId) {
+        // LoadingCache load(K key) will throw an exception if we return null here,
+        // throw ComputationStateNotFoundException to represent semantics better.
+        ComputationConfig computationConfig =
+            computationConfigFetcher
+                .getConfig(computationId)
+                .orElseThrow(() -> new ComputationStateNotFoundException(computationId));
+        stateNameMap.putAll(computationConfig.stateNameMap());
+        return new ComputationState(
+            computationId,
+            fixMultiOutputInfosOnParDoInstructions.apply(computationConfig.mapTask()),
+            workUnitExecutor,
+            !computationConfig.userTransformToStateFamilyName().isEmpty()
+                ? computationConfig.userTransformToStateFamilyName()
+                : stateNameMap,
+            perComputationStateCacheViewFactory.apply(computationId));
+      }
+    };
+  }
+
+  /**
+   * Returns the {@link ComputationState} associated with the given computationId. May perform IO if
+   * a value is not present, and it is possible that after IO is performed there is no value
+   * correlated with that computationId.
+   */
+  public Optional<ComputationState> get(String computationId) {
+    try {
+      return Optional.ofNullable(computationCache.get(computationId));
+    } catch (ExecutionException | ComputationStateNotFoundException e) {
+      if (e.getCause() instanceof ComputationStateNotFoundException) {
+        LOG.error(
+            "Trying to fetch unknown computation={}, known computations are {}.",
+            computationId,
+            ImmutableSet.copyOf(computationCache.asMap().keySet()));
+      } else {
+        LOG.warn("Error occurred fetching computation for computationId={}", computationId, e);
+      }
+    }
+
+    return Optional.empty();
+  }
+
+  public Optional<ComputationState> getIfPresent(String computationId) {
+    return Optional.ofNullable(computationCache.getIfPresent(computationId));
+  }
+
+  /** Returns a read-only view of all computations. */
+  public ImmutableList<ComputationState> getAllComputations() {

Review Comment:
   should this be getAllPresentComputations?  



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1588528633


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceConfigFetcher.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap.toImmutableMap;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse.NameMapEntry;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.HashBasedTable;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Table;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Fetches computation config from Streaming Appliance. */
+@Internal
+@ThreadSafe
+public final class StreamingApplianceConfigFetcher implements ComputationConfig.Fetcher {
+
+  private static final Logger LOG = LoggerFactory.getLogger(StreamingApplianceConfigFetcher.class);
+
+  private final WindmillServerStub windmillServer;
+  private final Consumer<StreamingPipelineConfig> onPipelineConfig;
+  private final ConcurrentHashMap<String, String> systemNameToComputationIdMap;
+  private final Function<MapTask, MapTask> fixMapTaskMultiOutputInfoFn;
+
+  public StreamingApplianceConfigFetcher(
+      WindmillServerStub windmillServer,
+      Consumer<StreamingPipelineConfig> onPipelineConfig,
+      Function<MapTask, MapTask> fixMapTaskMultiOutputInfoFn) {
+    this.windmillServer = windmillServer;
+    this.onPipelineConfig = onPipelineConfig;

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceConfigFetcher.java:
##########
@@ -0,0 +1,142 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap.toImmutableMap;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse.NameMapEntry;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.HashBasedTable;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Table;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Fetches computation config from Streaming Appliance. */
+@Internal
+@ThreadSafe
+public final class StreamingApplianceConfigFetcher implements ComputationConfig.Fetcher {

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585823786


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                true,
+                options.getGlobalConfigRefreshPeriod().getMillis(),
+                dataflowServiceClient,
+                executorSupplier,
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS,
+                config ->
+                    onPipelineConfig(
+                        config,
+                        stateNameMap,
+                        windmillServer::setWindmillServiceEndpoints,
+                        maxWorkItemCommitBytes))
+            : new StreamingApplianceConfigFetcher(
+                windmillServer,
+                config -> consumeUserStepToStateFamilyName(config, stateNameMap),

Review Comment:
   removed



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1591857977


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);
+          break;
+        }
+        LOG.info("Haven't received initial global configuration, will retry in 5 seconds");
+        sleepUninterruptibly(5, TimeUnit.SECONDS);
+      }
+    }
+    LOG.info("Initial global configuration received, harness is now ready");
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getComputationConfigInternal(
+      String computationId) {
+    Optional<StreamingEnginePipelineConfig> streamingConfig = getConfigInternal(computationId);
+    streamingConfig.ifPresent(onStreamingConfig);

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/ComputationConfig.java:
##########
@@ -0,0 +1,59 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.auto.value.AutoValue;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+
+@Internal
+@AutoValue
+public abstract class ComputationConfig {
+
+  public static ComputationConfig create(
+      MapTask mapTask,
+      @Nullable Map<String, String> userTransformToStateFamilyName,
+      Map<String, String> stateNameMap) {
+    return new AutoValue_ComputationConfig(
+        mapTask,
+        Optional.ofNullable(userTransformToStateFamilyName)
+            .map(ImmutableMap::copyOf)
+            .orElseGet(ImmutableMap::of),
+        ImmutableMap.copyOf(stateNameMap));
+  }
+
+  public abstract MapTask mapTask();
+
+  public abstract ImmutableMap<String, String> userTransformToStateFamilyName();
+
+  public abstract ImmutableMap<String, String> stateNameMap();
+
+  /** Interface to fetch configurations for a specific computation. */
+  @FunctionalInterface
+  public interface Fetcher {
+    default void start() {}
+
+    default void stop() {}
+
+    Optional<ComputationConfig> getConfig(String computationId);

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceComputationConfigFetcher.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap.toImmutableMap;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse.NameMapEntry;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.HashBasedTable;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Table;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Fetches computation config from Streaming Appliance. */
+@Internal
+@ThreadSafe
+public final class StreamingApplianceComputationConfigFetcher implements ComputationConfig.Fetcher {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingApplianceComputationConfigFetcher.class);
+
+  private final WindmillServerStub windmillServer;
+  private final ConcurrentHashMap<String, String> systemNameToComputationIdMap;
+
+  public StreamingApplianceComputationConfigFetcher(WindmillServerStub windmillServer) {
+    this.windmillServer = windmillServer;
+    this.systemNameToComputationIdMap = new ConcurrentHashMap<>();
+  }
+
+  private static Table<String, String, String> transformUserNameToStateFamilyByComputationId(
+      Windmill.GetConfigResponse response) {
+    // a row in the table is <ComputationId, TransformUserName, StateFamilyName>
+    Table<String, String, String> computationIdTransformUserNameStateFamilyNameTable =
+        HashBasedTable.create();
+    for (Windmill.GetConfigResponse.ComputationConfigMapEntry computationConfig :
+        response.getComputationConfigMapList()) {
+      for (Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry entry :
+          computationConfig.getComputationConfig().getTransformUserNameToStateFamilyList()) {
+        computationIdTransformUserNameStateFamilyNameTable.put(
+            computationConfig.getComputationId(),
+            entry.getTransformUserName(),
+            entry.getStateFamily());
+      }
+    }
+
+    return computationIdTransformUserNameStateFamilyNameTable;
+  }
+
+  /** Deserialize {@link MapTask} and populate MultiOutputInfos in MapTask. */
+  private Optional<MapTask> deserializeAndFixMapTask(String serializedMapTask) {
+    try {
+      return Optional.of(Transport.getJsonFactory().fromString(serializedMapTask, MapTask.class));
+    } catch (IOException e) {
+      LOG.warn("Parsing MapTask failed: {}", serializedMapTask, e);
+    }
+    return Optional.empty();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+
+    GetConfigResponse response =
+        windmillServer.getConfig(

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceComputationConfigFetcher.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap.toImmutableMap;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse.NameMapEntry;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.HashBasedTable;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Table;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Fetches computation config from Streaming Appliance. */
+@Internal
+@ThreadSafe
+public final class StreamingApplianceComputationConfigFetcher implements ComputationConfig.Fetcher {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingApplianceComputationConfigFetcher.class);
+
+  private final WindmillServerStub windmillServer;
+  private final ConcurrentHashMap<String, String> systemNameToComputationIdMap;
+
+  public StreamingApplianceComputationConfigFetcher(WindmillServerStub windmillServer) {
+    this.windmillServer = windmillServer;
+    this.systemNameToComputationIdMap = new ConcurrentHashMap<>();
+  }
+
+  private static Table<String, String, String> transformUserNameToStateFamilyByComputationId(
+      Windmill.GetConfigResponse response) {
+    // a row in the table is <ComputationId, TransformUserName, StateFamilyName>

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1588487721


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -718,100 +834,27 @@ int numCommitThreads() {
   public void start() {
     running.set(true);
 
-    if (windmillServiceEnabled) {
-      // Schedule the background getConfig thread. Blocks until windmillServer stub is ready.
-      schedulePeriodicGlobalConfigRequests();
-    }
+    configFetcher.start();
 
     memoryMonitorThread.start();
     dispatchThread.start();
     sampler.start();
 
-    if (options.getPeriodicStatusPageOutputDirectory() != null) {
-      ScheduledExecutorService statusPageTimer = executorSupplier.apply("DumpStatusPages");
-      statusPageTimer.scheduleWithFixedDelay(
-          () -> {
-            Collection<Capturable> pages = statusPages.getDebugCapturePages();
-            if (pages.isEmpty()) {
-              LOG.warn("No captured status pages.");
-            }
-            long timestamp = clock.get().getMillis();
-            for (Capturable page : pages) {
-              PrintWriter writer = null;
-              try {
-                File outputFile =
-                    new File(
-                        options.getPeriodicStatusPageOutputDirectory(),
-                        ("StreamingDataflowWorker"
-                                + options.getWorkerId()
-                                + "_"
-                                + page.pageName()
-                                + timestamp
-                                + ".html")
-                            .replaceAll("/", "_"));
-                writer = new PrintWriter(outputFile, UTF_8.name());
-                page.captureData(writer);
-              } catch (IOException e) {
-                LOG.warn("Error dumping status page.", e);
-              } finally {
-                if (writer != null) {
-                  writer.close();
-                }
-              }
-            }
-          },
-          60,
-          60,
-          TimeUnit.SECONDS);
-      scheduledExecutors.add(statusPageTimer);
-    }
     workCommitter.start();
     workerStatusReporter.start();
     activeWorkRefresher.start();
   }
 
   public void startStatusPages() {

Review Comment:
   today we don't start them for tests (same across batch and streaming harnesses)



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1593187770


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -102,49 +112,112 @@ public static StreamingEngineComputationConfigFetcher forTesting(
         hasReceivedGlobalConfig,
         globalConfigRefreshPeriodMillis,
         dataflowServiceClient,
-        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        executorSupplier.apply(CONFIG_REFRESHER_THREAD_NAME),
         onStreamingConfig);
   }
 
-  private static BackOff defaultConfigBackoff() {
-    return FluentBackoff.DEFAULT
-        .withInitialBackoff(Duration.millis(100))
-        .withMaxBackoff(Duration.standardMinutes(1))
-        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
-        .backoff();
-  }
-
-  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+  @VisibleForTesting
+  static MapTask createMapTask(StreamingComputationConfig computationConfig) {
     return new MapTask()
         .setSystemName(computationConfig.getSystemName())
         .setStageName(computationConfig.getStageName())
         .setInstructions(computationConfig.getInstructions());
   }
 
+  private static Optional<StreamingConfigTask> fetchConfigWithRetry(
+      ThrowingFetchWorkItemFn fetchWorkItemFn) {
+    BackOff backoff = BACKOFF_FACTORY.backoff();
+    while (true) {
+      try {
+        return fetchWorkItemFn
+            .fetchWorkItem()
+            .map(
+                workItem -> {
+                  StreamingConfigTask config = workItem.getStreamingConfigTask();
+                  Preconditions.checkState(
+                      config != null,
+                      "Received invalid WorkItem without StreamingConfigTask. WorkItem={}",
+                      workItem);
+                  return config;
+                });
+      } catch (IllegalArgumentException | IOException e) {
+        LOG.warn("Error fetching config: ", e);
+        try {
+          if (!BackOffUtils.next(Sleeper.DEFAULT, backoff)) {
+            return Optional.empty();
+          }
+        } catch (IOException ioe) {
+          LOG.warn("Error backing off, will not retry: ", ioe);
+          return Optional.empty();
+        } catch (InterruptedException ie) {
+          Thread.currentThread().interrupt();
+          return Optional.empty();
+        }
+      }
+    }
+  }
+
+  private static Optional<StreamingEnginePipelineConfig> createPipelineConfig(

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1599125929


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -218,32 +241,46 @@ public void testGetAllComputations() {
   @Test
   public void testTotalCurrentActiveGetWorkBudget() {
     String computationId = "computationId";
+    String computationId2 = "computationId2";
     MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
     Map<String, String> userTransformToStateFamilyName =
         ImmutableMap.of("userTransformName", "stateFamilyName");
     ComputationConfig computationConfig =
         ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
     when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    when(configFetcher.fetchConfig(eq(computationId2))).thenReturn(Optional.of(computationConfig));
+    Work work1 = createWork(1, 1);
+    Work work2 = createWork(2, 2);
+    Work work3 = createWork(3, 3);
+
+    // Activate 3 Work(s) for computationId
     Optional<ComputationState> maybeComputationState = computationStateCache.get(computationId);
     assertTrue(maybeComputationState.isPresent());
-
     ComputationState computationState = maybeComputationState.get();
     ShardedKey shardedKey = ShardedKey.create(ByteString.EMPTY, 1);
-    Work work1 = createWork(1, 1);
-    Work work2 = createWork(2, 2);
-    Work work3 = createWork(3, 3);
     computationState.activateWork(shardedKey, work1);
     computationState.activateWork(shardedKey, work2);
     computationState.activateWork(shardedKey, work3);
 
+    // Activate 3 Work(s) for computationId2
+    Optional<ComputationState> maybeComputationState2 = computationStateCache.get(computationId);

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1593188055


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1599120343


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -3391,7 +3347,13 @@ public void testActiveWorkFailure() throws Exception {
 
     DataflowWorkerHarnessOptions options = createTestingPipelineOptions();
     options.setActiveWorkRefreshPeriodMillis(100);
-    StreamingDataflowWorker worker = makeWorker(instructions, options, true /* publishCounters */);
+    StreamingDataflowWorker worker =
+        makeWorker(
+            defaultWorkerParams()

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1594449401


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1594105601


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertFalse(computationState.isPresent());
+  }
+
+  @Test
+  public void testGet_usesUserTransformToStateFamilyNameIfNotEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, userTransformToStateFamilyName, ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_defaultsToStateNameMapWhenUserTransformToStateFamilyNameEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, ImmutableMap.of(), ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(computationStateCache.getGlobalUsernameToStateFamilyNameMap());
+  }
+
+  @Test
+  public void testGet_buildsStateNameMap() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> stateNameMap = ImmutableMap.of("stateName1", "stateName");
+    ComputationConfig computationConfig = ComputationConfig.create(mapTask, null, stateNameMap);
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    assertThat(computationStateCache.getGlobalUsernameToStateFamilyNameMap())
+        .containsExactlyEntriesIn(stateNameMap);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.getIfPresent(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateNotCached() {
+    Optional<ComputationState> computationState =
+        computationStateCache.getIfPresent("computationId");
+    assertFalse(computationState.isPresent());
+    verifyNoInteractions(configFetcher);
+  }
+
+  @Test
+  public void testGetAllComputations() {
+    String computationId1 = "computationId1";
+    String computationId2 = "computationId2";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId1))).thenReturn(Optional.of(computationConfig));
+    when(configFetcher.fetchConfig(eq(computationId2))).thenReturn(Optional.of(computationConfig));
+
+    computationStateCache.get(computationId1);
+    computationStateCache.get(computationId2);
+    Set<String> computationIds = ImmutableSet.of(computationId1, computationId2);
+    computationStateCache
+        .getAllPresentComputations()
+        .forEach(
+            computationState -> {
+              assertThat(computationIds).contains(computationState.getComputationId());

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1594099112


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1591858823


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1591857816


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);
+          break;
+        }
+        LOG.info("Haven't received initial global configuration, will retry in 5 seconds");
+        sleepUninterruptibly(5, TimeUnit.SECONDS);
+      }
+    }
+    LOG.info("Initial global configuration received, harness is now ready");
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getComputationConfigInternal(
+      String computationId) {
+    Optional<StreamingEnginePipelineConfig> streamingConfig = getConfigInternal(computationId);
+    streamingConfig.ifPresent(onStreamingConfig);
+    return streamingConfig;
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getGlobalConfig() {
+    return getConfigInternal(null);
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getConfigInternal(@Nullable String computation) {

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEnginePipelineConfig.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.auto.value.AutoValue;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+
+@AutoValue
+@Internal
+public abstract class StreamingEnginePipelineConfig {
+
+  private static final long DEFAULT_MAX_WORK_ITEM_COMMIT_BYTES = 180 << 20;
+
+  public static StreamingEnginePipelineConfig.Builder builder() {
+    return new AutoValue_StreamingEnginePipelineConfig.Builder()
+        .setMaxWorkItemCommitBytes(DEFAULT_MAX_WORK_ITEM_COMMIT_BYTES)
+        .setComputationConfig(null)
+        .setUserStepToStateFamilyNameMap(new HashMap<>())
+        .setWindmillServiceEndpoints(ImmutableSet.of());
+  }
+
+  public abstract long maxWorkItemCommitBytes();
+
+  public abstract Map<String, String> userStepToStateFamilyNameMap();
+
+  public abstract Optional<StreamingComputationConfig> computationConfig();

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+    return new MapTask()
+        .setSystemName(computationConfig.getSystemName())
+        .setStageName(computationConfig.getStageName())
+        .setInstructions(computationConfig.getInstructions());
+  }
+
+  @Override
+  public void start() {
+    fetchInitialPipelineGlobalConfig();
+    schedulePeriodicGlobalConfigRequests();
+  }
+
+  @Override
+  public Optional<ComputationConfig> getConfig(String computationId) {
+    Preconditions.checkArgument(
+        !computationId.isEmpty(),
+        "computationId is empty. Cannot fetch computation config without a computationId.");
+    return getComputationConfigInternal(computationId)
+        .flatMap(
+            config -> {
+              Map<String, String> stateNameMap = config.userStepToStateFamilyNameMap();
+              return config
+                  .computationConfig()
+                  .map(
+                      computationConfig ->
+                          ComputationConfig.create(
+                              createMapTask(computationConfig),
+                              computationConfig.getTransformUserNameToStateFamily(),
+                              stateNameMap));
+            });
+  }
+
+  @Override
+  public void stop() {
+    // We have already shutdown or start has not been called.
+    if (globalConfigRefresher.isShutdown() || !hasReceivedGlobalConfig.get()) {
+      return;
+    }
+
+    globalConfigRefresher.shutdown();
+    boolean isTerminated = false;
+    try {
+      isTerminated = globalConfigRefresher.awaitTermination(10, TimeUnit.SECONDS);
+    } catch (InterruptedException e) {
+      LOG.warn("Error occurred shutting down: {}", globalConfigRefresher);
+    }
+    if (!isTerminated) {
+      globalConfigRefresher.shutdownNow();
+    }
+  }
+
+  /**
+   * Initially b Schedules a background thread that periodically sends getConfig requests to
+   * Dataflow Service to obtain the windmill service endpoint.
+   */
+  @SuppressWarnings("FutureReturnValueIgnored")
+  private void schedulePeriodicGlobalConfigRequests() {
+    globalConfigRefresher.scheduleWithFixedDelay(
+        () -> getGlobalConfig().ifPresent(onStreamingConfig),
+        0,
+        globalConfigRefreshPeriodMillis,
+        TimeUnit.MILLISECONDS);
+  }
+
+  /**
+   * Blocks until we have received the initial global config from Dataflow or an exception is
+   * thrown.
+   */
+  private synchronized void fetchInitialPipelineGlobalConfig() {
+    if (!hasReceivedGlobalConfig.get()) {
+      // Get the initial global configuration. This will initialize the windmillServer stub.
+      while (true) {
+        LOG.info("Sending request to get initial global configuration for this worker.");
+        Optional<StreamingEnginePipelineConfig> globalConfig = getGlobalConfig();
+        if (globalConfig.isPresent()) {
+          onStreamingConfig.accept(globalConfig.get());
+          hasReceivedGlobalConfig.compareAndSet(false, true);
+          break;
+        }
+        LOG.info("Haven't received initial global configuration, will retry in 5 seconds");
+        sleepUninterruptibly(5, TimeUnit.SECONDS);
+      }
+    }
+    LOG.info("Initial global configuration received, harness is now ready");
+  }
+
+  private Optional<StreamingEnginePipelineConfig> getComputationConfigInternal(

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

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


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -797,9 +806,30 @@ private StreamingDataflowWorker makeWorker(
       Supplier<Instant> clock,
       Function<String, ScheduledExecutorService> executorSupplier,
       int localRetryTimeoutMs) {
+    return makeWorker(
+        ImmutableMap.of(),
+        instructions,
+        options,
+        publishCounters,
+        clock,
+        executorSupplier,
+        localRetryTimeoutMs);
+  }
+
+  private StreamingDataflowWorker makeWorker(

Review Comment:
   there are 6 makeWorkers, it seems some autovalue builder in this test would make it more readable and less duplication of the default for various params.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -102,49 +112,112 @@ public static StreamingEngineComputationConfigFetcher forTesting(
         hasReceivedGlobalConfig,
         globalConfigRefreshPeriodMillis,
         dataflowServiceClient,
-        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        executorSupplier.apply(CONFIG_REFRESHER_THREAD_NAME),
         onStreamingConfig);
   }
 
-  private static BackOff defaultConfigBackoff() {
-    return FluentBackoff.DEFAULT
-        .withInitialBackoff(Duration.millis(100))
-        .withMaxBackoff(Duration.standardMinutes(1))
-        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
-        .backoff();
-  }
-
-  private MapTask createMapTask(StreamingComputationConfig computationConfig) {
+  @VisibleForTesting
+  static MapTask createMapTask(StreamingComputationConfig computationConfig) {
     return new MapTask()
         .setSystemName(computationConfig.getSystemName())
         .setStageName(computationConfig.getStageName())
         .setInstructions(computationConfig.getInstructions());
   }
 
+  private static Optional<StreamingConfigTask> fetchConfigWithRetry(
+      ThrowingFetchWorkItemFn fetchWorkItemFn) {
+    BackOff backoff = BACKOFF_FACTORY.backoff();
+    while (true) {
+      try {
+        return fetchWorkItemFn
+            .fetchWorkItem()
+            .map(
+                workItem -> {
+                  StreamingConfigTask config = workItem.getStreamingConfigTask();
+                  Preconditions.checkState(
+                      config != null,
+                      "Received invalid WorkItem without StreamingConfigTask. WorkItem={}",
+                      workItem);
+                  return config;
+                });
+      } catch (IllegalArgumentException | IOException e) {
+        LOG.warn("Error fetching config: ", e);
+        try {
+          if (!BackOffUtils.next(Sleeper.DEFAULT, backoff)) {
+            return Optional.empty();
+          }
+        } catch (IOException ioe) {
+          LOG.warn("Error backing off, will not retry: ", ioe);
+          return Optional.empty();
+        } catch (InterruptedException ie) {
+          Thread.currentThread().interrupt();
+          return Optional.empty();
+        }
+      }
+    }
+  }
+
+  private static Optional<StreamingEnginePipelineConfig> createPipelineConfig(

Review Comment:
   don't think this needs to return optional



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+

Review Comment:
   nit: rm blank line



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static java.util.stream.Collectors.toMap;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingApplianceComputationConfigFetcherTest {
+  private final WindmillServerStub mockWindmillServer = mock(WindmillServerStub.class);
+
+  @Test
+  public void testGetComputationConfig() throws IOException {
+    List<Windmill.GetConfigResponse.NameMapEntry> nameMapEntries =
+        ImmutableList.of(
+            Windmill.GetConfigResponse.NameMapEntry.newBuilder()
+                .setUserName("userName1")
+                .setSystemName("systemName1")
+                .build(),
+            Windmill.GetConfigResponse.NameMapEntry.newBuilder()
+                .setUserName("userName2")
+                .setSystemName("userName2")
+                .build());
+    String serializedMapTask =
+        Transport.getJsonFactory()
+            .toString(
+                new MapTask()
+                    .setSystemName("systemName")
+                    .setStageName("stageName")
+                    .setInstructions(ImmutableList.of()));
+    Windmill.GetConfigResponse getConfigResponse =
+        Windmill.GetConfigResponse.newBuilder()
+            .addAllNameMap(nameMapEntries)
+            .addComputationConfigMap(
+                Windmill.GetConfigResponse.ComputationConfigMapEntry.newBuilder()
+                    .setComputationId("systemName")
+                    .setComputationConfig(
+                        Windmill.ComputationConfig.newBuilder()
+                            .addTransformUserNameToStateFamily(
+                                Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                                    .newBuilder()
+                                    .setStateFamily("stateFamilyName")
+                                    .setTransformUserName("transformUserName")
+                                    .build())
+                            .build())
+                    .build())
+            .addCloudWorks(serializedMapTask)
+            .build();
+    ComputationConfig expectedConfig =
+        ComputationConfig.create(
+            Transport.getJsonFactory().fromString(serializedMapTask, MapTask.class),
+            getConfigResponse.getComputationConfigMapList().stream()
+                .map(Windmill.GetConfigResponse.ComputationConfigMapEntry::getComputationConfig)
+                .flatMap(
+                    computationConfig ->
+                        computationConfig.getTransformUserNameToStateFamilyList().stream())
+                .collect(
+                    toMap(
+                        Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                            ::getTransformUserName,
+                        Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                            ::getStateFamily)),
+            nameMapEntries.stream()
+                .collect(
+                    toMap(
+                        Windmill.GetConfigResponse.NameMapEntry::getUserName,
+                        Windmill.GetConfigResponse.NameMapEntry::getSystemName)));
+    StreamingApplianceComputationConfigFetcher configLoader =
+        createStreamingApplianceConfigLoader();
+    when(mockWindmillServer.getConfig(any())).thenReturn(getConfigResponse);
+    Optional<ComputationConfig> config = configLoader.fetchConfig("someComputationId");
+    assertTrue(config.isPresent());
+    assertThat(config.get()).isEqualTo(expectedConfig);
+  }
+
+  @Test
+  public void testGetComputationConfig_whenNoConfigReturned() {
+    StreamingApplianceComputationConfigFetcher configLoader =
+        createStreamingApplianceConfigLoader();
+    when(mockWindmillServer.getConfig(any())).thenReturn(null);
+    Optional<ComputationConfig> configResponse = configLoader.fetchConfig("someComputationId");
+    assertFalse(configResponse.isPresent());
+  }
+

Review Comment:
   add test that empty computation throws exception



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),
+        onPipelineConfig);
+  }
+
+  @After
+  public void cleanUp() {
+    streamingEngineConfigFetcher.stop();
+  }
+
+  @Test
+  public void testStart_requiresInitialConfig() throws IOException, InterruptedException {
+    WorkItem initialConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    CountDownLatch waitForInitialConfig = new CountDownLatch(1);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(initialConfig));
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            0,
+            config -> {
+              try {
+                receivedPipelineConfig.add(config);
+                waitForInitialConfig.await();
+              } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+              }
+            });
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    waitForInitialConfig.countDown();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    initialConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testStart_startsPeriodicConfigRequests() throws IOException, InterruptedException {
+    WorkItem firstConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    WorkItem secondConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(15L));
+    WorkItem thirdConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(100L));
+    CountDownLatch numExpectedRefreshes = new CountDownLatch(3);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(firstConfig))
+        .thenReturn(Optional.of(secondConfig))
+        .thenReturn(Optional.of(thirdConfig));
+
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            Duration.millis(100).getMillis(),
+            config -> {
+              receivedPipelineConfig.add(config);
+              numExpectedRefreshes.countDown();
+            });
+
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    numExpectedRefreshes.await();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)

Review Comment:
   seems safer to stop the fetcher's background thread before accessing received config (or use a concurrent set)



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCache.java:
##########
@@ -54,6 +56,7 @@ public final class ComputationStateCache implements StatusDataProvider {
 
   private static final Logger LOG = LoggerFactory.getLogger(ComputationStateCache.class);
 
+  private final ConcurrentMap<String, String> globalUsernameToStateFamilyNameMap;

Review Comment:
   nit: global has connotations and makes it sound like static global, how about pipelineUserNameToStateFamilyNameMap



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertFalse(computationState.isPresent());
+  }
+
+  @Test
+  public void testGet_usesUserTransformToStateFamilyNameIfNotEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, userTransformToStateFamilyName, ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_defaultsToStateNameMapWhenUserTransformToStateFamilyNameEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, ImmutableMap.of(), ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(computationStateCache.getGlobalUsernameToStateFamilyNameMap());
+  }
+
+  @Test
+  public void testGet_buildsStateNameMap() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> stateNameMap = ImmutableMap.of("stateName1", "stateName");
+    ComputationConfig computationConfig = ComputationConfig.create(mapTask, null, stateNameMap);
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    assertThat(computationStateCache.getGlobalUsernameToStateFamilyNameMap())
+        .containsExactlyEntriesIn(stateNameMap);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.getIfPresent(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateNotCached() {
+    Optional<ComputationState> computationState =
+        computationStateCache.getIfPresent("computationId");
+    assertFalse(computationState.isPresent());
+    verifyNoInteractions(configFetcher);
+  }
+
+  @Test
+  public void testGetAllComputations() {

Review Comment:
   nit: allpresentcomputations



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());

Review Comment:
   add similar test where fetchConfig throws an exception



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {

Review Comment:
   how about combining the above and this one by just verifying on both of the get calls above?
   
   If you feel strongly about them being separate I think this one should come first since it's doing less



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertFalse(computationState.isPresent());

Review Comment:
   call get again and verify the fetch occurs



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertFalse(computationState.isPresent());
+  }
+
+  @Test
+  public void testGet_usesUserTransformToStateFamilyNameIfNotEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, userTransformToStateFamilyName, ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_defaultsToStateNameMapWhenUserTransformToStateFamilyNameEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, ImmutableMap.of(), ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(computationStateCache.getGlobalUsernameToStateFamilyNameMap());
+  }
+
+  @Test
+  public void testGet_buildsStateNameMap() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> stateNameMap = ImmutableMap.of("stateName1", "stateName");
+    ComputationConfig computationConfig = ComputationConfig.create(mapTask, null, stateNameMap);
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    assertThat(computationStateCache.getGlobalUsernameToStateFamilyNameMap())
+        .containsExactlyEntriesIn(stateNameMap);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.getIfPresent(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateNotCached() {
+    Optional<ComputationState> computationState =
+        computationStateCache.getIfPresent("computationId");
+    assertFalse(computationState.isPresent());
+    verifyNoInteractions(configFetcher);
+  }
+
+  @Test
+  public void testGetAllComputations() {
+    String computationId1 = "computationId1";
+    String computationId2 = "computationId2";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId1))).thenReturn(Optional.of(computationConfig));
+    when(configFetcher.fetchConfig(eq(computationId2))).thenReturn(Optional.of(computationConfig));
+
+    computationStateCache.get(computationId1);
+    computationStateCache.get(computationId2);
+    Set<String> computationIds = ImmutableSet.of(computationId1, computationId2);
+    computationStateCache
+        .getAllPresentComputations()
+        .forEach(
+            computationState -> {
+              assertThat(computationIds).contains(computationState.getComputationId());
+              assertThat(computationState.getMapTask()).isEqualTo(mapTask);
+              assertThat(computationState.getTransformUserNameToStateFamily())
+                  .isEqualTo(userTransformToStateFamilyName);
+            });
+  }
+
+  @Test
+  public void testTotalCurrentActiveGetWorkBudget() {

Review Comment:
   woul;d be better test with multiple computationstate that it has to aggregate over



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),

Review Comment:
   just move into forTesting method?



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertFalse(computationState.isPresent());
+  }
+
+  @Test
+  public void testGet_usesUserTransformToStateFamilyNameIfNotEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, userTransformToStateFamilyName, ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_defaultsToStateNameMapWhenUserTransformToStateFamilyNameEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, ImmutableMap.of(), ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(computationStateCache.getGlobalUsernameToStateFamilyNameMap());
+  }
+
+  @Test
+  public void testGet_buildsStateNameMap() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> stateNameMap = ImmutableMap.of("stateName1", "stateName");
+    ComputationConfig computationConfig = ComputationConfig.create(mapTask, null, stateNameMap);
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    assertThat(computationStateCache.getGlobalUsernameToStateFamilyNameMap())
+        .containsExactlyEntriesIn(stateNameMap);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.getIfPresent(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateNotCached() {
+    Optional<ComputationState> computationState =
+        computationStateCache.getIfPresent("computationId");
+    assertFalse(computationState.isPresent());
+    verifyNoInteractions(configFetcher);
+  }
+
+  @Test
+  public void testGetAllComputations() {
+    String computationId1 = "computationId1";
+    String computationId2 = "computationId2";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId1))).thenReturn(Optional.of(computationConfig));
+    when(configFetcher.fetchConfig(eq(computationId2))).thenReturn(Optional.of(computationConfig));
+
+    computationStateCache.get(computationId1);
+    computationStateCache.get(computationId2);
+    Set<String> computationIds = ImmutableSet.of(computationId1, computationId2);
+    computationStateCache
+        .getAllPresentComputations()
+        .forEach(
+            computationState -> {
+              assertThat(computationIds).contains(computationState.getComputationId());

Review Comment:
   As is this would pass if getAllPresentComputations returned nothing.
   
   verify that it contains both computation ids



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingApplianceComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static java.util.stream.Collectors.toMap;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.io.IOException;
+import java.util.List;
+import java.util.Optional;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.WindmillServerStub;
+import org.apache.beam.sdk.extensions.gcp.util.Transport;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingApplianceComputationConfigFetcherTest {
+  private final WindmillServerStub mockWindmillServer = mock(WindmillServerStub.class);
+
+  @Test
+  public void testGetComputationConfig() throws IOException {
+    List<Windmill.GetConfigResponse.NameMapEntry> nameMapEntries =
+        ImmutableList.of(
+            Windmill.GetConfigResponse.NameMapEntry.newBuilder()
+                .setUserName("userName1")
+                .setSystemName("systemName1")
+                .build(),
+            Windmill.GetConfigResponse.NameMapEntry.newBuilder()
+                .setUserName("userName2")
+                .setSystemName("userName2")
+                .build());
+    String serializedMapTask =
+        Transport.getJsonFactory()
+            .toString(
+                new MapTask()
+                    .setSystemName("systemName")
+                    .setStageName("stageName")
+                    .setInstructions(ImmutableList.of()));
+    Windmill.GetConfigResponse getConfigResponse =
+        Windmill.GetConfigResponse.newBuilder()
+            .addAllNameMap(nameMapEntries)
+            .addComputationConfigMap(
+                Windmill.GetConfigResponse.ComputationConfigMapEntry.newBuilder()
+                    .setComputationId("systemName")
+                    .setComputationConfig(
+                        Windmill.ComputationConfig.newBuilder()
+                            .addTransformUserNameToStateFamily(
+                                Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                                    .newBuilder()
+                                    .setStateFamily("stateFamilyName")
+                                    .setTransformUserName("transformUserName")
+                                    .build())
+                            .build())
+                    .build())
+            .addCloudWorks(serializedMapTask)
+            .build();
+    ComputationConfig expectedConfig =
+        ComputationConfig.create(
+            Transport.getJsonFactory().fromString(serializedMapTask, MapTask.class),
+            getConfigResponse.getComputationConfigMapList().stream()
+                .map(Windmill.GetConfigResponse.ComputationConfigMapEntry::getComputationConfig)
+                .flatMap(
+                    computationConfig ->
+                        computationConfig.getTransformUserNameToStateFamilyList().stream())
+                .collect(
+                    toMap(
+                        Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                            ::getTransformUserName,
+                        Windmill.ComputationConfig.TransformUserNameToStateFamilyEntry
+                            ::getStateFamily)),
+            nameMapEntries.stream()
+                .collect(
+                    toMap(
+                        Windmill.GetConfigResponse.NameMapEntry::getUserName,
+                        Windmill.GetConfigResponse.NameMapEntry::getSystemName)));
+    StreamingApplianceComputationConfigFetcher configLoader =
+        createStreamingApplianceConfigLoader();
+    when(mockWindmillServer.getConfig(any())).thenReturn(getConfigResponse);
+    Optional<ComputationConfig> config = configLoader.fetchConfig("someComputationId");
+    assertTrue(config.isPresent());
+    assertThat(config.get()).isEqualTo(expectedConfig);
+  }
+
+  @Test
+  public void testGetComputationConfig_whenNoConfigReturned() {
+    StreamingApplianceComputationConfigFetcher configLoader =
+        createStreamingApplianceConfigLoader();
+    when(mockWindmillServer.getConfig(any())).thenReturn(null);
+    Optional<ComputationConfig> configResponse = configLoader.fetchConfig("someComputationId");
+    assertFalse(configResponse.isPresent());
+  }
+

Review Comment:
   add test that if the windmillfetcher throws exception that it is propagated to configLoader.fetchConfig



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),
+        onPipelineConfig);
+  }
+
+  @After
+  public void cleanUp() {
+    streamingEngineConfigFetcher.stop();
+  }
+
+  @Test
+  public void testStart_requiresInitialConfig() throws IOException, InterruptedException {
+    WorkItem initialConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    CountDownLatch waitForInitialConfig = new CountDownLatch(1);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(initialConfig));
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            0,
+            config -> {
+              try {
+                receivedPipelineConfig.add(config);
+                waitForInitialConfig.await();
+              } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+              }
+            });
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    waitForInitialConfig.countDown();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    initialConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testStart_startsPeriodicConfigRequests() throws IOException, InterruptedException {
+    WorkItem firstConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    WorkItem secondConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(15L));
+    WorkItem thirdConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(100L));
+    CountDownLatch numExpectedRefreshes = new CountDownLatch(3);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(firstConfig))
+        .thenReturn(Optional.of(secondConfig))
+        .thenReturn(Optional.of(thirdConfig));

Review Comment:
   will there be a flaky error if a 4th fetch comes in before the background thread stops? shoudl some sort of default response be setup?



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(

Review Comment:
   nit: s/Loader/Fetcher/



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),
+        onPipelineConfig);
+  }
+
+  @After
+  public void cleanUp() {
+    streamingEngineConfigFetcher.stop();
+  }
+
+  @Test
+  public void testStart_requiresInitialConfig() throws IOException, InterruptedException {
+    WorkItem initialConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    CountDownLatch waitForInitialConfig = new CountDownLatch(1);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(initialConfig));
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            0,
+            config -> {
+              try {
+                receivedPipelineConfig.add(config);
+                waitForInitialConfig.await();
+              } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+              }
+            });
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    waitForInitialConfig.countDown();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    initialConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testStart_startsPeriodicConfigRequests() throws IOException, InterruptedException {
+    WorkItem firstConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    WorkItem secondConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(15L));
+    WorkItem thirdConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(100L));
+    CountDownLatch numExpectedRefreshes = new CountDownLatch(3);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(firstConfig))
+        .thenReturn(Optional.of(secondConfig))

Review Comment:
   test that if an exception is thrown in the middle that later fetches still work



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),
+        onPipelineConfig);
+  }
+
+  @After
+  public void cleanUp() {
+    streamingEngineConfigFetcher.stop();
+  }
+
+  @Test
+  public void testStart_requiresInitialConfig() throws IOException, InterruptedException {
+    WorkItem initialConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    CountDownLatch waitForInitialConfig = new CountDownLatch(1);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(initialConfig));
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            0,
+            config -> {
+              try {
+                receivedPipelineConfig.add(config);
+                waitForInitialConfig.await();
+              } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+              }
+            });
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    waitForInitialConfig.countDown();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    initialConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testStart_startsPeriodicConfigRequests() throws IOException, InterruptedException {
+    WorkItem firstConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    WorkItem secondConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(15L));
+    WorkItem thirdConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(100L));
+    CountDownLatch numExpectedRefreshes = new CountDownLatch(3);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(firstConfig))
+        .thenReturn(Optional.of(secondConfig))
+        .thenReturn(Optional.of(thirdConfig));
+
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            Duration.millis(100).getMillis(),
+            config -> {
+              receivedPipelineConfig.add(config);
+              numExpectedRefreshes.countDown();
+            });
+
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    numExpectedRefreshes.await();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    firstConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build(),
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    secondConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build(),
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    thirdConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testGetComputationConfig() throws IOException {
+    streamingEngineConfigFetcher =
+        createConfigLoader(/* waitForInitialConfig= */ false, 0, ignored -> {});
+    String computationId = "computationId";
+    String stageName = "stageName";
+    String systemName = "systemName";
+    StreamingComputationConfig pipelineConfig =
+        new StreamingComputationConfig()
+            .setComputationId(computationId)
+            .setStageName(stageName)
+            .setSystemName(systemName)
+            .setInstructions(ImmutableList.of());
+
+    WorkItem workItem =
+        new WorkItem()
+            .setStreamingConfigTask(
+                new StreamingConfigTask()
+                    .setStreamingComputationConfigs(ImmutableList.of(pipelineConfig)));
+
+    when(mockDataflowServiceClient.getStreamingConfigWorkItem(anyString()))
+        .thenReturn(Optional.of(workItem));
+    Optional<ComputationConfig> actualPipelineConfig =
+        streamingEngineConfigFetcher.fetchConfig(computationId);
+
+    assertTrue(actualPipelineConfig.isPresent());
+    assertThat(actualPipelineConfig.get())
+        .isEqualTo(
+            ComputationConfig.create(
+                StreamingEngineComputationConfigFetcher.createMapTask(pipelineConfig),
+                ImmutableMap.of(),
+                ImmutableMap.of()));
+  }
+
+  @Test
+  public void testGetComputationConfig_noComputationPresent() throws IOException {

Review Comment:
   test the dataflowserviceclient returnign an exception



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1594102553


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertFalse(computationState.isPresent());

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.runners.dataflow.worker.streaming;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.MapTask;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.beam.runners.dataflow.worker.streaming.config.ComputationConfig;
+import org.apache.beam.runners.dataflow.worker.util.BoundedQueueExecutor;
+import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
+import org.apache.beam.runners.dataflow.worker.windmill.state.WindmillStateCache;
+import org.apache.beam.runners.dataflow.worker.windmill.work.budget.GetWorkBudget;
+import org.apache.beam.sdk.fn.IdGenerators;
+import org.apache.beam.vendor.grpc.v1p60p1.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.joda.time.Instant;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ComputationStateCacheTest {
+  private final BoundedQueueExecutor workExecutor = mock(BoundedQueueExecutor.class);
+  private final WindmillStateCache.ForComputation stateCache =
+      mock(WindmillStateCache.ForComputation.class);
+  private final ComputationConfig.Fetcher configFetcher = mock(ComputationConfig.Fetcher.class);
+  private ComputationStateCache computationStateCache;
+
+  private static Work createWork(long workToken, long cacheToken) {
+
+    return Work.create(
+        Windmill.WorkItem.newBuilder()
+            .setKey(ByteString.copyFromUtf8(""))
+            .setShardingKey(1)
+            .setWorkToken(workToken)
+            .setCacheToken(cacheToken)
+            .build(),
+        Instant::now,
+        Collections.emptyList(),
+        unused -> {});
+  }
+
+  @Before
+  public void setUp() {
+    computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, ignored -> stateCache, IdGenerators.decrementingLongs());
+  }
+
+  @Test
+  public void testGet_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_computationStateNotCachedOrFetchable() {
+    String computationId = "computationId";
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.empty());
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertFalse(computationState.isPresent());
+  }
+
+  @Test
+  public void testGet_usesUserTransformToStateFamilyNameIfNotEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, userTransformToStateFamilyName, ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGet_defaultsToStateNameMapWhenUserTransformToStateFamilyNameEmpty() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(
+            mapTask, ImmutableMap.of(), ImmutableMap.of("stateName1", "stateName"));
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    Optional<ComputationState> computationState = computationStateCache.get(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(computationStateCache.getGlobalUsernameToStateFamilyNameMap());
+  }
+
+  @Test
+  public void testGet_buildsStateNameMap() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> stateNameMap = ImmutableMap.of("stateName1", "stateName");
+    ComputationConfig computationConfig = ComputationConfig.create(mapTask, null, stateNameMap);
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    assertThat(computationStateCache.getGlobalUsernameToStateFamilyNameMap())
+        .containsExactlyEntriesIn(stateNameMap);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateCached() {
+    String computationId = "computationId";
+    MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
+    Map<String, String> userTransformToStateFamilyName =
+        ImmutableMap.of("userTransformName", "stateFamilyName");
+    ComputationConfig computationConfig =
+        ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
+    when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    computationStateCache.get(computationId);
+    Optional<ComputationState> computationState = computationStateCache.getIfPresent(computationId);
+    assertTrue(computationState.isPresent());
+    assertThat(computationState.get().getComputationId()).isEqualTo(computationId);
+    assertThat(computationState.get().getMapTask()).isEqualTo(mapTask);
+    assertThat(computationState.get().getTransformUserNameToStateFamily())
+        .isEqualTo(userTransformToStateFamilyName);
+  }
+
+  @Test
+  public void testGetIfPresent_computationStateNotCached() {
+    Optional<ComputationState> computationState =
+        computationStateCache.getIfPresent("computationId");
+    assertFalse(computationState.isPresent());
+    verifyNoInteractions(configFetcher);
+  }
+
+  @Test
+  public void testGetAllComputations() {

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585844460


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                true,
+                options.getGlobalConfigRefreshPeriod().getMillis(),
+                dataflowServiceClient,
+                executorSupplier,
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS,
+                config ->
+                    onPipelineConfig(
+                        config,
+                        stateNameMap,
+                        windmillServer::setWindmillServiceEndpoints,
+                        maxWorkItemCommitBytes))
+            : new StreamingApplianceConfigFetcher(
+                windmillServer,
+                config -> consumeUserStepToStateFamilyName(config, stateNameMap),
+                FIX_MULTI_OUTPUT_INFOS_ON_PAR_DO_INSTRUCTIONS);
+    ComputationStateCache computationStateCache =
+        ComputationStateCache.create(
+            configFetcher, workExecutor, windmillStateCache::forComputation);
+    if (windmillServer instanceof GrpcWindmillServer) {

Review Comment:
   i actually realized that appliance does not refresh heartbeats which is what that consumer of heartbeat responses is for.
   
    we only call refresh active work on get data stream if streaming engine is enabled.



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585822456


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingPipelineConfig.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.auto.value.AutoValue;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+
+/** Pipeline configuration for jobs running w/ Streaming Engine. */
+@AutoValue
+@Internal
+public abstract class StreamingPipelineConfig {
+
+  private static final long DEFAULT_MAX_WORK_ITEM_COMMIT_BYTES = 180 << 20;
+
+  public static StreamingPipelineConfig.Builder builder() {
+    return new AutoValue_StreamingPipelineConfig.Builder()
+        .setMaxWorkItemCommitBytes(DEFAULT_MAX_WORK_ITEM_COMMIT_BYTES)
+        .setComputationConfig(null)
+        .setUserStepToStateFamilyNameMap(new HashMap<>())
+        .setWindmillServiceEndpoints(ImmutableSet.of());
+  }
+
+  public static StreamingPipelineConfig forAppliance(

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585820746


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(

Review Comment:
   removed this was supposed to just use the create method 



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "scwhittle (via GitHub)" <gi...@apache.org>.
scwhittle merged PR #31133:
URL: https://github.com/apache/beam/pull/31133


-- 
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] add computation state cache, config loaders, and status pages [beam]

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


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -800,110 +805,39 @@ private DataflowWorkerHarnessOptions createTestingPipelineOptions(String... args
   }
 
   private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      Supplier<Instant> clock,
-      Function<String, ScheduledExecutorService> executorSupplier,
-      int localRetryTimeoutMs) {
-    return makeWorker(
-        ImmutableMap.of(),
-        instructions,
-        options,
-        publishCounters,
-        clock,
-        executorSupplier,
-        localRetryTimeoutMs);
-  }
-
-  private StreamingDataflowWorker makeWorker(
-      Map<String, String> stateNameMappings,
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      Supplier<Instant> clock,
-      Function<String, ScheduledExecutorService> executorSupplier,
-      int localRetryTimeoutMs) {
-    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
-    stateNameMap.putAll(stateNameMappings);
-    stateNameMap.putAll(ImmutableMap.of(DEFAULT_PARDO_USER_NAME, DEFAULT_PARDO_STATE_FAMILY));
+      StreamingDataflowWorkerTestParams streamingDataflowWorkerTestParams) {
     StreamingDataflowWorker worker =
         StreamingDataflowWorker.forTesting(
-            stateNameMap,
+            streamingDataflowWorkerTestParams.stateNameMappings(),
             server,
-            Collections.singletonList(defaultMapTask(instructions)),
+            Collections.singletonList(
+                defaultMapTask(streamingDataflowWorkerTestParams.instructions())),
             IntrinsicMapTaskExecutorFactory.defaultFactory(),
             mockWorkUnitClient,
-            options,
-            publishCounters,
+            streamingDataflowWorkerTestParams.options(),
+            streamingDataflowWorkerTestParams.publishCounters(),
             hotKeyLogger,
-            clock,
-            executorSupplier,
-            localRetryTimeoutMs);
+            streamingDataflowWorkerTestParams.clock(),
+            streamingDataflowWorkerTestParams.executorSupplier(),
+            streamingDataflowWorkerTestParams.localRetryTimeoutMs(),
+            streamingDataflowWorkerTestParams.maxWorkItemCommitBytes());
     this.computationStateCache = worker.getComputationStateCache();
     return worker;
   }
 
-  private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      Supplier<Instant> clock,
-      Function<String, ScheduledExecutorService> executorSupplier) {
-    return makeWorker(instructions, options, publishCounters, clock, executorSupplier, -1);
-  }
-
-  private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters) {
-    return makeWorker(
-        instructions,
-        options,
-        publishCounters,
-        Instant::now,
-        (threadName) -> Executors.newSingleThreadScheduledExecutor(),
-        -1);
-  }
-
-  private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      Map<String, String> stateNameMap) {
-    return makeWorker(
-        stateNameMap,
-        instructions,
-        options,
-        publishCounters,
-        Instant::now,
-        (threadName) -> Executors.newSingleThreadScheduledExecutor(),
-        -1);
-  }
-
-  private StreamingDataflowWorker makeWorker(
-      List<ParallelInstruction> instructions,
-      DataflowWorkerHarnessOptions options,
-      boolean publishCounters,
-      int localRetryTimeoutMs) {
-    return makeWorker(
-        instructions,
-        options,
-        publishCounters,
-        Instant::now,
-        (threadName) -> Executors.newSingleThreadScheduledExecutor(),
-        localRetryTimeoutMs);
-  }
-
   @Test
   public void testBasicHarness() throws Exception {
     List<ParallelInstruction> instructions =
         Arrays.asList(
             makeSourceInstruction(StringUtf8Coder.of()),
             makeSinkInstruction(StringUtf8Coder.of(), 0));
-
     StreamingDataflowWorker worker =
-        makeWorker(instructions, createTestingPipelineOptions(), true /* publishCounters */);
+        makeWorker(
+            defaultWorkerParams()
+                .setInstructions(instructions)
+                .publishCounters()
+                .setOptions(createTestingPipelineOptions())

Review Comment:
   can setOptions(createTestingPipelineOptions()) since it's default



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -3203,12 +3145,21 @@ public void testExceptionInvalidatesCache() throws Exception {
                 WindowingStrategy.globalDefault()),
             makeSinkInstruction(StringUtf8Coder.of(), 1, GlobalWindow.Coder.INSTANCE));
 
+    defaultWorkerParams()

Review Comment:
   rm, not used



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/ComputationStateCacheTest.java:
##########
@@ -218,32 +241,46 @@ public void testGetAllComputations() {
   @Test
   public void testTotalCurrentActiveGetWorkBudget() {
     String computationId = "computationId";
+    String computationId2 = "computationId2";
     MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName");
     Map<String, String> userTransformToStateFamilyName =
         ImmutableMap.of("userTransformName", "stateFamilyName");
     ComputationConfig computationConfig =
         ComputationConfig.create(mapTask, userTransformToStateFamilyName, ImmutableMap.of());
     when(configFetcher.fetchConfig(eq(computationId))).thenReturn(Optional.of(computationConfig));
+    when(configFetcher.fetchConfig(eq(computationId2))).thenReturn(Optional.of(computationConfig));
+    Work work1 = createWork(1, 1);
+    Work work2 = createWork(2, 2);
+    Work work3 = createWork(3, 3);
+
+    // Activate 3 Work(s) for computationId
     Optional<ComputationState> maybeComputationState = computationStateCache.get(computationId);
     assertTrue(maybeComputationState.isPresent());
-
     ComputationState computationState = maybeComputationState.get();
     ShardedKey shardedKey = ShardedKey.create(ByteString.EMPTY, 1);
-    Work work1 = createWork(1, 1);
-    Work work2 = createWork(2, 2);
-    Work work3 = createWork(3, 3);
     computationState.activateWork(shardedKey, work1);
     computationState.activateWork(shardedKey, work2);
     computationState.activateWork(shardedKey, work3);
 
+    // Activate 3 Work(s) for computationId2
+    Optional<ComputationState> maybeComputationState2 = computationStateCache.get(computationId);

Review Comment:
   nit: how about just activating work1 on computationState and work2, work3 on comptuationState2. Then we're not deviating from normal usage of work (shouldn't be activated on multiple/different comptuatoins) in case it causes issues down the line.
   
   



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -3368,7 +3318,13 @@ public void testActiveWorkRefresh() throws Exception {
 
     DataflowWorkerHarnessOptions options = createTestingPipelineOptions();
     options.setActiveWorkRefreshPeriodMillis(100);
-    StreamingDataflowWorker worker = makeWorker(instructions, options, true /* publishCounters */);
+    StreamingDataflowWorker worker =
+        makeWorker(
+            defaultWorkerParams()

Review Comment:
   does passing in "--activeWorkRefreshPeriodMillis=100" let you get rid of options?



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -3391,7 +3347,13 @@ public void testActiveWorkFailure() throws Exception {
 
     DataflowWorkerHarnessOptions options = createTestingPipelineOptions();
     options.setActiveWorkRefreshPeriodMillis(100);
-    StreamingDataflowWorker worker = makeWorker(instructions, options, true /* publishCounters */);
+    StreamingDataflowWorker worker =
+        makeWorker(
+            defaultWorkerParams()

Review Comment:
   ditto, here and below



-- 
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] add computation state cache, config loaders, and status pages [beam]

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

   Assigning reviewers. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @riteshghorse added as fallback since no labels match configuration
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1594567156


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),
+        onPipelineConfig);
+  }
+
+  @After
+  public void cleanUp() {
+    streamingEngineConfigFetcher.stop();
+  }
+
+  @Test
+  public void testStart_requiresInitialConfig() throws IOException, InterruptedException {
+    WorkItem initialConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    CountDownLatch waitForInitialConfig = new CountDownLatch(1);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(initialConfig));
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            0,
+            config -> {
+              try {
+                receivedPipelineConfig.add(config);
+                waitForInitialConfig.await();
+              } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+              }
+            });
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    waitForInitialConfig.countDown();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    initialConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testStart_startsPeriodicConfigRequests() throws IOException, InterruptedException {
+    WorkItem firstConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    WorkItem secondConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(15L));
+    WorkItem thirdConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(100L));
+    CountDownLatch numExpectedRefreshes = new CountDownLatch(3);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(firstConfig))
+        .thenReturn(Optional.of(secondConfig))
+        .thenReturn(Optional.of(thirdConfig));
+
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            Duration.millis(100).getMillis(),
+            config -> {
+              receivedPipelineConfig.add(config);
+              numExpectedRefreshes.countDown();
+            });
+
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    numExpectedRefreshes.await();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),
+        onPipelineConfig);
+  }
+
+  @After
+  public void cleanUp() {
+    streamingEngineConfigFetcher.stop();
+  }
+
+  @Test
+  public void testStart_requiresInitialConfig() throws IOException, InterruptedException {
+    WorkItem initialConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    CountDownLatch waitForInitialConfig = new CountDownLatch(1);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(initialConfig));
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            0,
+            config -> {
+              try {
+                receivedPipelineConfig.add(config);
+                waitForInitialConfig.await();
+              } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+              }
+            });
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    waitForInitialConfig.countDown();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    initialConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testStart_startsPeriodicConfigRequests() throws IOException, InterruptedException {
+    WorkItem firstConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    WorkItem secondConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(15L));
+    WorkItem thirdConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(100L));
+    CountDownLatch numExpectedRefreshes = new CountDownLatch(3);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(firstConfig))
+        .thenReturn(Optional.of(secondConfig))
+        .thenReturn(Optional.of(thirdConfig));

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcherTest.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.function.Consumer;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.joda.time.Duration;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StreamingEngineComputationConfigFetcherTest {
+  private final WorkUnitClient mockDataflowServiceClient = mock(WorkUnitClient.class);
+  private StreamingEngineComputationConfigFetcher streamingEngineConfigFetcher;
+
+  private StreamingEngineComputationConfigFetcher createConfigLoader(
+      boolean waitForInitialConfig,
+      long globalConfigRefreshPeriod,
+      Consumer<StreamingEnginePipelineConfig> onPipelineConfig) {
+    return StreamingEngineComputationConfigFetcher.forTesting(
+        !waitForInitialConfig,
+        globalConfigRefreshPeriod,
+        mockDataflowServiceClient,
+        ignored -> Executors.newSingleThreadScheduledExecutor(),
+        onPipelineConfig);
+  }
+
+  @After
+  public void cleanUp() {
+    streamingEngineConfigFetcher.stop();
+  }
+
+  @Test
+  public void testStart_requiresInitialConfig() throws IOException, InterruptedException {
+    WorkItem initialConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    CountDownLatch waitForInitialConfig = new CountDownLatch(1);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(initialConfig));
+    streamingEngineConfigFetcher =
+        createConfigLoader(
+            /* waitForInitialConfig= */ true,
+            0,
+            config -> {
+              try {
+                receivedPipelineConfig.add(config);
+                waitForInitialConfig.await();
+              } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+              }
+            });
+    Thread asyncStartConfigLoader = new Thread(streamingEngineConfigFetcher::start);
+    asyncStartConfigLoader.start();
+    waitForInitialConfig.countDown();
+    asyncStartConfigLoader.join();
+    assertThat(receivedPipelineConfig)
+        .containsExactly(
+            StreamingEnginePipelineConfig.builder()
+                .setMaxWorkItemCommitBytes(
+                    initialConfig.getStreamingConfigTask().getMaxWorkItemCommitBytes())
+                .build());
+  }
+
+  @Test
+  public void testStart_startsPeriodicConfigRequests() throws IOException, InterruptedException {
+    WorkItem firstConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(10L));
+    WorkItem secondConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(15L));
+    WorkItem thirdConfig =
+        new WorkItem()
+            .setJobId("job")
+            .setStreamingConfigTask(new StreamingConfigTask().setMaxWorkItemCommitBytes(100L));
+    CountDownLatch numExpectedRefreshes = new CountDownLatch(3);
+    Set<StreamingEnginePipelineConfig> receivedPipelineConfig = new HashSet<>();
+    when(mockDataflowServiceClient.getGlobalStreamingConfigWorkItem())
+        .thenReturn(Optional.of(firstConfig))
+        .thenReturn(Optional.of(secondConfig))

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1591858632


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(

Review Comment:
   done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/config/StreamingEngineComputationConfigFetcher.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.runners.dataflow.worker.streaming.config;
+
+import static java.util.stream.StreamSupport.stream;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet.toImmutableSet;
+import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
+
+import com.google.api.services.dataflow.model.MapTask;
+import com.google.api.services.dataflow.model.StreamingComputationConfig;
+import com.google.api.services.dataflow.model.StreamingConfigTask;
+import com.google.api.services.dataflow.model.WorkItem;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.ThreadSafe;
+import org.apache.beam.runners.dataflow.worker.WorkUnitClient;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.util.BackOff;
+import org.apache.beam.sdk.util.BackOffUtils;
+import org.apache.beam.sdk.util.FluentBackoff;
+import org.apache.beam.sdk.util.Sleeper;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Splitter;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableSet;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.net.HostAndPort;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.joda.time.Duration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Internal
+@ThreadSafe
+public final class StreamingEngineComputationConfigFetcher implements ComputationConfig.Fetcher {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(StreamingEngineComputationConfigFetcher.class);
+  private static final String GLOBAL_PIPELINE_CONFIG_REFRESHER = "GlobalPipelineConfigRefresher";
+
+  private final long globalConfigRefreshPeriodMillis;
+  private final WorkUnitClient dataflowServiceClient;
+  private final ScheduledExecutorService globalConfigRefresher;
+  private final Consumer<StreamingEnginePipelineConfig> onStreamingConfig;
+  private final AtomicBoolean hasReceivedGlobalConfig;
+
+  private StreamingEngineComputationConfigFetcher(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      ScheduledExecutorService globalConfigRefresher,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    this.globalConfigRefreshPeriodMillis = globalConfigRefreshPeriodMillis;
+    this.dataflowServiceClient = dataflowServiceClient;
+    this.globalConfigRefresher = globalConfigRefresher;
+    this.onStreamingConfig = onStreamingConfig;
+    this.hasReceivedGlobalConfig = new AtomicBoolean(hasReceivedGlobalConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher create(
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        /* hasReceivedGlobalConfig= */ false,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        Executors.newSingleThreadScheduledExecutor(
+            new ThreadFactoryBuilder().setNameFormat(GLOBAL_PIPELINE_CONFIG_REFRESHER).build()),
+        onStreamingConfig);
+  }
+
+  public static StreamingEngineComputationConfigFetcher forTesting(
+      boolean hasReceivedGlobalConfig,
+      long globalConfigRefreshPeriodMillis,
+      WorkUnitClient dataflowServiceClient,
+      Function<String, ScheduledExecutorService> executorSupplier,
+      Consumer<StreamingEnginePipelineConfig> onStreamingConfig) {
+    return new StreamingEngineComputationConfigFetcher(
+        hasReceivedGlobalConfig,
+        globalConfigRefreshPeriodMillis,
+        dataflowServiceClient,
+        executorSupplier.apply(GLOBAL_PIPELINE_CONFIG_REFRESHER),
+        onStreamingConfig);
+  }
+
+  private static BackOff defaultConfigBackoff() {
+    return FluentBackoff.DEFAULT
+        .withInitialBackoff(Duration.millis(100))
+        .withMaxBackoff(Duration.standardMinutes(1))
+        .withMaxCumulativeBackoff(Duration.standardMinutes(5))
+        .backoff();
+  }
+
+  private MapTask createMapTask(StreamingComputationConfig computationConfig) {

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1595912396


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorkerTest.java:
##########
@@ -797,9 +806,30 @@ private StreamingDataflowWorker makeWorker(
       Supplier<Instant> clock,
       Function<String, ScheduledExecutorService> executorSupplier,
       int localRetryTimeoutMs) {
+    return makeWorker(
+        ImmutableMap.of(),
+        instructions,
+        options,
+        publishCounters,
+        clock,
+        executorSupplier,
+        localRetryTimeoutMs);
+  }
+
+  private StreamingDataflowWorker makeWorker(

Review Comment:
   done used a builder with some test parameters



-- 
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] add computation state cache, config loaders, and status pages [beam]

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

   failing test is unrelated and passes on local runs


-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585821365


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -387,24 +393,53 @@ private StreamingDataflowWorker(
     LOG.debug("WindmillServiceEndpoint: {}", options.getWindmillServiceEndpoint());
     LOG.debug("WindmillServicePort: {}", options.getWindmillServicePort());
     LOG.debug("LocalWindmillHostport: {}", options.getLocalWindmillHostport());
-    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes);
+    LOG.debug("maxWorkItemCommitBytes: {}", maxWorkItemCommitBytes.get());
   }
 
   public static StreamingDataflowWorker fromOptions(DataflowWorkerHarnessOptions options) {
     long clientId = clientIdGenerator.nextLong();
     MemoryMonitor memoryMonitor = MemoryMonitor.fromOptions(options);
-    ConcurrentMap<String, ComputationState> computationMap = new ConcurrentHashMap<>();
     ConcurrentMap<String, StageInfo> stageInfo = new ConcurrentHashMap<>();
+    ConcurrentMap<String, String> stateNameMap = new ConcurrentHashMap<>();
     StreamingCounters streamingCounters = StreamingCounters.create();
-
+    WorkUnitClient dataflowServiceClient = new DataflowWorkUnitClient(options, LOG);
+    BoundedQueueExecutor workExecutor = createWorkUnitExecutor(options);
+    AtomicInteger maxWorkItemCommitBytes = new AtomicInteger(Integer.MAX_VALUE);
+    WindmillStateCache windmillStateCache =
+        WindmillStateCache.ofSizeMbs(options.getWorkerCacheMb());
+    Function<String, ScheduledExecutorService> executorSupplier =
+        threadName ->
+            Executors.newSingleThreadScheduledExecutor(
+                new ThreadFactoryBuilder().setNameFormat(threadName).build());
     GrpcWindmillStreamFactory windmillStreamFactory =
         createWindmillStreamFactory(options, clientId);
-    WindmillServerStub windmillServer =
-        createWindmillServerStub(
-            options,
-            windmillStreamFactory,
-            new WorkHeartbeatResponseProcessor(
-                computationId -> Optional.ofNullable(computationMap.get(computationId))));
+    WindmillServerStub windmillServer = createWindmillServerStub(options, windmillStreamFactory);
+    ComputationConfig.Fetcher configFetcher =
+        options.isEnableStreamingEngine()
+            ? StreamingEngineConfigFetcher.forTesting(
+                true,

Review Comment:
   it is used in a different test



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1585963336


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -373,10 +350,39 @@ private StreamingDataflowWorker(
             clock,
             options.getActiveWorkRefreshPeriodMillis(),
             stuckCommitDurationMillis,
-            () -> Collections.unmodifiableCollection(computationMap.values()),
+            computationStateCache::getAllComputations,
             sampler,
             metricTrackingWindmillServer::refreshActiveWork,
             executorSupplier.apply("RefreshWork"));
+
+    WorkerStatusPages workerStatusPages =
+        WorkerStatusPages.create(DEFAULT_STATUS_PORT, memoryMonitor, () -> true);
+    this.statusPages =
+        windmillServiceEnabled
+            ? StreamingWorkerStatusPages.forStreamingEngine(

Review Comment:
   done



-- 
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] add computation state cache, config loaders, and status pages [beam]

Posted by "m-trieu (via GitHub)" <gi...@apache.org>.
m-trieu commented on code in PR #31133:
URL: https://github.com/apache/beam/pull/31133#discussion_r1588498420


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -931,15 +941,19 @@ void streamingDispatchLoop() {
                   Instant inputDataWatermark,
                   Instant synchronizedProcessingTime,
                   Windmill.WorkItem workItem,
-                  Collection<LatencyAttribution> getWorkStreamLatencies) -> {
-                memoryMonitor.waitForResources("GetWork");
-                scheduleWorkItem(
-                    getComputationState(computation),
-                    inputDataWatermark,
-                    synchronizedProcessingTime,
-                    workItem,
-                    getWorkStreamLatencies);
-              });
+                  Collection<LatencyAttribution> getWorkStreamLatencies) ->
+                  computationStateCache
+                      .get(computation)
+                      .ifPresent(

Review Comment:
   added more logging in the ComputationStateCache
   
   ```
     public Optional<ComputationState> get(String computationId) {
       try {
         return Optional.ofNullable(computationCache.get(computationId));
       } catch (ExecutionException | ComputationStateNotFoundException e) {
         if (e.getCause() instanceof ComputationStateNotFoundException) {
           LOG.error(
               "Trying to fetch unknown computation={}, known computations are {}.",
               computationId,
               getAllComputationIds());
         } else {
           LOG.warn("Error occurred fetching computation for computationId={}", computationId, e);
         }
       }
   ```
   
   



-- 
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