Skip to content

Speed up tests #408

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

Merged
merged 3 commits into from
May 15, 2025
Merged

Speed up tests #408

merged 3 commits into from
May 15, 2025

Conversation

ellnix
Copy link
Contributor

@ellnix ellnix commented Mar 16, 2025

In preparation for adding more tests, which itself is in preparation for some serious refactoring.

Summary by CodeRabbit

  • Tests
    • Improved test setup by switching from individual record creation to bulk inserts for better efficiency.
    • Updated test utilities and setup methods to modify how search indexes are cleared by removing specific arguments.
    • Added clarifying comments to indicate synchronous test behavior.
    • Simplified helper methods and removed unnecessary waiting for asynchronous tasks in some test cases.
    • Added missing test data attributes to ensure data completeness.

Copy link

codecov bot commented Mar 16, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.69%. Comparing base (c3fc3f1) to head (9f01362).
Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #408   +/-   ##
=======================================
  Coverage   90.69%   90.69%           
=======================================
  Files          14       14           
  Lines         849      849           
=======================================
  Hits          770      770           
  Misses         79       79           

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@wesharper wesharper left a comment

Choose a reason for hiding this comment

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

Overall, looks good! I've had to go through and make similar changes a handful of times for our own tests. Little stuff like this can make all the difference.

@@ -34,9 +34,9 @@ def ms_id

module TestUtil
def self.reset_animals!
Cat.clear_index!(true)
Cat.clear_index!

Choose a reason for hiding this comment

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

What exactly did the true do? Is this just a style cleanup or are there perf implications?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

clear_index! and a lot of other methods in this gem have a single argument that is a synchronous flag, i. e. whether to await the resulting task. This absolutely has performance implications (although not all that many since awaiting is not really avoidable).

I often write descriptions in git commits, here's the one on the commit of this change:

Unnecessary awaits should be avoided, generally these methods are meant
to be called at the beginning of the test and for best performance we
should wait on tasks right before an assertion.

So the performance implication is being lazy and putting off the await for as long as possible.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Also confusion like this is why I really don't like flags, consider this method signature:

      def ms_reindex!(batch_size = MeiliSearch::Rails::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false)

Not only is the first argument just a magic number (in most cases), but the second argument is a flag. And because we do not encourage the use of await, we have the flag come second so specifying only the flag takes this form:

Color.ms_reindex!(MeiliSearch::Rails::IndexSettings::DEFAULT_BATCH_SIZE, true)

I would argue this does not look great.

In concert with a specific batch size, you get this borderline incomprehensible method call:

Color.ms_reindex!(50, true)

In conclusion, I would really like to change these methods :)

Choose a reason for hiding this comment

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

Makes sense, thanks for the writeup. Agreed on the method signature. kwargs are definitely preferred IMO as well.

ellnix and others added 3 commits May 15, 2025 11:51
Unnecessary awaits should be avoided, generally these methods are meant
to be called at the beginning of the test and for best performance we
should wait on tasks right before an assertion.
Use insert_all instead of running callbacks, remove unnecessary awaits.
@brunoocasali brunoocasali marked this pull request as ready for review May 15, 2025 15:00
Copy link

coderabbitai bot commented May 15, 2025

Walkthrough

Test setup code across several spec and support files was updated to remove the true argument from clear_index! method calls. Some tests switched from individual record creation to bulk insertion with insert_all, and added or clarified comments regarding synchronous operations. Helper methods and test data preparation were also simplified in some specs.

Changes

File(s) Change Summary
spec/model_methods_spec.rb, spec/safe_index_spec.rb Switched from individual record creation to bulk insert_all for test data; updated index clearing calls; added clarifying comments about synchronous operations.
spec/ms_clean_up_job_spec.rb Added requires for support models; simplified helper method by removing explicit wait for indexing tasks.
spec/support/models/animals.rb, spec/support/models/book.rb,
spec/support/models/color.rb, spec/support/models/movie.rb,
spec/support/models/people.rb Removed the true argument from clear_index! calls in test utility methods; no other logic changes.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Case
    participant Model as Model (e.g. Book, Color)
    participant Index as Search Index

    Test->>Model: insert_all(records)
    Test->>Model: clear_index!()
    Model->>Index: Clear index (default settings)
    Test->>Model: reindex!() (if needed)
    Model->>Index: Reindex matching records
    Test->>Model: Run assertions
Loading

Poem

In the warren where tests abound,
We hop from one to many found.
No more "true"—just clear and bright,
Bulk inserts make setup light.
Synchronous hops, comments anew,
Rabbits rejoice in code so true!
🐇✨

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.

🔧 RuboCop (1.73)
spec/safe_index_spec.rb

Error: The RSpec/FilePath cop has been split into RSpec/SpecFilePathFormat and RSpec/SpecFilePathSuffix.
(obsolete configuration found in .rubocop_todo.yml, please update it)

spec/support/models/animals.rb

Error: The RSpec/FilePath cop has been split into RSpec/SpecFilePathFormat and RSpec/SpecFilePathSuffix.
(obsolete configuration found in .rubocop_todo.yml, please update it)

spec/model_methods_spec.rb

Error: The RSpec/FilePath cop has been split into RSpec/SpecFilePathFormat and RSpec/SpecFilePathSuffix.
(obsolete configuration found in .rubocop_todo.yml, please update it)

  • 5 others

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between c3fc3f1 and 9f01362.

📒 Files selected for processing (8)
  • spec/model_methods_spec.rb (3 hunks)
  • spec/ms_clean_up_job_spec.rb (1 hunks)
  • spec/safe_index_spec.rb (1 hunks)
  • spec/support/models/animals.rb (1 hunks)
  • spec/support/models/book.rb (1 hunks)
  • spec/support/models/color.rb (1 hunks)
  • spec/support/models/movie.rb (1 hunks)
  • spec/support/models/people.rb (1 hunks)
🔇 Additional comments (10)
spec/support/models/people.rb (1)

28-28: Great optimization: Removed redundant synchronous parameter.

This change removes the explicit true parameter from clear_index!, allowing the method to use its default behavior which speeds up the tests. Since People is already configured with synchronous: true in its Meilisearch configuration (line 12), the explicit parameter was redundant.

spec/support/models/movie.rb (1)

18-18:

❓ Verification inconclusive

Verify test behavior without synchronous parameter.

Removing the true parameter from clear_index! may change the operation from synchronous to asynchronous. Unlike other models, Movie does not have synchronous: true in its configuration, so this change might require additional verification.


🏁 Script executed:

#!/bin/bash
# Check if any tests depend on synchronous behavior after clearing the index
grep -r "Movie\.clear_index" --include="*.rb" spec/

Length of output: 166


Confirm Movie.clear_index! synchronization

We found only two calls to Movie.clear_index! in the specs:

  • spec/support/models/movie.rb
  • spec/pagination/will_paginate_spec.rb

Both now use the no-argument form. Please verify that the default implementation of Movie.clear_index! still runs synchronously in our test setup. If it’s now asynchronous, you should either add synchronous: true to the Movie index configuration or introduce an explicit wait in these specs to avoid intermittent failures.

spec/support/models/color.rb (1)

42-42: Optimization: Removed redundant synchronous parameter.

This change removes the explicit true parameter from clear_index!, which aligns with the PR's goal of speeding up tests. Since Color is already configured with synchronous: true (line 13), the parameter was redundant.

spec/support/models/book.rb (1)

38-38: Improved test performance by removing redundant parameter.

Removing the true parameter from clear_index! is a good optimization. Since Book is already configured with synchronous: true (line 14), the explicit parameter was redundant. This change helps achieve the PR's goal of speeding up tests.

spec/ms_clean_up_job_spec.rb (2)

2-3: Good addition of explicit requirements

Adding these explicit requires improves clarity by making dependencies visible, especially since the test uses both models (Book directly and Restaurant in the nested context).


12-14: Well-simplified helper method

Simplifying the create_indexed_record helper by removing unnecessary waiting for indexing tasks is a good performance optimization. Since MSCleanUpJob is being tested on its cleanup abilities rather than indexing behavior, this change speeds up tests without compromising test validity.

spec/safe_index_spec.rb (1)

11-12: Excellent performance optimization with bulk insertion

Replacing five individual record creations with a single insert_all operation followed by an explicit reindex is a significant performance improvement:

  1. Reduces database operations from five to one
  2. Minimizes the overhead of multiple index updates
  3. Avoids triggering callbacks and validations multiple times

The subsequent reindex! call ensures the search index is properly updated after the bulk insert.

spec/model_methods_spec.rb (3)

11-17: Good performance optimization with bulk insertion

Replacing individual record creations with a single insert_all operation reduces database operations and improves test performance. The proper structure with rubocop directives helps maintain code quality while making a necessary performance exception.


21-22: Improved performance and scoping

Two good changes here:

  1. Removing the true argument from clear_index! avoids unnecessary synchronous waiting
  2. Changing the reindexing scope to filter by name provides a clearer test condition

These changes maintain test functionality while improving performance.


70-71: Helpful clarifying comments

These comments provide valuable context about the synchronous nature of certain models, explaining why explicit awaiting is unnecessary. This improves code readability and helps future contributors understand the test behavior without sacrificing performance.

Also applies to: 82-83

✨ Finishing Touches
  • 📝 Generate Docstrings

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

Copy link
Member

@brunoocasali brunoocasali left a comment

Choose a reason for hiding this comment

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

bors merge

@brunoocasali brunoocasali added skip-changelog The PR will not appear in the release changelogs maintenance Anything related to maintenance (CI, tests, refactoring...) and removed skip-changelog The PR will not appear in the release changelogs labels May 15, 2025
@ellnix ellnix closed this May 15, 2025
@meili-bors meili-bors bot merged commit 96dd4a4 into meilisearch:main May 15, 2025
12 of 13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
maintenance Anything related to maintenance (CI, tests, refactoring...)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants