Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(runtime): fall back when psutil cannot read /proc

ZQR110150ee9a104c1c
diff --git a/deeptutor/runtime/memory_probe.py b/deeptutor/runtime/memory_probe.py
index 527f5c613..333b5d3a7 100644
--- a/deeptutor/runtime/memory_probe.py
+++ b/deeptutor/runtime/memory_probe.py
@@ -143,6 +143,15 @@ def _scan_psutil(psutil: Any) -> tuple[list[ProcessMemory], bool]:
candidates = [root, *root.children(recursive=True)]
except psutil.Error:
return [], True
+ except (PermissionError, OSError):
+ # HarmonyOS / restricted /proc: ``children()`` walks every
+ # ``/proc/<pid>/stat`` via ``_ppid_map()``. Reading init's entry raises
+ # a raw ``PermissionError``, which is *not* a subclass of
+ # ``psutil.Error``, so it used to escape to the HTTP layer (#1076).
+ # The psutil-free walker already skips unreadable pids.
+ if sys.platform.startswith("linux"):
+ return _scan_proc()
+ return _scan_psutil_self(psutil)
found: list[ProcessMemory] = []
for proc in candidates:
@@ -152,7 +161,7 @@ def _scan_psutil(psutil: Any) -> tuple[list[ProcessMemory], bool]:
name = proc.name() or ""
try:
cmdline = " ".join(proc.cmdline()[:3])
- except (psutil.AccessDenied, psutil.Error):
+ except (psutil.AccessDenied, psutil.Error, PermissionError, OSError):
cmdline = ""
found.append(
ProcessMemory(
@@ -161,7 +170,7 @@ def _scan_psutil(psutil: Any) -> tuple[list[ProcessMemory], bool]:
rss_bytes=rss,
)
)
- except psutil.Error:
+ except (psutil.Error, PermissionError, OSError):
# The tree is live; a child exiting mid-walk is expected, not an error.
continue
if not any(p.pid == os.getpid() for p in found):
@@ -177,7 +186,7 @@ def _scan_psutil_self(psutil: Any) -> tuple[list[ProcessMemory], bool]:
return [
ProcessMemory(pid=proc.pid, label="backend", rss_bytes=int(proc.memory_info().rss))
], True
- except psutil.Error:
+ except (psutil.Error, PermissionError, OSError):
return [], True
diff --git a/tests/runtime/test_memory_probe.py b/tests/runtime/test_memory_probe.py
index 2fbf78e24..efbf0f020 100644
--- a/tests/runtime/test_memory_probe.py
+++ b/tests/runtime/test_memory_probe.py
@@ -167,3 +167,79 @@ def test_capture_is_empty_when_no_backend_is_available(monkeypatch: pytest.Monke
assert snapshot.processes == ()
assert snapshot.total_rss_bytes == 0
+
+
+def test_scan_psutil_falls_back_when_children_raises_permission_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """HarmonyOS: psutil.children() raises raw PermissionError on /proc/1/stat (#1076)."""
+
+ class _PsutilError(Exception):
+ pass
+
+ class _BoomProcess:
+ def children(self, recursive: bool = False):
+ raise PermissionError("[Errno 13] Permission denied: '/proc/1/stat'")
+
+ class _FakePsutil:
+ Error = _PsutilError
+ AccessDenied = _PsutilError
+
+ @staticmethod
+ def pid_exists(pid: int) -> bool:
+ return True
+
+ @staticmethod
+ def Process(pid: int | None = None):
+ return _BoomProcess()
+
+ fallback = (
+ [memory_probe.ProcessMemory(pid=os.getpid(), label="backend", rss_bytes=1024)],
+ True,
+ )
+ monkeypatch.setattr(memory_probe.sys, "platform", "linux")
+ monkeypatch.setattr(memory_probe, "_scan_proc", lambda: fallback)
+
+ processes, partial = memory_probe._scan_psutil(_FakePsutil())
+
+ assert processes == fallback[0]
+ assert partial is True
+
+
+def test_scan_psutil_self_path_when_permission_error_off_linux(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _PsutilError(Exception):
+ pass
+
+ class _BoomProcess:
+ def children(self, recursive: bool = False):
+ raise PermissionError("denied")
+
+ @property
+ def pid(self) -> int:
+ return os.getpid()
+
+ def memory_info(self):
+ return type("MI", (), {"rss": 2048})()
+
+ class _FakePsutil:
+ Error = _PsutilError
+ AccessDenied = _PsutilError
+
+ @staticmethod
+ def pid_exists(pid: int) -> bool:
+ return True
+
+ @staticmethod
+ def Process(pid: int | None = None):
+ return _BoomProcess()
+
+ monkeypatch.setattr(memory_probe.sys, "platform", "darwin")
+
+ processes, partial = memory_probe._scan_psutil(_FakePsutil())
+
+ assert len(processes) == 1
+ assert processes[0].pid == os.getpid()
+ assert processes[0].rss_bytes == 2048
+ assert partial is True