Repository navigation
Description
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:
-
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') -
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
BulkIngesterwithmaxConcurrentRequests(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)
-
available()violates theAsyncDataProducercontract.
java-client/.../rest5_client/MultiBufferEntity.javalines 110–112:public int available() { return currentBuffer.remaining(); }
produce()setscurrentBuffer = nullonce the last buffer has been written. The javadoc ofAsyncDataProducer.available()says it "should return zero if the data producer is unable to produce any more data".produce()can also callchannel.endStream()more than once. httpcore's ownBasicAsyncEntityProducerguards against that with anendOfStreamflag. -
The read cursor is shared by all attempts of a request.
- The entity keeps its read position in
iterator/currentBuffer.iteratoris not volatile and there is no synchronization. Rest5Client.RequestContextpasses the same entity instance to every attempt (rest5-client/.../low_level/Rest5Client.javaline 886:builder.setEntity((AsyncEntityProducer) request.httpRequest.getEntity())).releaseResources(),close()andfailed()reset the cursor viainit(). httpclient5 calls these whenever an exchange ends, independently of other exchanges that may still be producing. On a response with status >= 400,InternalAbstractHttpAsyncClientcallsrequestProducer.releaseResources()while the request body may still be streaming (lines 313–314).
- The entity keeps its read position in
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
\nseparator. 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,
currentBufferbecomesnull, and the other stream'sisOutputReady()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 guardendStream():@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
producecycle, 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