Skip to content

Conversation

@jkroll-deepgram
Copy link
Contributor

@jkroll-deepgram jkroll-deepgram commented Jul 8, 2025

Proposed changes

Downgrade tasks cancelled error log line to debug-level.

Mitigates an issue reported by several customers: #501

That log line isn't really needed at error-level because it will always be raised when cancelling tasks.

Types of changes

What types of changes does your code introduce to the community Python SDK?
Put an x in the boxes that apply

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update or tests (if none of the other choices apply) - logging change

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

  • I have read the CONTRIBUTING doc
  • I have lint'ed all of my code using repo standards
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Further comments

Summary by CodeRabbit

  • Style
    • Adjusted logging behavior for cancellation errors to reduce unnecessary error messages. These events now appear at the debug level instead of the error level.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 8, 2025

Walkthrough

The changes adjust the logging level for asyncio.CancelledError exceptions in the finish methods of several asynchronous WebSocket client classes. Specifically, log messages for these exceptions are downgraded from error level to debug level. No other control flow or public API modifications are introduced.

Changes

File(s) Change Summary
deepgram/clients/agent/v1/websocket/async_client.py Changed logging for asyncio.CancelledError in finish from error to debug level.
deepgram/clients/common/v1/abstract_async_websocket.py Changed logging for asyncio.CancelledError in finish from error to debug level.
deepgram/clients/listen/v1/websocket/async_client.py Changed logging for asyncio.CancelledError in finish from error to debug level.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Pylint (3.3.7)
deepgram/clients/common/v1/abstract_async_websocket.py
deepgram/clients/agent/v1/websocket/async_client.py
deepgram/clients/listen/v1/websocket/async_client.py

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bc2d160 and 77ab1a0.

📒 Files selected for processing (3)
  • deepgram/clients/agent/v1/websocket/async_client.py (1 hunks)
  • deepgram/clients/common/v1/abstract_async_websocket.py (1 hunks)
  • deepgram/clients/listen/v1/websocket/async_client.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • deepgram/clients/common/v1/abstract_async_websocket.py
  • deepgram/clients/agent/v1/websocket/async_client.py
  • deepgram/clients/listen/v1/websocket/async_client.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.
@jpvajda jpvajda requested review from jpvajda and lukeocodes July 8, 2025 19:08
@jpvajda
Copy link
Contributor

jpvajda commented Jul 8, 2025

@jkroll-deepgram Thanks for putting this PR up. Here are some clarifications from Co-Pilot on this change and possible implictations.

I want to ensure this the expected behavior we want and also validate some testing has been done on this change:

Implications of the Change

The selected line changes the logging level for a specific exception:

- self._logger.error("tasks cancelled error: %s", e) + self._logger.debug("tasks cancelled error: %s", e)

Implications:

  • Logging Level: Previously, when an asyncio.CancelledError occurred, the event was logged as an error. Now, it will be logged as a debug message.
  • Visibility: Errors are generally visible in production logs, while debug logs are usually hidden unless debug logging is enabled. This means routine task cancellations (which may be expected during shutdowns or cancellations) will no longer clutter the error logs.
  • Intent: This change suggests that CancelledError is considered a normal/expected part of the workflow for this method, and not an exceptional failure.

Testing Recommendations

To ensure this change works as intended, the following types of tests should be considered:

1. Unit Testing

  • Scenario: Simulate the cancellation of the async task that triggers this except block.
  • Check: Confirm that the logger method .debug() is called with the correct message and NOT .error().
  • Example (using unittest.mock):
    with patch.object(client._logger, "debug") as mock_debug: # simulate CancelledError in the relevant method ... mock_debug.assert_called_with("tasks cancelled error: %s", ANY)
  • Negative Check: Ensure .error() is NOT called for CancelledError.

2. Integration Testing

  • Scenario: Run the service or client in an environment that mimics real cancellation events (e.g., shutting down the client, cancelling tasks).
  • Check:
    • With log level set to ERROR, the cancellation messages should not appear.
    • With log level set to DEBUG, the cancellation messages should appear.

Summary:
This change reduces the noise in error logs by demoting expected cancellation exceptions to debug-level logging. Test by simulating cancellations, verifying logger calls, and ensuring appropriate log visibility at different log levels.

@lukeocodes lukeocodes changed the title Downgrade 'tasks cancelled error' to debug-level logline fix(logging): Downgrade 'tasks cancelled error' to debug-level logline Jul 9, 2025
@cpierce-deepgram
Copy link

@jkroll-deepgram your solution doesn't solve the problem and, even if it would have, might have caused unintended issues elsewhere. I believe the correct fix would be to update abstract_async_websocket.py line 491

490: except asyncio.CancelledError as e: 491: self._logger.error("tasks cancelled error: %s", e) 492: self._logger.debug("AbstractAsyncWebSocketClient.finish LEAVE") 493: return True

Adjusting the log from error to debug at this point fixes the problem and has no indirect effects.

@cpierce-deepgram
Copy link

@jkroll-deepgram 😅 I must apologize. I didn't pay attention to a modification I made during testing that made it look like your solution failed. After proper retesting, your solution passes. In addition, the additional fixes you made were made in the appropriate sections of code and shouldn't cause any unintended consequences.

✅ Passes Testing

Copy link
Contributor

@jpvajda jpvajda left a comment

Choose a reason for hiding this comment

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

Based on @cpierce-deepgram validation this change should be ok to merge. cc @lukeocodes for awareness.

@jpvajda jpvajda changed the title fix(logging): Downgrade 'tasks cancelled error' to debug-level logline fix: Logging - Downgrade 'tasks cancelled error' to debug-level logline Jul 15, 2025
@lukeocodes
Copy link
Contributor

@jkroll-deepgram LGTM

@jpvajda this can be merged with a "fix: " prefix as-per the PR title

@jpvajda jpvajda force-pushed the downgrade-tasks-cancelled-logline branch from bc2d160 to 77ab1a0 Compare July 15, 2025 16:46
@jpvajda
Copy link
Contributor

jpvajda commented Jul 15, 2025

@jkroll-deepgram @cpierce-deepgram Thanks for the work on this! I'll merge this PR in and release it with the next SDK release.

@cpierce-deepgram
Copy link

Here is the script I used to test

import asyncio import httpx import logging import os from dotenv import load_dotenv from deepgram.utils import verboselogs from deepgram import ( AsyncListenWebSocketClient, DeepgramClientOptions, LiveTranscriptionEvents, LiveOptions, ) # Load environment variables from .env file load_dotenv() # Fetch the Deepgram API key api_key = os.getenv("API_KEY") if not api_key: raise EnvironmentError("Missing API_KEY in environment variables or .env file.") # Setup verbose logging for debugging verboselogs.install() logger = logging.getLogger() logger.setLevel(logging.INFO) # Format log messages formatter = logging.Formatter( "[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s", "%Y-%m-%d %H:%M:%S" ) console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) logger.addHandler(console_handler) # URL of the audio stream source URL = "http://stream.live.vc.bbcmedia.co.uk/bbc_world_service" async def main(): """  Connects to a live audio stream, sends the stream to Deepgram in real-time,  and prints out transcribed speech as it comes in.   This function demonstrates how to use Deepgram's AsyncListenWebSocketClient  with a live audio stream using httpx and asyncio.  """ try: # Initialize Deepgram client with API key config = DeepgramClientOptions(api_key=api_key) # type: ignore dg_connection = AsyncListenWebSocketClient(config) # Handle transcription events async def on_message(self, result, **kwargs): sentence = result.channel.alternatives[0].transcript if sentence: print(f"speaker: {sentence}") # Register the event listener for transcripts dg_connection.on(LiveTranscriptionEvents.Transcript, on_message) # type: ignore # Set transcription options options = LiveOptions(model="nova-3") print("\n\nPress Enter to stop recording...\n\n") # Start the Deepgram connection success = await dg_connection.start(options) if not success: logger.error("Failed to start Deepgram connection.") return stop_event = asyncio.Event() async def stream_audio(): """  Streams audio from the given URL and sends it to Deepgram for transcription.  """ try: logger.info("Creating HTTP client for stream...") async with httpx.AsyncClient() as client: async with client.stream("GET", URL, timeout=None) as response: logger.info(f"Connected to audio stream: {response.status_code}") async for chunk in response.aiter_bytes(): if stop_event.is_set(): logger.info("Stop signal received. Ending audio stream.") break await dg_connection.send(chunk) except asyncio.CancelledError: logger.warning("Audio streaming was cancelled.") except Exception as e: logger.exception(f"Error during audio streaming: {e}") # Start streaming audio in a background task audio_task = asyncio.create_task(stream_audio()) # Wait for user to press Enter await asyncio.get_event_loop().run_in_executor(None, input) # Signal the audio stream to stop and wait for task to finish stop_event.set() await audio_task # Cleanly close the Deepgram connection await dg_connection.finish() print("Transcription finished.") except Exception as e: logger.exception(f"Error during transcription: {e}") return if __name__ == "__main__": asyncio.run(main())
@jpvajda jpvajda merged commit eca4b1e into deepgram:main Jul 15, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

4 participants