Add test when toolchain is not declared but it has been used in action

PiperOrigin-RevId: 505727217
Change-Id: Ie2ff3331e1c3da008e076c3e94d0597e3f6ee44c
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java
index 221362a..863549b 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkActionFactory.java
@@ -457,6 +457,13 @@
     }
   }
 
+  private void verifyAutomaticExecGroupExists(String execGroup, RuleContext ctx)
+      throws EvalException {
+    if (!ctx.hasToolchainContext(execGroup)) {
+      throw Starlark.errorf("Action declared for non-existent toolchain '%s'.", execGroup);
+    }
+  }
+
   private void checkValidGroupName(String execGroup) throws EvalException {
     if (!StarlarkExecGroupCollection.isValidGroupName(execGroup)) {
       throw Starlark.errorf("Invalid name for exec group '%s'.", execGroup);
@@ -726,7 +733,7 @@
       builder.setExecGroup(execGroup);
     } else if (useAutoExecGroups && toolchainUnchecked != Starlark.NONE) {
       String toolchain = (String) toolchainUnchecked;
-      verifyExecGroupExists(toolchain, ruleContext);
+      verifyAutomaticExecGroupExists(toolchain, ruleContext);
       builder.setExecGroup(toolchain);
     } else {
       builder.setExecGroup(ExecGroup.DEFAULT_EXEC_GROUP_NAME);
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java b/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java
index be59edf..e5e05b5 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/AutoExecGroupsTest.java
@@ -600,6 +600,26 @@
     "{action: ctx.actions.run}",
     "{action: ctx.actions.run_shell}",
   })
+  public void toolchainNotDefinedButUsedInAction(String action) throws Exception {
+    createCustomRule(
+        /* action= */ action,
+        /* actionParameters= */ "toolchain = '//rule:toolchain_type_1',",
+        /* extraAttributes= */ "",
+        /* toolchains= */ "[]",
+        /* execGroups= */ "");
+    useConfiguration("--incompatible_auto_exec_groups");
+
+    reporter.removeHandler(failFastHandler);
+    getConfiguredTarget("//test:custom_rule_name");
+
+    assertContainsEvent("Action declared for non-existent toolchain '//rule:toolchain_type_1'");
+  }
+
+  @Test
+  @TestParameters({
+    "{action: ctx.actions.run}",
+    "{action: ctx.actions.run_shell}",
+  })
   public void customExecGroupsAndToolchain(String action) throws Exception {
     String customExecGroups =
         "    'custom_exec_group': exec_group(\n"