Skip to content

Commit 24a20a5

Browse files
authored
Fix O(cols^2) PPL result materialization on wide schemas (#5940)
--------- Signed-off-by: Peng Huo <penghuo@gmail.com>
1 parent 95050df commit 24a20a5

3 files changed

Lines changed: 311 additions & 9 deletions

File tree

Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.opensearch.executor;
7+
8+
import com.google.common.collect.ImmutableList;
9+
import java.sql.Connection;
10+
import java.sql.DriverManager;
11+
import java.sql.ResultSet;
12+
import java.sql.ResultSetMetaData;
13+
import java.sql.Statement;
14+
import java.util.ArrayList;
15+
import java.util.LinkedHashMap;
16+
import java.util.List;
17+
import java.util.Map;
18+
import java.util.Properties;
19+
import java.util.concurrent.TimeUnit;
20+
import org.apache.calcite.DataContext;
21+
import org.apache.calcite.config.CalciteConnectionConfig;
22+
import org.apache.calcite.jdbc.CalciteConnection;
23+
import org.apache.calcite.linq4j.Enumerable;
24+
import org.apache.calcite.linq4j.Linq4j;
25+
import org.apache.calcite.rel.RelCollations;
26+
import org.apache.calcite.rel.type.RelDataType;
27+
import org.apache.calcite.rel.type.RelDataTypeFactory;
28+
import org.apache.calcite.schema.ScannableTable;
29+
import org.apache.calcite.schema.Schema;
30+
import org.apache.calcite.schema.SchemaPlus;
31+
import org.apache.calcite.schema.Statistic;
32+
import org.apache.calcite.schema.Statistics;
33+
import org.apache.calcite.schema.impl.AbstractSchema;
34+
import org.apache.calcite.sql.SqlCall;
35+
import org.apache.calcite.sql.SqlNode;
36+
import org.apache.calcite.sql.type.SqlTypeName;
37+
import org.checkerframework.checker.nullness.qual.Nullable;
38+
import org.openjdk.jmh.annotations.Benchmark;
39+
import org.openjdk.jmh.annotations.BenchmarkMode;
40+
import org.openjdk.jmh.annotations.Fork;
41+
import org.openjdk.jmh.annotations.Level;
42+
import org.openjdk.jmh.annotations.Measurement;
43+
import org.openjdk.jmh.annotations.Mode;
44+
import org.openjdk.jmh.annotations.OutputTimeUnit;
45+
import org.openjdk.jmh.annotations.Param;
46+
import org.openjdk.jmh.annotations.Scope;
47+
import org.openjdk.jmh.annotations.Setup;
48+
import org.openjdk.jmh.annotations.State;
49+
import org.openjdk.jmh.annotations.TearDown;
50+
import org.openjdk.jmh.annotations.Warmup;
51+
import org.openjdk.jmh.infra.Blackhole;
52+
53+
/**
54+
* Measures the cost of materializing a Calcite JDBC {@link ResultSet} into {@code Map<String,
55+
* ExprValue>} rows under a wide schema. Reading each cell by column name — the pre-fix path in
56+
* {@code OpenSearchExecutionEngine.buildResultSet} — triggers Avatica's case-insensitive linear
57+
* scan of the column metadata on every call and makes materialization O(rows × columns²). Reading
58+
* by JDBC ordinal — the current path — is linear.
59+
*
60+
* <p>Run with: {@code ./gradlew :benchmarks:jmh -Pjmh.includes=BuildResultSetBenchmark}. The two
61+
* {@code @Benchmark} methods below mirror the two code paths; the ratio between them should grow
62+
* with the column count.
63+
*/
64+
@Warmup(iterations = 1)
65+
@Measurement(iterations = 3)
66+
@BenchmarkMode(Mode.AverageTime)
67+
@OutputTimeUnit(TimeUnit.MILLISECONDS)
68+
@State(Scope.Benchmark)
69+
@Fork(value = 1)
70+
public class BuildResultSetBenchmark {
71+
72+
@Param({"100", "1000", "5000"})
73+
private int columns;
74+
75+
@Param({"100"})
76+
private int rows;
77+
78+
private Connection connection;
79+
private String selectAll;
80+
81+
@Setup(Level.Trial)
82+
public void setupTrial() throws Exception {
83+
Properties info = new Properties();
84+
// Match the engine's default (case-sensitive=false) so getObject(String) hits the same
85+
// equalsIgnoreCase scan it does at runtime.
86+
info.setProperty("caseSensitive", "false");
87+
connection = DriverManager.getConnection("jdbc:calcite:", info);
88+
SchemaPlus root = connection.unwrap(CalciteConnection.class).getRootSchema();
89+
SchemaPlus bench = root.add("BENCH", new AbstractSchema());
90+
bench.add("T", new WideTable(columns, rows));
91+
StringBuilder sb = new StringBuilder("SELECT ");
92+
for (int i = 1; i <= columns; i++) {
93+
if (i > 1) sb.append(',');
94+
sb.append("\"c").append(i).append('"');
95+
}
96+
sb.append(" FROM \"BENCH\".\"T\"");
97+
selectAll = sb.toString();
98+
}
99+
100+
@TearDown(Level.Trial)
101+
public void tearDown() throws Exception {
102+
if (connection != null) connection.close();
103+
}
104+
105+
/** Pre-fix behaviour: read each cell by column name. */
106+
@Benchmark
107+
public void materializeByName(Blackhole bh) throws Exception {
108+
try (Statement stmt = connection.createStatement();
109+
ResultSet rs = stmt.executeQuery(selectAll)) {
110+
ResultSetMetaData md = rs.getMetaData();
111+
int cc = md.getColumnCount();
112+
List<Map<String, Object>> all = new ArrayList<>(rows);
113+
while (rs.next()) {
114+
Map<String, Object> row = new LinkedHashMap<>(cc);
115+
for (int i = 1; i <= cc; i++) {
116+
String name = md.getColumnName(i);
117+
row.put(name, rs.getObject(name));
118+
}
119+
all.add(row);
120+
}
121+
bh.consume(all);
122+
}
123+
}
124+
125+
/** Current behaviour: read each cell by JDBC ordinal, matching the fix for issue #5939. */
126+
@Benchmark
127+
public void materializeByOrdinal(Blackhole bh) throws Exception {
128+
try (Statement stmt = connection.createStatement();
129+
ResultSet rs = stmt.executeQuery(selectAll)) {
130+
ResultSetMetaData md = rs.getMetaData();
131+
int cc = md.getColumnCount();
132+
String[] names = new String[cc];
133+
for (int i = 1; i <= cc; i++) {
134+
names[i - 1] = md.getColumnName(i);
135+
}
136+
List<Map<String, Object>> all = new ArrayList<>(rows);
137+
while (rs.next()) {
138+
Map<String, Object> row = new LinkedHashMap<>(cc);
139+
for (int i = 1; i <= cc; i++) {
140+
row.put(names[i - 1], rs.getObject(i));
141+
}
142+
all.add(row);
143+
}
144+
bh.consume(all);
145+
}
146+
}
147+
148+
/** In-memory table with {@code columns} VARCHAR fields and {@code rows} identical string rows. */
149+
static class WideTable implements ScannableTable {
150+
private final int columns;
151+
private final int rows;
152+
153+
WideTable(int columns, int rows) {
154+
this.columns = columns;
155+
this.rows = rows;
156+
}
157+
158+
@Override
159+
public RelDataType getRowType(RelDataTypeFactory factory) {
160+
RelDataTypeFactory.Builder builder = factory.builder();
161+
for (int i = 1; i <= columns; i++) {
162+
builder.add("c" + i, SqlTypeName.VARCHAR);
163+
}
164+
return builder.build();
165+
}
166+
167+
@Override
168+
public Enumerable<@Nullable Object[]> scan(DataContext root) {
169+
Object[][] data = new Object[rows][columns];
170+
for (int r = 0; r < rows; r++) {
171+
for (int c = 0; c < columns; c++) {
172+
data[r][c] = "v";
173+
}
174+
}
175+
return Linq4j.asEnumerable(data);
176+
}
177+
178+
@Override
179+
public Statistic getStatistic() {
180+
return Statistics.of((double) rows, ImmutableList.of(), RelCollations.createSingleton(0));
181+
}
182+
183+
@Override
184+
public Schema.TableType getJdbcTableType() {
185+
return Schema.TableType.TABLE;
186+
}
187+
188+
@Override
189+
public boolean isRolledUp(String column) {
190+
return false;
191+
}
192+
193+
@Override
194+
public boolean rolledUpColumnValidInsideAgg(
195+
String column,
196+
SqlCall call,
197+
@Nullable SqlNode parent,
198+
@Nullable CalciteConnectionConfig config) {
199+
return false;
200+
}
201+
}
202+
}

‎opensearch/src/main/java/org/opensearch/sql/opensearch/executor/OpenSearchExecutionEngine.java‎

Lines changed: 59 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package org.opensearch.sql.opensearch.executor;
77

88
import com.google.common.base.Suppliers;
9+
import java.lang.reflect.Field;
910
import java.sql.PreparedStatement;
1011
import java.sql.ResultSet;
1112
import java.sql.ResultSetMetaData;
@@ -20,6 +21,7 @@
2021
import java.util.concurrent.ConcurrentHashMap;
2122
import java.util.concurrent.atomic.AtomicReference;
2223
import java.util.function.Supplier;
24+
import org.apache.calcite.avatica.util.Cursor;
2325
import org.apache.calcite.avatica.util.StructImpl;
2426
import org.apache.calcite.plan.RelOptUtil;
2527
import org.apache.calcite.rel.RelNode;
@@ -430,31 +432,37 @@ private static Object processValue(Object value, RelDataType type) throws SQLExc
430432
return value;
431433
}
432434

433-
private QueryResponse buildResultSet(
434-
ResultSet resultSet, RelDataType rowTypes, Integer querySizeLimit) throws SQLException {
435-
// Get the ResultSet metadata to know about columns
435+
QueryResponse buildResultSet(ResultSet resultSet, RelDataType rowTypes, Integer querySizeLimit)
436+
throws SQLException {
436437
ResultSetMetaData metaData = resultSet.getMetaData();
437438
int columnCount = metaData.getColumnCount();
438439
List<RelDataType> fieldTypes =
439440
rowTypes.getFieldList().stream().map(RelDataTypeField::getType).toList();
441+
// Materialise cells via the Avatica accessor list to avoid Avatica's per-cell case-insensitive
442+
// column-name scan, which makes getObject(String) O(rows x columns^2) on wide schemas (#5939).
443+
String[] columnNames = new String[columnCount];
444+
for (int i = 1; i <= columnCount; i++) {
445+
columnNames[i - 1] = metaData.getColumnName(i);
446+
}
447+
List<Cursor.Accessor> accessors = resolveAvaticaAccessors(resultSet);
440448
List<ExprValue> values = new ArrayList<>();
441-
// Iterate through the ResultSet
442449
while (resultSet.next() && (querySizeLimit == null || values.size() < querySizeLimit)) {
443450
Map<String, ExprValue> row = new LinkedHashMap<String, ExprValue>();
444-
// Loop through each column
445451
for (int i = 1; i <= columnCount; i++) {
446-
String columnName = metaData.getColumnName(i);
447-
Object value = resultSet.getObject(columnName);
452+
Object value =
453+
accessors != null
454+
? accessors.get(i - 1).getObject()
455+
: resultSet.getObject(columnNames[i - 1]);
448456
Object converted = processValue(value, fieldTypes.get(i - 1));
449457
ExprValue exprValue = ExprValueUtils.fromObjectValue(converted);
450-
row.put(columnName, exprValue);
458+
row.put(columnNames[i - 1], exprValue);
451459
}
452460
values.add(ExprTupleValue.fromExprValueMap(row));
453461
}
454462

455463
List<Column> columns = new ArrayList<>(metaData.getColumnCount());
456464
for (int i = 1; i <= columnCount; ++i) {
457-
String columnName = metaData.getColumnName(i);
465+
String columnName = columnNames[i - 1];
458466
RelDataType fieldType = fieldTypes.get(i - 1);
459467
// TODO: Correct this after fixing issue github.com/opensearch-project/sql/issues/3751
460468
// The element type of struct and array is currently set to ANY.
@@ -498,6 +506,48 @@ private QueryResponse buildResultSet(
498506
return response;
499507
}
500508

509+
// Resolved once at class-load. Any failure (Avatica renamed/removed the field, module
510+
// restrictions block setAccessible) raises ExceptionInInitializerError so an Avatica upgrade
511+
// surfaces immediately instead of silently reintroducing the #5939 O(cols^2) hot path.
512+
private static final Class<?> AVATICA_RESULT_SET_CLASS;
513+
private static final Field AVATICA_ACCESSOR_LIST_FIELD;
514+
515+
static {
516+
try {
517+
AVATICA_RESULT_SET_CLASS = Class.forName("org.apache.calcite.avatica.AvaticaResultSet");
518+
AVATICA_ACCESSOR_LIST_FIELD = AVATICA_RESULT_SET_CLASS.getDeclaredField("accessorList");
519+
AVATICA_ACCESSOR_LIST_FIELD.setAccessible(true);
520+
} catch (ReflectiveOperationException e) {
521+
throw new ExceptionInInitializerError(
522+
new IllegalStateException(
523+
"AvaticaResultSet.accessorList is no longer reachable via reflection", e));
524+
}
525+
}
526+
527+
/**
528+
* Returns the {@code AvaticaResultSet}'s per-column {@link Cursor.Accessor} list, or {@code null}
529+
* if {@code resultSet} is not an {@code AvaticaResultSet}. Reflection is required because neither
530+
* public {@code getObject} overload returns the raw value at ordinal cost: {@code getObject(int)}
531+
* applies {@code AvaticaSite.get} type coercion (geopoint→WKT, list→ {@code ArrayImpl},
532+
* float→double), and {@code getObject(String)} runs an O(cols) label scan per cell (#5939).
533+
*/
534+
@SuppressWarnings("unchecked")
535+
private static List<Cursor.Accessor> resolveAvaticaAccessors(ResultSet resultSet)
536+
throws SQLException {
537+
if (!resultSet.isWrapperFor(AVATICA_RESULT_SET_CLASS)) return null;
538+
try {
539+
return (List<Cursor.Accessor>)
540+
AVATICA_ACCESSOR_LIST_FIELD.get(resultSet.unwrap(AVATICA_RESULT_SET_CLASS));
541+
} catch (IllegalAccessException e) {
542+
// setAccessible succeeded at init; losing access here would be a JVM-level regression, not
543+
// an Avatica change. Surface loudly rather than falling back to O(cols^2).
544+
throw new IllegalStateException(
545+
"AvaticaResultSet.accessorList became inaccessible after setAccessible; #5939 fast path"
546+
+ " broken.",
547+
e);
548+
}
549+
}
550+
501551
/** Registers opensearch-dependent functions */
502552
private void registerOpenSearchFunctions() {
503553
Optional<NodeClient> nodeClient = client.getNodeClient();

‎opensearch/src/test/java/org/opensearch/sql/opensearch/executor/OpenSearchExecutionEngineTest.java‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import static org.junit.jupiter.api.Assertions.assertTrue;
1313
import static org.junit.jupiter.api.Assertions.fail;
1414
import static org.mockito.ArgumentMatchers.any;
15+
import static org.mockito.ArgumentMatchers.anyString;
1516
import static org.mockito.Mockito.lenient;
1617
import static org.mockito.Mockito.mock;
1718
import static org.mockito.Mockito.verify;
@@ -22,6 +23,8 @@
2223

2324
import java.io.ObjectInput;
2425
import java.io.ObjectOutput;
26+
import java.sql.ResultSet;
27+
import java.sql.ResultSetMetaData;
2528
import java.sql.SQLException;
2629
import java.util.ArrayList;
2730
import java.util.Arrays;
@@ -30,6 +33,10 @@
3033
import java.util.Optional;
3134
import java.util.concurrent.atomic.AtomicReference;
3235
import lombok.RequiredArgsConstructor;
36+
import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
37+
import org.apache.calcite.rel.type.RelDataType;
38+
import org.apache.calcite.rel.type.RelDataTypeFactory;
39+
import org.apache.calcite.sql.type.SqlTypeName;
3340
import org.junit.jupiter.api.BeforeEach;
3441
import org.junit.jupiter.api.DisplayNameGeneration;
3542
import org.junit.jupiter.api.DisplayNameGenerator;
@@ -290,6 +297,49 @@ void does_not_flag_unrelated_failures_as_pit_context_limit() {
290297
assertFalse(OpenSearchExecutionEngine.isPitContextLimitReached(chain));
291298
}
292299

300+
@Test
301+
void build_result_set_falls_back_to_name_lookup_for_non_avatica_result_sets()
302+
throws SQLException {
303+
// Non-Avatica ResultSets have no accessor list; the engine must still materialize correctly
304+
// using the name-based read path. The Avatica fast path (which avoids the quadratic scan
305+
// described in issue #5939) is exercised by Calcite-backed integration tests.
306+
int columnCount = 2000;
307+
int rowCount = 5;
308+
309+
ResultSetMetaData metaData = mock(ResultSetMetaData.class);
310+
when(metaData.getColumnCount()).thenReturn(columnCount);
311+
for (int i = 1; i <= columnCount; i++) {
312+
when(metaData.getColumnName(i)).thenReturn("c" + i);
313+
}
314+
315+
ResultSet resultSet = mock(ResultSet.class);
316+
when(resultSet.getMetaData()).thenReturn(metaData);
317+
AtomicReference<Integer> consumed = new AtomicReference<>(0);
318+
when(resultSet.next())
319+
.thenAnswer(
320+
invocation -> {
321+
int c = consumed.get();
322+
if (c >= rowCount) return false;
323+
consumed.set(c + 1);
324+
return true;
325+
});
326+
when(resultSet.getObject(anyString())).thenReturn("v");
327+
328+
RelDataTypeFactory typeFactory = new JavaTypeFactoryImpl();
329+
RelDataTypeFactory.Builder rowBuilder = typeFactory.builder();
330+
for (int i = 1; i <= columnCount; i++) {
331+
rowBuilder.add("c" + i, typeFactory.createSqlType(SqlTypeName.VARCHAR));
332+
}
333+
RelDataType rowType = rowBuilder.build();
334+
335+
OpenSearchExecutionEngine engine =
336+
new OpenSearchExecutionEngine(client, protector, new PlanSerializer(null));
337+
QueryResponse response = engine.buildResultSet(resultSet, rowType, null);
338+
339+
assertEquals(rowCount, response.getResults().size());
340+
assertEquals(columnCount, response.getSchema().getColumns().size());
341+
}
342+
293343
@Test
294344
void pit_context_limit_check_survives_self_referential_cause() {
295345
// A throwable whose cause is itself must not loop forever (getCause() == this).

0 commit comments

Comments
 (0)