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

[PR] split write rename and temp table deletion into to dofns with a shuffle [beam]

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

   
   ------------------------
   
   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] split write rename and temp table deletion into to dofns with a shuffle [beam]

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

   Assigning reviewers. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @Abacn for label java.
   R: @chamikaramj for label io.
   
   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] split write rename and temp table deletion into to dofns with a shuffle [beam]

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


##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/WriteRename.java:
##########
@@ -95,237 +83,376 @@ public WriteRename(
       CreateDisposition createDisposition,
       int maxRetryJobs,
       @Nullable String kmsKey,
-      @Nullable ValueProvider<String> loadJobProjectId) {
+      @Nullable ValueProvider<String> loadJobProjectId,
+      PCollectionView<String> copyJobIdPrefixView) {
     this.bqServices = bqServices;
     this.jobIdToken = jobIdToken;
     this.firstPaneWriteDisposition = writeDisposition;
     this.firstPaneCreateDisposition = createDisposition;
     this.maxRetryJobs = maxRetryJobs;
     this.kmsKey = kmsKey;
     this.loadJobProjectId = loadJobProjectId;
+    this.copyJobIdPrefixView = copyJobIdPrefixView;
   }
 
-  @StartBundle
-  public void startBundle(StartBundleContext c) {
-    pendingJobs.clear();
+  @Override
+  public PCollection<TableDestination> expand(
+      PCollection<Iterable<KV<TableDestination, Result>>> input) {
+    return input
+        .apply(
+            "WriteRename",
+            ParDo.of(
+                    new WriteRenameFn(
+                        bqServices,
+                        jobIdToken,
+                        firstPaneWriteDisposition,
+                        firstPaneCreateDisposition,
+                        maxRetryJobs,
+                        kmsKey,
+                        loadJobProjectId))
+                .withSideInputs(copyJobIdPrefixView))
+        // We apply a fusion break here to ensure that the temp file renaming won't attempt to
+        // rename a temp file is then deleted in the TempTableCleanupFn

Review Comment:
   ```suggestion
           // We apply a fusion break here to ensure that on retries, the temp table renaming won't attempt to
           // rename a temp table that was previously deleted in TempTableCleanupFn
   ```



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/WriteRename.java:
##########
@@ -95,237 +83,376 @@ public WriteRename(
       CreateDisposition createDisposition,
       int maxRetryJobs,
       @Nullable String kmsKey,
-      @Nullable ValueProvider<String> loadJobProjectId) {
+      @Nullable ValueProvider<String> loadJobProjectId,
+      PCollectionView<String> copyJobIdPrefixView) {
     this.bqServices = bqServices;
     this.jobIdToken = jobIdToken;
     this.firstPaneWriteDisposition = writeDisposition;
     this.firstPaneCreateDisposition = createDisposition;
     this.maxRetryJobs = maxRetryJobs;
     this.kmsKey = kmsKey;
     this.loadJobProjectId = loadJobProjectId;
+    this.copyJobIdPrefixView = copyJobIdPrefixView;
   }
 
-  @StartBundle
-  public void startBundle(StartBundleContext c) {
-    pendingJobs.clear();
+  @Override
+  public PCollection<TableDestination> expand(
+      PCollection<Iterable<KV<TableDestination, Result>>> input) {
+    return input
+        .apply(
+            "WriteRename",
+            ParDo.of(
+                    new WriteRenameFn(
+                        bqServices,
+                        jobIdToken,
+                        firstPaneWriteDisposition,
+                        firstPaneCreateDisposition,
+                        maxRetryJobs,
+                        kmsKey,
+                        loadJobProjectId))
+                .withSideInputs(copyJobIdPrefixView))
+        // We apply a fusion break here to ensure that the temp file renaming won't attempt to
+        // rename a temp file is then deleted in the TempTableCleanupFn
+        .apply(Reshuffle.viaRandomKey())
+        .apply("RemoveTempTables", ParDo.of(new TempTableCleanupFn(bqServices)))
+        .setCoder(TableDestinationCoder.of());
   }
 
-  @Teardown
-  public void onTeardown() {
-    try {
-      if (datasetService != null) {
-        datasetService.close();
-        datasetService = null;
-      }
-    } catch (Exception e) {
-      throw new RuntimeException(e);
+  public static class PendingJobData implements Serializable {
+
+    final BigQueryHelpers.PendingJob retryJob;
+    final TableDestination tableDestination;
+    final List<String> tempTables;
+    final BoundedWindow window;
+
+    public PendingJobData(
+        BigQueryHelpers.PendingJob retryJob,
+        TableDestination tableDestination,
+        List<String> tempTables,
+        BoundedWindow window) {
+      this.retryJob = retryJob;
+      this.tableDestination = tableDestination;
+      this.tempTables = tempTables;
+      this.window = window;
     }
   }
 
-  @ProcessElement
-  public void processElement(
-      @Element Iterable<KV<TableDestination, WriteTables.Result>> element,
-      ProcessContext c,
-      BoundedWindow window)
-      throws Exception {
-    Multimap<TableDestination, WriteTables.Result> tempTables = ArrayListMultimap.create();
-    for (KV<TableDestination, WriteTables.Result> entry : element) {
-      tempTables.put(entry.getKey(), entry.getValue());
+  public static class WriteRenameFn
+      extends DoFn<
+          Iterable<KV<TableDestination, WriteTables.Result>>, KV<TableDestination, List<String>>> {
+    private static final Logger LOG = LoggerFactory.getLogger(WriteRenameFn.class);
+
+    private final BigQueryServices bqServices;
+    private final PCollectionView<String> jobIdToken;
+
+    // In the triggered scenario, the user-supplied create and write dispositions only apply to the
+    // first trigger pane, as that's when when the table is created. Subsequent loads should always
+    // append to the table, and so use CREATE_NEVER and WRITE_APPEND dispositions respectively.
+    private final WriteDisposition firstPaneWriteDisposition;
+    private final CreateDisposition firstPaneCreateDisposition;
+    private final int maxRetryJobs;
+    private final @Nullable String kmsKey;
+    private final @Nullable ValueProvider<String> loadJobProjectId;
+    private transient @Nullable DatasetService datasetService;
+
+    // All pending copy jobs.
+    private List<PendingJobData> pendingJobs = Lists.newArrayList();
+
+    public WriteRenameFn(
+        BigQueryServices bqServices,
+        PCollectionView<String> jobIdToken,
+        WriteDisposition writeDisposition,
+        CreateDisposition createDisposition,
+        int maxRetryJobs,
+        @Nullable String kmsKey,
+        @Nullable ValueProvider<String> loadJobProjectId) {
+      this.bqServices = bqServices;
+      this.jobIdToken = jobIdToken;
+      this.firstPaneWriteDisposition = writeDisposition;
+      this.firstPaneCreateDisposition = createDisposition;
+      this.maxRetryJobs = maxRetryJobs;
+      this.kmsKey = kmsKey;
+      this.loadJobProjectId = loadJobProjectId;
+    }
+
+    @StartBundle
+    public void startBundle(StartBundleContext c) {
+      pendingJobs.clear();
     }
-    for (Map.Entry<TableDestination, Collection<WriteTables.Result>> entry :
-        tempTables.asMap().entrySet()) {
-      // Process each destination table.
-      // Do not copy if no temp tables are provided.
-      if (!entry.getValue().isEmpty()) {
-        pendingJobs.add(startWriteRename(entry.getKey(), entry.getValue(), c, window));
+
+    @Teardown
+    public void onTeardown() {
+      try {
+        if (datasetService != null) {
+          datasetService.close();
+          datasetService = null;
+        }
+      } catch (Exception e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    @ProcessElement
+    public void processElement(
+        @Element Iterable<KV<TableDestination, WriteTables.Result>> element,
+        ProcessContext c,
+        BoundedWindow window)
+        throws Exception {
+      Multimap<TableDestination, WriteTables.Result> tempTables = ArrayListMultimap.create();
+      for (KV<TableDestination, WriteTables.Result> entry : element) {
+        tempTables.put(entry.getKey(), entry.getValue());
+      }
+      for (Map.Entry<TableDestination, Collection<WriteTables.Result>> entry :
+          tempTables.asMap().entrySet()) {
+        // Process each destination table.
+        // Do not copy if no temp tables are provided.
+        if (!entry.getValue().isEmpty()) {
+          pendingJobs.add(startWriteRename(entry.getKey(), entry.getValue(), c, window));
+        }
       }
     }
-  }
 
-  @FinishBundle
-  public void finishBundle(FinishBundleContext c) throws Exception {
-    DatasetService datasetService =
-        getDatasetService(c.getPipelineOptions().as(BigQueryOptions.class));
-    PendingJobManager jobManager = new PendingJobManager();
-    for (PendingJobData pendingJob : pendingJobs) {
-      jobManager.addPendingJob(
-          pendingJob.retryJob,
-          j -> {
-            try {
-              if (pendingJob.tableDestination.getTableDescription() != null) {
-                TableReference ref = pendingJob.tableDestination.getTableReference();
-                datasetService.patchTableDescription(
-                    ref.clone()
-                        .setTableId(BigQueryHelpers.stripPartitionDecorator(ref.getTableId())),
-                    pendingJob.tableDestination.getTableDescription());
+    @FinishBundle
+    public void finishBundle(FinishBundleContext c) throws Exception {
+      DatasetService datasetService =
+          getDatasetService(c.getPipelineOptions().as(BigQueryOptions.class));
+      PendingJobManager jobManager = new PendingJobManager();
+      for (PendingJobData pendingJob : pendingJobs) {
+        jobManager.addPendingJob(
+            pendingJob.retryJob,
+            j -> {
+              try {
+                if (pendingJob.tableDestination.getTableDescription() != null) {
+                  TableReference ref = pendingJob.tableDestination.getTableReference();
+                  datasetService.patchTableDescription(
+                      ref.clone()
+                          .setTableId(BigQueryHelpers.stripPartitionDecorator(ref.getTableId())),
+                      pendingJob.tableDestination.getTableDescription());
+                }
+                c.output(
+                    KV.of(pendingJob.tableDestination, pendingJob.tempTables),
+                    pendingJob.window.maxTimestamp(),
+                    pendingJob.window);
+                return null;
+              } catch (IOException | InterruptedException e) {
+                return e;
               }
-              c.output(
-                  pendingJob.tableDestination, pendingJob.window.maxTimestamp(), pendingJob.window);
-              removeTemporaryTables(datasetService, pendingJob.tempTables);
-              return null;
-            } catch (IOException | InterruptedException e) {
-              return e;
-            }
-          });
+            });
+      }
+      jobManager.waitForDone();
     }
-    jobManager.waitForDone();
-  }
 
-  private DatasetService getDatasetService(PipelineOptions pipelineOptions) throws IOException {
-    if (datasetService == null) {
-      datasetService = bqServices.getDatasetService(pipelineOptions.as(BigQueryOptions.class));
+    private DatasetService getDatasetService(PipelineOptions pipelineOptions) throws IOException {
+      if (datasetService == null) {
+        datasetService = bqServices.getDatasetService(pipelineOptions.as(BigQueryOptions.class));
+      }
+      return datasetService;
     }
-    return datasetService;
-  }
 
-  private PendingJobData startWriteRename(
-      TableDestination finalTableDestination,
-      Iterable<WriteTables.Result> tempTableNames,
-      ProcessContext c,
-      BoundedWindow window)
-      throws Exception {
-    // The pane may have advanced either here due to triggering or due to an upstream trigger. We
-    // check the upstream
-    // trigger to handle the case where an earlier pane triggered the single-partition path. If this
-    // happened, then the
-    // table will already exist so we want to append to the table.
-    WriteTables.@Nullable Result firstTempTable = Iterables.getFirst(tempTableNames, null);
-    boolean isFirstPane =
-        firstTempTable != null && firstTempTable.isFirstPane() && c.pane().isFirst();
-    WriteDisposition writeDisposition =
-        isFirstPane ? firstPaneWriteDisposition : WriteDisposition.WRITE_APPEND;
-    CreateDisposition createDisposition =
-        isFirstPane ? firstPaneCreateDisposition : CreateDisposition.CREATE_NEVER;
-    List<TableReference> tempTables =
-        StreamSupport.stream(tempTableNames.spliterator(), false)
-            .map(
-                result ->
-                    BigQueryHelpers.fromJsonString(result.getTableName(), TableReference.class))
-            .collect(Collectors.toList());
-
-    // Make sure each destination table gets a unique job id.
-    String jobIdPrefix =
-        BigQueryResourceNaming.createJobIdWithDestination(
-            c.sideInput(jobIdToken), finalTableDestination, -1, c.pane().getIndex());
-
-    BigQueryHelpers.PendingJob retryJob =
-        startCopy(
-            bqServices.getJobService(c.getPipelineOptions().as(BigQueryOptions.class)),
-            getDatasetService(c.getPipelineOptions().as(BigQueryOptions.class)),
-            jobIdPrefix,
-            finalTableDestination.getTableReference(),
-            tempTables,
-            writeDisposition,
-            createDisposition,
-            kmsKey,
-            loadJobProjectId);
-    return new PendingJobData(retryJob, finalTableDestination, tempTables, window);
-  }
+    private PendingJobData startWriteRename(
+        TableDestination finalTableDestination,
+        Iterable<WriteTables.Result> tempTableNames,
+        ProcessContext c,
+        BoundedWindow window)
+        throws Exception {
+      // The pane may have advanced either here due to triggering or due to an upstream trigger. We
+      // check the upstream
+      // trigger to handle the case where an earlier pane triggered the single-partition path. If
+      // this
+      // happened, then the
+      // table will already exist so we want to append to the table.
+      WriteTables.@Nullable Result firstTempTable = Iterables.getFirst(tempTableNames, null);
+      boolean isFirstPane =
+          firstTempTable != null && firstTempTable.isFirstPane() && c.pane().isFirst();
+      WriteDisposition writeDisposition =
+          isFirstPane ? firstPaneWriteDisposition : WriteDisposition.WRITE_APPEND;
+      CreateDisposition createDisposition =
+          isFirstPane ? firstPaneCreateDisposition : CreateDisposition.CREATE_NEVER;
+      List<TableReference> tempTables =
+          StreamSupport.stream(tempTableNames.spliterator(), false)
+              .map(
+                  result ->
+                      BigQueryHelpers.fromJsonString(result.getTableName(), TableReference.class))
+              .collect(Collectors.toList());
 
-  private BigQueryHelpers.PendingJob startCopy(
-      JobService jobService,
-      DatasetService datasetService,
-      String jobIdPrefix,
-      TableReference ref,
-      List<TableReference> tempTables,
-      WriteDisposition writeDisposition,
-      CreateDisposition createDisposition,
-      @Nullable String kmsKey,
-      @Nullable ValueProvider<String> loadJobProjectId) {
-    JobConfigurationTableCopy copyConfig =
-        new JobConfigurationTableCopy()
-            .setSourceTables(tempTables)
-            .setDestinationTable(ref)
-            .setWriteDisposition(writeDisposition.name())
-            .setCreateDisposition(createDisposition.name());
-    if (kmsKey != null) {
-      copyConfig.setDestinationEncryptionConfiguration(
-          new EncryptionConfiguration().setKmsKeyName(kmsKey));
+      List<String> tempTableStrings =
+          StreamSupport.stream(tempTableNames.spliterator(), false)
+              .map(Result::getTableName)
+              .collect(Collectors.toList());
+      ;

Review Comment:
   Why do we convert from TableReference to strings here then back to TableReference in `TempTableCleanupFn`? Might be worth adding a comment here to clarify



-- 
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] split write rename and temp table deletion into to dofns with a shuffle [beam]

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

   fixes #22920


-- 
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] split write rename and temp table deletion into to dofns with a shuffle [beam]

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


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