Copilot commented on code in PR #10110:
URL: https://github.com/apache/gravitino/pull/10110#discussion_r2870963741


##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/OptimizerCmd.java:
##########
@@ -0,0 +1,785 @@
+/*
+ * 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.gravitino.maintenance.optimizer;
+
+import com.google.common.base.Preconditions;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.OutputStreamWriter;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.maintenance.optimizer.api.common.MetricSample;
+import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;
+import org.apache.gravitino.maintenance.optimizer.api.monitor.EvaluationResult;
+import org.apache.gravitino.maintenance.optimizer.api.monitor.MetricScope;
+import org.apache.gravitino.maintenance.optimizer.api.monitor.MetricsProvider;
+import org.apache.gravitino.maintenance.optimizer.command.rule.CommandRules;
+import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv;
+import 
org.apache.gravitino.maintenance.optimizer.common.StatisticsInputContent;
+import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;
+import org.apache.gravitino.maintenance.optimizer.common.util.ProviderUtils;
+import org.apache.gravitino.maintenance.optimizer.monitor.Monitor;
+import org.apache.gravitino.maintenance.optimizer.recommender.Recommender;
+import 
org.apache.gravitino.maintenance.optimizer.recommender.util.PartitionUtils;
+import org.apache.gravitino.maintenance.optimizer.updater.UpdateType;
+import org.apache.gravitino.maintenance.optimizer.updater.Updater;
+import 
org.apache.gravitino.maintenance.optimizer.updater.calculator.local.LocalStatisticsCalculator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** CLI entry point for optimizer actions. */
+public class OptimizerCmd {
+  private static final Logger LOG = 
LoggerFactory.getLogger(OptimizerCmd.class);
+  private static final String DEFAULT_CONF_PATH =
+      Paths.get("conf", "gravitino-optimizer.conf").toString();
+  private static final long DEFAULT_RANGE_SECONDS = 24 * 3600L;
+  private static final long METRICS_LIST_FROM_SECONDS = 0L;
+  private static final long METRICS_LIST_TO_SECONDS = Long.MAX_VALUE;
+  private static final Set<CliOption> GLOBAL_OPTION_SPECS = 
EnumSet.of(CliOption.CONF_PATH);
+  private static final String DEFAULT_USAGE =
+      "./bin/gravitino-optimizer.sh --type <command> [options]";
+  private static final Map<OptimizerCommandType, CommandOptionSpec> 
COMMAND_OPTION_SPECS =
+      Map.of(
+          OptimizerCommandType.RECOMMEND_STRATEGY_TYPE,
+          CommandOptionSpec.of(
+              EnumSet.of(CliOption.IDENTIFIERS, CliOption.STRATEGY_TYPE),
+              EnumSet.noneOf(CliOption.class),
+              "./bin/gravitino-optimizer.sh --type recommend-strategy-type 
--identifiers c.db.t1,c.db.t2 --strategy-type compaction"),
+          OptimizerCommandType.UPDATE_STATISTICS,
+          CommandOptionSpec.of(
+              EnumSet.of(CliOption.CALCULATOR_NAME),
+              EnumSet.of(CliOption.IDENTIFIERS, CliOption.STATISTICS_PAYLOAD, 
CliOption.FILE_PATH),
+              "./bin/gravitino-optimizer.sh --type update-statistics 
--calculator-name local-stats-calculator --file-path ./table-stats.jsonl",
+              statisticsInputRules()),
+          OptimizerCommandType.APPEND_METRICS,
+          CommandOptionSpec.of(
+              EnumSet.of(CliOption.CALCULATOR_NAME),
+              EnumSet.of(CliOption.IDENTIFIERS, CliOption.STATISTICS_PAYLOAD, 
CliOption.FILE_PATH),
+              "./bin/gravitino-optimizer.sh --type append-metrics 
--calculator-name local-stats-calculator --statistics-payload '<jsonl-lines>'",
+              statisticsInputRules()),
+          OptimizerCommandType.MONITOR_METRICS,
+          CommandOptionSpec.of(
+              EnumSet.of(CliOption.IDENTIFIERS, CliOption.ACTION_TIME),
+              EnumSet.of(CliOption.RANGE_SECONDS, CliOption.PARTITION_PATH),
+              "./bin/gravitino-optimizer.sh --type monitor-metrics 
--identifiers c.db.t --action-time 1735689600"),
+          OptimizerCommandType.LIST_TABLE_METRICS,
+          CommandOptionSpec.of(
+              EnumSet.of(CliOption.IDENTIFIERS),
+              EnumSet.of(CliOption.PARTITION_PATH),
+              "./bin/gravitino-optimizer.sh --type list-table-metrics 
--identifiers c.db.t"),
+          OptimizerCommandType.LIST_JOB_METRICS,
+          CommandOptionSpec.of(
+              EnumSet.of(CliOption.IDENTIFIERS),
+              EnumSet.noneOf(CliOption.class),
+              "./bin/gravitino-optimizer.sh --type list-job-metrics 
--identifiers c.db.job"));
+  private static final Map<OptimizerCommandType, CommandHandler> 
COMMAND_HANDLERS =
+      Map.of(
+          OptimizerCommandType.RECOMMEND_STRATEGY_TYPE, 
OptimizerCmd::executeRecommendStrategyType,
+          OptimizerCommandType.UPDATE_STATISTICS, 
OptimizerCmd::executeUpdateStatistics,
+          OptimizerCommandType.APPEND_METRICS, 
OptimizerCmd::executeAppendMetrics,
+          OptimizerCommandType.MONITOR_METRICS, 
OptimizerCmd::executeMonitorMetrics,
+          OptimizerCommandType.LIST_TABLE_METRICS, 
OptimizerCmd::executeListTableMetrics,
+          OptimizerCommandType.LIST_JOB_METRICS, 
OptimizerCmd::executeListJobMetrics);
+  private static final String LOCAL_STATS_CALCULATOR_NAME = 
LocalStatisticsCalculator.NAME;
+
+  static {
+    validateCommandDefinitions();
+  }
+
+  public static void main(String[] args) {
+    run(args, System.out, System.err);
+  }
+
+  static void run(String[] args, PrintStream out, PrintStream err) {
+    Options options = buildOptions();
+
+    CommandLineParser parser = new DefaultParser();
+    CommandLine cmd;
+    OptimizerCommandType optimizerType = null;
+    try {
+      cmd = parser.parse(options, args);
+      if (cmd.hasOption(CliOption.HELP.longOpt())) {
+        String helpType = cmd.getOptionValue(CliOption.TYPE.longOpt());
+        if (StringUtils.isBlank(helpType)) {
+          printGlobalHelp(options, out);
+        } else {
+          printCommandHelp(OptimizerCommandType.fromString(helpType), out);
+        }
+        return;
+      }
+
+      optimizerType = 
OptimizerCommandType.fromString(cmd.getOptionValue(CliOption.TYPE.longOpt()));
+      validateCommandOptions(cmd, optimizerType);
+      String confPath = cmd.getOptionValue(CliOption.CONF_PATH.longOpt(), 
DEFAULT_CONF_PATH);
+      String[] identifiers = 
cmd.getOptionValues(CliOption.IDENTIFIERS.longOpt());
+      String strategyType = 
cmd.getOptionValue(CliOption.STRATEGY_TYPE.longOpt());
+      String calculatorName = 
cmd.getOptionValue(CliOption.CALCULATOR_NAME.longOpt());
+      String actionTime = cmd.getOptionValue(CliOption.ACTION_TIME.longOpt());
+      String rangeSeconds =
+          cmd.getOptionValue(
+              CliOption.RANGE_SECONDS.longOpt(), 
Long.toString(DEFAULT_RANGE_SECONDS));
+      String partitionPathRaw = 
cmd.getOptionValue(CliOption.PARTITION_PATH.longOpt());
+      String statisticsPayload = 
cmd.getOptionValue(CliOption.STATISTICS_PAYLOAD.longOpt());
+      String filePath = cmd.getOptionValue(CliOption.FILE_PATH.longOpt());
+      Optional<StatisticsInputContent> statisticsInputContent =
+          buildStatisticsInputContent(statisticsPayload, filePath);
+      CommandContext context =
+          new CommandContext(
+              new OptimizerEnv(loadOptimizerConfig(confPath)),
+              identifiers,
+              strategyType,
+              calculatorName,
+              actionTime,
+              rangeSeconds,
+              partitionPathRaw,
+              statisticsInputContent,
+              out);
+      executeCommand(optimizerType, context);
+    } catch (ParseException e) {
+      err.println(e.getMessage());
+      printGlobalHelp(options, out);
+      LOG.error("Error parsing command line arguments", e);
+    } catch (IllegalArgumentException e) {
+      err.println(e.getMessage());
+      if (optimizerType != null) {
+        printCommandHelp(optimizerType, out);
+      } else {
+        printGlobalHelp(options, out);
+      }
+      LOG.error("Command validation failed", e);
+    } catch (Exception e) {
+      err.println(e.getMessage());
+      LOG.error("Error executing optimizer command", e);
+    }
+  }
+
+  private static OptimizerConfig loadOptimizerConfig(String confPath) {
+    OptimizerConfig config = new OptimizerConfig();
+    try {
+      if (StringUtils.isNotBlank(confPath)) {
+        File confFile = Paths.get(confPath).toFile();
+        if (Files.exists(confFile.toPath())) {
+          config.loadFromProperties(config.loadPropertiesFromFile(confFile));
+          return config;

Review Comment:
   When a user provides `--conf-path` pointing to a nonexistent file, the code 
falls through to `config.loadFromFile(confPath)`. This method treats its 
argument as a file *name* to look up under the `GRAVITINO_CONF_DIR` (or 
`GRAVITINO_HOME/conf`) environment variable, concatenating the env var path 
with the user's full path — producing a confusing error like "Config file 
/etc/gravitino/conf//my/path.conf not found" instead of a clear message about 
the specified path not existing. The fix should be to throw an explicit 
`IllegalArgumentException` when `confPath` is non-blank but the file doesn't 
exist, instead of falling through to `loadFromFile`.
   ```suggestion
             return config;
           } else {
             throw new IllegalArgumentException(
                 "Specified optimizer config file does not exist: " + confPath);
   ```



##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/command/rule/CommandRules.java:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.gravitino.maintenance.optimizer.command.rule;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Predicate;
+import org.apache.commons.cli.CommandLine;
+
+/**
+ * Factory and utility methods for optimizer command validation rules.
+ *
+ * <p>The rule system is designed for command-specific option checks that go 
beyond simple
+ * required/optional definitions. Typical scenarios:
+ *
+ * <ul>
+ *   <li>Mutual exclusion: only one of two inputs can be provided.
+ *   <li>Conditional requirement: when a trigger option has some value, 
another option set becomes
+ *       mandatory.
+ *   <li>Conditional forbid: when a trigger option has some value, some 
options must not be used.
+ * </ul>
+ *
+ * <p>Example:
+ *
+ * <pre>{@code
+ * CommandRules.ValidationPlan rules =
+ *     CommandRules.newBuilder()
+ *         .addMutuallyExclusive(
+ *             List.of("statistics-payload", "file-path"),
+ *             "--statistics-payload and --file-path cannot be used together")
+ *         .addRequireAnyWhenOption(
+ *             "calculator-name",
+ *             "local-stats-calculator"::equals,
+ *             List.of("statistics-payload", "file-path"),
+ *             "Command '%s' with --calculator-name local-stats-calculator 
requires one of "
+ *                 + "--statistics-payload or --file-path.")
+ *         .addForbidWhenOption(
+ *             "calculator-name",
+ *             value -> !"local-stats-calculator".equals(value),
+ *             List.of("statistics-payload", "file-path"),
+ *             "--statistics-payload and --file-path are only supported when 
--calculator-name "
+ *                 + "is local-stats-calculator.")
+ *         .build();
+ *
+ * rules.validate(cmd, "update-statistics");
+ * }</pre>
+ */
+public final class CommandRules {
+  private CommandRules() {}
+
+  /** Returns a no-op plan, useful for commands that have no extra rule 
checks. */
+  public static ValidationPlan emptyPlan() {
+    return new ValidationPlan(List.of());
+  }
+
+  /** Returns a mutable builder for composing a {@link ValidationPlan}. */
+  public static Builder newBuilder() {
+    return new Builder();
+  }
+
+  /** Returns true if an option is effectively provided (has argument value(s) 
and not blank). */
+  public static boolean hasEffectiveValue(CommandLine cmd, String longOpt) {
+    return RuleUtils.hasEffectiveValue(cmd, longOpt);
+  }
+
+  /** Immutable executable rule set for one command type. */
+  public static final class ValidationPlan {
+    private final List<CommandRule> rules;
+
+    private ValidationPlan(List<CommandRule> rules) {
+      this.rules = List.copyOf(rules);
+    }
+
+    public void validate(CommandLine cmd, String commandType) {
+      for (CommandRule rule : rules) {
+        rule.validate(cmd, commandType);
+      }
+    }
+  }
+
+  public static final class Builder {
+    private final List<CommandRule> rules = new ArrayList<>();
+
+    /**
+     * Adds a mutual exclusion rule.
+     *
+     * <p>Example: forbid using both {@code --statistics-payload} and {@code 
--file-path} in the
+     * same command.
+     */
+    public Builder addMutuallyExclusive(List<String> options, String 
messageTemplate) {
+      rules.add(new MutuallyExclusiveRule(options, messageTemplate));
+      return this;
+    }
+
+    /**
+     * Adds a rule that requires at least one option in {@code options} to be 
provided.
+     *
+     * <p>The {@code messageTemplate} can include {@code %s}. The first 
placeholder is always bound
+     * to {@code commandType} at runtime; the rest are from {@code formatArgs}.
+     */
+    public Builder addRequireAny(
+        List<String> options, String messageTemplate, Object... formatArgs) {
+      rules.add(new RequireAnyRule(options, messageTemplate, formatArgs));
+      return this;
+    }
+
+    /**
+     * Adds a rule that forbids {@code forbiddenOptions} when the trigger 
option matches the
+     * predicate.
+     *
+     * <p>Example: when {@code --calculator-name != local-stats-calculator}, 
forbid {@code
+     * --statistics-payload} and {@code --file-path}.
+     */
+    public Builder addForbidWhenOption(
+        String triggerOption,
+        Predicate<String> triggerPredicate,
+        List<String> forbiddenOptions,
+        String messageTemplate,
+        Object... formatArgs) {
+      rules.add(
+          new ForbidWhenOptionRule(
+              triggerOption, triggerPredicate, forbiddenOptions, 
messageTemplate, formatArgs));
+      return this;
+    }
+
+    /**
+     * Adds a rule that requires at least one option when the trigger option 
matches the predicate.
+     *
+     * <p>Example: when {@code --calculator-name == local-stats-calculator}, 
require one of {@code
+     * --statistics-payload} or {@code --file-path}.
+     */
+    public Builder addRequireAnyWhenOption(
+        String triggerOption,
+        Predicate<String> triggerPredicate,
+        List<String> options,
+        String messageTemplate,
+        Object... formatArgs) {
+      return addRequireWhenOption(
+          triggerOption,
+          triggerPredicate,
+          new RequireAnyRule(options, messageTemplate, formatArgs));
+    }
+
+    /** Finalizes the builder and returns an immutable validation plan. */

Review Comment:
   The Javadoc for the private `addRequireWhenOption` method says "Finalizes 
the builder and returns an immutable validation plan." but this method actually 
adds a `RequireWhenOptionRule` to the builder's rule list and returns the 
builder for chaining — it does not finalize anything. The `build()` method is 
the one that finalizes. The Javadoc should be corrected to describe what this 
method actually does, e.g., "Adds a conditional rule that delegates to another 
rule when the trigger option matches the predicate."
   ```suggestion
       /**
        * Adds a conditional rule that delegates to another rule when the 
trigger option matches
        * the predicate.
        *
        * @param triggerOption The option whose value is evaluated by the 
predicate.
        * @param triggerPredicate The predicate used to test the trigger 
option's value.
        * @param delegate The rule to apply when the predicate evaluates to 
{@code true}.
        * @return This builder for chaining.
        */
   ```



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to