Skip to content

With Rest5Client over HTTP/2 (TLS + ALPN h2), bulk requests sent via BulkIngester intermittently fail #1399

Open

Description

@dani72

Java API client version

9.5.6

Java version

25.0.5.1

Elasticsearch Version

9.5.6

Problem description

Summary

With Rest5Client over HTTP/2 (TLS + ALPN h2), bulk requests sent via BulkIngester intermittently fail in two ways:

  1. Corrupted request body. Elasticsearch rejects the request because an NDJSON line starts in the middle of a document:

    [es/bulk] failed: [x_content_parse_exception] [1:1] Unexpected character (',' (code 44)): expected a value
      at [Source: (byte[])", <tail of a field value>\"}"; line: 1, column: 1]
    
    [es/bulk] failed: [x_content_parse_exception] [1:1] Unrecognized token '<tail of a base64 value>': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
    
  2. NullPointerException in MultiBufferEntity.available():

    java.lang.NullPointerException: Cannot invoke "java.nio.ByteBuffer.remaining()" because "this.currentBuffer" is null
      at co.elastic.clients.transport.rest5_client.MultiBufferEntity.available(MultiBufferEntity.java:111)
      at org.apache.hc.core5.http.nio.support.BasicRequestProducer.available(BasicRequestProducer.java:98)
      at org.apache.hc.client5.http.impl.async.InternalAbstractHttpAsyncClient$3.available(InternalAbstractHttpAsyncClient.java:291)
      at org.apache.hc.client5.http.impl.async.HttpAsyncMainClientExec$1.available(HttpAsyncMainClientExec.java:162)
      at org.apache.hc.client5.http.impl.async.LoggingAsyncClientExchangeHandler.available(LoggingAsyncClientExchangeHandler.java:80)
      at org.apache.hc.core5.http2.impl.nio.ClientH2StreamHandler.isOutputReady(ClientH2StreamHandler.java:131)
      at org.apache.hc.core5.http2.impl.nio.H2Stream.isOutputReady(H2Stream.java:198)
      at org.apache.hc.core5.http2.impl.nio.AbstractH2StreamMultiplexer.onOutput(AbstractH2StreamMultiplexer.java:490)
      ...
      at org.apache.hc.core5.reactor.ssl.SSLIOSession.encryptData(SSLIOSession.java:657)
      ...
    

The documents themselves are valid. They are built as Maps and serialized by the client's JacksonJsonpMapper, so the serialized output cannot contain raw newlines inside strings. The corruption therefore happens in the transport.

Forcing HTTP/1.1 makes both errors disappear completely. We set HttpVersionPolicy.FORCE_HTTP_1 via TlsConfig on a custom PoolingAsyncClientConnectionManager.

Environment

  • Spring Boot 4.1.2 (auto-configured Rest5Client)
  • elasticsearch-java 9.5.6, httpclient5 5.6.5, httpcore5 / httpcore5-h2 5.4.4
  • HTTPS, HTTP/2 negotiated via ALPN, request compression disabled
  • BulkIngester with maxConcurrentRequests(4), maxOperations(100), maxSize(512 KB), flushInterval(60s)
  • Documents are partly large (Base64 fields, several hundred KB)
  • Number of configured nodes:

Analysis (based on the v9.5.6 sources)

  1. available() violates the AsyncDataProducer contract.
    java-client/.../rest5_client/MultiBufferEntity.java lines 110–112:

    public int available() {
        return currentBuffer.remaining();
    }

    produce() sets currentBuffer = null once the last buffer has been written. The javadoc of AsyncDataProducer.available() says it "should return zero if the data producer is unable to produce any more data". produce() can also call channel.endStream() more than once. httpcore's own BasicAsyncEntityProducer guards against that with an endOfStream flag.

  2. The read cursor is shared by all attempts of a request.

    • The entity keeps its read position in iterator / currentBuffer. iterator is not volatile and there is no synchronization.
    • Rest5Client.RequestContext passes the same entity instance to every attempt (rest5-client/.../low_level/Rest5Client.java line 886: builder.setEntity((AsyncEntityProducer) request.httpRequest.getEntity())).
    • releaseResources(), close() and failed() reset the cursor via init(). httpclient5 calls these whenever an exchange ends, independently of other exchanges that may still be producing. On a response with status >= 400, InternalAbstractHttpAsyncClient calls requestProducer.releaseResources() while the request body may still be streaming (lines 313–314).

Why HTTP/2 exposes it (our interpretation, not proven)

With HTTP/2, all concurrent bulk requests are multiplexed on one connection. ClientH2StreamHandler.isOutputReady() polls available() for every open stream on every output event.

If two streams drive the same MultiBufferEntity, for example an old attempt and a retry, they write from the same currentBuffer object:

  • Stream A sends the head of document X.
  • Stream B continues with the tail of X right after a \n separator. Elasticsearch then sees an NDJSON line that starts in the middle of a value, which is exactly the parse error above.
  • When one stream drains the entity, currentBuffer becomes null, and the other stream's isOutputReady() throws the NPE.

With HTTP/1.1, each attempt uses its own connection and the producer is driven sequentially, which hides the problem. #1165 (body sent twice with compression enabled) looks like another symptom of the same shared, resettable cursor.

Suggested fix

  • Minimal: make available() null-safe and guard endStream():
    @Override
    public int available() {
        ByteBuffer b = currentBuffer;
        return b == null ? 0 : b.remaining();
    }
  • Proper: do not keep the read cursor in the shared entity. Create a fresh producer, with its own iterator and buffer duplicates, per attempt or per produce cycle, over the immutable list of buffers. releaseResources() on one exchange must not affect another one.

Side finding

ElasticsearchTransportBase.NdJsonSeparator (line 355) is a single static ByteBuffer that is added to every NDJSON body. MultiBufferEntity duplicates it, which is fine. OpenTelemetryForElasticsearch (line 255 ff.) mutates the shared buffers in place (mark()/decode()/reset()) when search body capture is enabled. Concurrent msearch requests could therefore lose their separators.

Workaround

Force HTTP/1.1 on the Rest5Client's connection manager (TlsConfig.custom().setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_1)). Note that replacing the connection manager through setHttpClientConfigCallback also drops the auto-configured credentials, TLS and timeouts, so they have to be set again.

Related: #1165

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