Repository: home-assistant/core
Pull request: Fix Automation/Script: sequence within a parallel ignoring enabled flag
<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->

## Proposed change
<!--
Fix an issue where a "sequence" within a "parallel" could not be disabled as the enabled flag was not checked.
Added test to ensure this issue does not reoccur
-->


## Type of change
<!--
  What type of change does your PR introduce to Home Assistant?
  NOTE: Please, check only 1! box!
  If your PR requires multiple boxes to be checked, you'll most likely need to
  split it into multiple PRs. This makes things easier and faster to code review.
-->

- [ ] Dependency upgrade
- [X] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] New feature (which adds functionality to an existing integration)
- [ ] Deprecation (breaking change to happen in the future)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests

## Additional information
<!--
  Details are important, and help maintainers processing your PR.
  Please be sure to fill out additional details, if applicable.
-->

- This PR fixes or closes issue: fixes #125438
- This PR is related to issue: #125438
- Link to documentation pull request: 
- Link to developer documentation pull request: 
- Link to frontend pull request: 

## Checklist
<!--
  Put an `x` in the boxes that apply. You can also fill these out after
  creating the PR. If you're unsure about any of them, don't hesitate to ask.
  We're here to help! This is simply a reminder of what we are going to look
  for before merging your code.
-->

- [X] The code change is tested and works locally.
- [X] Local tests pass. **Your PR cannot be merged unless tests pass**
- [X] There is no commented out code in this PR.
- [X] I have followed the [development checklist][dev-checklist]
- [X] I have followed the [perfect PR recommendations][perfect-pr]
- [X] The code has been formatted using Ruff (`ruff format homeassistant tests`)
- [X] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]

If the code communicates with devices, web services, or third-party tools:

- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.  
      Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.  
      Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.

<!--
  This project is very active and we have a high turnover of pull requests.

  Unfortunately, the number of incoming pull requests is higher than what our
  reviewers can review and merge so there is a long backlog of pull requests
  waiting for review. You can help here!
  
  By reviewing another pull request, you will help raise the code quality of
  that pull request and the final review will be faster. This way the general
  pace of pull request reviews will go up and your wait time will go down.
  
  When picking a pull request to review, try to choose one that hasn't yet
  been reviewed.

  Thanks for helping out!
-->

To help with the load of incoming pull requests:

- [ ] I have reviewed two other [open pull requests][prs] in this repository.

[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure

<!--
  Thank you for contributing <3

  Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/development_checklist/
[manifest-docs]: https://developers.home-assistant.io/docs/creating_integration_manifest/
[quality-scale]: https://developers.home-assistant.io/docs/integration_quality_scale_index/
[docs-repository]: https://github.com/home-assistant/home-assistant.io
[perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr


Problem statement:
Scripts/Automations - Sequence inside Parallel ignoring being disabled
### The problem

first noticed this in 2024.8 and remains in 2024.9.
running haos on a HA yellow

if you have a parallel building block that has sequence building blocks inside it then the sequences ignore "enabled: false" and run

so you have

parallel block
> Sequence Block 1
>>some stuff

> Sequence Block 2
>>some other stuff

even if "Sequence Block 2" is disabled then "some other stuff" still runs

have attached yaml for my repro script below using 2 dummy switch helpers and attached the trace showing both sequences running despite the 2nd one being disabled

Obviously a highly specific situation but caused me some issues that I had to work around so felt I should report

### What version of Home Assistant Core has the issue?

2024.9.1

### What was the last working version of Home Assistant Core?

_No response_

### What type of installation are you running?

Home Assistant OS

### Integration causing the issue

_No response_

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

```yaml
alias: bug repro
sequence:
  - parallel:
      - sequence:
          - action: input_boolean.toggle
            target:
              entity_id: input_boolean.dummy_switch_1
            data: {}
      - sequence:
          - action: input_boolean.toggle
            target:
              entity_id: input_boolean.dummy_switch_2
            data: {}
            enabled: true
        enabled: false
description: ""
```


### Anything in the logs that might be useful for us?

```txt
{
  "trace": {
    "last_step": "sequence/0/parallel/1/sequence/0",
    "run_id": "e72cbc4040455a101c6ef4ac9c20e63c",
    "state": "stopped",
    "script_execution": "finished",
    "timestamp": {
      "start": "2024-09-06T20:07:43.592581+00:00",
      "finish": "2024-09-06T20:07:43.608815+00:00"
    },
    "domain": "script",
    "item_id": "bug_repro",
    "trace": {
      "sequence/0": [
        {
          "path": "sequence/0",
          "timestamp": "2024-09-06T20:07:43.593733+00:00",
          "changed_variables": {
            "this": {
              "entity_id": "script.bug_repro",
              "state": "off",
              "attributes": {
                "last_triggered": "2024-09-06T20:02:28.407484+00:00",
                "mode": "single",
                "current": 0,
                "friendly_name": "bug repro"
              },
              "last_changed": "2024-09-06T20:02:53.486709+00:00",
              "last_reported": "2024-09-06T20:02:53.486709+00:00",
              "last_updated": "2024-09-06T20:02:53.486709+00:00",
              "context": {
                "id": "01J74EXDXER0BRVRV8GTNFVC4J",
                "parent_id": null,
                "user_id": null
              }
            },
            "context": {
              "id": "01J74F69783QXYRE0PE1EDHMYK",
              "parent_id": null,
              "user_id": "47977d8561934a268fa577c524482c56"
            }
          }
        }
      ],
      "sequence/0/parallel/0/sequence/0": [
        {
          "path": "sequence/0/parallel/0/sequence/0",
          "timestamp": "2024-09-06T20:07:43.595173+00:00",
          "result": {
            "params": {
              "domain": "input_boolean",
              "service": "toggle",
              "service_data": {},
              "target": {
                "entity_id": [
                  "input_boolean.dummy_switch_1"
                ]
              }
            },
            "running_script": false
          }
        }
      ],
      "sequence/0/parallel/1/sequence/0": [
        {
          "path": "sequence/0/parallel/1/sequence/0",
          "timestamp": "2024-09-06T20:07:43.598026+00:00",
          "result": {
            "params": {
              "domain": "input_boolean",
              "service": "toggle",
              "service_data": {},
              "target": {
                "entity_id": [
                  "input_boolean.dummy_switch_2"
                ]
              }
            },
            "running_script": false
          }
        }
      ]
    },
    "config": {
      "alias": "bug repro",
      "sequence": [
        {
          "parallel": [
            {
              "sequence": [
                {
                  "action": "input_boolean.toggle",
                  "target": {
                    "entity_id": "input_boolean.dummy_switch_1"
                  },
                  "data": {}
                }
              ]
            },
            {
              "sequence": [
                {
                  "action": "input_boolean.toggle",
                  "target": {
                    "entity_id": "input_boolean.dummy_switch_2"
                  },
                  "data": {},
                  "enabled": true
                }
              ],
              "enabled": false
            }
          ]
        }
      ],
      "description": ""
    },
    "blueprint_inputs": null,
    "context": {
      "id": "01J74F69783QXYRE0PE1EDHMYK",
      "parent_id": null,
      "user_id": "47977d8561934a268fa577c524482c56"
    }
  },
  "logbookEntries": []
}
```


### Additional information

_No response_

Hints from issue discussion:
Hey there @home-assistant/core, mind taking a look at this issue as it has been labeled with an integration (`automation`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L166) for? Thanks!

<details>
<summary>Code owner commands</summary>


Code owners of `automation` can trigger bot actions by commenting:

- `@home-assistant close` Closes the issue.
- `@home-assistant rename Awesome new title` Renames the issue.
- `@home-assistant reopen` Reopen the issue.
- `@home-assistant unassign automation` Removes the current integration label and assignees on the issue, add the integration domain after the command.
- `@home-assistant add-label needs-more-information` Add a label (needs-more-information, problem in dependency, problem in custom component) to the issue.
- `@home-assistant remove-label needs-more-information` Remove a label (needs-more-information, problem in dependency, problem in custom component) on the issue.

</details>


<sub><sup>(message by CodeOwnersMention)</sup></sub>

---

[automation documentation](https://www.home-assistant.io/integrations/automation)
[automation source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/automation)
<sub><sup>(message by IssueLinks)</sup></sub>
I think this needs something in the ballpark here:

![CleanShot 2024-11-26 at 14 47 31@2x](https://github.com/user-attachments/assets/a5a97bcc-2b32-4ab9-ac38-b9162066b341)

(in `helpers/script.py`); Small thought... probably not the best... still wanted to note it here :)
There hasn't been any activity on this issue recently. Due to the high number of incoming GitHub notifications, we have to clean some of the old issues, as many of them have already been resolved with the latest updates.
Please make sure to update to the latest Home Assistant version and check if that solves the issue. Let us know if that works for you by adding a comment 👍
This issue has now been marked as stale and will be closed if no further activity occurs. Thank you for your contributions.
I have had a go at fixing this in https://github.com/home-assistant/core/pull/136393 however it currently incomplete. it does actually solve the issue but it doesn't report back "not run as disabled" in the trace and instead just says "did not run". maybe someone could help me finish this off as I am not sure how to go about this.
@frenck 
I was about to open a new issue when I found this open one.

I have been having this issue on:
Core 2025.2.4
Supervisor 2025.02.4
Operating System   14.1
Frontend 20250214.0

I see it's tagged as stale.
I don't want to destroy some automations by deleting half of it.

Commit message: add test for ensuring sequence inside parallel follows enabled tag

Patch to review:
diff --git a/homeassistant/helpers/script.py b/homeassistant/helpers/script.py
index 43429bdb1d26da..08af68742db1f8 100644
--- a/homeassistant/helpers/script.py
+++ b/homeassistant/helpers/script.py
@@ -653,6 +653,10 @@ async def async_run_with_trace(idx: int, script: Script) -> None:
             """Run a script with a trace path."""
             trace_path_stack_cv.set(copy(trace_path_stack_cv.get()))
             with trace_path([str(idx), "sequence"]):
+                if not script.enabled:
+                    self._log("Skipping disabled parallel script: %s", script.name)
+                    trace_set_result(enabled=False)
+                    return
                 await self._async_run_script(script, parallel=True)
 
         results = await asyncio.gather(
@@ -1442,6 +1446,7 @@ def __init__(
         script_mode: str = DEFAULT_SCRIPT_MODE,
         top_level: bool = True,
         variables: ScriptVariables | None = None,
+        enabled: bool = True,
     ) -> None:
         """Initialize the script."""
         if not (all_scripts := hass.data.get(DATA_SCRIPTS)):
@@ -1462,6 +1467,7 @@ def __init__(
         self.name = name
         self.unique_id = f"{domain}.{name}-{id(self)}"
         self.domain = domain
+        self.enabled = enabled
         self.running_description = running_description or f"{domain} script"
         self._change_listener = change_listener
         self._change_listener_job = (
@@ -2002,6 +2008,7 @@ async def _async_prep_parallel_scripts(self, step: int) -> list[Script]:
                 max_runs=self.max_runs,
                 logger=self._logger,
                 top_level=False,
+                enabled=parallel_script.get(CONF_ENABLED, True),
             )
             parallel_script.change_listener = partial(
                 self._chain_change_listener, parallel_script
diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py
index 4c7075905284f1..9aa34c5d19bdb1 100644
--- a/tests/helpers/test_script.py
+++ b/tests/helpers/test_script.py
@@ -6658,3 +6658,40 @@ async def test_calling_service_backwards_compatible(
             ],
         }
     )
+
+
+async def test_enabled_seq_in_para(
+    hass: HomeAssistant, caplog: pytest.LogCaptureFixture
+) -> None:
+    """Test to ensure seqeuene inside parallel follows enabled tag."""
+    sequence = cv.SCRIPT_SCHEMA(
+        {
+            "parallel": [
+                {
+                    "sequence": [
+                        {"event": "test_event", "event_data": {"inside": "disabled"}}
+                    ],
+                    "enabled": "false",
+                },
+                {
+                    "sequence": [
+                        {"event": "test_event", "event_data": {"inside": "enabled"}}
+                    ],
+                    "enabled": "true",
+                },
+            ]
+        }
+    )
+
+    script_obj = script.Script(hass, sequence, "Test Name", "test_domain")
+
+    await script_obj.async_run(context=Context())
+    await hass.async_block_till_done()
+
+    expected_trace = {
+        "0": [{"result": {"enabled": False}}],
+        "0/parallel/1/sequence/0": [
+            {"result": {"event": "test_event", "event_data": {"inside": "enabled"}}}
+        ],
+    }
+    assert_action_trace(expected_trace)


Code review comments:
diff_hunk: @@ -653,6 +653,10 @@ async def async_run_with_trace(idx: int, script: Script) -> None:
             """Run a script with a trace path."""
             trace_path_stack_cv.set(copy(trace_path_stack_cv.get()))
             with trace_path([str(idx), "sequence"]):
+                if not script.enabled:
+                    self._log("Skipping disabled parallel script: %s", script.name)
+                    trace_set_result(enabled=False)
+                    return
path: homeassistant/helpers/script.py
text: @user1:
If `enabled` is an attribute of a `Script`, it should ideally be checked there, probably in `Script.async_run`.

@user1:
Although the intention is to never use it for top-level script anyway, so if that is documented, then I guess moving the check simply to `_async_run_script` should also be OK.

@author:
@user1 fair warning this is my first PR in core so please feel free to hand hold a bit if you want... or shout at me for doing it wrong :) I am happy either way.

when moving the check up to to `_async_run_script ` do you mean something like this?
![image](https://github.com/user-attachments/assets/f8e704cc-eb94-4aa1-955e-f0643bc40e71)


@user1:
Yes, but:
- do not move the docstring
- check for just `script.enabled`, do not check for `parallel`
- adjust the log by removing parallel

@author:
@user1 right, gotcha, so its more generic, like this?
![image](https://github.com/user-attachments/assets/12e79249-ceda-4a74-a9a4-a76e9d3a3650)


@user1:
Yes

@author:
@user1 cool, I have updated. thanks for bearing with me. you also hinted that it should be documented that its intended only for use when running a non-top-level script. I am not sure exactly where that would go...

@user1:
You can put it in the docstring of the `__init__` method of `Script`.

@author:
@user1 forgive me being the n00b here but could you give me a hint on this one. 
do you mean adding comment here?
![image](https://github.com/user-attachments/assets/2634672d-851a-488a-8e47-e351cf23612d)
or do you mean adding to this?
![image](https://github.com/user-attachments/assets/900b8ed9-a1e1-4342-949f-0535eb30d5e9)
or something else entirely?

I am currently swinging wildly between feeling like an idiot and glad to be learning

@user1:
Add it here https://github.com/home-assistant/core/blob/195b1e85ccd7c55efcb8fffe6615d1be98aa1712/homeassistant/helpers/script.py#L1451 leaving one empty line of space.

@author:
@user1 like this?
![image](https://github.com/user-attachments/assets/89f5a80f-b2b7-4576-9b6e-a078c8fc252e)



@user1:
It should look like this: https://github.com/home-assistant/core/blob/dev/homeassistant/core.py#L163-L166

@author:
@user1 okay that should be that sorted now