Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
Expand All @@ -75,6 +76,12 @@ class NestedRepartitionInteropIntegrationTest {
private static final int BATCHES = 4;
private static final int BATCH_ROWS = 60_000;

// Both tests check the same pair of files per column, which take most of the class's time to
// write: each pair is written once and shared. A class's methods run one at a time.
@TempDir
static Path filesDir;
private static final Map<Column, Path[]> FILES = new EnumMap<>(Column.class);

static {
NativeLoader.loadJni();
// Arrow resolves arrow.uuid on export only once UuidType has registered itself
Expand Down Expand Up @@ -103,14 +110,13 @@ enum Column {

@ParameterizedTest
@EnumSource(Column.class)
void javaCutsTheChunksJniCuts(Column column, @TempDir Path tmp) throws Exception {
// Given
Path jniFile = tmp.resolve("jni.vortex");
Path javaFile = tmp.resolve("java.vortex");
writeWithJni(jniFile, column);
void javaCutsTheChunksJniCuts(Column column) throws Exception {
// Given — the column as vortex-jni cuts it

// When
writeWithJava(javaFile, column);
// When — and as the Java writer cuts it (both written once per class, shared)
Path[] files = files(column);
Path jniFile = files[0];
Path javaFile = files[1];

// Then
long[] expected = chunkRowCounts(jniFile);
Expand All @@ -126,12 +132,11 @@ void javaCutsTheChunksJniCuts(Column column, @TempDir Path tmp) throws Exception
/// range starts and ends mid-chunk and spans a batch boundary, so vortex-jni slices the joins.
@ParameterizedTest
@EnumSource(Column.class)
void jniReadsTheJavaChunksAsItsOwn(Column column, @TempDir Path tmp) throws Exception {
void jniReadsTheJavaChunksAsItsOwn(Column column) throws Exception {
// Given
Path jniFile = tmp.resolve("jni.vortex");
Path javaFile = tmp.resolve("java.vortex");
writeWithJni(jniFile, column);
writeWithJava(javaFile, column);
Path[] files = files(column);
Path jniFile = files[0];
Path javaFile = files[1];

// When
List<String> result = readWithJni(javaFile, 0, (long) BATCHES * BATCH_ROWS);
Expand All @@ -142,6 +147,18 @@ void jniReadsTheJavaChunksAsItsOwn(Column column, @TempDir Path tmp) throws Exce
assertThat(slice).isEqualTo(readWithJni(jniFile, 50_000, 130_000));
}

/// `column` written by vortex-jni (`[0]`) and by the Java writer (`[1]`), once per class.
private static Path[] files(Column column) throws Exception {
Path[] files = FILES.get(column);
if (files == null) {
files = new Path[]{filesDir.resolve(column + "-jni.vortex"), filesDir.resolve(column + "-java.vortex")};
writeWithJni(files[0], column);
writeWithJava(files[1], column);
FILES.put(column, files);
}
return files;
}

// ── row model, shared by both writers ──────────────────────────────────────

private static int listLength(Column column, int row) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,36 @@
import dev.hardwood.reader.ParquetFileReader;
import dev.hardwood.reader.RowReader;
import dev.hardwood.schema.ColumnSchema;
import dev.hardwood.schema.FileSchema;
import io.github.dfa1.vortex.csv.CsvExporter;
import io.github.dfa1.vortex.csv.ExportOptions;
import io.github.dfa1.vortex.core.model.ColumnName;
import io.github.dfa1.vortex.parquet.ParquetImporter;
import io.github.dfa1.vortex.reader.Chunk;
import io.github.dfa1.vortex.reader.ScanOptions;
import io.github.dfa1.vortex.reader.VortexReader;
import io.github.dfa1.vortex.reader.array.Array;
import io.github.dfa1.vortex.reader.array.BoolArray;
import io.github.dfa1.vortex.reader.array.DoubleArray;
import io.github.dfa1.vortex.reader.array.FloatArray;
import io.github.dfa1.vortex.reader.array.IntArray;
import io.github.dfa1.vortex.reader.array.LongArray;
import io.github.dfa1.vortex.reader.array.MaskedArray;
import io.github.dfa1.vortex.reader.array.VarBinArray;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;

/// Oracle vs SUT correctness test for the parquet importer.
/// The Parquet importer against a direct Parquet read, on a real file: the NYC Yellow Taxi
/// 2024-01 month, about 3M rows of integers, timestamps, doubles, strings and nulls. hardwood
/// (the oracle) reads the Parquet rows, [VortexReader] the file `ParquetImporter` wrote, and every
/// cell must match: integers, booleans and strings by value, floats bit for bit, nulls as nulls.
///
/// Oracle: hardwood reads the parquet file row-by-row and emits a CSV using the same
/// formatting rules as `CsvExporter` (`Long.toString` / `Double.toString` / raw string).
///
/// SUT: `ParquetImporter` converts the parquet file to a Vortex file, then
/// `CsvExporter` exports it to CSV.
///
/// A zero-diff between the two CSVs proves the Java parquet importer preserves every
/// value exactly.
///
/// Tagged `slow` (~14 s for ~3M rows): skipped locally, run on CI.
/// Tagged `slow` (a 50 MB download, ~3M rows): skipped locally, run on CI.
@Tag("slow")
class TaxiParquetOracleVsJavaIntegrationTest {

Expand All @@ -45,112 +43,84 @@ class TaxiParquetOracleVsJavaIntegrationTest {
"https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2024-01.parquet";
private static final String TAXI_NAME = "yellow_tripdata_2024-01.parquet";

// CsvExporter writes RFC 4180 records (FastCSV's default), whatever the platform: not newLine()
private static final String RECORD_SEPARATOR = "\r\n";

@Test
void parquetImport_csvExport_matchesDirectParquetRead(@TempDir Path tmp) throws Exception {
void parquetImport_preservesEveryCell(@TempDir Path tmp) throws Exception {
// Given
Path taxiParquet = LocalHttpCache.downloadIfMissingOrSkip(
tmp, LocalHttpCache.ROOT, URI.create(TAXI_URL), TAXI_NAME);
Path vortex = tmp.resolve("taxi.vortex");

Path oracleCsv = tmp.resolve("oracle.csv");
Path sutVortex = tmp.resolve("sut.vortex");
Path sutCsv = tmp.resolve("sut.csv");

// When — oracle: hardwood → CSV
writeOracleCsv(taxiParquet, oracleCsv);

// When — SUT: parquet → vortex → CSV
ParquetImporter.importParquet(taxiParquet, sutVortex);
try (BufferedWriter writer = Files.newBufferedWriter(sutCsv)) {
CsvExporter.exportCsv(sutVortex, writer, ExportOptions.defaults());
}

// Then — zero diff, compared without loading either 3M-line file into the heap
long result = Files.mismatch(oracleCsv, sutCsv);
assertThat(result).as(() -> firstDifferentLine(oracleCsv, sutCsv)).isEqualTo(-1L);
}
// When
ParquetImporter.importParquet(taxiParquet, vortex);

/// The first line where the two files differ: built only when [Files#mismatch] found a
/// difference, for the assertion message.
private static String firstDifferentLine(Path expected, Path actual) {
try (BufferedReader e = Files.newBufferedReader(expected);
BufferedReader a = Files.newBufferedReader(actual)) {
long line = 1;
while (true) {
String expectedLine = e.readLine();
String actualLine = a.readLine();
if (!Objects.equals(expectedLine, actualLine)) {
return "line " + line + ": expected <" + expectedLine + "> but was <" + actualLine + ">";
}
if (expectedLine == null) {
return "the files differ only in line terminators";
}
line++;
}
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
// Then — every row of both, cell by cell; the month has about 3M trips
long result = compareEveryCell(taxiParquet, vortex);
assertThat(result).isGreaterThan(2_900_000L);
}

@SuppressWarnings("SameParameterValue")
private static void writeOracleCsv(Path parquet, Path csv) throws IOException {
/// Walks the Parquet rows and the Vortex chunks in step, failing on the first cell that
/// differs or on either side running out first; returns the number of rows compared.
private static long compareEveryCell(Path parquet, Path vortex) throws Exception {
try (ParquetFileReader pfr = ParquetFileReader.open(InputFile.of(parquet));
RowReader rows = pfr.rowReader();
BufferedWriter out = Files.newBufferedWriter(csv)) {

FileSchema schema = pfr.getFileSchema();
List<ColumnSchema> cols = schema.getColumns();

// header
StringBuilder sb = new StringBuilder();
for (int c = 0; c < cols.size(); c++) {
if (c > 0) {
sb.append(',');
}
sb.append(cols.get(c).name());
}
out.write(sb.toString());
out.write(RECORD_SEPARATOR);

// rows — same formatting rules as CsvExporter.cellValue()
while (rows.hasNext()) {
rows.next();
sb.setLength(0);
for (int c = 0; c < cols.size(); c++) {
if (c > 0) {
sb.append(',');
VortexReader reader = VortexReader.open(vortex);
var scan = reader.scan(ScanOptions.all())) {
List<ColumnSchema> cols = pfr.getFileSchema().getColumns();
long row = 0;
while (scan.hasNext()) {
try (Chunk chunk = scan.next()) {
Array[] columns = new Array[cols.size()];
for (int c = 0; c < cols.size(); c++) {
columns[c] = chunk.column(ColumnName.of(cols.get(c).name()));
}
for (long i = 0; i < chunk.rowCount(); i++, row++) {
if (!rows.hasNext()) {
fail("the Vortex file has more rows than the Parquet file's " + row);
}
rows.next();
for (int c = 0; c < cols.size(); c++) {
compareCell(cols.get(c), rows, columns[c], i, row);
}
}
sb.append(formatCell(cols.get(c), rows));
}
out.write(sb.toString());
out.write(RECORD_SEPARATOR);
}
if (rows.hasNext()) {
fail("the Parquet file has more rows than the Vortex file's " + row);
}
return row;
}
}

/// Formats a parquet cell using the same rules as `CsvExporter.cellValue`: a null field
/// renders as an empty CSV field regardless of the column's type, matching how a
/// `MaskedArray`'s validity bit — not a type-specific zero default — decides nullness.
///
/// @param col the column schema
/// @param reader the row reader positioned at the current row
/// @return the formatted cell string
private static String formatCell(ColumnSchema col, RowReader reader) {
/// One cell. A plain check, not an AssertJ assertion: this runs some 57M times.
private static void compareCell(ColumnSchema col, RowReader rows, Array column, long i, long row) {
String name = col.name();
if (col.repetitionType() == RepetitionType.OPTIONAL && reader.isNull(name)) {
return "";
boolean parquetNull = col.repetitionType() == RepetitionType.OPTIONAL && rows.isNull(name);
Array values = column;
if (column instanceof MaskedArray masked) {
if (!masked.isValid(i)) {
if (!parquetNull) {
fail("row " + row + ", " + name + ": null in Vortex, a value in Parquet");
}
return;
}
values = masked.inner();
}
if (parquetNull) {
fail("row " + row + ", " + name + ": a value in Vortex, null in Parquet");
}
return switch (col.type()) {
case INT32 -> Integer.toString(reader.getInt(name));
case INT64 -> Long.toString(reader.getLong(name));
case FLOAT -> Float.toString(reader.getFloat(name));
case DOUBLE -> Double.toString(reader.getDouble(name));
case BOOLEAN -> Boolean.toString(reader.getBoolean(name));
case BYTE_ARRAY -> reader.getString(name);
boolean same = switch (col.type()) {
case INT32 -> rows.getInt(name) == ((IntArray) values).getInt(i);
case INT64 -> rows.getLong(name) == ((LongArray) values).getLong(i);
case FLOAT -> Float.floatToIntBits(rows.getFloat(name)) == Float.floatToIntBits(((FloatArray) values).getFloat(i));
case DOUBLE -> Double.doubleToLongBits(rows.getDouble(name))
== Double.doubleToLongBits(((DoubleArray) values).getDouble(i));
case BOOLEAN -> rows.getBoolean(name) == ((BoolArray) values).getBoolean(i);
case BYTE_ARRAY -> rows.getString(name).equals(((VarBinArray) values).getString(i));
default -> throw new UnsupportedOperationException(
"unsupported parquet type: " + col.type() + " (column: " + name + ")");
};
if (!same) {
fail("row " + row + ", " + name + ": Vortex differs from Parquet");
}
}
}
Loading