Skip to content

fix: harden /api/activity endpoint — prevent JSONDecodeError in CI#498

Merged
jaylfc merged 4 commits into
jaylfc:masterfrom
hognek:fix/activity-endpoint-resilience
May 31, 2026
Merged

fix: harden /api/activity endpoint — prevent JSONDecodeError in CI#498
jaylfc merged 4 commits into
jaylfc:masterfrom
hognek:fix/activity-endpoint-resilience

Conversation

@hognek
Copy link
Copy Markdown
Contributor

@hognek hognek commented May 31, 2026

Summary

The /api/activity endpoint returns 200 with empty body on CI runners, causing test_activity_endpoint_returns_shape to fail with JSONDecodeError: Expecting value across multiple PRs.

Root cause

request.app.state.hardware_profile accessed directly with dot notation, which raises AttributeError (not caught) when the state attribute is missing in test environments. Additionally, sub-function calls (get_cpu_per_core, get_vram_usage, get_npu_per_core, etc.) can fail on headless CI runners.

Fix

  • Use getattr for safe hardware_profile access
  • Wrap all sub-function calls in try/except with sensible fallback defaults
  • get_npu_frequency() intentionally left unwrapped (it's already resilient internally)

Testing

  • All existing tests should pass, including test_activity_endpoint_returns_shape
  • The endpoint now gracefully degrades instead of returning empty responses

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Improved error handling and robustness of the activity endpoint to gracefully handle missing or unavailable system information.
    • Enhanced stability when retrieving hardware profile and system statistics (CPU, GPU, thermal zones, network rates, and processes).
    • System stats now return safely with fallback values instead of failing when data is unavailable.

…n failures

- Use getattr for hardware_profile to handle missing state (test environments)
- Wrap vram, cpu, npu, gpu, thermal, zram, network, process calls in try/except
- Return empty defaults instead of crashing on partial failures
- Fixes flaky test_activity_endpoint_returns_shape JSONDecodeError
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 31, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

The /api/activity endpoint is refactored for robustness. Hardware profile initialization, system statistics gathering, and response serialization are decoupled with defensive error handling. Each system-stat helper is now precomputed with isolated try/except guards and fallback defaults, and the response payload uses these cached values instead of inline calls.

Changes

Activity endpoint defensive initialization and stats precomputation

Layer / File(s) Summary
Hardware profile defensive initialization
tinyagentos/routes/activity.py
Hardware profile is retrieved safely via getattr with broader exception handling for asdict conversion and GPU VRAM extraction, producing None fallbacks on error.
System statistics precomputation with error guards
tinyagentos/routes/activity.py
CPU cores, NPU cores, GPU load, thermal zones, zram stats, network rates, and top processes are each called within individual try/except blocks with explicit default fallbacks (empty lists or dicts) for robustness.
Response payload wiring with precomputed variables
tinyagentos/routes/activity.py
The JSON response now consumes precomputed cached variables (cpu_cores, npu_cores, gpu_load, thermal, zram, net_rates, procs) rather than invoking stats helpers at serialization time.

🎯 2 (Simple) | ⏱️ ~10 minutes

🐰 The activity endpoint hops with grace,
Errors caught in each safe place,
Stats precomputed, no surprises now,
Fallbacks guard with a steady bow,
Resilience blooms in every flow.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: hardening the /api/activity endpoint to prevent JSONDecodeError in CI by adding defensive error handling.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
tinyagentos/routes/activity.py (1)

78-111: 💤 Low value

Optional: collapse the repeated try/except blocks into a helper.

The seven guarded calls share identical structure. A small _safe helper would reduce duplication and make the fallback contract explicit, without changing behavior. (Broad Exception is fine here—it won't swallow KeyboardInterrupt/SystemExit—so the Ruff BLE001 hints can be ignored for this defensive path.)

♻️ Proposed helper-based refactor
def _safe(fn, default):
    try:
        return fn()
    except Exception:
        return default
-    try:
-        cpu_cores = get_cpu_per_core()
-    except Exception:
-        cpu_cores = []
-
-    try:
-        npu_cores = get_npu_per_core()
-    except Exception:
-        npu_cores = []
-
-    try:
-        gpu_load = get_gpu_load()
-    except Exception:
-        gpu_load = {}
-
-    try:
-        thermal = get_thermal_zones()
-    except Exception:
-        thermal = []
-
-    try:
-        zram = get_zram_stats()
-    except Exception:
-        zram = {}
-
-    try:
-        net_rates = get_network_rates()
-    except Exception:
-        net_rates = {}
-
-    try:
-        procs = get_top_processes(limit=10)
-    except Exception:
-        procs = []
+    cpu_cores = _safe(get_cpu_per_core, [])
+    npu_cores = _safe(get_npu_per_core, [])
+    gpu_load = _safe(get_gpu_load, {})
+    thermal = _safe(get_thermal_zones, [])
+    zram = _safe(get_zram_stats, {})
+    net_rates = _safe(get_network_rates, {})
+    procs = _safe(lambda: get_top_processes(limit=10), [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tinyagentos/routes/activity.py` around lines 78 - 111, Repeated try/except
blocks around sensor calls (get_cpu_per_core, get_npu_per_core, get_gpu_load,
get_thermal_zones, get_zram_stats, get_network_rates, get_top_processes) should
be collapsed into a small helper to reduce duplication and make fallbacks
explicit; add a helper like _safe(fn, default) that calls fn() and returns
default on Exception, then replace each try/except with cpu_cores =
_safe(get_cpu_per_core, []), npu_cores = _safe(get_npu_per_core, []), gpu_load =
_safe(get_gpu_load, {}), thermal = _safe(get_thermal_zones, []), zram =
_safe(get_zram_stats, {}), net_rates = _safe(get_network_rates, {}), and procs =
_safe(lambda: get_top_processes(limit=10), []).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tinyagentos/routes/activity.py`:
- Around line 78-111: Repeated try/except blocks around sensor calls
(get_cpu_per_core, get_npu_per_core, get_gpu_load, get_thermal_zones,
get_zram_stats, get_network_rates, get_top_processes) should be collapsed into a
small helper to reduce duplication and make fallbacks explicit; add a helper
like _safe(fn, default) that calls fn() and returns default on Exception, then
replace each try/except with cpu_cores = _safe(get_cpu_per_core, []), npu_cores
= _safe(get_npu_per_core, []), gpu_load = _safe(get_gpu_load, {}), thermal =
_safe(get_thermal_zones, []), zram = _safe(get_zram_stats, {}), net_rates =
_safe(get_network_rates, {}), and procs = _safe(lambda:
get_top_processes(limit=10), []).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 07bb2b91-c876-4925-9f62-bd32284cf632

📥 Commits

Reviewing files that changed from the base of the PR and between ce9a23a and 17953ef.

📒 Files selected for processing (1)
  • tinyagentos/routes/activity.py

@jaylfc jaylfc merged commit 2b221f6 into jaylfc:master May 31, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants