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 more leaked SearchResponse instances in tests #102822

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
import java.util.stream.IntStream;

import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertResponse;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
Expand Down Expand Up @@ -504,11 +505,13 @@ public void testSearchRouting() throws Exception {
// do nothing
}
}
final var profileResults = search.get().getProfileResults();
assertThat(profileResults, not(anEmptyMap()));
for (final var searchShardProfileKey : profileResults.keySet()) {
assertThat(searchShardProfileKeys, hasItem(searchShardProfileKey));
}
assertResponse(search, resp -> {
final var profileResults = resp.getProfileResults();
assertThat(profileResults, not(anEmptyMap()));
for (final var searchShardProfileKey : profileResults.keySet()) {
assertThat(searchShardProfileKeys, hasItem(searchShardProfileKey));
}
});
}
// Search with PIT
for (int i = 0; i < 10; i++) {
Expand All @@ -524,14 +527,13 @@ public void testSearchRouting() throws Exception {
}
String pitId = client().execute(TransportOpenPointInTimeAction.TYPE, openRequest).actionGet().getPointInTimeId();
try {
final var profileResults = prepareSearch().setPointInTime(new PointInTimeBuilder(pitId))
.setProfile(true)
.get()
.getProfileResults();
assertThat(profileResults, not(anEmptyMap()));
for (final var profileKey : profileResults.keySet()) {
assertThat(profileKey, in(searchShardProfileKeys));
}
assertResponse(prepareSearch().setPointInTime(new PointInTimeBuilder(pitId)).setProfile(true), response -> {
var profileResults = response.getProfileResults();
assertThat(profileResults, not(anEmptyMap()));
for (final var profileKey : profileResults.keySet()) {
assertThat(profileKey, in(searchShardProfileKeys));
}
});
} finally {
client().execute(TransportClosePointInTimeAction.TYPE, new ClosePointInTimeRequest(pitId));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.Collection;
import java.util.List;

import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertResponse;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;

Expand Down Expand Up @@ -69,8 +70,7 @@ private void testLostMaster(CheckedBiConsumer<String, String, Exception> loseMas

index("test", "test", "{}");

assertThat(prepareSearch("test").setScroll("30m").get().getScrollId(), is(notNullValue()));

assertResponse(prepareSearch("test").setScroll("30m"), response -> assertThat(response.getScrollId(), is(notNullValue())));
loseMaster.accept(master, dataNode);
// in the past, this failed because the search context for the scroll would prevent the shard lock from being released.
ensureYellow();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public void testOpenContextsAfterRejections() throws Exception {
}
for (int i = 0; i < numSearches; i++) {
try {
responses[i].get();
responses[i].get().decRef();
} catch (Exception t) {}
}
assertBusy(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,7 @@ public void testPopularTermManyDeletedDocs() throws Exception {
);
}

request.get();

request.get().decRef();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public void testRequestBreaker() throws Exception {
.collectMode(randomFrom(Aggregator.SubAggCollectionMode.values()))
.order(BucketOrder.aggregation("cardinality", randomBoolean()))
.subAggregation(cardinality("cardinality").precisionThreshold(randomLongBetween(1, 40000)).field("field1.keyword"))
).get();
).get().decRef();
} catch (ElasticsearchException e) {
if (ExceptionsHelper.unwrap(e, CircuitBreakingException.class) == null) {
throw e;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
package org.elasticsearch.search.aggregations.bucket;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.test.ESIntegTestCase;

import java.util.ArrayList;
Expand All @@ -19,6 +18,7 @@
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailuresAndResponse;
import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.is;

Expand Down Expand Up @@ -78,14 +78,15 @@ protected void indexData() throws Exception {

indexRandom(true, docs);

SearchResponse resp = prepareSearch("idx").setRouting(routing1).setQuery(matchAllQuery()).get();
assertNoFailures(resp);
long totalOnOne = resp.getHits().getTotalHits().value;
assertThat(totalOnOne, is(15L));
resp = prepareSearch("idx").setRouting(routing2).setQuery(matchAllQuery()).get();
assertNoFailures(resp);
long totalOnTwo = resp.getHits().getTotalHits().value;
assertThat(totalOnTwo, is(12L));
assertNoFailuresAndResponse(prepareSearch("idx").setRouting(routing1).setQuery(matchAllQuery()), resp -> {
long totalOnOne = resp.getHits().getTotalHits().value;
assertThat(totalOnOne, is(15L));
});
assertNoFailuresAndResponse(prepareSearch("idx").setRouting(routing2).setQuery(matchAllQuery()), resp -> {
assertNoFailures(resp);
long totalOnTwo = resp.getHits().getTotalHits().value;
assertThat(totalOnTwo, is(12L));
});
}

protected List<IndexRequestBuilder> indexDoc(String shard, String key, int times) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
package org.elasticsearch.test.search.aggregations.bucket;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.bucket.terms.SignificantTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
Expand All @@ -29,7 +28,7 @@
import static org.elasticsearch.test.ESIntegTestCase.client;
import static org.elasticsearch.test.ESIntegTestCase.prepareSearch;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailuresAndResponse;
import static org.hamcrest.Matchers.equalTo;

public class SharedSignificantTermsTestMethods {
Expand All @@ -48,22 +47,25 @@ public static void aggregateAndCheckFromSeveralShards(ESIntegTestCase testCase)
}

private static void checkSignificantTermsAggregationCorrect(ESIntegTestCase testCase) {
SearchResponse response = prepareSearch(INDEX_NAME).addAggregation(
terms("class").field(CLASS_FIELD).subAggregation(significantTerms("sig_terms").field(TEXT_FIELD))
).get();
assertNoFailures(response);
StringTerms classes = response.getAggregations().get("class");
Assert.assertThat(classes.getBuckets().size(), equalTo(2));
for (Terms.Bucket classBucket : classes.getBuckets()) {
Map<String, Aggregation> aggs = classBucket.getAggregations().asMap();
Assert.assertTrue(aggs.containsKey("sig_terms"));
SignificantTerms agg = (SignificantTerms) aggs.get("sig_terms");
Assert.assertThat(agg.getBuckets().size(), equalTo(1));
SignificantTerms.Bucket sigBucket = agg.iterator().next();
String term = sigBucket.getKeyAsString();
String classTerm = classBucket.getKeyAsString();
Assert.assertTrue(term.equals(classTerm));
}
assertNoFailuresAndResponse(
prepareSearch(INDEX_NAME).addAggregation(
terms("class").field(CLASS_FIELD).subAggregation(significantTerms("sig_terms").field(TEXT_FIELD))
),
response -> {
StringTerms classes = response.getAggregations().get("class");
Assert.assertThat(classes.getBuckets().size(), equalTo(2));
for (Terms.Bucket classBucket : classes.getBuckets()) {
Map<String, Aggregation> aggs = classBucket.getAggregations().asMap();
Assert.assertTrue(aggs.containsKey("sig_terms"));
SignificantTerms agg = (SignificantTerms) aggs.get("sig_terms");
Assert.assertThat(agg.getBuckets().size(), equalTo(1));
SignificantTerms.Bucket sigBucket = agg.iterator().next();
String term = sigBucket.getKeyAsString();
String classTerm = classBucket.getKeyAsString();
Assert.assertTrue(term.equals(classTerm));
}
}
);
}

public static void index01Docs(String type, String settings, ESIntegTestCase testCase) throws ExecutionException, InterruptedException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import org.elasticsearch.action.admin.indices.shrink.ResizeType;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.internal.Client;
import org.elasticsearch.cluster.metadata.IndexMetadata;
Expand Down Expand Up @@ -70,7 +69,7 @@
import static org.elasticsearch.search.aggregations.AggregationBuilders.dateHistogram;
import static org.elasticsearch.snapshots.SearchableSnapshotsSettings.SEARCHABLE_SNAPSHOT_STORE_TYPE;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailuresAndResponse;
import static org.elasticsearch.xpack.searchablesnapshots.SearchableSnapshots.SNAPSHOT_RECOVERY_STATE_FACTORY_KEY;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.containsString;
Expand Down Expand Up @@ -110,19 +109,25 @@ public void testCreateAndRestorePartialSearchableSnapshot() throws Exception {

populateIndex(indexName, 10_000);

final TotalHits originalAllHits = internalCluster().client()
.prepareSearch(indexName)
.setTrackTotalHits(true)
.get()
.getHits()
.getTotalHits();
final TotalHits originalBarHits = internalCluster().client()
final TotalHits originalAllHits;
var originalResponse = internalCluster().client().prepareSearch(indexName).setTrackTotalHits(true).get();
try {
originalAllHits = originalResponse.getHits().getTotalHits();
} finally {
originalResponse.decRef();
}
final TotalHits originalBarHits;
var barResponse = internalCluster().client()
.prepareSearch(indexName)
.setTrackTotalHits(true)
.setQuery(matchQuery("foo", "bar"))
.get()
.getHits()
.getTotalHits();
.get();
try {
originalBarHits = barResponse.getHits().getTotalHits();
} finally {
barResponse.decRef();
}

logger.info("--> [{}] in total, of which [{}] match the query", originalAllHits, originalBarHits);

expectThrows(
Expand Down Expand Up @@ -462,48 +467,60 @@ public void testRequestCacheOnFrozen() throws Exception {
// use a fixed client for the searches, as clients randomize timeouts, which leads to different cache entries
Client client = client();

final SearchResponse r1 = client.prepareSearch("test-index")
.setSize(0)
.setSearchType(SearchType.QUERY_THEN_FETCH)
.addAggregation(
dateHistogram("histo").field("f").timeZone(ZoneId.of("+01:00")).minDocCount(0).calendarInterval(DateHistogramInterval.MONTH)
)
.get();
assertNoFailures(r1);

assertRequestCacheState(client(), "test-index", 0, 1);

// The cached is actually used
assertThat(
indicesAdmin().prepareStats("test-index").setRequestCache(true).get().getTotal().getRequestCache().getMemorySizeInBytes(),
greaterThan(0L)
);

for (int i = 0; i < 10; ++i) {
final SearchResponse r2 = client.prepareSearch("test-index")
assertNoFailuresAndResponse(
client.prepareSearch("test-index")
.setSize(0)
.setSearchType(SearchType.QUERY_THEN_FETCH)
.addAggregation(
dateHistogram("histo").field("f")
.timeZone(ZoneId.of("+01:00"))
.minDocCount(0)
.calendarInterval(DateHistogramInterval.MONTH)
)
.get();
assertNoFailures(r2);
assertRequestCacheState(client(), "test-index", i + 1, 1);
Histogram h1 = r1.getAggregations().get("histo");
Histogram h2 = r2.getAggregations().get("histo");
final List<? extends Histogram.Bucket> buckets1 = h1.getBuckets();
final List<? extends Histogram.Bucket> buckets2 = h2.getBuckets();
assertEquals(buckets1.size(), buckets2.size());
for (int j = 0; j < buckets1.size(); ++j) {
final Histogram.Bucket b1 = buckets1.get(j);
final Histogram.Bucket b2 = buckets2.get(j);
assertEquals(b1.getKey(), b2.getKey());
assertEquals(b1.getDocCount(), b2.getDocCount());
),
r1 -> {
assertRequestCacheState(client(), "test-index", 0, 1);

// The cached is actually used
assertThat(
indicesAdmin().prepareStats("test-index")
.setRequestCache(true)
.get()
.getTotal()
.getRequestCache()
.getMemorySizeInBytes(),
greaterThan(0L)
);

for (int i = 0; i < 10; ++i) {
final int idx = i;
assertNoFailuresAndResponse(
client.prepareSearch("test-index")
.setSize(0)
.setSearchType(SearchType.QUERY_THEN_FETCH)
.addAggregation(
dateHistogram("histo").field("f")
.timeZone(ZoneId.of("+01:00"))
.minDocCount(0)
.calendarInterval(DateHistogramInterval.MONTH)
),
r2 -> {
assertRequestCacheState(client(), "test-index", idx + 1, 1);
Histogram h1 = r1.getAggregations().get("histo");
Histogram h2 = r2.getAggregations().get("histo");
final List<? extends Histogram.Bucket> buckets1 = h1.getBuckets();
final List<? extends Histogram.Bucket> buckets2 = h2.getBuckets();
assertEquals(buckets1.size(), buckets2.size());
for (int j = 0; j < buckets1.size(); ++j) {
final Histogram.Bucket b1 = buckets1.get(j);
final Histogram.Bucket b2 = buckets2.get(j);
assertEquals(b1.getKey(), b2.getKey());
assertEquals(b1.getDocCount(), b2.getDocCount());
}
}
);
}
}
}
);

// shut down shard and check that cache entries are actually removed
indicesAdmin().prepareClose("test-index").get();
Expand Down
Loading