-
Notifications
You must be signed in to change notification settings - Fork 398
Expand file tree
/
Copy pathEETDMLOracle.java
More file actions
532 lines (493 loc) · 25.8 KB
/
Copy pathEETDMLOracle.java
File metadata and controls
532 lines (493 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
package sqlancer.common.oracle;
import java.sql.SQLException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import sqlancer.IgnoreMeException;
import sqlancer.Randomly;
import sqlancer.Reproducer;
import sqlancer.SQLGlobalState;
import sqlancer.common.ast.newast.Expression;
import sqlancer.common.gen.EETDMLGenerator;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.common.query.SQLancerResultSet;
import sqlancer.common.schema.AbstractSchema;
import sqlancer.common.schema.AbstractTable;
import sqlancer.common.schema.AbstractTableColumn;
import sqlancer.common.schema.AbstractTables;
/**
* EET (Equivalent Expression Transformation) oracle for DML statements, based on "Detecting Logic Bugs in Database
* Engines via Equivalent Expression Transformation" (Jiang & Su, OSDI'24).
*
* <p>
* Whereas {@link EETOracle} transforms a SELECT and compares the two result sets, this oracle transforms a DML
* statement and compares the two database states produced.
*
* <p>
* Adapted from the DQE oracle, state is observed with an auxiliary column ({@link EETDMLGenerator#ROW_ID_COLUMN}) which
* uniquely identifies each row, and each statement is executed inside a transaction that is rolled back, so the two
* statements can be compared against the same starting state without permanently modifying the database. The state is
* captured as a full post-image: each surviving row's identifier together with its content column values, ordered by
* the identifier. This single value-level surface covers every DML statement — a DELETE removes rows from it, an UPDATE
* changes values in it, an INSERT adds rows to it (row identity alone would suffice for DELETE, but not for UPDATE,
* which also transforms the written values). Because rolling back a statement requires a transactional storage engine,
* the DBMS-specific setup must ensure only such engines are used while this oracle is active.
*
* <p>
* DELETE, UPDATE and INSERT are currently supported (one is chosen at random per check). INSERT uses the
* {@code INSERT ... SELECT} form so its transformed value expressions may reference columns; each inserted row is given
* a deterministic identifier derived from its source row so the two runs' post-images align. To support reduction, a
* {@link Reproducer} replays the whole comparison (adding and stamping the row-identifier column, running both
* statements in rolled-back transactions and comparing the post-images) against the reduced database.
*
* @param <E>
* the DBMS-specific expression class
* @param <S>
* the DBMS-specific schema class
* @param <T>
* the DBMS-specific table class
* @param <C>
* the DBMS-specific column class
* @param <G>
* the DBMS-specific global state class
*/
public class EETDMLOracle<E extends Expression<C>, S extends AbstractSchema<?, T>, T extends AbstractTable<C, ?, ?>, C extends AbstractTableColumn<?, ?>, G extends SQLGlobalState<?, S>>
implements TestOracle<G> {
private final G state;
private EETDMLGenerator<E, T, C> gen;
private final EETTransformer<E, ?> transformer;
private final ExpectedErrors errors;
private static final int MAX_DIFF_ROWS_REPORTED = 10; // max differing post-image rows displayed in report log
private String generatedQueryString;
private Reproducer<G> reproducer;
// The SQL and metadata to run and observe one DML comparison, captured as strings so a reproducer can replay it
// against a reduced database without the generator or live schema objects.
private static final class ComparisonQueries {
private final String originalStatement;
private final String transformedStatement;
private final String addRowIdColumn;
private final String stampRowIds;
private final String beginTransaction;
private final String rollback;
private final String dropRowIdColumn;
private final String selectPostImage;
private final int columnCount;
ComparisonQueries(String originalStatement, String transformedStatement, String addRowIdColumn,
String stampRowIds, String beginTransaction, String rollback, String dropRowIdColumn,
String selectPostImage, int columnCount) {
this.originalStatement = originalStatement;
this.transformedStatement = transformedStatement;
this.addRowIdColumn = addRowIdColumn;
this.stampRowIds = stampRowIds;
this.beginTransaction = beginTransaction;
this.rollback = rollback;
this.dropRowIdColumn = dropRowIdColumn;
this.selectPostImage = selectPostImage;
this.columnCount = columnCount;
}
}
// The post-images the original and transformed statements produced, compared for equality to detect the bug.
private static final class PostImages {
private final List<List<String>> original;
private final List<List<String>> transformed;
PostImages(List<List<String>> original, List<List<String>> transformed) {
this.original = original;
this.transformed = transformed;
}
}
// Reproduces a post-image mismatch against the reduced database. Unlike EETOracle's comparison reproducer this does
// not extend AbstractComparisonReproducer: the two sides are not independent, because the row-id stamping (UUID())
// must run once so both observe the same rows, so both post-images are computed together.
private final class EETDMLReproducer implements Reproducer<G> {
private final ComparisonQueries queries;
EETDMLReproducer(ComparisonQueries queries) {
this.queries = queries;
}
@Override
public boolean bugStillTriggers(G globalState) {
PostImages images;
try {
images = computePostImages(globalState, queries);
} catch (AssertionError | SQLException | RuntimeException e) {
// any failure re-running the comparison means this reduced database no longer shows the mismatch
return false;
}
return !images.original.equals(images.transformed);
}
@Override
public String getBugInformation() {
StringBuilder sb = new StringBuilder();
sb.append("-- On the database set up by the statements above, the following statements leave the database"
+ " in different states:").append(System.lineSeparator());
renderStatementLines(sb, queries);
return sb.toString();
}
}
// Builds the reproducer for an unexpected DBMS error, which replays the whole comparison and checks the same error
// still fires.
private UnexpectedErrorReproducer<G> errorReproducer(ComparisonQueries queries, String expectedErrorMessage) {
UnexpectedErrorReproducer.Execution<G> execution = globalState -> computePostImages(globalState, queries);
StringBuilder sb = new StringBuilder();
renderStatementLines(sb, queries);
return new UnexpectedErrorReproducer<>(execution, expectedErrorMessage, sb.toString());
}
// Renders the failing statements as commented lines, shared by the mismatch and the unexpected-error reproducers.
private static void renderStatementLines(StringBuilder sb, ComparisonQueries queries) {
sb.append("-- original: ").append(queries.originalStatement).append(';').append(System.lineSeparator());
sb.append("-- transformed: ").append(queries.transformedStatement).append(';').append(System.lineSeparator());
}
public EETDMLOracle(G state, EETDMLGenerator<E, T, C> gen, ExpectedErrors expectedErrors) {
if (state == null || gen == null || expectedErrors == null) {
throw new IllegalArgumentException("Null variables used to initialize test oracle.");
}
this.state = state;
this.gen = gen;
this.transformer = gen.createTransformer();
this.errors = expectedErrors;
}
@Override
public void check() throws SQLException {
reproducer = null;
List<T> tables = state.getSchema().getDatabaseTables();
if (tables.isEmpty()) {
throw new IgnoreMeException();
}
// A DML statement targets a single table, so operate on exactly one; confining the generator to it keeps the
// predicate and value expressions from referencing another table's columns (which would render invalid
// single-table DML).
T table = Randomly.fromList(tables);
gen = gen.setTablesAndColumns(new AbstractTables<>(List.of(table)));
E predicate = gen.generateBooleanExpression();
// The WHERE predicate is evaluated in a boolean context.
E transformedPredicate = transformer.transform(predicate, true);
// Optionally cap the statement with a LIMIT. The limit and its ordering (a random column subset, made a total
// order by the row-id tiebreaker) are decided once and applied identically to both statements, so the capped
// row set is deterministic and equal across the runs while still exercising varied orderings.
Integer limit = null;
List<C> orderByColumns = List.of();
if (Randomly.getBoolean()) {
limit = (int) Randomly.getNotCachedInteger(0, 10);
orderByColumns = Randomly.subset(table.getColumns());
}
// Generators for the different kinds of statement this oracle supports. One is chosen at random per check
List<DMLStatementGenerator<E, T, C>> statementGenerators = List.of(this::generateDeleteStatements,
this::generateUpdateStatements, this::generateInsertStatements);
StatementPair statements = Randomly.fromList(statementGenerators).generate(table, predicate,
transformedPredicate, orderByColumns, limit);
String originalStatement = statements.original;
String transformedStatement = statements.transformed;
generatedQueryString = originalStatement;
// Capture, as strings, everything needed to run and observe this comparison: the two statements plus the
// auxiliary-column setup, per-run snapshot and teardown. A reproducer replays these against a reduced database,
// where the live generator and schema objects no longer apply.
ComparisonQueries queries = new ComparisonQueries(originalStatement, transformedStatement,
gen.addRowIdColumnStatement(table), gen.stampRowIdsStatement(table), gen.beginTransactionStatement(),
gen.rollbackTransactionStatement(), gen.dropRowIdColumnStatement(table),
gen.selectPostImageStatement(table), gen.postImageColumns(table).size());
PostImages images;
try {
images = computePostImages(state, queries);
} catch (AssertionError unexpectedError) {
reproducer = errorReproducer(queries, TestOracleUtils.getUnexpectedErrorMessage(unexpectedError));
throw unexpectedError;
}
reproducer = new EETDMLReproducer(queries);
if (!images.original.equals(images.transformed)) {
throw new AssertionError(mismatchMessage(table, originalStatement, transformedStatement, images.original,
images.transformed));
}
}
/**
* Runs the whole comparison against {@code globalState}: adds and stamps the row-identifier column once (so both
* runs observe the same rows), snapshots the post-image each statement produces (each inside a rolled-back
* transaction), and drops the column. Both {@link #check()} and the reproducers call this, the former against the
* live database and the latter against a reduced one. A DBMS error the oracle tolerates aborts with
* {@link IgnoreMeException}; an oracle logic bug or unexpected error surfaces as {@link AssertionError}.
*
* @param globalState
* the state whose connection the comparison runs against
* @param queries
* the statements and auxiliary SQL to run
*
* @return the post-images the original and transformed statements produced
*
* @throws SQLException
* if a DBMS interaction fails
*/
private PostImages computePostImages(G globalState, ComparisonQueries queries) throws SQLException {
// Add the auxiliary column outside the try, then guard everything after it with the finally that drops it: the
// ALTER auto-commits (it is not undone by ROLLBACK), so a failure between adding and dropping would leak the
// column and cause cascading duplicate-column failures
if (!new SQLQueryAdapter(queries.addRowIdColumn, errors, true).execute(globalState)) {
throw new IgnoreMeException();
}
try {
// Stamp identifiers once, in autocommit mode, before both runs: both then observe the same rows.
if (!new SQLQueryAdapter(queries.stampRowIds, errors).execute(globalState)) {
throw new IgnoreMeException();
}
List<List<String>> original = snapshotSide(globalState, queries.originalStatement, queries);
List<List<String>> transformed = snapshotSide(globalState, queries.transformedStatement, queries);
return new PostImages(original, transformed);
} finally {
new SQLQueryAdapter(queries.dropRowIdColumn, errors, true).execute(globalState);
}
}
/**
* Generates a DML statement of one kind together with its transformed counterpart. The kinds share this signature
* so the oracle can pick one of them at random per check.
*
* @param <E>
* the DBMS-specific expression class
* @param <T>
* the DBMS-specific table class
* @param <C>
* the DBMS-specific column class
*/
@FunctionalInterface
private interface DMLStatementGenerator<E, T, C> {
StatementPair generate(T table, E predicate, E transformedPredicate, List<C> orderByColumns, Integer limit);
}
/**
* A DML statement and its transformed counterpart, which must leave the database in the same state.
*/
private static final class StatementPair {
private final String original;
private final String transformed;
StatementPair(String original, String transformed) {
this.original = original;
this.transformed = transformed;
}
}
/**
* Generates an UPDATE and its transformed counterpart. Besides the WHERE predicate, UPDATE also transforms the
* written values: each SET value expression is transformed in a scalar context.
*
* @param table
* the table being modified
* @param predicate
* the WHERE predicate of the original statement
* @param transformedPredicate
* the transformed WHERE predicate, used by the transformed statement
* @param orderByColumns
* the columns ordering the statement, empty if it is not capped by a limit
* @param limit
* the maximum number of rows to modify, or {@code null} for no limit
*
* @return the original statement together with its transformed counterpart
*/
private StatementPair generateUpdateStatements(T table, E predicate, E transformedPredicate, List<C> orderByColumns,
Integer limit) {
List<Map.Entry<C, E>> assignments = gen.generateSetAssignments();
List<Map.Entry<C, E>> transformedAssignments = new ArrayList<>();
for (Map.Entry<C, E> assignment : assignments) {
E transformedValue = transformer.transform(assignment.getValue(), false);
transformedAssignments.add(new AbstractMap.SimpleEntry<>(assignment.getKey(), transformedValue));
}
return new StatementPair(gen.updateStatement(table, assignments, predicate, orderByColumns, limit),
gen.updateStatement(table, transformedAssignments, transformedPredicate, orderByColumns, limit));
}
/**
* Generates a DELETE and its transformed counterpart, which differ only in their WHERE predicate.
*
* @param table
* the table being modified
* @param predicate
* the WHERE predicate of the original statement
* @param transformedPredicate
* the transformed WHERE predicate, used by the transformed statement
* @param orderByColumns
* the columns ordering the statement, empty if it is not capped by a limit
* @param limit
* the maximum number of rows to modify, or {@code null} for no limit
*
* @return the original statement together with its transformed counterpart
*/
private StatementPair generateDeleteStatements(T table, E predicate, E transformedPredicate, List<C> orderByColumns,
Integer limit) {
return new StatementPair(gen.deleteStatement(table, predicate, orderByColumns, limit),
gen.deleteStatement(table, transformedPredicate, orderByColumns, limit));
}
/**
* Generates an {@code INSERT ... SELECT} and its transformed counterpart. Besides the WHERE predicate, which
* filters the source rows and is optional here, INSERT also transforms each inserted value in a scalar context.
*
* <p>
* The ordering and limit cap the source rows the statement reads, so it inserts one row per source row kept.
*
* @param table
* the table being modified
* @param predicate
* the WHERE predicate of the original statement
* @param transformedPredicate
* the transformed WHERE predicate, used by the transformed statement
* @param orderByColumns
* the columns ordering the source rows, empty if the statement is not capped by a limit
* @param limit
* the maximum number of source rows to insert from, or {@code null} for no limit
*
* @return the original statement together with its transformed counterpart
*/
private StatementPair generateInsertStatements(T table, E predicate, E transformedPredicate, List<C> orderByColumns,
Integer limit) {
List<E> values = gen.generateInsertValues();
List<E> transformedValues = new ArrayList<>();
for (E value : values) {
transformedValues.add(transformer.transform(value, false));
}
boolean withPredicate = Randomly.getBoolean();
return new StatementPair(
gen.insertStatement(table, values, withPredicate ? predicate : null, orderByColumns, limit),
gen.insertStatement(table, transformedValues, withPredicate ? transformedPredicate : null,
orderByColumns, limit));
}
/**
* Executes {@code statement} inside a transaction that is always rolled back, and returns the resulting post-image:
* the surviving rows' identifier and content column values, ordered by identifier (the resulting database state). A
* DBMS error the oracle tolerates aborts with {@link IgnoreMeException}; an oracle logic bug or unexpected error
* surfaces as {@link AssertionError}.
*
* @param globalState
* the state whose connection the statement runs against
* @param statement
* the DML statement to execute
* @param queries
* supplies the transaction control and post-image select SQL and the post-image's column count
*
* @return the post-image, as one string list (identifier followed by content column values) per surviving row
*
* @throws SQLException
* if a DBMS interaction other than running {@code statement} fails; an error from {@code statement}
* itself instead surfaces as {@link IgnoreMeException} or {@link AssertionError}
*/
private List<List<String>> snapshotSide(G globalState, String statement, ComparisonQueries queries)
throws SQLException {
new SQLQueryAdapter(queries.beginTransaction).execute(globalState);
try {
// execute reports (throws AssertionError for) unexpected errors and returns false for expected ones.
boolean succeeded = new SQLQueryAdapter(statement, errors).execute(globalState);
if (!succeeded) {
// The statement hit an error the oracle tolerates; do not compare states (as EETOracle does for
// SELECT).
throw new IgnoreMeException();
}
return snapshotPostImage(globalState, queries.selectPostImage, queries.columnCount);
} finally {
new SQLQueryAdapter(queries.rollback).execute(globalState);
}
}
/**
* Reads the post-image produced by {@code selectStatement} into one string list per row (each column via
* {@code getString}). A DBMS error the oracle tolerates aborts with {@link IgnoreMeException}; an oracle logic bug
* or unexpected error surfaces as {@link AssertionError}.
*
* @param globalState
* the state whose connection the select runs against
* @param selectStatement
* the post-image select to read; its columns are the identifier followed by the content columns
* @param columnCount
* the number of columns to read from each row
*
* @return the read rows, in the select's order
*
* @throws SQLException
* if cleanup fails (errors thrown elsewhere will always be rethrown as {@link IgnoreMeException} or
* {@link AssertionError})
*/
private List<List<String>> snapshotPostImage(G globalState, String selectStatement, int columnCount)
throws SQLException {
List<List<String>> rows = new ArrayList<>();
SQLQueryAdapter q = new SQLQueryAdapter(selectStatement, errors, true,
globalState.getOptions().canonicalizeSqlString());
SQLancerResultSet result = null;
try {
result = q.executeAndGet(globalState);
if (result == null) {
throw new IgnoreMeException();
}
while (result.next()) {
List<String> row = new ArrayList<>(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.add(result.getString(i));
}
rows.add(row);
}
} catch (Exception e) {
if (e instanceof IgnoreMeException) {
throw e;
}
Throwable current = e;
while (current != null) {
if (current.getMessage() != null && errors.errorIsExpected(current.getMessage())) {
throw new IgnoreMeException();
}
current = current.getCause();
}
throw new AssertionError(selectStatement, e);
} finally {
if (result != null && !result.isClosed()) {
result.close();
}
}
return rows;
}
private String mismatchMessage(T table, String originalStatement, String transformedStatement,
List<List<String>> originalImage, List<List<String>> transformedImage) {
List<String> header = gen.postImageColumns(table);
// Where the identifier sits within a post-image row, per the layout the generator defines
int rowIdIndex = header.indexOf(EETDMLGenerator.ROW_ID_COLUMN);
Map<String, List<String>> originalByRowId = indexByRowId(originalImage, rowIdIndex);
Map<String, List<String>> transformedByRowId = indexByRowId(transformedImage, rowIdIndex);
Set<String> allRowIds = new TreeSet<>();
allRowIds.addAll(originalByRowId.keySet());
allRowIds.addAll(transformedByRowId.keySet());
String nl = System.lineSeparator();
StringBuilder message = new StringBuilder()
.append("-- The original and transformed statements left the database in different states.").append(nl)
.append("-- original: ").append(originalStatement).append(';').append(nl).append("-- transformed: ")
.append(transformedStatement).append(';').append(nl).append("-- differing post-image rows (")
.append(String.join(", ", header)).append("):").append(nl);
int shown = 0;
for (String rowId : allRowIds) {
List<String> originalRow = originalByRowId.get(rowId);
List<String> transformedRow = transformedByRowId.get(rowId);
if (Objects.equals(originalRow, transformedRow)) {
continue;
}
if (shown == MAX_DIFF_ROWS_REPORTED) {
message.append("-- ... (further differences omitted)").append(nl);
break;
}
message.append("-- original: ").append(renderRow(originalRow)).append(nl);
message.append("-- transformed: ").append(renderRow(transformedRow)).append(nl);
shown++;
}
return message.toString();
}
// Indexes a post-image by its row identifier, which each row holds at rowIdIndex
private static Map<String, List<String>> indexByRowId(List<List<String>> image, int rowIdIndex) {
Map<String, List<String>> byRowId = new LinkedHashMap<>();
for (List<String> row : image) {
byRowId.put(row.get(rowIdIndex), row);
}
return byRowId;
}
// Renders a post-image row for the finding message, or "(row absent)" when the row is missing on that side
private static String renderRow(List<String> row) {
return row == null ? "(row absent)" : row.toString();
}
@Override
public String getLastQueryString() {
return generatedQueryString;
}
@Override
public Reproducer<G> getLastReproducer() {
return reproducer;
}
}