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

Optimize the canMatch phase on the data node #14511

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

bugmakerrrrrr
Copy link
Contributor

Description

Two changes here:

  1. short circuit can match check, respond with CanMatchResponse(false, null) if cannot match(minMax value is useless if corresponding shard is not match);
  2. only primary searchAfter field will be evaluated if exists.

Related Issues

Resolves #[Issue number to be closed when this PR is merged]

Check List

  • Functionality includes testing.
  • API changes companion pull request created, if applicable.
  • Public documentation issue/PR created, if applicable.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

Copy link
Contributor

✅ Gradle check result for ada899d: SUCCESS

Copy link

codecov bot commented Jun 23, 2024

Codecov Report

Attention: Patch coverage is 60.60606% with 13 lines in your changes missing coverage. Please review.

Project coverage is 71.72%. Comparing base (49b7cd4) to head (8c91a12).
Report is 199 commits behind head on main.

Files with missing lines Patch % Lines
...main/java/org/opensearch/search/SearchService.java 75.00% 0 Missing and 6 partials ⚠️
...ensearch/search/internal/ContextIndexSearcher.java 0.00% 4 Missing and 1 partial ⚠️
...nsearch/search/searchafter/SearchAfterBuilder.java 33.33% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main   #14511      +/-   ##
============================================
- Coverage     71.84%   71.72%   -0.12%     
+ Complexity    62820    62720     -100     
============================================
  Files          5169     5169              
  Lines        294664   294672       +8     
  Branches      42615    42621       +6     
============================================
- Hits         211691   211344     -347     
- Misses        65530    65898     +368     
+ Partials      17443    17430      -13     

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

Copy link
Collaborator

@jainankitk jainankitk left a comment

Choose a reason for hiding this comment

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

@bugmakerrrrrr - Thank you for this PR. Given the single threaded nature of canMatch phase, every optimization is critical, especially when 100-1000s of shards are involved! Is there any way to quantify the impact of this change? Also, are the existing tests sufficient to catch any regressions? If not, can we add test cases for the missing code paths?

Comment on lines 1630 to 1635
if (aliasFilterCanMatch == false) {
return new CanMatchResponse(false, null);
}

// null query means match_all
boolean canMatch = canRewriteToMatchNone(request.source()) == false
|| request.source().query() instanceof MatchNoneQueryBuilder == false;
if (canMatch == false) {
return new CanMatchResponse(false, null);
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can this be better written as below:

if (aliasFilterCanMatch == false || (canRewriteToMatchNone(request.source()) && request.source().query() instanceof MatchNoneQueryBuilder))
    return new CanMatchResponse(false, null);
}

Comment on lines +1685 to +1687
private static FieldDoc getPrimarySearchAfterFieldDoc(
FieldSortBuilder primarySortBuilder,
Object primarySearchAfter,
QueryShardContext context
) throws IOException {
final Optional<SortAndFormats> sortOpt = SortBuilder.buildSort(List.of(primarySortBuilder), context);
return sortOpt.map(sortAndFormats -> SearchAfterBuilder.buildFieldDoc(sortAndFormats, new Object[] { primarySearchAfter }))
.orElse(null);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Unable to see any optimization from this refactoring. Seems more like restructuring and not sure if the readability is improving.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The previous implementation would construct all sortFields if user request contains multi SortBuilders and search after fields, but what we need is just the primary sort search after field.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Is it possible to qualitatively quantify the impact? Maybe some approximation of the worst case query earlier that would be improved with this change

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think that this is quite simple, for example, if I have following query:

{
  "query": {
    "match_all": {}
  },
  "track_total_hits": false,
  "sort": [
    {
      "grade": "desc"
    },
    {
      "age": "asc"
    },
    {
      "id": "asc"
    }
  ],
  "search_after": [
    10,
    20,
    12345
  ]
}

Previously, we have to evaluate and build these all three sort fields, now we just need to build the primary sort field. The idea behind this change is same as FieldSortBuilder.getPrimaryFieldSortOrNull.

boolean canMatch = canRewriteToMatchNone(request.source()) == false
|| request.source().query() instanceof MatchNoneQueryBuilder == false;
if (canMatch == false) {
return new CanMatchResponse(false, null);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we assume that CanMatchResponse(false, null) equivalent to CanMatchResponse(false,<non-null>)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think yes, CanMatchPreFilterSearchPhase extract the min/max values of each shard response and use them to pre-sort the shards prior to running the subsequent phases. However, the unmatched shard will be skipped in the following phases, so its min/max value will have no impact on the query task.

@bugmakerrrrrr
Copy link
Contributor Author

Is there any way to quantify the impact of this change? Also, are the existing tests sufficient to catch any regressions?

No, this optimization is just for reducing unnecessary computation or IO. Currently, I am unable to accurately measure the impact of this change.

If not, can we add test cases for the missing code paths?

Sure.

Copy link
Contributor

❌ Gradle check result for 5186664: FAILURE

Please examine the workflow log, locate, and copy-paste the failure(s) below, then iterate to green. Is the failure a flaky test unrelated to your change?

@bugmakerrrrrr
Copy link
Contributor Author

@jainankitk friendly ping

if (searchContext.searchAfter() != null
&& searchContext.request() != null
&& searchContext.request().source() != null
&& Objects.equals(searchContext.trackTotalHitsUpTo(), SearchContext.TRACK_TOTAL_HITS_DISABLED)) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Any specific reason for using Object.equals given both the values are primitives

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No, I just copied the code from SearchService (in which trackTotalHitsUpto can be null), I can fix this.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Can you update this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sure

Comment on lines +1685 to +1687
private static FieldDoc getPrimarySearchAfterFieldDoc(
FieldSortBuilder primarySortBuilder,
Object primarySearchAfter,
QueryShardContext context
) throws IOException {
final Optional<SortAndFormats> sortOpt = SortBuilder.buildSort(List.of(primarySortBuilder), context);
return sortOpt.map(sortAndFormats -> SearchAfterBuilder.buildFieldDoc(sortAndFormats, new Object[] { primarySearchAfter }))
.orElse(null);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is it possible to qualitatively quantify the impact? Maybe some approximation of the worst case query earlier that would be improved with this change

@jainankitk
Copy link
Collaborator

@bugmakerrrrrr - While the changes look okay, I am still unsure about the impact and need of this code change. Even if not using some benchmark, having some idea of potential improvement with this change will be good!

if (searchContext.searchAfter() != null && searchContext.request() != null && searchContext.request().source() != null) {
// Skipping search on shard/segment entirely can cause mismatch on total_tracking_hits, hence skip only if
// track_total_hits is false.
if (searchContext.searchAfter() != null
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@jainankitk The potential improvements are mostly related to short circuit. For example, we can check the conditions upfront here and avoid to build sort field or read min max values unnecessary.

} else {
// null query means match_all
canMatch = aliasFilterCanMatch;
if (aliasFilterCanMatch == false
Copy link
Contributor Author

Choose a reason for hiding this comment

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

here is the same

Comment on lines 1622 to 1630

if (hasRefreshPending) {
final FieldSortBuilder sortBuilder = FieldSortBuilder.getPrimaryFieldSortOrNull(request.source());
final MinAndMax<?> minMax = sortBuilder != null ? FieldSortBuilder.getMinMaxOrNull(context, sortBuilder) : null;
return new CanMatchResponse(true, minMax);
}

final boolean aliasFilterCanMatch = request.getAliasFilter().getQueryBuilder() instanceof MatchNoneQueryBuilder == false;
FieldSortBuilder sortBuilder = FieldSortBuilder.getPrimaryFieldSortOrNull(request.source());
MinAndMax<?> minMax = sortBuilder != null ? FieldSortBuilder.getMinMaxOrNull(context, sortBuilder) : null;
boolean canMatch;
if (canRewriteToMatchNone(request.source())) {
QueryBuilder queryBuilder = request.source().query();
canMatch = aliasFilterCanMatch && queryBuilder instanceof MatchNoneQueryBuilder == false;
} else {
// null query means match_all
canMatch = aliasFilterCanMatch;
if (aliasFilterCanMatch == false
Copy link
Collaborator

@jainankitk jainankitk Aug 5, 2024

Choose a reason for hiding this comment

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

Can we rewrite this as below:

  1. aliasFilterCanMatch is used as double negation, better change it to aliasFilterCannotMatch
  2. sortBuilder and minMax can be done in one place if CanMatch(false, null) is pulled up!
if (!hasRefreshPending) {
  final boolean aliasFilterCannotMatch = request.getAliasFilter().getQueryBuilder() instanceof MatchNoneQueryBuilder;
  if (aliasFilterCannotMatch || (canRewriteToMatchNone(request.source()) && request.source().query() instanceof MatchNoneQueryBuilder) {
    return new CanMatchResponse(false, null);
  }
}

final FieldSortBuilder sortBuilder = FieldSortBuilder.getPrimaryFieldSortOrNull(request.source());
final MinAndMax<?> minMax = sortBuilder != null ? FieldSortBuilder.getMinMaxOrNull(context, sortBuilder) : null;
if (hasRefreshPending) {
  return new CanMatchResponse(true, minMax);
}

Copy link
Collaborator

@jainankitk jainankitk left a comment

Choose a reason for hiding this comment

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

Thanks @bugmakerrrrrr, LGTM except one minor comment!

@jainankitk
Copy link
Collaborator

Also can you add entry in CHANGELOG.md, before this change can be reviewed by maintainer and merged!

canMatch = canMatchSearchAfter(searchAfterFieldDoc, minMax, sortBuilder, trackTotalHitsUpto);
}
}
return new CanMatchResponse(canMatch, canMatch ? minMax : null);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Also, can we just not send over minMax? Should get ignored if canMatch is false anyway?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think that setting minMax as null is equivalent to not sending this value.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Then we probably should not even care what we are sending for minMax if canMatch is false? So below should also work?

new CanMatchResponse(canMatch, minMax);

// Check for sort.missing == null, since in case of missing values sort queries, if segment/shard's min/max
// is out of search_after range, it still should be printed and hence we should not skip segment/shard.
if (Objects.equals(trackTotalHitsUpto, SearchContext.TRACK_TOTAL_HITS_DISABLED)
&& minMax != null
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do we need minMax != null here, since it is validated in canMatchSearchAfter(searchAfterFieldDoc, minMax, sortBuilder, trackTotalHitsUpto)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

if minMax == null, we can avoid to build primary sort field. The validation in canMatchSearchAfter is mainly used in query phase.

Copy link
Contributor

github-actions bot commented Aug 6, 2024

✅ Gradle check result for 8c91a12: SUCCESS

Copy link
Collaborator

@jainankitk jainankitk left a comment

Choose a reason for hiding this comment

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

LGTM! Can one of the maintainers help review this PR? @msfroh @sohami @reta

canMatch = canMatchSearchAfter(searchAfterFieldDoc, minMax, sortBuilder, trackTotalHitsUpto);
}
}
return new CanMatchResponse(canMatch, canMatch ? minMax : null);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Then we probably should not even care what we are sending for minMax if canMatch is false? So below should also work?

new CanMatchResponse(canMatch, minMax);

@jainankitk
Copy link
Collaborator

@bugmakerrrrrr - Can you resolve the failing CHANGELOG verifier and codecov check while one of the maintainer reviews this PR?

@opensearch-trigger-bot
Copy link
Contributor

This PR is stalled because it has been open for 30 days with no activity.

@opensearch-trigger-bot opensearch-trigger-bot bot added the stalled Issues that have stalled label Sep 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stalled Issues that have stalled
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants