You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by "FrankChen021 (via GitHub)" <gi...@apache.org> on 2026/10/24 05:31:54 UTC

[PR] fix!: send query response trailers only to clients that send TE: trailers (druid)

FrankChen021 opened a new pull request, #20717:
URL: https://github.com/apache/druid/pull/20717

   ### Description
   
   Brokers and Historicals always declare `Trailer: X-Druid-Response-Complete` and send that trailer after the last chunk of every streamed `/druid/v2` and `/druid/v2/sql` response.
   
   JDK-8383439 ("Enhance HTTP Client Response Handling", October 2026 CPU) shipped in JDK 17.0.21, 21.0.13 and 25.0.5. It makes `java.net.http.HttpClient` require CRLF right after the last chunk (new `ChunkedBodyParser.tryConsumeCRLF` in `jdk.internal.net.http.ResponseContent`). A trailer section now fails the response with `java.net.ProtocolException: CR expected`. Older JDKs skipped those 2 bytes without checking them. So on current JDKs, any `java.net.http` client that queries a Broker or Historical directly fails at the end of the response. That includes the Druid JDBC driver (`DruidHttpClientImpl`) and `ResponseIdentityHeaderTest`, which now fails deterministically on CI since `setup-java` picked up Zulu 25.0.5. RFC 9112 §7.1 says recipients should accept trailers, so this looks like a JDK regression. I found no public OpenJDK report; JDK-8383439 itself is not public.
   
   #### Fix
   
   `QueryResultPusher` now declares and sends trailers only when the request has `TE: trailers`, which is how RFC 9110 §10.1.4 has a client say it accepts trailers. Without that header, responses are unchanged apart from the missing `Trailer` header and trailer section.
   
   No Druid code reads `X-Druid-Response-Complete` or `X-Error-Message` (`DirectDruidClient` doesn't). The Router drops trailers anyway, because Jetty's proxy treats `TE` and `Trailer` as hop-by-hop headers. So Broker→Historical and Router traffic behaves the same as before.
   
   #### Evidence
   
   - **CI on Zulu 25.0.5 fails.** [This job](https://github.com/apache/druid/actions/runs/40058080998/job/120765742115) resolved `Zulu 25.0.5+8` (2026-10-24 03:25 UTC). In `ResponseIdentityHeaderTest`, the three query tests (Broker native, Broker SQL, Historical native) fail with `java.net.ProtocolException: CR expected`; the four GET tests pass.
   - **CI on Zulu 25.0.4 passes.** [This master job](https://github.com/apache/druid/actions/runs/40051516682/job/120745017496) resolved `Zulu 25.0.4+1.1` (01:49 UTC the same day) and `ResponseIdentityHeaderTest` passed 7/7. Master is green only because nothing has merged since `setup-java` switched to 25.0.5. It will also start failing on the 17 and 21 jobs once they resolve 17.0.21 and 21.0.13.
   - **Wire format.** A raw-socket capture of a Broker `/druid/v2/sql` response ends with `0\r\nX-Druid-Response-Complete: true\r\n\r\n`.
   - **JDK change.** JDK-8383439 was committed to openjdk `jdk17u`, `jdk21u` and `jdk25u` on 2026-10-16. The first GA tags that contain it are `jdk-17.0.21-ga`, `jdk-21.0.13-ga` and `jdk-25.0.5-ga`.
   
   #### Release note
   
   Brokers and Historicals now send the `X-Druid-Response-Complete` and `X-Error-Message` HTTP trailers only when the request includes the `TE: trailers` header. Clients that read these trailers must send that header. This fixes query failures (`java.net.ProtocolException: CR expected`) in `java.net.http.HttpClient`-based clients, including the Druid JDBC driver, on JDK 17.0.21, 21.0.13 and 25.0.5.
   
   <hr>
   
   ##### Key changed/added classes in this PR
    * `QueryResultPusher`
    * `QueryResponseTrailerTest` (new embedded test: raw-socket wire check with and without `TE: trailers`, plus `HttpClient` reads from Broker and Historical)
   
   <hr>
   
   This PR has:
   
   - [x] been self-reviewed.
   - [x] added unit tests or modified existing tests to cover new code paths.
   - [x] added integration tests.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] fix!: fix CI and JDK HttpClient failures on JDK 25.0.5 caused by query response trailers (druid)

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #20717:
URL: https://github.com/apache/druid/pull/20717#discussion_r4366191553


##########
embedded-tests/src/test/java/org/apache/druid/testing/embedded/server/QueryResponseTrailerTest.java:
##########
@@ -0,0 +1,188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.testing.embedded.server;
+
+import org.apache.druid.server.QueryResource;
+import org.apache.druid.testing.embedded.EmbeddedBroker;
+import org.apache.druid.testing.embedded.EmbeddedCoordinator;
+import org.apache.druid.testing.embedded.EmbeddedDruidCluster;
+import org.apache.druid.testing.embedded.EmbeddedDruidServer;
+import org.apache.druid.testing.embedded.EmbeddedHistorical;
+import org.apache.druid.testing.embedded.EmbeddedOverlord;
+import org.apache.druid.testing.embedded.junit5.EmbeddedClusterTestBase;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import java.io.InputStream;
+import java.net.Socket;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.Locale;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Verifies that streamed query responses carry the {@link QueryResource#RESPONSE_COMPLETE_TRAILER_HEADER} trailer only
+ * when the client sends {@code TE: trailers}, so that clients which reject trailers, such as
+ * {@link java.net.http.HttpClient} on recent JDK updates, can read query results.
+ */
+public class QueryResponseTrailerTest extends EmbeddedClusterTestBase
+{
+  private static final String SQL_QUERY = "{\"query\": \"SELECT 1\"}";
+  private static final String NATIVE_QUERY = """
+      {
+        "queryType": "timeseries",
+        "dataSource": "missing_datasource",
+        "granularity": "all",
+        "intervals": ["2000/3000"],
+        "aggregations": [{"type": "count", "name": "rows"}]
+      }
+      """;
+
+  private final EmbeddedCoordinator coordinator = new EmbeddedCoordinator();
+  private final EmbeddedOverlord overlord = new EmbeddedOverlord();
+  private final EmbeddedBroker broker = new EmbeddedBroker();
+  private final EmbeddedHistorical historical = new EmbeddedHistorical();
+  private final HttpClient client = HttpClient.newHttpClient();
+
+  @Override
+  protected EmbeddedDruidCluster createCluster()
+  {
+    return EmbeddedDruidCluster.withEmbeddedDerbyAndZookeeper()
+                               .addServer(coordinator)
+                               .addServer(overlord)
+                               .addServer(broker)
+                               .addServer(historical);
+  }
+
+  @AfterAll
+  public void closeClient()
+  {
+    client.close();
+  }
+
+  @Test
+  @Timeout(30)
+  public void testTrailersOnlyWhenClientSendsTeTrailers() throws Exception
+  {
+    for (final String path : new String[]{"/druid/v2/sql", "/druid/v2"}) {
+      final String body = path.endsWith("sql") ? SQL_QUERY : NATIVE_QUERY;
+
+      final String withoutTe = sendRaw(broker, path, body, false);
+      Assertions.assertTrue(withoutTe.startsWith("HTTP/1.1 200"), withoutTe);
+      Assertions.assertFalse(withoutTe.contains(QueryResource.RESPONSE_COMPLETE_TRAILER_HEADER), withoutTe);
+
+      final String withTe = sendRaw(broker, path, body, true);
+      Assertions.assertTrue(withTe.startsWith("HTTP/1.1 200"), withTe);
+      Assertions.assertTrue(
+          withTe.endsWith("\r\n0\r\n" + QueryResource.RESPONSE_COMPLETE_TRAILER_HEADER + ": true\r\n\r\n"),
+          withTe
+      );
+    }
+  }
+
+  @Test
+  @Timeout(30)
+  public void testJavaHttpClientReadsStreamedResults() throws Exception
+  {
+    assertJavaHttpClientReadsResults(broker, "/druid/v2/sql", SQL_QUERY);
+    assertJavaHttpClientReadsResults(broker, "/druid/v2", NATIVE_QUERY);
+    assertJavaHttpClientReadsResults(historical, "/druid/v2", NATIVE_QUERY);
+  }
+
+  private void assertJavaHttpClientReadsResults(
+      final EmbeddedDruidServer<?> server,
+      final String path,
+      final String body
+  ) throws Exception
+  {
+    final HttpRequest request = HttpRequest.newBuilder(URI.create(getServerUrl(server) + path))
+                                           .header("Content-Type", "application/json")
+                                           .timeout(Duration.ofSeconds(10))
+                                           .POST(HttpRequest.BodyPublishers.ofString(body))
+                                           .build();
+    final HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
+    Assertions.assertEquals(200, response.statusCode());
+    try (InputStream in = response.body()) {
+      Assertions.assertTrue(new String(in.readAllBytes(), StandardCharsets.UTF_8).startsWith("["));
+    }
+  }
+
+  /**
+   * Sends a request over a raw keep-alive socket and returns the response bytes as they appear on the wire, including
+   * chunk framing and trailers, which {@link HttpClient} does not expose.
+   */
+  private String sendRaw(
+      final EmbeddedDruidServer<?> server,
+      final String path,
+      final String body,
+      final boolean teTrailers
+  ) throws Exception
+  {
+    final URI uri = URI.create(getServerUrl(server));
+    final byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
+    final String request = "POST " + path + " HTTP/1.1\r\n"
+                           + "Host: " + uri.getHost() + "\r\n"
+                           + "Content-Type: application/json\r\n"
+                           + "Content-Length: " + bodyBytes.length + "\r\n"
+                           + (teTrailers ? "TE: trailers\r\nConnection: TE\r\n" : "")
+                           + "\r\n";
+    try (Socket socket = new Socket(uri.getHost(), uri.getPort())) {
+      socket.setSoTimeout(10_000);
+      socket.getOutputStream().write(request.getBytes(StandardCharsets.US_ASCII));
+      socket.getOutputStream().write(bodyBytes);
+      socket.getOutputStream().flush();
+
+      final InputStream in = socket.getInputStream();
+      final StringBuilder response = new StringBuilder();
+      while (!isComplete(response)) {
+        final int b = in.read();
+        if (b < 0) {
+          break;
+        }
+        response.append((char) b);
+      }
+      return response.toString();
+    }
+  }
+
+  private static boolean isComplete(final CharSequence response)
+  {
+    final String text = response.toString();
+    final int headersEnd = text.indexOf("\r\n\r\n");
+    if (headersEnd < 0) {
+      return false;
+    }
+    final String headers = text.substring(0, headersEnd).toLowerCase(Locale.ROOT);
+    final Matcher contentLength = Pattern.compile("\r\ncontent-length: *(\\d+)").matcher(headers);
+    if (contentLength.find()) {
+      return text.length() >= headersEnd + 4 + Integer.parseInt(contentLength.group(1));

Review Comment:
   ## CodeQL / Missing catch of NumberFormatException
   
   Potential uncaught 'java.lang.NumberFormatException'.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/12118)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] fix!: fix CI and JDK HttpClient failures on JDK 25.0.5 caused by query response trailers (druid)

Posted by "gianm (via GitHub)" <gi...@apache.org>.
gianm merged PR #20717:
URL: https://github.com/apache/druid/pull/20717


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org