Skip to content

fix(notifications): harden credentials retrieval, cooldown memory leak, malformed segment validation, and health observability - #14260

Merged
Git-on-my-level merged 1 commit into
BasedHardware:mainfrom
TheRWX:fix/notifications-hardening
Sep 17, 2026
Merged

Git-on-my-level merged 1 commit into
BasedHardware:mainfrom
TheRWX:fix/notifications-hardening

Conversation

@TheRWX

@TheRWX TheRWX commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #14259

Summary

Hardens plugins/notifications (hey_omi.py) with dynamic and lazy credential access, memory leak elimination for session cooldowns, malformed segment filtering, OpenAI fallback protection, validated notification dispatch, and service health observability.

Root Cause & Operational Fixes

  1. Fatal Import-Time Exception on Unconfigured Environment Variables:

    • Replaced module-level raise ValueError(...) and eager OpenAI(...) client instantiation with dynamic accessors (get_openai_api_key, get_openai_client, get_omi_credentials).
    • Prevents plugins/main.py from crashing on startup in test or container environments lacking production credentials.
    • Removed top-level print statements to prevent stdout log pollution.
  2. Session Cooldown Memory Leak Elimination:

    • Enhanced MessageBuffer.cleanup_old_sessions() to prune matching session cooldown timestamps from notification_cooldowns alongside buffers, and sweep any orphaned cooldown records older than 1 hour.
  3. Malformed Segment Defense:

    • Added _extract_segments_text to cleanly filter None, non-dict objects, non-string text values, and whitespace-only segments, preventing unhandled AttributeError and HTTP 500 errors.
  4. Fail-Fast OpenAI Dispatch:

    • Guarded get_openai_response to immediately return safe fallback when OpenAI client is unconfigured, eliminating thread-blocking exponential retry cycles.
  5. Notification Dispatch Validation & Timeout Protection:

    • Added parameter validation to send_omi_notification to verify non-empty uid and message payloads and valid credentials before dispatching network requests.
    • Handled network exceptions cleanly without leaking sensitive headers.
  6. Observability & Sanity Endpoints:

    • Added standard GET /health endpoint returning service status and credential readiness.
    • Added GET /status endpoint with active session counts, uptime, and configuration status.
    • Sanitized internal error details in GET /webhook/setup-status.
    • Modularized webhook handler into sub-functions to keep all functions well below the 150-line architecture threshold.
  7. Comprehensive Hermetic Test Suite:

    • Expanded plugins/notifications/test_hey_omi_extraction.py with 15 new test cases in HeyOmiHardeningTests covering all hardening paths.
    • Suite executes completely under python3 -S in 0.020s with zero third-party dependencies.

Verification

  • python3 -S plugins/notifications/test_hey_omi_extraction.py: 22 tests passed in 0.020s.
  • python3 -S plugins/oauth/test_client_log_safety.py: 5 tests passed in 1.598s (zero banned logging tokens).
  • bash scripts/pr-preflight --lane ci: 15/15 checks passed in 56.80s with 0 warnings and 0 errors.

Failure class (fixes)

Failure-Class: none


Bounty Reward Requested: $50.00 USD
Bounty Payout Destination (PayPal): [email protected]

Review in cubic

…tion and health

- Retrieve OpenAI and OMI integration credentials dynamically rather than failing fatally on module import
- Evict expired notification cooldown timestamps during session buffer cleanup to prevent memory leaks
- Filter and normalize segment payloads against None and non-dict/non-string items
- Add fail-fast fallback handling in get_openai_response when OpenAI client is unconfigured
- Validate recipient UID and message payload before dispatching OMI notifications
- Modularize webhook trigger and question processing to remain within architecture limits
- Expose /health and /status endpoints and sanitize setup-status exception details
- Expand test suite with 15 hermetic hardening tests (22 total tests passing in 0.028s)
@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed in depth and verified against the actual files at the head commit - this is a genuinely useful hardening pass on the notifications plugin, and the expanded hermetic tests (22/22 pass with credentials stripped) lock in every claimed fix.

What I verified:

  • plugins/notifications/hey_omi.py — the import-time crash was real: plugins/main.py does from notifications import hey_omi at startup, and the old module-level raise ValueError on missing OPENAI_API_KEY / HEY_OMI_APP_ID / HEY_OMI_APP_SECRET took the whole plugin server down in unconfigured environments. The lazy get_openai_client() / get_omi_credentials() accessors fix it cleanly, and running the suite with all three env vars unset is itself a regression test for that path.
  • hey_omi.py MessageBuffer.cleanup_old_sessions() — cooldown entries are now pruned alongside expired buffers plus an orphan sweep for entries older than an hour; the unbounded notification_cooldowns growth is closed, and test_cleanup_old_sessions_evicts_buffers_and_cooldowns covers both paths (paired eviction and orphan sweep).
  • hey_omi.py _extract_segments_text() — None/non-dict/non-string/blank segments are now skipped instead of raising AttributeError into a 500; test_malformed_segments_gracefully_skipped feeds exactly the nasty list ([None, 12345, "invalid", {}, {"text": None}, ...]).
  • hey_omi.py get_openai_response() — unconfigured client now returns the fallback immediately, and moving the tenacity @retry onto the inner _dispatch_openai_completion() means the guard is no longer retried three times with exponential backoff. Good catch on that subtlety.
  • hey_omi.py send_omi_notification() — validates uid/message/credentials before any network call; exception logging uses type names only, so no header/secret leakage. The setup-status endpoint also stops reflecting raw str(e) into 500 details.
  • plugins/notifications/test_hey_omi_extraction.py — the richer OpenAI stub (chat.completions.create) and requests.exceptions namespace make the harness match the new call paths; the _Clock patch keeps timing-sensitive trigger-window logic deterministic.

Two non-blocking notes for a follow-up, neither worth blocking on:

  1. get_openai_client() caches the client permanently once built, so rotating OPENAI_API_KEY requires a process restart. If hot reload matters for your deployment, compare the key on each call before reusing the cached client.
  2. has_processed plus the new was_detected_before/continue guard in webhook() overlaps the old continue behavior; harmless, but a small comment tying them together would help future readers.

One behavior change maintainers should be aware of (not a defect): without credentials the plugin now boots and answers with a canned fallback instead of failing fast. That is the right trade-off for this sub-app, and the new configured flag on /notifications/health and /notifications/status is the right compensating visibility — just worth knowing the failure mode moved from startup crash to silent fallback.

Coverage suggestions if you want to strengthen further: a two-call test asserting buffer reset semantics after dispatch (response_sent/trigger_detected), and one pinning the '?'-append in _dispatch_collected_question.

Thanks for the clean, well-scoped fix and the disciplined test work.

This feedback is from an automated review assistant acting for the maintainers; human maintainer sign-off is still required before merge (credential-handling behavior change).


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution python labels Sep 17, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed both files at head 9f4279e. Verdict: approve.

  • Lazy credential handling (get_openai_client / get_omi_credentials) replaces the import-time raise ValueErrors — the plugins service can now boot without OPENAI/HEY_OMI env set, and unconfigured calls degrade to FALLBACK_OPENAI_RESPONSE / False instead of crashing.
  • Memory: cleanup_old_sessions now also prunes notification_cooldowns (incl. orphaned timestamps) alongside expired buffers — the cooldown dict previously grew forever.
  • _extract_segments_text drops non-dict/non-str/empty segments before processing; webhook validates session_id and strips ids.
  • setup_status no longer echoes raw exception text into a 500; health/status/setup report only booleans, no secret material. Retry semantics unchanged (decorator moved onto _dispatch_openai_completion, still caught → fallback).
  • Trigger/question-aggregation logic is behavior-preserving vs the #13545 fix; the trigger-step skip is expressed via was_detected_before instead of continue, equivalent.
  • Verified locally at head: python3 plugins/notifications/test_hey_omi_extraction.py → 22/22 OK (hermetic; requests/openai stubbed before import). Suite is CI-wired via hey-omi-question-extraction-tests.

CI green on this head, merge-tree clean, no review threads.

@Git-on-my-level
Git-on-my-level merged commit 8f73efc into BasedHardware:main Sep 17, 2026
39 of 40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

positive-signal Automation verified a genuine fix/quality contribution python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Plugin] Harden credentials retrieval, cooldown memory leak, malformed segment validation, and health observability in notifications plugin

2 participants