Automated rollback of commit 526ec17843b931d41e7d7ff9a8d68d6c90bce1ec.

*** Reason for rollback ***

b/119190539

*** Original change description ***

Add a new BEP event for the location of output from the `query`, `cquery`, and `aquery` commands. Add a new common query flag --upload_query_output_using_bep that controls whether these commands print their output to the console or whether they upload them to remote storage using BEP.

RELNOTES: The new --upload_query_output_using_bep query/cquery/aquery flag causes query outputs to be uploaded via BEP.
PiperOrigin-RevId: 220530561
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/NoBuildEvent.java b/src/main/java/com/google/devtools/build/lib/analysis/NoBuildEvent.java
index 12de98a..8009e32 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/NoBuildEvent.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/NoBuildEvent.java
@@ -22,7 +22,6 @@
 import com.google.devtools.build.lib.buildeventstream.GenericBuildEvent;
 import com.google.devtools.build.lib.buildeventstream.ProgressEvent;
 import com.google.devtools.build.lib.util.ProcessUtils;
-import java.util.ArrayList;
 import java.util.Collection;
 
 /** This event raised to indicate that no build will be happening for the given command. */
@@ -32,89 +31,35 @@
   private final Long startTimeMillis;
   private final boolean separateFinishedEvent;
   private final boolean showProgress;
-  private final ImmutableList<BuildEventId> additionalChildrenEvents;
 
-  private NoBuildEvent(
+  public NoBuildEvent(
       String command,
       Long startTimeMillis,
       boolean separateFinishedEvent,
       boolean showProgress,
-      String id,
-      ImmutableList<BuildEventId> additionalChildrenEvents) {
+      String id) {
     this.command = command;
     this.startTimeMillis = startTimeMillis;
     this.separateFinishedEvent = separateFinishedEvent;
     this.showProgress = showProgress;
     this.id = id;
-    this.additionalChildrenEvents = additionalChildrenEvents;
   }
 
-  public static Builder newBuilder() {
-    return new Builder();
+  public NoBuildEvent(String command, Long startTimeMillis, boolean separateFinishedEvent) {
+    this(command, startTimeMillis, separateFinishedEvent, false, null);
   }
 
-  /** Builder for {@link NoBuildEvent}. */
-  public static class Builder {
-    private String command = null;
-    private String id = null;
-    private boolean showProgress = false;
-    private Long startTimeMillis = null;
-    private boolean separateFinishedEvent = false;
-    private ArrayList<BuildEventId> additionalChildrenEvents = new ArrayList<>();
-
-    private Builder() {
-    }
-
-    public Builder setCommand(String command) {
-      this.command = command;
-      return this;
-    }
-
-    public Builder setId(String id) {
-      this.id = id;
-      return this;
-    }
-
-    public Builder setShowProgress(boolean showProgress) {
-      this.showProgress = showProgress;
-      return this;
-    }
-
-    public Builder setStartTimeMillis(long startTimeMillis) {
-      this.startTimeMillis = startTimeMillis;
-      return this;
-    }
-
-    public Builder setSeparateFinishedEvent(boolean separateFinishedEvent) {
-      this.separateFinishedEvent = separateFinishedEvent;
-      return this;
-    }
-
-    public Builder addAdditionalChildrenEvents(Iterable<BuildEventId> additionalChildrenEvents) {
-      additionalChildrenEvents.forEach(this.additionalChildrenEvents::add);
-      return this;
-    }
-
-    public NoBuildEvent build() {
-      return new NoBuildEvent(
-          command,
-          startTimeMillis,
-          separateFinishedEvent,
-          showProgress,
-          id,
-          ImmutableList.copyOf(additionalChildrenEvents));
-    }
+  public NoBuildEvent() {
+    this(null, null, false);
   }
 
   @Override
   public Collection<BuildEventId> getChildrenEvents() {
-    ImmutableList.Builder allChildrenEventsBuilder = ImmutableList.builder();
-    allChildrenEventsBuilder.add(ProgressEvent.INITIAL_PROGRESS_UPDATE);
-    allChildrenEventsBuilder.addAll(additionalChildrenEvents);
     if (separateFinishedEvent) {
-      allChildrenEventsBuilder.add(BuildEventId.buildFinished());
+      return ImmutableList.of(ProgressEvent.INITIAL_PROGRESS_UPDATE, BuildEventId.buildFinished());
+    } else {
+      return ImmutableList.of(ProgressEvent.INITIAL_PROGRESS_UPDATE);
     }
-    return allChildrenEventsBuilder.build();
   }
 
   @Override
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/NoBuildRequestFinishedEvent.java b/src/main/java/com/google/devtools/build/lib/analysis/NoBuildRequestFinishedEvent.java
index ac82e9d..f1294f2 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/NoBuildRequestFinishedEvent.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/NoBuildRequestFinishedEvent.java
@@ -17,10 +17,7 @@
 import com.google.devtools.build.lib.buildeventstream.BuildCompletingEvent;
 import com.google.devtools.build.lib.util.ExitCode;
 
-/**
- * A {@link BuildEvent} indicating that a request (that does not involve building) should be treated
- * as finished.
- */
+/** {@link BuildEvent} indicating that a request that does not involve building as finished. */
 public final class NoBuildRequestFinishedEvent extends BuildCompletingEvent {
   public NoBuildRequestFinishedEvent(ExitCode exitCode, long finishTimeMillis) {
     super(exitCode, finishTimeMillis);
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/commands/FetchCommand.java b/src/main/java/com/google/devtools/build/lib/bazel/commands/FetchCommand.java
index 5efe089..60fe650 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/commands/FetchCommand.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/commands/FetchCommand.java
@@ -116,13 +116,12 @@
 
     env.getReporter()
         .post(
-            NoBuildEvent.newBuilder()
-                .setCommand(env.getCommandName())
-                .setStartTimeMillis(env.getCommandStartTime())
-                .setSeparateFinishedEvent(true)
-                .setShowProgress(true)
-                .setId(env.getCommandId().toString())
-                .build());
+            new NoBuildEvent(
+                env.getCommandName(),
+                env.getCommandStartTime(),
+                true,
+                true,
+                env.getCommandId().toString()));
 
     // 2. Evaluate expression:
     QueryEvalResult queryEvalResult = null;
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/commands/SyncCommand.java b/src/main/java/com/google/devtools/build/lib/bazel/commands/SyncCommand.java
index e123e96..2630778 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/commands/SyncCommand.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/commands/SyncCommand.java
@@ -75,13 +75,12 @@
     try {
       env.getReporter()
           .post(
-              NoBuildEvent.newBuilder()
-                  .setCommand(env.getCommandName())
-                  .setStartTimeMillis(env.getCommandStartTime())
-                  .setSeparateFinishedEvent(true)
-                  .setShowProgress(true)
-                  .setId(env.getCommandId().toString())
-                  .build());
+              new NoBuildEvent(
+                  env.getCommandName(),
+                  env.getCommandStartTime(),
+                  true,
+                  true,
+                  env.getCommandId().toString()));
       env.setupPackageCache(options, env.getRuntime().getDefaultsPackageContent());
       SkyframeExecutor skyframeExecutor = env.getSkyframeExecutor();
       skyframeExecutor.injectExtraPrecomputedValues(
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventstream/BuildEventId.java b/src/main/java/com/google/devtools/build/lib/buildeventstream/BuildEventId.java
index 27a4cfb..f5848ce 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventstream/BuildEventId.java
+++ b/src/main/java/com/google/devtools/build/lib/buildeventstream/BuildEventId.java
@@ -313,12 +313,4 @@
                 BuildEventStreamProtos.BuildEventId.BuildMetricsId.getDefaultInstance())
             .build());
   }
-
-  public static BuildEventId queryOutput() {
-    return new BuildEventId(
-        BuildEventStreamProtos.BuildEventId.newBuilder()
-            .setQueryOutput(
-                BuildEventStreamProtos.BuildEventId.QueryOutputId.getDefaultInstance())
-            .build());
-  }
 }
diff --git a/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto b/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto
index fc7779e..5941665 100644
--- a/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto
+++ b/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto
@@ -193,11 +193,6 @@
   message BuildMetricsId {
   }
 
-  // Identifier of an event providing information about the location of
-  // query/cquery/acquery command output.
-  message QueryOutputId {
-  }
-
   oneof id {
     UnknownBuildEventId unknown = 1;
     ProgressId progress = 2;
@@ -221,7 +216,6 @@
     BuildFinishedId build_finished = 9;
     BuildToolLogsId build_tool_logs = 20;
     BuildMetricsId build_metrics = 22;
-    QueryOutputId query_output = 23;
   }
 }
 
@@ -671,30 +665,6 @@
   repeated File log = 1;
 }
 
-// For 'query', 'cquery', and 'aquery' commands, an Event that describes where
-// the output was written to.
-message QueryOutput {
-  // Marker message type to indicate that Bazel printed the query output to
-  // stdout on the console. Note that this also implies that the output is in a
-  // Progress event.
-  message OutputPrintedToConsole {
-  }
-
-  // Marker message type to indicate that the query output upload didn't occur
-  // for some reason. Either there was an error, or the appropriate flags to
-  // enable remote file uploading weren't set,
-  message UploadFailed {
-  }
-
-  oneof payload {
-    OutputPrintedToConsole output_printed_to_console = 1;
-    // If this field is set, 'query_output_file.uri' will be the URI of where
-    // the query output was uploaded.
-    File query_output_file = 2;
-    UploadFailed upload_failed = 3;
-  };
-}
-
 // Message describing a build event. Events will have an identifier that
 // is unique within a given build invocation; they also announce follow-up
 // events as children. More details, which are specific to the kind of event
@@ -725,6 +695,5 @@
     BuildFinished finished = 14;
     BuildToolLogs build_tool_logs = 23;
     BuildMetrics build_metrics = 24;
-    QueryOutput query_output = 25;
   };
 }
diff --git a/src/main/java/com/google/devtools/build/lib/buildtool/BuildTool.java b/src/main/java/com/google/devtools/build/lib/buildtool/BuildTool.java
index d01e1af..dd37a7f 100644
--- a/src/main/java/com/google/devtools/build/lib/buildtool/BuildTool.java
+++ b/src/main/java/com/google/devtools/build/lib/buildtool/BuildTool.java
@@ -117,10 +117,7 @@
     boolean catastrophe = false;
     try {
       try (SilentCloseable c = Profiler.instance().profile("BuildStartingEvent")) {
-        env.getEventBus().post(new BuildStartingEvent(
-            env,
-            request,
-            getAdditionalChildrenEventsForBuildStartingEvent()));
+        env.getEventBus().post(new BuildStartingEvent(env, request));
       }
       logger.info("Build identifier: " + request.getId());
 
@@ -221,10 +218,6 @@
           PostAnalysisQueryCommandLineException {
   }
 
-  protected ImmutableList<BuildEventId> getAdditionalChildrenEventsForBuildStartingEvent() {
-    return ImmutableList.of();
-  }
-
   private void reportExceptionError(Exception e) {
     if (e.getMessage() != null) {
       getReporter().handle(Event.error(e.getMessage()));
diff --git a/src/main/java/com/google/devtools/build/lib/buildtool/PostAnalysisQueryBuildTool.java b/src/main/java/com/google/devtools/build/lib/buildtool/PostAnalysisQueryBuildTool.java
index 659f524..66f205d 100644
--- a/src/main/java/com/google/devtools/build/lib/buildtool/PostAnalysisQueryBuildTool.java
+++ b/src/main/java/com/google/devtools/build/lib/buildtool/PostAnalysisQueryBuildTool.java
@@ -13,11 +13,9 @@
 // limitations under the License.
 package com.google.devtools.build.lib.buildtool;
 
-import com.google.common.collect.ImmutableList;
 import com.google.devtools.build.lib.analysis.AnalysisResult;
 import com.google.devtools.build.lib.analysis.ViewCreationFailedException;
 import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
-import com.google.devtools.build.lib.buildeventstream.BuildEventId;
 import com.google.devtools.build.lib.events.Event;
 import com.google.devtools.build.lib.query2.NamedThreadSafeOutputFormatterCallback;
 import com.google.devtools.build.lib.query2.PostAnalysisQueryEnvironment;
@@ -26,7 +24,6 @@
 import com.google.devtools.build.lib.query2.engine.QueryException;
 import com.google.devtools.build.lib.query2.engine.QueryExpression;
 import com.google.devtools.build.lib.runtime.CommandEnvironment;
-import com.google.devtools.build.lib.runtime.QueryBEPHelper;
 import com.google.devtools.build.lib.skyframe.SkyframeExecutorWrappingWalkableGraph;
 import com.google.devtools.build.skyframe.WalkableGraph;
 import java.io.IOException;
@@ -82,11 +79,6 @@
       TopLevelConfigurations topLevelConfigurations,
       WalkableGraph walkableGraph);
 
-  @Override
-  protected ImmutableList<BuildEventId> getAdditionalChildrenEventsForBuildStartingEvent() {
-    return ImmutableList.of(QueryBEPHelper.getBuildEventIdOfQueryOutputEvent());
-  }
-
   private void doPostAnalysisQuery(
       BuildRequest request,
       BuildConfiguration hostConfiguration,
@@ -95,38 +87,36 @@
       throws InterruptedException, QueryException, IOException {
     WalkableGraph walkableGraph =
         SkyframeExecutorWrappingWalkableGraph.of(env.getSkyframeExecutor());
+
     PostAnalysisQueryEnvironment<T> postAnalysisQueryEnvironment =
         getQueryEnvironment(request, hostConfiguration, topLevelConfigurations, walkableGraph);
-    try (QueryBEPHelper queryBepHelper =
-        QueryBEPHelper.create(env, postAnalysisQueryEnvironment.getCommonQueryOptions())) {
-      Iterable<NamedThreadSafeOutputFormatterCallback<T>> callbacks =
-          postAnalysisQueryEnvironment.getDefaultOutputFormatters(
-              postAnalysisQueryEnvironment.getAccessor(),
-              env.getReporter(),
-              queryBepHelper.getOutputStreamForQueryOutput(),
-              env.getSkyframeExecutor(),
-              hostConfiguration,
-              runtime.getRuleClassProvider().getTrimmingTransitionFactory(),
-              env.getPackageManager());
-      String outputFormat = postAnalysisQueryEnvironment.getOutputFormat();
-      NamedThreadSafeOutputFormatterCallback<T> callback =
-          NamedThreadSafeOutputFormatterCallback.selectCallback(outputFormat, callbacks);
-      if (callback == null) {
-        env.getReporter()
-            .handle(
-                Event.error(
-                    String.format(
-                        "Invalid output format '%s'. Valid values are: %s",
-                        outputFormat,
-                        NamedThreadSafeOutputFormatterCallback.callbackNames(callbacks))));
-        return;
-      }
-      QueryEvalResult result =
-          postAnalysisQueryEnvironment.evaluateQuery(queryExpression, callback);
-      if (result.isEmpty()) {
-        env.getReporter().handle(Event.info("Empty query results"));
-      }
-      queryBepHelper.afterQueryOutputIsWritten();
+
+    Iterable<NamedThreadSafeOutputFormatterCallback<T>> callbacks =
+        postAnalysisQueryEnvironment.getDefaultOutputFormatters(
+            postAnalysisQueryEnvironment.getAccessor(),
+            env.getReporter(),
+            env.getReporter().getOutErr().getOutputStream(),
+            env.getSkyframeExecutor(),
+            hostConfiguration,
+            runtime.getRuleClassProvider().getTrimmingTransitionFactory(),
+            env.getPackageManager());
+    String outputFormat = postAnalysisQueryEnvironment.getOutputFormat();
+    NamedThreadSafeOutputFormatterCallback<T> callback =
+        NamedThreadSafeOutputFormatterCallback.selectCallback(outputFormat, callbacks);
+    if (callback == null) {
+      env.getReporter()
+          .handle(
+              Event.error(
+                  String.format(
+                      "Invalid output format '%s'. Valid values are: %s",
+                      outputFormat,
+                      NamedThreadSafeOutputFormatterCallback.callbackNames(callbacks))));
+      return;
+    }
+    QueryEvalResult result =
+        postAnalysisQueryEnvironment.evaluateQuery(queryExpression, callback);
+    if (result.isEmpty()) {
+      env.getReporter().handle(Event.info("Empty query results"));
     }
   }
 
diff --git a/src/main/java/com/google/devtools/build/lib/buildtool/buildevent/BuildStartingEvent.java b/src/main/java/com/google/devtools/build/lib/buildtool/buildevent/BuildStartingEvent.java
index c5d4d2c..0601782 100644
--- a/src/main/java/com/google/devtools/build/lib/buildtool/buildevent/BuildStartingEvent.java
+++ b/src/main/java/com/google/devtools/build/lib/buildtool/buildevent/BuildStartingEvent.java
@@ -37,7 +37,6 @@
   private final BuildRequest request;
   private final String workspace;
   private final String pwd;
-  private final ImmutableList<BuildEventId> additionalChildEvents;
 
   /**
    * Construct the BuildStartingEvent
@@ -45,10 +44,7 @@
    * @param request the build request.
    * @param env the environment of the request invocation.
    */
-  public BuildStartingEvent(
-      CommandEnvironment env,
-      BuildRequest request,
-      ImmutableList<BuildEventId> additionalChildEvents) {
+  public BuildStartingEvent(CommandEnvironment env, BuildRequest request) {
     this.request = request;
     if (env != null) {
       this.outputFileSystem = env.determineOutputFileSystem();
@@ -63,7 +59,6 @@
       this.pwd = null;
       this.outputFileSystem = null;
     }
-    this.additionalChildEvents = additionalChildEvents;
   }
 
   /**
@@ -87,18 +82,16 @@
 
   @Override
   public Collection<BuildEventId> getChildrenEvents() {
-    return ImmutableList.<BuildEventId>builder()
-        .add(ProgressEvent.INITIAL_PROGRESS_UPDATE)
-        .add(BuildEventId.unstructuredCommandlineId())
-        .add(BuildEventId.structuredCommandlineId(CommandLineEvent.OriginalCommandLineEvent.LABEL))
-        .add(BuildEventId.structuredCommandlineId(CommandLineEvent.CanonicalCommandLineEvent.LABEL))
-        .add(BuildEventId.structuredCommandlineId(CommandLineEvent.ToolCommandLineEvent.LABEL))
-        .add(BuildEventId.optionsParsedId())
-        .add(BuildEventId.workspaceStatusId())
-        .add(BuildEventId.targetPatternExpanded(request.getTargets()))
-        .add(BuildEventId.buildFinished())
-        .addAll(additionalChildEvents)
-        .build();
+    return ImmutableList.of(
+        ProgressEvent.INITIAL_PROGRESS_UPDATE,
+        BuildEventId.unstructuredCommandlineId(),
+        BuildEventId.structuredCommandlineId(CommandLineEvent.OriginalCommandLineEvent.LABEL),
+        BuildEventId.structuredCommandlineId(CommandLineEvent.CanonicalCommandLineEvent.LABEL),
+        BuildEventId.structuredCommandlineId(CommandLineEvent.ToolCommandLineEvent.LABEL),
+        BuildEventId.optionsParsedId(),
+        BuildEventId.workspaceStatusId(),
+        BuildEventId.targetPatternExpanded(request.getTargets()),
+        BuildEventId.buildFinished());
   }
 
   @Override
diff --git a/src/main/java/com/google/devtools/build/lib/query2/ActionGraphQueryEnvironment.java b/src/main/java/com/google/devtools/build/lib/query2/ActionGraphQueryEnvironment.java
index f3a4cac..fb42478 100644
--- a/src/main/java/com/google/devtools/build/lib/query2/ActionGraphQueryEnvironment.java
+++ b/src/main/java/com/google/devtools/build/lib/query2/ActionGraphQueryEnvironment.java
@@ -13,7 +13,6 @@
 // limitations under the License.
 package com.google.devtools.build.lib.query2;
 
-import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.util.concurrent.AsyncFunction;
@@ -75,32 +74,7 @@
       String parserPrefix,
       PathPackageLocator pkgPath,
       Supplier<WalkableGraph> walkableGraphSupplier,
-      AqueryOptions aqueryOptions) {
-    this(
-        keepGoing,
-        eventHandler,
-        extraFunctions,
-        topLevelConfigurations,
-        hostConfiguration,
-        parserPrefix,
-        pkgPath,
-        walkableGraphSupplier,
-        aqueryOptions.toSettings(),
-        aqueryOptions);
-  }
-
-  @VisibleForTesting
-  public ActionGraphQueryEnvironment(
-      boolean keepGoing,
-      ExtendedEventHandler eventHandler,
-      Iterable<QueryFunction> extraFunctions,
-      TopLevelConfigurations topLevelConfigurations,
-      BuildConfiguration hostConfiguration,
-      String parserPrefix,
-      PathPackageLocator pkgPath,
-      Supplier<WalkableGraph> walkableGraphSupplier,
-      Set<Setting> settings,
-      AqueryOptions aqueryOptions) {
+      Set<Setting> settings) {
     super(
         keepGoing,
         eventHandler,
@@ -110,8 +84,7 @@
         parserPrefix,
         pkgPath,
         walkableGraphSupplier,
-        settings,
-        aqueryOptions);
+        settings);
     this.configuredTargetKeyExtractor =
         configuredTargetValue -> {
           try {
@@ -129,6 +102,28 @@
     this.accessor =
         new ConfiguredTargetValueAccessor(
             walkableGraphSupplier.get(), this.configuredTargetKeyExtractor);
+  }
+
+  public ActionGraphQueryEnvironment(
+      boolean keepGoing,
+      ExtendedEventHandler eventHandler,
+      Iterable<QueryFunction> extraFunctions,
+      TopLevelConfigurations topLevelConfigurations,
+      BuildConfiguration hostConfiguration,
+      String parserPrefix,
+      PathPackageLocator pkgPath,
+      Supplier<WalkableGraph> walkableGraphSupplier,
+      AqueryOptions aqueryOptions) {
+    this(
+        keepGoing,
+        eventHandler,
+        extraFunctions,
+        topLevelConfigurations,
+        hostConfiguration,
+        parserPrefix,
+        pkgPath,
+        walkableGraphSupplier,
+        aqueryOptions.toSettings());
     this.aqueryOptions = aqueryOptions;
   }
 
diff --git a/src/main/java/com/google/devtools/build/lib/query2/CommonQueryOptions.java b/src/main/java/com/google/devtools/build/lib/query2/CommonQueryOptions.java
index 4adb1f6..a87719f 100644
--- a/src/main/java/com/google/devtools/build/lib/query2/CommonQueryOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/query2/CommonQueryOptions.java
@@ -92,17 +92,6 @@
     return settings;
   }
 
-  @Option(
-      name = "upload_query_output_using_bep",
-      defaultValue = "false",
-      documentationCategory = OptionDocumentationCategory.QUERY,
-      effectTags = {OptionEffectTag.AFFECTS_OUTPUTS},
-      help = "If this flag is set to 'true' and other relevant BEP flags are set as appropriate, "
-          + "query output will not be written to stdout and will instead be uploaded to a remote "
-          + "file, and the location of this file will be reported in the BEP."
-  )
-  public boolean uploadQueryOutputUsingBEP;
-
   ///////////////////////////////////////////////////////////
   // PROTO OUTPUT FORMATTER OPTIONS                        //
   ///////////////////////////////////////////////////////////
diff --git a/src/main/java/com/google/devtools/build/lib/query2/ConfiguredTargetQueryEnvironment.java b/src/main/java/com/google/devtools/build/lib/query2/ConfiguredTargetQueryEnvironment.java
index a08ff97..231f0df 100644
--- a/src/main/java/com/google/devtools/build/lib/query2/ConfiguredTargetQueryEnvironment.java
+++ b/src/main/java/com/google/devtools/build/lib/query2/ConfiguredTargetQueryEnvironment.java
@@ -13,7 +13,6 @@
 // limitations under the License.
 package com.google.devtools.build.lib.query2;
 
-import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.util.concurrent.AsyncFunction;
@@ -91,32 +90,7 @@
       String parserPrefix,
       PathPackageLocator pkgPath,
       Supplier<WalkableGraph> walkableGraphSupplier,
-      CqueryOptions cqueryOptions) {
-    this(
-        keepGoing,
-        eventHandler,
-        extraFunctions,
-        topLevelConfigurations,
-        hostConfiguration,
-        parserPrefix,
-        pkgPath,
-        walkableGraphSupplier,
-        cqueryOptions.toSettings(),
-        cqueryOptions);
-  }
-
-  @VisibleForTesting
-  public ConfiguredTargetQueryEnvironment(
-      boolean keepGoing,
-      ExtendedEventHandler eventHandler,
-      Iterable<QueryFunction> extraFunctions,
-      TopLevelConfigurations topLevelConfigurations,
-      BuildConfiguration hostConfiguration,
-      String parserPrefix,
-      PathPackageLocator pkgPath,
-      Supplier<WalkableGraph> walkableGraphSupplier,
-      Set<Setting> settings,
-      CqueryOptions cqueryOptions) {
+      Set<Setting> settings) {
     super(
         keepGoing,
         eventHandler,
@@ -126,8 +100,7 @@
         parserPrefix,
         pkgPath,
         walkableGraphSupplier,
-        settings,
-        cqueryOptions);
+        settings);
     this.accessor = new ConfiguredTargetAccessor(walkableGraphSupplier.get(), this);
     this.configuredTargetKeyExtractor =
         element -> {
@@ -142,6 +115,28 @@
             throw new IllegalStateException("Interruption unexpected in configured query", e);
           }
         };
+  }
+
+  public ConfiguredTargetQueryEnvironment(
+      boolean keepGoing,
+      ExtendedEventHandler eventHandler,
+      Iterable<QueryFunction> extraFunctions,
+      TopLevelConfigurations topLevelConfigurations,
+      BuildConfiguration hostConfiguration,
+      String parserPrefix,
+      PathPackageLocator pkgPath,
+      Supplier<WalkableGraph> walkableGraphSupplier,
+      CqueryOptions cqueryOptions) {
+    this(
+        keepGoing,
+        eventHandler,
+        extraFunctions,
+        topLevelConfigurations,
+        hostConfiguration,
+        parserPrefix,
+        pkgPath,
+        walkableGraphSupplier,
+        cqueryOptions.toSettings());
     this.cqueryOptions = cqueryOptions;
   }
 
diff --git a/src/main/java/com/google/devtools/build/lib/query2/PostAnalysisQueryEnvironment.java b/src/main/java/com/google/devtools/build/lib/query2/PostAnalysisQueryEnvironment.java
index 5be6a7a..256041e 100644
--- a/src/main/java/com/google/devtools/build/lib/query2/PostAnalysisQueryEnvironment.java
+++ b/src/main/java/com/google/devtools/build/lib/query2/PostAnalysisQueryEnvironment.java
@@ -96,7 +96,6 @@
   private final String parserPrefix;
   private final PathPackageLocator pkgPath;
   private final Supplier<WalkableGraph> walkableGraphSupplier;
-  private final CommonQueryOptions commonQueryOptions;
   protected WalkableGraph graph;
 
   private static final Function<SkyKey, ConfiguredTargetKey> SKYKEY_TO_CTKEY =
@@ -127,15 +126,13 @@
       String parserPrefix,
       PathPackageLocator pkgPath,
       Supplier<WalkableGraph> walkableGraphSupplier,
-      Set<Setting> settings,
-      CommonQueryOptions commonQueryOptions) {
+      Set<Setting> settings) {
     super(keepGoing, true, Rule.ALL_LABELS, eventHandler, settings, extraFunctions);
     this.topLevelConfigurations = topLevelConfigurations;
     this.hostConfiguration = hostConfiguration;
     this.parserPrefix = parserPrefix;
     this.pkgPath = pkgPath;
     this.walkableGraphSupplier = walkableGraphSupplier;
-    this.commonQueryOptions = commonQueryOptions;
   }
 
   public abstract ImmutableList<NamedThreadSafeOutputFormatterCallback<T>>
@@ -192,10 +189,6 @@
     return hostConfiguration;
   }
 
-  public CommonQueryOptions getCommonQueryOptions() {
-    return commonQueryOptions;
-  }
-
   // TODO(bazel-team): It's weird that this untemplated function exists. Fix? Or don't implement?
   @Override
   public Target getTarget(Label label) throws TargetNotFoundException, InterruptedException {
diff --git a/src/main/java/com/google/devtools/build/lib/query2/QueryOutputEvent.java b/src/main/java/com/google/devtools/build/lib/query2/QueryOutputEvent.java
deleted file mode 100644
index e415084..0000000
--- a/src/main/java/com/google/devtools/build/lib/query2/QueryOutputEvent.java
+++ /dev/null
@@ -1,126 +0,0 @@
-// Copyright 2018 The Bazel Authors. All rights reserved.
-//
-// Licensed 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 com.google.devtools.build.lib.query2;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ImmutableList;
-import com.google.devtools.build.lib.buildeventstream.BuildEvent;
-import com.google.devtools.build.lib.buildeventstream.BuildEvent.LocalFile.LocalFileType;
-import com.google.devtools.build.lib.buildeventstream.BuildEventContext;
-import com.google.devtools.build.lib.buildeventstream.BuildEventId;
-import com.google.devtools.build.lib.buildeventstream.BuildEventStreamProtos;
-import com.google.devtools.build.lib.buildeventstream.GenericBuildEvent;
-import com.google.devtools.build.lib.vfs.Path;
-import java.util.Collection;
-
-/**
- * A {@link BuildEvent} reporting the location of output from `query`, `cquery`, and `aquery`
- * commands.
- */
-public abstract class QueryOutputEvent implements BuildEvent {
-  public static final BuildEventId BUILD_EVENT_ID = BuildEventId.queryOutput();
-
-  private QueryOutputEvent() {
-  }
-
-  public static QueryOutputEvent forOutputWrittenToStdout() {
-    return new QueryOutputPrintedToConsoleEvent();
-  }
-
-  public static QueryOutputEvent forOutputWrittenToFile(
-      String commandName, Path queryOutputFilePath) {
-    return new QueryOutputWrittenToFileEvent(commandName, queryOutputFilePath);
-  }
-
-  @Override
-  public BuildEventId getEventId() {
-    return BUILD_EVENT_ID;
-  }
-
-  @Override
-  public Collection<BuildEventId> getChildrenEvents() {
-    return ImmutableList.of();
-  }
-
-  @VisibleForTesting
-  public abstract boolean equalsForTesting(QueryOutputEvent other);
-
-  private static class QueryOutputPrintedToConsoleEvent extends QueryOutputEvent {
-    @Override
-    public BuildEventStreamProtos.BuildEvent asStreamProto(BuildEventContext context) {
-      BuildEventStreamProtos.QueryOutput queryOutput =
-          BuildEventStreamProtos.QueryOutput.newBuilder()
-              .setOutputPrintedToConsole(
-                  BuildEventStreamProtos.QueryOutput.OutputPrintedToConsole.getDefaultInstance())
-              .build();
-      return GenericBuildEvent.protoChaining(this).setQueryOutput(queryOutput).build();
-    }
-
-    @Override
-    public boolean equalsForTesting(QueryOutputEvent other) {
-      return other instanceof QueryOutputPrintedToConsoleEvent;
-    }
-  }
-
-  private static class QueryOutputWrittenToFileEvent extends QueryOutputEvent {
-    private final String commandName;
-    private final Path queryOutputFilePath;
-
-    private QueryOutputWrittenToFileEvent(String commandName, Path queryOutputFilePath) {
-      this.commandName = commandName;
-      this.queryOutputFilePath = queryOutputFilePath;
-    }
-
-    @Override
-    public BuildEventStreamProtos.BuildEvent asStreamProto(BuildEventContext context) {
-      String uri = context.pathConverter().apply(queryOutputFilePath);
-      BuildEventStreamProtos.QueryOutput.Builder queryOutputBuilder =
-          BuildEventStreamProtos.QueryOutput.newBuilder();
-      if (uri != null) {
-        queryOutputBuilder.setQueryOutputFile(
-            BuildEventStreamProtos.File.newBuilder()
-                .setName(commandName + " output")
-                .setUri(uri)
-                .build());
-      } else {
-        queryOutputBuilder.setUploadFailed(
-            BuildEventStreamProtos.QueryOutput.UploadFailed.getDefaultInstance());
-      }
-
-      return GenericBuildEvent.protoChaining(this)
-          .setQueryOutput(queryOutputBuilder.build())
-          .build();
-    }
-
-    @Override
-    public Collection<LocalFile> referencedLocalFiles() {
-      // TODO(nharmata): Introduce a new LocalFileType that has a more appropriate retention policy.
-      // TODO(nharmata): Introduce a feature to LocalFile that causes the file gets deleted after
-      // the upload succeeds.
-      return ImmutableList.of(new LocalFile(queryOutputFilePath, LocalFileType.OUTPUT));
-    }
-
-    @Override
-    public boolean equalsForTesting(QueryOutputEvent other) {
-      if (!(other instanceof QueryOutputWrittenToFileEvent)) {
-        return false;
-      }
-      QueryOutputWrittenToFileEvent otherQueryOutputWrittenToFileEvent =
-          (QueryOutputWrittenToFileEvent) other;
-      return this.commandName.equals(otherQueryOutputWrittenToFileEvent.commandName)
-          && this.queryOutputFilePath.equals(
-              otherQueryOutputWrittenToFileEvent.queryOutputFilePath);
-    }
-  }
-}
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/QueryBEPHelper.java b/src/main/java/com/google/devtools/build/lib/runtime/QueryBEPHelper.java
deleted file mode 100644
index 4287432..0000000
--- a/src/main/java/com/google/devtools/build/lib/runtime/QueryBEPHelper.java
+++ /dev/null
@@ -1,193 +0,0 @@
-// Copyright 2018 The Bazel Authors. All rights reserved.
-//
-// Licensed 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 com.google.devtools.build.lib.runtime;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ImmutableList;
-import com.google.common.eventbus.EventBus;
-import com.google.devtools.build.lib.analysis.NoBuildEvent;
-import com.google.devtools.build.lib.analysis.NoBuildRequestFinishedEvent;
-import com.google.devtools.build.lib.buildeventstream.BuildEventId;
-import com.google.devtools.build.lib.query2.CommonQueryOptions;
-import com.google.devtools.build.lib.query2.QueryOutputEvent;
-import com.google.devtools.build.lib.util.ExitCode;
-import com.google.devtools.build.lib.vfs.Path;
-import java.io.IOException;
-import java.io.OutputStream;
-
-/** Helper for interfacing with the BEP from the `query`, `cquery`, and `aquery` commands. */
-public interface QueryBEPHelper extends AutoCloseable {
-  OutputStream getOutputStreamForQueryOutput();
-
-  void afterQueryOutputIsWritten();
-
-  @Override
-  void close() throws IOException;
-
-  static BuildEventId getBuildEventIdOfQueryOutputEvent() {
-    return QueryOutputEvent.BUILD_EVENT_ID;
-  }
-
-  static QueryBEPHelper create(
-      CommandEnvironment env, CommonQueryOptions commonQueryOptions) throws IOException {
-    if (commonQueryOptions.uploadQueryOutputUsingBEP) {
-      Path queryOutputFilePath = env.getOutputBase().getChild("tmp_query_output");
-      OutputStream queryOutputStream = queryOutputFilePath.getOutputStream();
-      return new QueryBEPHelperForUploadingQueryOutputUsingBEP(
-          env.getCommandName(),
-          env.getEventBus(),
-          queryOutputFilePath,
-          queryOutputStream);
-    } else {
-      return new QueryBEPHelperForStdoutOutput(
-          env.getEventBus(),
-          env.getReporter().getOutErr().getOutputStream());
-    }
-  }
-
-  static QueryBEPHelperForNonBuildingCommand createForNonBuildingCommand(
-      CommandEnvironment env, CommonQueryOptions commonQueryOptions) throws  IOException {
-    QueryBEPHelper delegate = create(env, commonQueryOptions);
-    return new QueryBEPHelperForNonBuildingCommand(env, delegate);
-  }
-
-  @VisibleForTesting
-  static QueryBEPHelper createForUnitTests(
-      String commandName,
-      EventBus eventBus,
-      CommonQueryOptions commonQueryOptions,
-      Path queryOutputFilePath,
-      OutputStream stdoutOutputStream) throws IOException {
-    if (commonQueryOptions.uploadQueryOutputUsingBEP) {
-      OutputStream queryOutputStream = queryOutputFilePath.getOutputStream();
-      return new QueryBEPHelperForUploadingQueryOutputUsingBEP(
-          commandName,
-          eventBus,
-          queryOutputFilePath,
-          queryOutputStream);
-    } else {
-      return new QueryBEPHelperForStdoutOutput(eventBus, stdoutOutputStream);
-    }
-  }
-
-  /**
-   * Implementation of {@link QueryBEPHelper} for the situation where we want to write query output
-   * to stdout on the console.
-   */
-  class QueryBEPHelperForStdoutOutput implements QueryBEPHelper {
-    private final EventBus eventBus;
-    private final OutputStream stdoutOutputStream;
-
-    private QueryBEPHelperForStdoutOutput(EventBus eventBus, OutputStream stdoutOutputStream) {
-      this.eventBus = eventBus;
-      this.stdoutOutputStream = stdoutOutputStream;
-    }
-
-    @Override
-    public OutputStream getOutputStreamForQueryOutput() {
-      return stdoutOutputStream;
-    }
-
-    @Override
-    public void afterQueryOutputIsWritten() {
-      eventBus.post(QueryOutputEvent.forOutputWrittenToStdout());
-    }
-
-    @Override
-    public void close() {
-      // Nothing to do here. The CommandEnvironment owns the stdout OutputStream.
-    }
-  }
-
-  /**
-   * Implementation of {@link QueryBEPHelper} for the situation where we want to write query output
-   * to a temporary file and then upload that temporary file via BEP.
-   */
-  class QueryBEPHelperForUploadingQueryOutputUsingBEP implements QueryBEPHelper {
-    private final String commandName;
-    private final EventBus eventBus;
-    private final Path queryOutputFilePath;
-    private final OutputStream queryOutputStream;
-
-    private QueryBEPHelperForUploadingQueryOutputUsingBEP(
-        String commandName,
-        EventBus eventBus,
-        Path queryOutputFilePath,
-        OutputStream queryOutputStream) {
-      this.commandName = commandName;
-      this.eventBus = eventBus;
-      this.queryOutputFilePath = queryOutputFilePath;
-      this.queryOutputStream = queryOutputStream;
-    }
-
-    @Override
-    public OutputStream getOutputStreamForQueryOutput() {
-      return queryOutputStream;
-    }
-
-    @Override
-    public void afterQueryOutputIsWritten() {
-      eventBus.post(QueryOutputEvent.forOutputWrittenToFile(commandName, queryOutputFilePath));
-    }
-
-    @Override
-    public void close() throws IOException {
-      queryOutputStream.close();
-    }
-  }
-
-  /** Implementation of {@link QueryBEPHelper} for commands that don't "build". */
-  class QueryBEPHelperForNonBuildingCommand implements QueryBEPHelper {
-    private final CommandEnvironment env;
-    private final QueryBEPHelper delegate;
-
-    private QueryBEPHelperForNonBuildingCommand(CommandEnvironment env, QueryBEPHelper delegate) {
-      this.env = env;
-      this.delegate = delegate;
-    }
-
-    public void beforeQueryOutputIsWritten() {
-      env.getEventBus()
-          .post(
-              NoBuildEvent.newBuilder()
-                  .setCommand(env.getCommandName())
-                  .setStartTimeMillis(env.getCommandStartTime())
-                  .addAdditionalChildrenEvents(
-                      ImmutableList.of(getBuildEventIdOfQueryOutputEvent()))
-                  .setSeparateFinishedEvent(true)
-                  .build());
-    }
-
-    @Override
-    public OutputStream getOutputStreamForQueryOutput() {
-      return delegate.getOutputStreamForQueryOutput();
-    }
-
-    @Override
-    public void afterQueryOutputIsWritten() {
-      delegate.afterQueryOutputIsWritten();
-    }
-
-    public void afterExitCodeIsDetermined(ExitCode exitCode) {
-      env.getEventBus().post(
-          new NoBuildRequestFinishedEvent(
-              exitCode, env.getRuntime().getClock().currentTimeMillis()));
-    }
-
-    @Override
-    public void close() throws IOException {
-      delegate.close();
-    }
-  }
-}
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/commands/CleanCommand.java b/src/main/java/com/google/devtools/build/lib/runtime/commands/CleanCommand.java
index 6a43a89..8b42274 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/commands/CleanCommand.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/commands/CleanCommand.java
@@ -127,7 +127,7 @@
   public BlazeCommandResult exec(CommandEnvironment env, OptionsParsingResult options) {
     Options cleanOptions = options.getOptions(Options.class);
     boolean async = cleanOptions.async;
-    env.getEventBus().post(NoBuildEvent.newBuilder().build());
+    env.getEventBus().post(new NoBuildEvent());
 
     // TODO(dmarting): Deactivate expunge_async on non-Linux platform until we completely fix it
     // for non-Linux platforms (https://github.com/bazelbuild/bazel/issues/1906).
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/commands/HelpCommand.java b/src/main/java/com/google/devtools/build/lib/runtime/commands/HelpCommand.java
index a928068..16d2d75 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/commands/HelpCommand.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/commands/HelpCommand.java
@@ -122,7 +122,7 @@
 
   @Override
   public BlazeCommandResult exec(CommandEnvironment env, OptionsParsingResult options) {
-    env.getEventBus().post(NoBuildEvent.newBuilder().build());
+    env.getEventBus().post(new NoBuildEvent());
 
     BlazeRuntime runtime = env.getRuntime();
     OutErr outErr = env.getReporter().getOutErr();
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/commands/InfoCommand.java b/src/main/java/com/google/devtools/build/lib/runtime/commands/InfoCommand.java
index cca8a11..a448723 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/commands/InfoCommand.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/commands/InfoCommand.java
@@ -167,7 +167,7 @@
       }
 
       String key = residue.size() == 1 ? residue.get(0) : null;
-      env.getEventBus().post(NoBuildEvent.newBuilder().build());
+      env.getEventBus().post(new NoBuildEvent());
       if (key != null) { // print just the value for the specified key:
         byte[] value;
         if (items.containsKey(key)) {
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/commands/LicenseCommand.java b/src/main/java/com/google/devtools/build/lib/runtime/commands/LicenseCommand.java
index ce8b2b6..d181bd2 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/commands/LicenseCommand.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/commands/LicenseCommand.java
@@ -51,7 +51,7 @@
 
   @Override
   public BlazeCommandResult exec(CommandEnvironment env, OptionsParsingResult options) {
-    env.getEventBus().post(NoBuildEvent.newBuilder().build());
+    env.getEventBus().post(new NoBuildEvent());
     OutErr outErr = env.getReporter().getOutErr();
 
     outErr.printOutLn("Licenses of all components included in this binary:\n");
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/commands/QueryCommand.java b/src/main/java/com/google/devtools/build/lib/runtime/commands/QueryCommand.java
index 2e5e064..ce13ac0 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/commands/QueryCommand.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/commands/QueryCommand.java
@@ -18,6 +18,8 @@
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Joiner;
 import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.analysis.NoBuildEvent;
+import com.google.devtools.build.lib.analysis.NoBuildRequestFinishedEvent;
 import com.google.devtools.build.lib.events.Event;
 import com.google.devtools.build.lib.packages.Target;
 import com.google.devtools.build.lib.pkgcache.PackageCacheOptions;
@@ -40,8 +42,6 @@
 import com.google.devtools.build.lib.runtime.CommandEnvironment;
 import com.google.devtools.build.lib.runtime.KeepGoingOption;
 import com.google.devtools.build.lib.runtime.LoadingPhaseThreadsOption;
-import com.google.devtools.build.lib.runtime.QueryBEPHelper;
-import com.google.devtools.build.lib.runtime.QueryBEPHelper.QueryBEPHelperForNonBuildingCommand;
 import com.google.devtools.build.lib.runtime.TargetProviderForQueryEnvironment;
 import com.google.devtools.build.lib.skyframe.SkyframeExecutorWrappingWalkableGraph;
 import com.google.devtools.build.lib.util.AbruptExitException;
@@ -143,44 +143,36 @@
     Set<Setting> settings = queryOptions.toSettings();
     boolean streamResults = QueryOutputUtils.shouldStreamResults(queryOptions, formatter);
 
-    try (QueryBEPHelperForNonBuildingCommand queryBEPHelperForNonBuildingCommand =
-        QueryBEPHelper.createForNonBuildingCommand(env, queryOptions)) {
-      Either<BlazeCommandResult, QueryEvalResult> result;
-      try (AbstractBlazeQueryEnvironment<Target> queryEnv =
-          newQueryEnvironment(
-              env,
-              options.getOptions(KeepGoingOption.class).keepGoing,
-              !streamResults,
-              queryOptions.universeScope,
-              options.getOptions(LoadingPhaseThreadsOption.class).threads,
-              settings)) {
-        result = doQuery(
-            query,
+    Either<BlazeCommandResult, QueryEvalResult> result;
+    try (AbstractBlazeQueryEnvironment<Target> queryEnv =
+        newQueryEnvironment(
             env,
-            queryOptions,
-            streamResults,
-            formatter,
-            queryEnv,
-            queryBEPHelperForNonBuildingCommand);
-      }
-      return result.map(
-          Function.identity(),
-          queryEvalResult -> {
-            if (queryEvalResult.isEmpty()) {
-              env.getReporter().handle(Event.info("Empty results"));
-            }
-            queryBEPHelperForNonBuildingCommand.afterQueryOutputIsWritten();
-            ExitCode exitCode = queryEvalResult.getSuccess()
-                ? ExitCode.SUCCESS
-                : ExitCode.PARTIAL_ANALYSIS_FAILURE;
-            queryBEPHelperForNonBuildingCommand.afterExitCodeIsDetermined(exitCode);
-            return BlazeCommandResult.exitCode(exitCode);
-          });
-    } catch (IOException e) {
-      env.getReporter()
-          .handle(Event.error("I/O error:" + e.getMessage()));
-      return BlazeCommandResult.exitCode(ExitCode.LOCAL_ENVIRONMENTAL_ERROR);
+            options.getOptions(KeepGoingOption.class).keepGoing,
+            !streamResults,
+            queryOptions.universeScope,
+            options.getOptions(LoadingPhaseThreadsOption.class).threads,
+            settings)) {
+      result = doQuery(
+          query,
+          env,
+          queryOptions,
+          streamResults,
+          formatter,
+          queryEnv);
     }
+    return result.map(
+        Function.identity(),
+        queryEvalResult -> {
+          if (queryEvalResult.isEmpty()) {
+            env.getReporter().handle(Event.info("Empty results"));
+          }
+          ExitCode exitCode = queryEvalResult.getSuccess()
+              ? ExitCode.SUCCESS
+              : ExitCode.PARTIAL_ANALYSIS_FAILURE;
+          env.getEventBus().post(
+              new NoBuildRequestFinishedEvent(exitCode, runtime.getClock().currentTimeMillis()));
+          return BlazeCommandResult.exitCode(exitCode);
+        });
   }
 
   private Either<BlazeCommandResult, QueryEvalResult> doQuery(
@@ -189,8 +181,7 @@
       QueryOptions queryOptions,
       boolean streamResults,
       OutputFormatter formatter,
-      AbstractBlazeQueryEnvironment<Target> queryEnv,
-      QueryBEPHelperForNonBuildingCommand queryBEPHelperForNonBuildingCommand) {
+      AbstractBlazeQueryEnvironment<Target> queryEnv) {
     QueryExpression expr;
     try {
       expr = QueryExpression.parse(query, queryEnv);
@@ -214,10 +205,9 @@
       // There is no particular reason for the 16384 constant here, except its a multiple of the
       // gRPC buffer size. We mainly don't want to send each label individually because the output
       // stream is connected to gRPC, and every write gets converted to one gRPC call.
-      out = new BufferedOutputStream(
-          queryBEPHelperForNonBuildingCommand.getOutputStreamForQueryOutput(), 16384);
+      out = new BufferedOutputStream(env.getReporter().getOutErr().getOutputStream(), 16384);
     } else {
-      out = queryBEPHelperForNonBuildingCommand.getOutputStreamForQueryOutput();
+      out = env.getReporter().getOutErr().getOutputStream();
     }
 
     ThreadSafeOutputFormatterCallback<Target> callback;
@@ -232,8 +222,6 @@
       callback = QueryUtil.newOrderedAggregateAllOutputFormatterCallback(queryEnv);
     }
 
-    queryBEPHelperForNonBuildingCommand.beforeQueryOutputIsWritten();
-
     QueryEvalResult result;
     boolean catastrophe = true;
     try {
@@ -273,6 +261,8 @@
       }
     }
 
+    env.getEventBus()
+        .post(new NoBuildEvent(env.getCommandName(), env.getCommandStartTime(), true));
     if (!streamResults) {
       disableAnsiCharactersFiltering(env);
       try {
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/commands/VersionCommand.java b/src/main/java/com/google/devtools/build/lib/runtime/commands/VersionCommand.java
index 2b4ceaa..16f5a5e 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/commands/VersionCommand.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/commands/VersionCommand.java
@@ -60,7 +60,7 @@
 
   @Override
   public BlazeCommandResult exec(CommandEnvironment env, OptionsParsingResult options) {
-    env.getEventBus().post(NoBuildEvent.newBuilder().build());
+    env.getEventBus().post(new NoBuildEvent());
     try {
       env.getReporter().getOutErr().printOutLn(
           getInfo(