fix(hw-oracle): clean up COMGR handles on errors #12812

Merged
malekaifa merged 2 commits from upstream-pr/12812 into main 2026-11-01 11:21:34 +00:00
malekaifa commented 2026-10-29 10:34:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by malekaifa on 2026-10-29T10:34:42Z.


What

tools/hw-oracle/oracle_hip.py owns several COMGR handles across multi-step operations. If a later COMGR call fails after acquisition, some of those handles currently escape without cleanup:

  • data handles returned by amd_comgr_action_data_get_data when reading the size or payload fails;
  • input data handles when populating them or creating/adding their data set fails;
  • the output data set in comgr_step when output or log extraction fails.

Move those resources under narrow finally cleanup while preserving the existing successful ownership transfer: a data set that is successfully returned remains caller-owned, while resources that cannot be returned are destroyed locally.

The regression tests inject failures after each relevant acquisition point and assert the corresponding release/destroy call.

Tested

  • Current-main negative control at aaccd0ba39b7d40fdbf19664575a7e567d8542f7: all four new focused tests fail on the missing cleanup calls.
  • Windows 11, Python 3.12: tools/hw-oracle/test_hw_oracle.py — 56 tests OK (4 skipped).
  • Windows 11, Python 3.9: tools/hw-oracle/test_hw_oracle.py — 56 tests OK (4 skipped).
  • WSL, Python 3.12.3: tools/hw-oracle/test_hw_oracle.py — 56 tests OK (2 skipped) on exact head 63a73e9b93bcb06de89b1eff3df1fad2f8cfe1d4.
  • Success-path mutation recheck on exact head 63a73e9b93: all six mutants that survived the first review are now killed by the focused regression coverage.
  • Windows, Python 3.12 and 3.9: tools/hw-oracle/test_compare_results.py — 12 tests OK on each.
  • py -3.12 tools/check_conventions.py --base origin/main — passed.
  • git diff --check origin/main...HEAD — clean.
  • py_compile of the changed hw-oracle Python files — passed.
  • Live overlap recheck: no open PR implements the COMGR cleanup or touches oracle_hip.py in this area. #12348 shares test_hw_oracle.py only in a separate VulkanRuntimeTests block; a synthetic merge with its current head is conflict-free.

Checklist

  • Based on current main; no other open PR implements the same behavior
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw; silent stubs are documented where applicable
  • No notes, investigation .md files or images added to the repository
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes (OpenAI Codex)
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5066428089 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12812). Originally posted by [malekaifa](https://github.com/malekaifa) on 2026-10-29T10:34:42Z. --- ### What `tools/hw-oracle/oracle_hip.py` owns several COMGR handles across multi-step operations. If a later COMGR call fails after acquisition, some of those handles currently escape without cleanup: - data handles returned by `amd_comgr_action_data_get_data` when reading the size or payload fails; - input data handles when populating them or creating/adding their data set fails; - the output data set in `comgr_step` when output or log extraction fails. Move those resources under narrow `finally` cleanup while preserving the existing successful ownership transfer: a data set that is successfully returned remains caller-owned, while resources that cannot be returned are destroyed locally. The regression tests inject failures after each relevant acquisition point and assert the corresponding release/destroy call. ### Tested - Current-`main` negative control at `aaccd0ba39b7d40fdbf19664575a7e567d8542f7`: all four new focused tests fail on the missing cleanup calls. - Windows 11, Python 3.12: `tools/hw-oracle/test_hw_oracle.py` — 56 tests OK (4 skipped). - Windows 11, Python 3.9: `tools/hw-oracle/test_hw_oracle.py` — 56 tests OK (4 skipped). - WSL, Python 3.12.3: `tools/hw-oracle/test_hw_oracle.py` — 56 tests OK (2 skipped) on exact head `63a73e9b93bcb06de89b1eff3df1fad2f8cfe1d4`. - Success-path mutation recheck on exact head `63a73e9b93`: all six mutants that survived the first review are now killed by the focused regression coverage. - Windows, Python 3.12 and 3.9: `tools/hw-oracle/test_compare_results.py` — 12 tests OK on each. - `py -3.12 tools/check_conventions.py --base origin/main` — passed. - `git diff --check origin/main...HEAD` — clean. - `py_compile` of the changed hw-oracle Python files — passed. - Live overlap recheck: no open PR implements the COMGR cleanup or touches `oracle_hip.py` in this area. #12348 shares `test_hw_oracle.py` only in a separate `VulkanRuntimeTests` block; a synthetic merge with its current head is conflict-free. ### Checklist - [x] Based on current `main`; no other open PR implements the same behavior - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except technical debt - [x] Unimplemented paths throw; silent stubs are documented where applicable - [x] No notes, investigation `.md` files or images added to the repository - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes (OpenAI Codex)
copilot-pull-request-reviewer[bot] commented 2026-10-29 10:38:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by copilot-pull-request-reviewer[bot] on 2026-10-29T10:38:24Z.

Review: COMMENTED


No active review issues were identified in the COMGR resource-cleanup changes.

No open issues 🎉

What changed in this PR

This PR fixes COMGR handle leaks in the hardware oracle’s HIP backend when intermediate operations fail, while preserving caller ownership of successfully returned data sets.

Changes:

  • Release acquired data handles even when reading or populating them fails.
  • Destroy locally owned data sets on failure and ensure action-info cleanup still runs.
  • Add four regression tests covering cleanup after injected COMGR failures.
File Description
tools/​hw-oracle/​test_hw_oracle.py Adds failure-injection tests for data-handle and data-set cleanup.
tools/​hw-oracle/​oracle_hip.py Adds scoped finally cleanup around COMGR resource lifetimes.

Review effort: Balanced

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5696353111 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12812#pullrequestreview-5696353111). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-10-29T10:38:24Z. **Review:** COMMENTED --- <!-- ccr-overview-v2 --> ### 🟢 Approval recommended No active review issues were identified in the COMGR resource-cleanup changes. **No open issues** 🎉 <details> <summary><strong>What changed in this PR</strong></summary> This PR fixes COMGR handle leaks in the hardware oracle’s HIP backend when intermediate operations fail, while preserving caller ownership of successfully returned data sets. **Changes:** - Release acquired data handles even when reading or populating them fails. - Destroy locally owned data sets on failure and ensure action-info cleanup still runs. - Add four regression tests covering cleanup after injected COMGR failures. | File | Description | | ---- | ----------- | | `tools/​hw-oracle/​test_hw_oracle.py` | Adds failure-injection tests for data-handle and data-set cleanup. | | `tools/​hw-oracle/​oracle_hip.py` | Adds scoped `finally` cleanup around COMGR resource lifetimes. | </details> <sub>Review effort: Balanced</sub>
rooklz commented 2026-10-29 12:25:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rooklz on 2026-10-29T12:25:04Z.

Review: COMMENTED


Reviewed @6af6f06ba6 on macOS arm64. Everything below was run host-side; I have no ROCm/COMGR here, so the module is only exercised through mocks, the same way your tests do it.

Checks

  • test_hw_oracle OK (skipped=3) on Python 3.9.6, 3.13.13 and 3.15.1.
  • check_conventions --base upstream/main, git diff --check and merge-tree against main 5454cd2e45: all clean.
  • pr_overlap probed 1398 PRs. 3 share files and all 3 merge cleanly, so no overlap.
  • I read through the three functions and the ownership looks right to me. A data set that data_set() returns stays caller-owned, destroy_data_set is only called after create_data_set succeeded, and info is still destroyed when the outputs destroy raises.

Test gap. The four new tests only cover failure paths. Because of that, the new try/finally structure isn't pinned on the success path. I ran 8 single-line mutants of oracle_hip.py, and 6 of them pass the whole suite:

mutant result
data_bytes: release only in except (leaks every successful handle) survives
data_bytes: chunks.append(buffer.raw[:size.value - 1]) survives
data_set: drop added = True (destroys the set it returns, use-after-free) survives
data_set: release input data only on error survives
data_set: create_data_set moved inside the guarded try killed
comgr_step: outputs_created = True from the start (destroys a never-created handle) survives
comgr_step: skip destroying outputs on success survives
comgr_step: destroy info outside finally killed

The test below kills all 8. It covers the success path of each of the three functions (exact handles released, returned set not destroyed, two chunks read correctly) and a create_data_set failure in comgr_step (no destroy of the uncreated outputs, info still destroyed). It passes on 3.9/3.13/3.15. It also passes against main's oracle_hip.py, which is expected because main already handles the success path correctly. Its job is to guard that behaviour now that the cleanup lives in finally blocks.

@@ -886,6 +886,53 @@ class HipOracleTests(unittest.TestCase):
         library.amd_comgr_destroy_data_set.assert_called_once()
         library.amd_comgr_destroy_action_info.assert_called_once()
 
+    def test_comgr_handles_are_released_once_on_success_and_never_when_not_created(self):
+        library = unittest.mock.MagicMock()
+        payloads = {0x11: b"first", 0x12: b"second!"}
+        library.amd_comgr_action_data_count.side_effect = lambda _set, _kind, count: setattr(count._obj, "value", 2) or 0
+        library.amd_comgr_action_data_get_data.side_effect = lambda _set, _kind, index, data: setattr(data._obj, "value", 0x11 + index) or 0
+
+        def read_data(data, size, buffer):
+            payload = payloads[data.value]
+            size._obj.value = len(payload)
+            if buffer is not None:
+                self.oracle_hip.ctypes.memmove(buffer, payload, len(payload))
+            return 0
+
+        library.amd_comgr_get_data.side_effect = read_data
+        with patch.object(self.oracle_hip, "comgr", return_value=library):
+            self.assertEqual(self.oracle_hip.data_bytes(self.oracle_hip.Handle(1), self.oracle_hip.DATA_RELOCATABLE),
+                             [b"first", b"second!"])
+        self.assertEqual([call.args[0].value for call in library.amd_comgr_release_data.call_args_list], [0x11, 0x12])
+
+        library = unittest.mock.MagicMock()
+        library.amd_comgr_create_data.side_effect = lambda _kind, data: setattr(data._obj, "value", 0x21) or 0
+        library.amd_comgr_create_data_set.side_effect = lambda data_set: setattr(data_set._obj, "value", 0x22) or 0
+        for name in ("amd_comgr_set_data", "amd_comgr_set_data_name", "amd_comgr_data_set_add"):
+            getattr(library, name).return_value = 0
+        with patch.object(self.oracle_hip, "comgr", return_value=library):
+            self.assertEqual(self.oracle_hip.data_set(self.oracle_hip.DATA_SOURCE, b"k.s", b"source").value, 0x22)
+        self.assertEqual([call.args[0].value for call in library.amd_comgr_release_data.call_args_list], [0x21])
+        library.amd_comgr_destroy_data_set.assert_not_called()
+
+        for created in (True, False):
+            library = unittest.mock.MagicMock()
+            for name in ("amd_comgr_create_action_info", "amd_comgr_action_info_set_isa_name", "amd_comgr_action_info_set_logging"):
+                getattr(library, name).return_value = 0
+            library.amd_comgr_create_data_set.return_value = 0 if created else 94
+            library.amd_comgr_do_action.return_value = 0
+            with self.subTest(created=created), patch.object(self.oracle_hip, "comgr", return_value=library), \
+                    patch.object(self.oracle_hip, "data_bytes", return_value=[b"object"]):
+                if created:
+                    self.oracle_hip.comgr_step((0x8,), "amdgcn-amd-amdhsa--gfx1010", [], self.oracle_hip.Handle(1),
+                                               self.oracle_hip.DATA_RELOCATABLE)
+                else:
+                    with self.assertRaises(self.oracle_hip.OracleError):
+                        self.oracle_hip.comgr_step((0x8,), "amdgcn-amd-amdhsa--gfx1010", [], self.oracle_hip.Handle(1),
+                                                   self.oracle_hip.DATA_RELOCATABLE)
+                self.assertEqual(library.amd_comgr_destroy_data_set.call_count, 1 if created else 0)
+                library.amd_comgr_destroy_action_info.assert_called_once()
+
     def test_device_selection_follows_rocr_visible_devices(self):
         library = unittest.mock.MagicMock()
         library.hipInit.return_value = 0
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5697636718 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12812#pullrequestreview-5697636718). Originally posted by [rooklz](https://github.com/rooklz) on 2026-10-29T12:25:04Z. **Review:** COMMENTED --- Reviewed @6af6f06ba6 on macOS arm64. Everything below was run host-side; I have no ROCm/COMGR here, so the module is only exercised through mocks, the same way your tests do it. **Checks** - `test_hw_oracle` OK (skipped=3) on Python 3.9.6, 3.13.13 and 3.15.1. - `check_conventions --base upstream/main`, `git diff --check` and `merge-tree` against main 5454cd2e45: all clean. - `pr_overlap` probed 1398 PRs. 3 share files and all 3 merge cleanly, so no overlap. - I read through the three functions and the ownership looks right to me. A data set that `data_set()` returns stays caller-owned, `destroy_data_set` is only called after `create_data_set` succeeded, and `info` is still destroyed when the outputs destroy raises. **Test gap.** The four new tests only cover failure paths. Because of that, the new `try`/`finally` structure isn't pinned on the success path. I ran 8 single-line mutants of `oracle_hip.py`, and 6 of them pass the whole suite: | mutant | result | |---|---| | `data_bytes`: release only in `except` (leaks every successful handle) | survives | | `data_bytes`: `chunks.append(buffer.raw[:size.value - 1])` | survives | | `data_set`: drop `added = True` (destroys the set it returns, use-after-free) | survives | | `data_set`: release input data only on error | survives | | `data_set`: `create_data_set` moved inside the guarded `try` | killed | | `comgr_step`: `outputs_created = True` from the start (destroys a never-created handle) | survives | | `comgr_step`: skip destroying outputs on success | survives | | `comgr_step`: destroy `info` outside `finally` | killed | The test below kills all 8. It covers the success path of each of the three functions (exact handles released, returned set not destroyed, two chunks read correctly) and a `create_data_set` failure in `comgr_step` (no destroy of the uncreated outputs, `info` still destroyed). It passes on 3.9/3.13/3.15. It also passes against main's `oracle_hip.py`, which is expected because main already handles the success path correctly. Its job is to guard that behaviour now that the cleanup lives in `finally` blocks. ```diff @@ -886,6 +886,53 @@ class HipOracleTests(unittest.TestCase): library.amd_comgr_destroy_data_set.assert_called_once() library.amd_comgr_destroy_action_info.assert_called_once() + def test_comgr_handles_are_released_once_on_success_and_never_when_not_created(self): + library = unittest.mock.MagicMock() + payloads = {0x11: b"first", 0x12: b"second!"} + library.amd_comgr_action_data_count.side_effect = lambda _set, _kind, count: setattr(count._obj, "value", 2) or 0 + library.amd_comgr_action_data_get_data.side_effect = lambda _set, _kind, index, data: setattr(data._obj, "value", 0x11 + index) or 0 + + def read_data(data, size, buffer): + payload = payloads[data.value] + size._obj.value = len(payload) + if buffer is not None: + self.oracle_hip.ctypes.memmove(buffer, payload, len(payload)) + return 0 + + library.amd_comgr_get_data.side_effect = read_data + with patch.object(self.oracle_hip, "comgr", return_value=library): + self.assertEqual(self.oracle_hip.data_bytes(self.oracle_hip.Handle(1), self.oracle_hip.DATA_RELOCATABLE), + [b"first", b"second!"]) + self.assertEqual([call.args[0].value for call in library.amd_comgr_release_data.call_args_list], [0x11, 0x12]) + + library = unittest.mock.MagicMock() + library.amd_comgr_create_data.side_effect = lambda _kind, data: setattr(data._obj, "value", 0x21) or 0 + library.amd_comgr_create_data_set.side_effect = lambda data_set: setattr(data_set._obj, "value", 0x22) or 0 + for name in ("amd_comgr_set_data", "amd_comgr_set_data_name", "amd_comgr_data_set_add"): + getattr(library, name).return_value = 0 + with patch.object(self.oracle_hip, "comgr", return_value=library): + self.assertEqual(self.oracle_hip.data_set(self.oracle_hip.DATA_SOURCE, b"k.s", b"source").value, 0x22) + self.assertEqual([call.args[0].value for call in library.amd_comgr_release_data.call_args_list], [0x21]) + library.amd_comgr_destroy_data_set.assert_not_called() + + for created in (True, False): + library = unittest.mock.MagicMock() + for name in ("amd_comgr_create_action_info", "amd_comgr_action_info_set_isa_name", "amd_comgr_action_info_set_logging"): + getattr(library, name).return_value = 0 + library.amd_comgr_create_data_set.return_value = 0 if created else 94 + library.amd_comgr_do_action.return_value = 0 + with self.subTest(created=created), patch.object(self.oracle_hip, "comgr", return_value=library), \ + patch.object(self.oracle_hip, "data_bytes", return_value=[b"object"]): + if created: + self.oracle_hip.comgr_step((0x8,), "amdgcn-amd-amdhsa--gfx1010", [], self.oracle_hip.Handle(1), + self.oracle_hip.DATA_RELOCATABLE) + else: + with self.assertRaises(self.oracle_hip.OracleError): + self.oracle_hip.comgr_step((0x8,), "amdgcn-amd-amdhsa--gfx1010", [], self.oracle_hip.Handle(1), + self.oracle_hip.DATA_RELOCATABLE) + self.assertEqual(library.amd_comgr_destroy_data_set.call_count, 1 if created else 0) + library.amd_comgr_destroy_action_info.assert_called_once() + def test_device_selection_follows_rocr_visible_devices(self): library = unittest.mock.MagicMock() library.hipInit.return_value = 0 ```
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!12812
No description provided.