Skip to content

Concurrent msearch fails with "must be terminated by a newline" #1400

Open

Description

@mtomik

Java API client version

9.4.8, but the bug is probably in all versions ( main )

Java version

25.0.2

Elasticsearch Version

9.3.7

Problem description

Hi,
I noticed, that when the search body capture is enabled - OpenTelemetryForElasticsearch, two concurrent msearch requests can cause this exception:

co.elastic.clients.elasticsearch._types.ElasticsearchException: [es/msearch] failed: [illegal_argument_exception] The msearch request must be terminated by a newline [\n]

From then on, every msearch will fail on that.

Possible cause from AI

  1. ElasticsearchTransportBase.collectNdJsonLines appends one static final ByteBuffer NdJsonSeparator after every NDJSON line, so all requests in the JVM share the same buffer instance.

  2. OpenTelemetryForElasticsearch.ContextImpl#beforeSendingHttpRequest captures the body by changing the state of these shared buffers in place:

    for (ByteBuffer buf: body) {
        buf.mark();
        sb.append(StandardCharsets.UTF_8.decode(buf));
        buf.reset();
    }

    mark, position and reset are not thread safe. When two threads do this on NdJsonSeparator at the same time, the following interleaving leaves it at position == limit for good:

    thread A: mark()          mark = 0
    thread A: decode()        position = 1
    thread B: mark()          mark = 1
    thread B: decode()        nothing left, position = 1
    thread A: reset()         position = mark = 1
    thread B: reset()         position = 1
    
  3. MultiBufferEntity sends NdJsonSeparator.duplicate(), which copies the corrupted position, so every later request gets an empty separator.

This was already noted as a possibility in the "Side finding" of #1399. This issue confirms it, with a reproduction.

Script to reproduce it

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.instrumentation.OpenTelemetryForElasticsearch;
import co.elastic.clients.transport.rest5_client.Rest5ClientTransport;
import co.elastic.clients.transport.rest5_client.low_level.Rest5Client;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.samplers.Sampler;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class MsearchSeparatorRace {

    private static final String INDEX = "msearch-separator-race";
    private static final int CONCURRENCY = 8;
    private static final int ROUNDS = 20;

    public static void main(String[] args) throws Exception {
        boolean captureSearchBody = args.length == 0 || Boolean.parseBoolean(args[0]);

        // Any recording tracer, so that span.isRecording() is true
        OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
                .setTracerProvider(SdkTracerProvider.builder().setSampler(Sampler.alwaysOn()).build())
                .build();

        Rest5Client restClient = Rest5Client.builder(URI.create("http://localhost:9200")).build();
        Rest5ClientTransport transport = new Rest5ClientTransport(restClient, new JacksonJsonpMapper(), null,
                new OpenTelemetryForElasticsearch(openTelemetry, captureSearchBody));
        ElasticsearchClient client = new ElasticsearchClient(transport);

        if (!client.indices().exists(e -> e.index(INDEX)).value()) {
            client.indices().create(c -> c.index(INDEX));
        }

        ExecutorService executor = Executors.newFixedThreadPool(CONCURRENCY);
        for (int round = 1; round <= ROUNDS; round++) {
            List<Future<?>> futures = new ArrayList<>();
            for (int i = 0; i < CONCURRENCY; i++) {
                futures.add(executor.submit(() -> client.msearch(m -> m
                        .searches(s -> s.header(h -> h.index(INDEX)).body(b -> b.size(0)))
                        .searches(s -> s.header(h -> h.index(INDEX)).body(b -> b.size(0))), Void.class)));
            }

            Map<String, Integer> outcomes = new TreeMap<>();
            for (Future<?> future : futures) {
                String outcome;
                try {
                    future.get(10, TimeUnit.SECONDS);
                    outcome = "OK";
                } catch (TimeoutException e) {
                    outcome = "TIMEOUT (no response after 10 s)";
                } catch (Exception e) {
                    outcome = String.valueOf(e.getCause() == null ? e : e.getCause().getMessage());
                }
                outcomes.merge(outcome, 1, Integer::sum);
            }
            System.out.println("round " + round + ": " + outcomes);
        }

        System.exit(0);
    }
}

Suggested fix
Read duplicates in the instrumentation, so that it never changes the state of the buffers being sent:

for (ByteBuffer buf: body) {
    sb.append(StandardCharsets.UTF_8.decode(buf.duplicate()));
}

As a further safeguard, collectNdJsonLines could add a fresh NdJsonSeparator.duplicate() (or asReadOnlyBuffer()) per line instead of the shared instance, so that no other reader of Request.body() can corrupt it either.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions