Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: stop get_response #323

Merged
merged 3 commits into from
Jan 9, 2025
Merged

fix: stop get_response #323

merged 3 commits into from
Jan 9, 2025

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Jan 9, 2025

companion to OpenVoiceOS/ovos-core#643

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced game skill stopping mechanism with more robust session handling.
    • Added retry option for user selection interactions.
  • Improvements

    • Centralized game stopping logic for clarity and maintainability.
    • Improved session stop handling with comprehensive control over stopping actions.
    • More flexible user response retrieval through additional parameters.
  • Bug Fixes

    • Refined session termination process.
    • Better management of ongoing interactions and responses.

Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

The pull request introduces modifications to three key files in the OVOS workshop: game_skill.py, ovos.py, and unit_tests.yml. In game_skill.py, the OVOSGameSkill class receives updates to its game stopping mechanism, introducing a new stop_game method and refactoring the existing stop method. In ovos.py, the OVOSSkill class sees changes to session handling and user interaction methods, including enhanced retry logic for user responses and more comprehensive session stopping procedures. Additionally, the unit test configurations have been updated to reflect changes in supported Python versions.

Changes

File Changes
ovos_workshop/skills/game_skill.py - Added PlayerState import from ovos_utils.ocp
- Introduced stop_game() method for programmatic game stopping
- Modified stop() method to serve as a callback
- Updated handle_deactivate() to use stop_game()
ovos_workshop/skills/ovos.py - Added num_retries parameter to ask_selection() method
- Enhanced _handle_session_stop() with more comprehensive stopping logic
- Improved handling of ongoing get_response operations
.github/workflows/unit_tests.yml - Removed py_build_tests job
- Updated unit_tests job to support Python versions [3.9, "3.10", "3.11"]

Possibly related PRs

Suggested reviewers

  • goldyfruit

Poem

🎮 A Rabbit's Game Farewell 🐰
With stop and pause, our game takes flight,
Releasing GUI with gentle might,
A message sent, the state now clear,
Our skill's adventure ends right here!
Game over, rabbit hops away 🚀


📜 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 91f16b7 and 7865348.

📒 Files selected for processing (2)
  • .github/workflows/unit_tests.yml (1 hunks)
  • test/unittests/test_skill.py (1 hunks)
🔇 Additional comments (3)
test/unittests/test_skill.py (1)

109-123: ⚠️ Potential issue

Consider alternatives to skipping the test.

While skipping the test is a temporary solution, it leaves critical functionality untested. The JSON serialization error occurs because Mock objects are being passed through the message bus, which requires JSON-serializable data.

Here are potential solutions:

  1. Instead of using a raw Mock, use side_effect to return JSON-serializable values:
skill.stop = Mock(side_effect=lambda: {"status": "success"})
  1. Alternatively, consider using a real implementation with controlled behavior:
class SerializableStop:
    def __call__(self):
        return {"status": "success"}

Let's verify if this is a widespread issue by checking for similar patterns:

✅ Verification successful

Mock serialization issue can be solved with a proper return value

The test failure occurs because the mocked stop method implicitly returns a Mock object, which the message bus tries to serialize. The original review's suggestion to use side_effect or a custom class is correct, but we can simplify it further:

# Option 1: Simple return value
skill.stop = Mock(return_value=None)  # or return_value={"status": "stopped"}

# Option 2: Lambda for more control
skill.stop = Mock(side_effect=lambda: None)

This is the only test in the codebase with this specific serialization issue, and the fix aligns with how other tests handle similar scenarios.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other tests that might have the same serialization issue
rg -l "Mock.*stop.*assert_called" test/

Length of output: 41


Script:

#!/bin/bash
# Search for Mock usage patterns in test files
echo "=== Mock usage patterns ==="
rg "Mock\(" test/ -A 2

echo -e "\n=== Skipped tests ==="
rg "@unittest.skip" test/

echo -e "\n=== Content of test_skill.py ==="
cat test/unittests/test_skill.py

Length of output: 13317

.github/workflows/unit_tests.yml (2)

Line range hint 46-54: Verify test dependencies installation.

The workflow installs system and Python dependencies. Let's ensure all required dependencies are properly specified.

Run this script to analyze the dependencies:

✅ Verification successful

Dependencies are properly configured

The workflow correctly installs:

  • Required system packages for audio processing and ML (libssl-dev, libfann-dev, portaudio19-dev, libpulse-dev)
  • Test dependencies from requirements/test.txt including ovos-core and testing frameworks
  • Base dependencies from requirements/requirements.txt through setup.py
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test dependencies and their availability

# Check if test.txt exists and its contents
echo "Checking test requirements file..."
fd -t f "test.txt" requirements/

# Look for any additional requirements files
echo "Checking for other requirements files..."
fd -t f "requirements.*\.txt"

# Check for any setup.py dependencies
echo "Checking setup.py dependencies..."
rg "install_requires" setup.py

Length of output: 458


Script:

#!/bin/bash
# Check contents of requirements files
echo "=== Main requirements.txt ==="
cat requirements/requirements.txt
echo -e "\n=== Test requirements.txt ==="
cat requirements/test.txt

# Search for packages that might need system libs
echo -e "\n=== Searching for audio-related packages ==="
rg -i "portaudio|pulseaudio|fann|ssl" requirements/

Length of output: 617

🧰 Tools
🪛 actionlint (1.7.4)

40-40: the runner of "actions/checkout@v2" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


37-37: Verify impact of dropping Python 3.7 and 3.8 support.

The removal of Python 3.7 and 3.8 from the test matrix is a breaking change that should be documented. While Python 3.7 reached EOL in June 2023, Python 3.8 is still supported until October 2024.

Let's verify if there are any dependencies or downstream projects that might be affected:

Finishing Touches

  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

@github-actions github-actions bot added fix and removed fix labels Jan 9, 2025
Copy link
Contributor

@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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
ovos_workshop/skills/game_skill.py (2)

121-132: Good implementation with room for improvement

The implementation provides a clean way to programmatically stop games. Consider these enhancements:

  1. Add type hints for the return value
  2. Document the return value in the docstring
  3. Consider handling the paused state explicitly in the logic flow
-    def stop_game(self):
+    def stop_game(self) -> bool:
         """to be called by skills if they want to stop game programatically
+
+        Returns:
+            bool: True if game was stopped, False if it wasn't playing
+        """
         if self.is_playing:
+            # Handle pause state first
+            if self.is_paused:
+                self._paused.clear()
-            self._paused.clear()
             self.gui.release()
             self.log.debug("changing OCP state: PlayerState.STOPPED ")
             self.bus.emit(Message("ovos.common_play.player.state",
                                   {"state": PlayerState.STOPPED}))
             self._playing.clear()
             self.on_stop_game()
             return True
         return False

Line range hint 283-289: Consider improving error handling granularity

The current try-except block encompasses multiple operations that could fail independently. Consider handling autosave and game abandonment separately for better error recovery.

     def handle_deactivate(self, message: Message):
         try:
             if self.is_paused:
                 self.log.info("Game is paused, keeping it active")
                 self.activate()  # keep the game in active skills list so it can still converse
             elif self.is_playing:
-                self._autosave()
-                self.log.info("Game abandoned due to inactivity")
-                self.on_abandon_game()
-                self.stop_game()
+                try:
+                    self._autosave()
+                except Exception as e:
+                    self.log.error(f"Autosave failed during deactivation: {e}")
+                
+                try:
+                    self.log.info("Game abandoned due to inactivity")
+                    self.on_abandon_game()
+                except Exception as e:
+                    self.log.error(f"Game abandonment handling failed: {e}")
+                
+                try:
+                    self.stop_game()
+                except Exception as e:
+                    self.log.error(f"Game stop failed: {e}")
         except Exception as e:
             self.log.exception(f"Error during game deactivation: {e}")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b364b6e and 91f16b7.

📒 Files selected for processing (2)
  • ovos_workshop/skills/game_skill.py (3 hunks)
  • ovos_workshop/skills/ovos.py (3 hunks)
🔇 Additional comments (5)
ovos_workshop/skills/ovos.py (2)

1351-1356: Enhanced session stopping with proper cleanup.

The changes improve session stopping by:

  1. Combining results from both stop_session and stop methods
  2. Adding cleanup of ongoing get_response operations

This ensures a more thorough cleanup when stopping sessions.


2154-2154: Added retry control for selection prompts.

The addition of the num_retries parameter provides better control over user interaction retries in the ask_selection method. This is a good enhancement for handling cases where users might need multiple attempts to make a valid selection.

Also applies to: 2192-2192

ovos_workshop/skills/game_skill.py (3)

6-6: LGTM: Import addition is appropriate

The addition of PlayerState from ovos_utils.ocp is necessary for the new stopping mechanism and follows the existing import pattern.


134-136: LGTM: Clean callback implementation

The stop method is well-implemented as a callback that delegates to stop_game. The docstring clearly indicates its intended usage.


287-287: LGTM: Consistent use of stop_game

The change to use stop_game ensures consistent cleanup behavior across all stopping scenarios.

@github-actions github-actions bot added fix and removed fix labels Jan 9, 2025
@JarbasAl JarbasAl merged commit 05d9d49 into dev Jan 9, 2025
6 checks passed
Copy link

codecov bot commented Jan 9, 2025

Codecov Report

Attention: Patch coverage is 14.28571% with 12 lines in your changes missing coverage. Please review.

Project coverage is 49.08%. Comparing base (43bfe5b) to head (7865348).
Report is 16 commits behind head on dev.

Files with missing lines Patch % Lines
ovos_workshop/skills/game_skill.py 0.00% 10 Missing ⚠️
ovos_workshop/skills/ovos.py 50.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #323      +/-   ##
==========================================
- Coverage   49.27%   49.08%   -0.19%     
==========================================
  Files          37       37              
  Lines        4426     4441      +15     
==========================================
- Hits         2181     2180       -1     
- Misses       2245     2261      +16     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@JarbasAl JarbasAl mentioned this pull request Jan 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant