Skip to content

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

Closed

Description

@TheRWX

Problem Statement

The OMI voice wake word and notification dispatch integration (plugins/notifications/hey_omi.py) provides real-time "Hey Omi" voice query detection, LLM question answering, and mobile notification dispatch. An audit of the module revealed several critical operational defects, memory leaks, and unhandled exception paths:

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

    • At top level:
      api_key = os.getenv('OPENAI_API_KEY')
      if not api_key:
          raise ValueError("OPENAI_API_KEY environment variable is required")
      ...
      if not omi_app_id or not omi_app_secret:
          raise ValueError("HEY_OMI_APP_ID and HEY_OMI_APP_SECRET environment variables are required")
    • Because plugins/main.py imports from notifications import hey_omi during application startup, running plugins/main.py in test environments, minimal CI runners, or local dev without production credentials crashes the entire FastAPI server immediately.
    • Top-level print(f"OMI App ID loaded: {omi_app_id}") pollutes standard output.
    • Eager initialization of client = OpenAI(...) prevents dynamic credential updates and causes startup crashes.
  2. Unbounded Memory Leak in Global Session Cooldowns:

    • notification_cooldowns = defaultdict(float) tracks notification dispatch timestamps for every session_id.
    • While MessageBuffer.cleanup_old_sessions() evicts conversation buffers older than 1 hour from self.buffers, notification_cooldowns was never purged. In high-traffic production environments, every unique user session leaks into notification_cooldowns indefinitely, creating a persistent memory leak.
  3. Unhandled AttributeError on Malformed or Null Segments:

    • In webhook:
      for segment in segments:
          if not segment.get('text') or has_processed:
              continue
          text = segment['text'].lower().strip()
    • If an incoming transcript segment list contains None or non-dict items, segment.get('text') raises AttributeError: 'NoneType' object has no attribute 'get'. If segment['text'] is a non-string value (e.g. integer or boolean), .lower() raises AttributeError: 'int' object has no attribute 'lower', resulting in an unhandled HTTP 500 error.
  4. Thread Blocking on Unconfigured OpenAI Calls:

    • In get_openai_response(text), decorated with @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10)), calling OpenAI when the client is unconfigured triggers 3 retry cycles with exponential backoff (sleeping 4 to 10 seconds per attempt), blocking worker threads for ~24 seconds before returning a fallback message.
  5. Missing Request Validation & Error Handling in Notification Dispatch:

    • send_omi_notification attempts outgoing HTTP POST requests even when uid, message, app_id, or app_secret are empty strings, causing failed network requests.
    • Exceptions are not cleanly classified between network timeouts and HTTP errors.
  6. Information Disclosure in Setup Status:

    • In setup_status: raise HTTPException(status_code=500, detail=str(e)) leaks raw internal exception strings to external callers.
    • The module lacks standard /health and runtime /status observability probes.

Proposed Solution

  1. Dynamic & Lazy Credential Management (plugins/notifications/hey_omi.py):

    • Replace top-level fatal ValueError crashes and eager client instantiation with lazy, safe accessors (get_openai_api_key, get_openai_client, get_omi_credentials).
    • Remove stdout pollution.
    • Allow the FastAPI application to import and start cleanly in all environments.
  2. Memory Leak Elimination in Cooldowns (MessageBuffer.cleanup_old_sessions):

    • Integrate cooldown pruning into MessageBuffer.cleanup_old_sessions(), purging matching session keys and sweeping orphaned cooldown timestamps older than 1 hour.
  3. Defensive Segment Parsing & Null Guards (_extract_segments_text):

    • Add _extract_segments_text to filter out None, non-dict, non-string, and empty segment texts safely.
  4. Fail-Fast OpenAI Dispatch (get_openai_response):

    • Immediately return safe fallback when OpenAI client is unconfigured, eliminating thread-blocking retry loops while retaining exponential retry for transient network errors.
  5. Validated Notification Dispatch (send_omi_notification):

    • Validate uid and message payloads and verify credentials before dispatching requests.
    • Classify request exceptions cleanly without leaking sensitive headers.
  6. Observability & Sanity Probes:

    • Add GET /health endpoint returning service status and configuration readiness.
    • Add GET /status endpoint with active buffer counts and uptime.
    • Sanitize internal error details in GET /webhook/setup-status.
    • Modularize webhook logic to maintain function lengths well below the 150-line architecture limit.
  7. Comprehensive Hermetic Test Suite (test_hey_omi_extraction.py):

    • Expanded hermetic test suite with 15 new test cases covering lazy credentials, memory leak pruning, malformed segment defense, timeout protection, and health endpoints (22 total tests passing in 0.028s under python3 -S).

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

Activity

  1. moved this from Someday to In progress in omi TODO / bountieson Sep 16, 2026
  2. jr92yhnt8b-commits commented on Sep 16, 2026

    @jr92yhnt8b-commits

    Before anyone spends implementation time here: is the proposed $50 bounty approved/funded by an Omi maintainer, and would a conforming PR for this scope be payout-eligible? If yes, please confirm the payout terms/claim process. I’m ready to take the task once funding and eligibility are explicit.

  3. TheRWX commented on Sep 16, 2026

    @TheRWX
    ContributorAuthor

    Thanks for checking in @jr92yhnt8b-commits. To clarify, the $50 mentioned is strictly a proposed amount submitted as part of the initial issue report; all bounty allocations, scope approvals, and payout decisions remain entirely at the discretion of the Omi maintainers.

    For visibility, the complete fix and hermetic test suite for this scope have already been implemented, verified (15/15 preflight checks passing, 22 hermetic tests green), and submitted in PR #14260, which is currently awaiting maintainer review.

  4. moved this from In progress to In review in omi TODO / bountieson Sep 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions