You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by "Jackie-Jiang (via GitHub)" <gi...@apache.org> on 2026/05/02 00:34:21 UTC
[PR] Refine RecordExtractor contract: TIMESTAMP narrows to Long, push time conversions per-format [pinot]
Jackie-Jiang opened a new pull request, #18400:
URL: https://github.com/apache/pinot/pull/18400
## Summary
Refines the type contract from #18378 along one principle: **every time-typed extractor output is timezone-independent.** That gives:
- **TIMESTAMP** → `Long` epoch millis. Format extractors narrow `java.sql.Timestamp` / `java.time.Instant` / `OffsetDateTime` / `ZonedDateTime` / `LocalDateTime` at their boundary; the SPI no longer carries a Timestamp branch. `Long` matches Pinot's TIMESTAMP physical storage and is the form pre-#18378 extractors already produced, so this is total backward-compat for the most common time column.
- **DATE / TIME** stay as `LocalDate` / `LocalTime` — no `long` form is TZ-independent for calendar dates and wall-clock times, so the wrapper is required.
## What changed
**SPI (`BaseRecordExtractor.convertSingleValue`):** trimmed to universal normalizations only — Number widening (`Byte`/`Short` → `Integer`, `BigInteger` → `BigDecimal`), `ByteBuffer` slicing, `Boolean`/`byte[]` passthrough, `toString()` fallback. All Temporal / Timestamp branches removed.
**Format extractors** now own their time conversions:
| Extractor | Change |
|---|---|
| `AvroRecordExtractor` | `Instant` → `Long` in the existing `convertSingleValue` override (`timestamp-millis` / `timestamp-micros`); `LocalDate` / `LocalTime` passthrough also moved here |
| `ParquetNativeRecordExtractor` | `INT96` / `TIMESTAMP_*` return `Long` directly from `extractValue`; `extract()` now bypasses `convert()` entirely (matches `ORCRecordExtractor`'s established pattern — `extractValue` already produces contract-typed values) |
| `ORCRecordExtractor` | `TIMESTAMP` / `TIMESTAMP_INSTANT` return `Long` via `tsv.time + tsv.nanos / 1_000_000` |
| `ArrowToGenericRowConverter` | `LocalDateTime` → `Long` via UTC interpretation |
**`JsonUtils`:** registers `JavaTimeModule` with explicit ISO-8601 formatters for `LocalDate` / `LocalTime` so `PinotDataType.toJson` serializes them correctly when they reach Jackson (today they crash without `jackson-datatype-jsr310`). `java.util.Date` / `java.sql.Timestamp` continue to serialize as numeric epoch millis under Jackson's default `WRITE_DATES_AS_TIMESTAMPS=true` — preserved deliberately to avoid disturbing legacy callers.
**`BaseRecordExtractor.shouldExtract`** removed — unused outside its own tests; format extractors always handle `_extractAll` themselves.
## Behavior changes for downstream consumers
- `Long` epoch millis instead of `Timestamp` for TIMESTAMP columns from any extractor. **Sub-millisecond precision is dropped at the extractor boundary** (matches Pinot's TIMESTAMP physical storage; pre-#18378 extractors already truncated here). For Parquet `TIMESTAMP_NANOS` / `TIMESTAMP_MICROS` and ORC `TIMESTAMP` this is a precision change vs. #18378-as-merged.
- `LocalDate` / `LocalTime` outputs reach Jackson via `PinotDataType.toJson` correctly; previously they threw without the JSR-310 module on the classpath. (This is the original Snowflake-preview-style integration-test failure that motivated the JsonUtils part of this PR.)
## Tests
Format-specific narrowing is exercised in each format's existing test (`AvroRecordExtractorTest`'s `testTimestamp{Millis,Micros}LogicalType*` was renamed and re-asserted against `Long`; `ORCRecordExtractorTest` / `ParquetNativeRecordExtractorTest` similarly). `BaseRecordExtractorTest` no longer carries time-type assertions and its Javadoc explicitly points at the format-level tests. New `JsonUtilsTest` cases cover ISO output for `LocalDate` / `LocalTime` plus nested `Map`/`List` containing them.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refine RecordExtractor contract: TIMESTAMP narrows to Long, push time conversions per-format [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3175845451
##########
pinot-spi/src/main/java/org/apache/pinot/spi/data/readers/BaseRecordExtractor.java:
##########
@@ -77,14 +68,6 @@ public void init(@Nullable Set<String> fields, @Nullable RecordExtractorConfig c
protected void initConfig(@Nullable RecordExtractorConfig config) {
}
Review Comment:
Acknowledged as a deliberate API change. `BaseRecordExtractor` is part of `pinot-spi`'s extractor API which has historically been treated as Evolving — `shouldExtract` was a thin convenience over `_extractAll || _fields.contains(name)` and had zero in-tree callers. Any third-party subclass that called it can switch to the inline check trivially. Trading the small breakage now for a cleaner API that doesn't pretend `_extractAll` and per-field include-list are interchangeable.
##########
pinot-spi/src/main/java/org/apache/pinot/spi/utils/JsonUtils.java:
##########
@@ -157,11 +188,6 @@ public static JsonNode stringToJsonNode(String jsonString)
return DEFAULT_READER.readTree(jsonString);
}
Review Comment:
Acknowledged. The pre-existing signature `Map<String, String>` was lying about the runtime type — internally it deserialized via `MAP_TYPE_REFERENCE` (`Map<String, Object>`), so any external caller using it as `Map<String, String>` would CCE on the first non-string value. Removing the broken method is a forcing function for callers who only got away with it because their data happened to be all-strings; they should migrate to the honest `jsonNodeToMap` (which is exactly the same code with the correct type). Net: shorter migration path than letting a buggy signature linger.
##########
pinot-spi/src/main/java/org/apache/pinot/spi/data/readers/BaseRecordExtractor.java:
##########
@@ -211,22 +194,18 @@ protected Map<Object, Object> convertRecord(Object value) {
getClass().getSimpleName() + " does not support nested records; override convertRecord() to enable.");
}
- /// Converts a single value per the [RecordExtractor] contract:
+ /// Universal normalizations for types that any format extractor might produce:
/// - `Byte` / `Short` widen to `Integer` so all small ints unify behind a single Pinot type
/// - [BigInteger] widens to [BigDecimal] (Pinot has no `BigInteger` data type; downstream transforms handle
/// `BigDecimal` natively)
/// - other `Number` (`Integer` / `Long` / `Float` / `Double` / `BigDecimal`) passes through
/// - `Boolean` passes through
/// - `byte[]` passes through
- /// - [Timestamp] passes through
/// - `ByteBuffer` materializes to `byte[]` (sliced so the source buffer's position is not advanced)
///
- /// [Temporal] family (`java.time`):
- /// - [LocalDate] / [LocalTime] pass through (TZ-independent date / time-of-day)
- /// - [Instant] / [OffsetDateTime] / [ZonedDateTime] bridge to [Timestamp] via [Timestamp#from] — all three are
- /// unambiguously TZ-anchored, so the conversion is lossless (sub-second nanos preserved)
- /// - [LocalDateTime] bridges to [Timestamp] interpreting the wall-clock as UTC
- /// - other [Temporal] types fall through to `value.toString()`
+ /// Date / time types (DATE / TIME / TIMESTAMP) are NOT handled here — see [RecordExtractor] for the contract
+ /// and the format-specific extractor (`convertSingleValue` override or direct construction in `extractValue`)
+ /// for the native-to-contract conversion.
Review Comment:
Acknowledged — this IS the contract refinement. Per the PR description: every time-typed extractor output is timezone-independent, and the right narrowing depends on what the format actually produces (Avro `timestamp-millis` from Instant, JDBC `getTimestamp()` from Timestamp, Parquet `INT96`, etc.). Pinot's bundled extractors that produce time types (Avro, Parquet, ORC, Arrow) are all updated in this PR. Third-party `BaseRecordExtractor` subclasses producing time types do need a one-time update — this is exactly the visible breakage we'd want for a contract change rather than silent behavior drift.
##########
pinot-spi/src/main/java/org/apache/pinot/spi/utils/MapUtils.java:
##########
@@ -50,11 +49,13 @@ private MapUtils() {
}
private static final Logger LOGGER = LoggerFactory.getLogger(MapUtils.class);
- private static final ObjectMapper SORTED_MAPPER =
- new ObjectMapper().configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
- private static final ObjectMapper UNSORTED_MAPPER = new ObjectMapper();
- private static final TypeReference<Map<String, Object>> MAP_TYPE_REFERENCE = new TypeReference<>() {
- };
+
+ // Pinot's standard ObjectMapper config (JSR-310 / ISO-8601 for LocalDate / LocalTime — see JsonUtils),
+ // plus key-ordered output for the sorted variant so byte output is a pure function of the logical map.
+ // Writes only — read paths delegate to JsonUtils, whose DEFAULT_READER is already JSR-310-aware.
+ private static final ObjectWriter SORTED_WRITER = JsonUtils.newObjectMapperWithJavaTime()
+ .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true).writer();
+ private static final ObjectWriter UNSORTED_WRITER = JsonUtils.newObjectMapperWithJavaTime().writer();
Review Comment:
Fair. Added 4 cases in `MapUtilsTest`:
- `testToStringSerializesLocalDateAsIsoString` / `testToStringSerializesLocalTimeAsIsoString` — JSR-310 → ISO output via the `MapUtils` writers (separate from `JsonUtils`).
- `testSerializeMapWithLocalDateRoundTrips` — full `serializeMap`/`deserializeMap` cycle confirms the binary path doesn't crash and the deserialized form is the expected ISO string.
- `testToStringSerializesNestedMapWithLocalDate` — the original integration-test-failure scenario: Map containing a nested Map with a LocalDate value.
##########
pinot-plugins/pinot-input-format/pinot-arrow/src/main/java/org/apache/pinot/plugin/inputformat/arrow/ArrowToGenericRowConverter.java:
##########
@@ -246,12 +245,10 @@ private Object convertArrowTypeToPinotCompatible(@Nullable Object value) {
return value.toString();
}
- // Handle Arrow LocalDateTime -> java.sql.Timestamp conversion
+ // Handle Arrow LocalDateTime -> Long epoch millis (per RecordExtractor contract: TIMESTAMP → Long).
if (value instanceof LocalDateTime) {
- // Arrow TimeStampMilliVector.getObject() returns LocalDateTime, but Pinot expects
- // java.sql.Timestamp objects for proper timestamp handling and native support
LocalDateTime dateTime = (LocalDateTime) value;
- return Timestamp.from(dateTime.toInstant(ZoneOffset.UTC));
+ return dateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
Review Comment:
Good catch. Added `testArrowTimestampConvertedToExactUtcEpochMillis`: builds a single-row Arrow batch with a fixed `baseTime = 1649924302123L` (instead of `System.currentTimeMillis()`), runs through the decoder, and asserts the converter emits exactly that long. This catches both wrong-math and wrong-zone regressions — if the converter started using JVM-local instead of UTC the assertion would fail (unless the JVM happens to be in UTC). `ArrowTestDataUtil.createMultiTypeArrowIpcData` got a new overload that takes the base time so the existing test still passes through with `System.currentTimeMillis()`.
##########
pinot-plugins/pinot-input-format/pinot-orc/src/main/java/org/apache/pinot/plugin/inputformat/orc/ORCRecordExtractor.java:
##########
@@ -206,13 +206,12 @@ private static Object extractSingleValue(String field, ColumnVector columnVector
}
case TIMESTAMP:
case TIMESTAMP_INSTANT: {
- // `time[rowId]` is epoch millis truncated to second precision; sub-second nanos (0..999_999_999)
+ // `time[rowId]` is epoch millis (truncated to second precision); sub-second nanos (0..999_999_999)
// live in `nanos[rowId]`. `TIMESTAMP_INSTANT` (UTC instant) shares the same vector layout as
- // `TIMESTAMP` (local). Construct a `Timestamp` and set the full nanos field to preserve precision.
+ // `TIMESTAMP` (local). Per the contract, output is `Long` epoch millis; sub-millisecond precision is
+ // dropped here to match Pinot's TIMESTAMP physical storage.
TimestampColumnVector tsv = (TimestampColumnVector) columnVector;
- Timestamp ts = new Timestamp(tsv.time[rowId]);
- ts.setNanos(tsv.nanos[rowId]);
- return ts;
+ return tsv.time[rowId] + tsv.nanos[rowId] / 1_000_000L;
Review Comment:
Fair. Added `testTimestampPreEpochExtractedAsLongEpochMillis`: pre-epoch value `-60_000` millis (1969-12-31T23:59:00Z) with `time = -60_000, nanos = 0`. ORC's `nanos` field is always non-negative (0..999_999_999), so the relevant edge case is whether the extractor's `time + nanos / 1_000_000` arithmetic handles negative `time` correctly — which it does because Java integer division on the non-negative `nanos` is well-defined and the addition preserves sign.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3179952749
##########
pinot-plugins/pinot-input-format/pinot-parquet/src/main/java/org/apache/pinot/plugin/inputformat/parquet/ParquetNativeRecordExtractor.java:
##########
@@ -148,95 +164,74 @@ private Object extractValue(Group from, int fieldIndex, Type fieldType, int inde
return BigDecimal.valueOf(longValue, decimalLogicalTypeAnnotation.getScale());
}
if (logicalTypeAnnotation instanceof LogicalTypeAnnotation.TimeLogicalTypeAnnotation) {
- // `TIME_MICROS` / `TIME_NANOS` → [LocalTime] preserving full nanosecond precision.
+ // `TIME_MICROS` / `TIME_NANOS` → [LocalTime] preserving full nanosecond precision, or raw value
+ // (in the column's declared unit) when configured.
+ if (_extractRawTimeValues) {
+ return longValue;
+ }
LogicalTypeAnnotation.TimeUnit timeUnit =
((LogicalTypeAnnotation.TimeLogicalTypeAnnotation) logicalTypeAnnotation).getUnit();
return LocalTime.ofNanoOfDay(timeUnit == LogicalTypeAnnotation.TimeUnit.MICROS ? longValue * 1_000L
: longValue);
}
if (logicalTypeAnnotation instanceof LogicalTypeAnnotation.TimestampLogicalTypeAnnotation) {
- // `TIMESTAMP_MILLIS` / `TIMESTAMP_MICROS` / `TIMESTAMP_NANOS` → `java.sql.Timestamp` preserving
- // sub-millisecond precision via `setNanos`.
- return timestampFromLong(longValue,
+ // `TIMESTAMP_MILLIS` / `TIMESTAMP_MICROS` / `TIMESTAMP_NANOS` → [Timestamp] preserving sub-millisecond
+ // nanos via `setNanos`. Raw mode returns the value as stored in the column's declared unit.
+ // TODO: `isAdjustedToUTC()` is ignored — a `timestamp-* adjustToUTC=false` field is local-clock
+ // time, not a UTC instant, but we treat all values as UTC instants per the Pinot TIMESTAMP
+ // contract. For local-datetime data the produced `Timestamp` will be off by the JVM TZ offset.
+ if (_extractRawTimeValues) {
+ return longValue;
+ }
+ return ParquetUtils.convertLongToTimestamp(longValue,
((LogicalTypeAnnotation.TimestampLogicalTypeAnnotation) logicalTypeAnnotation).getUnit());
Review Comment:
`timestamp-*` annotations with `isAdjustedToUTC=false` are still decoded as UTC instants here. For Parquet local timestamps that means the produced `Timestamp` is shifted by the JVM/default-zone offset, so ingestion silently stores the wrong wall-clock value. This needs to branch on `isAdjustedToUTC()` (or stay raw) instead of treating both variants identically.
##########
pinot-plugins/pinot-input-format/pinot-avro-base/src/main/java/org/apache/pinot/plugin/inputformat/avro/AvroRecordReaderConfig.java:
##########
@@ -20,17 +20,16 @@
import org.apache.pinot.spi.data.readers.RecordReaderConfig;
-/**
- * Config for {@link AvroRecordReader}
- */
+
+/// Config for [AvroRecordReader]. See [AvroRecordExtractorConfig] for the meaning of `extractRawTimeValues`.
public class AvroRecordReaderConfig implements RecordReaderConfig {
- private boolean _enableLogicalTypes = true;
+ private boolean _extractRawTimeValues;
- public boolean isEnableLogicalTypes() {
- return _enableLogicalTypes;
+ public boolean isExtractRawTimeValues() {
+ return _extractRawTimeValues;
}
- public void setEnableLogicalTypes(boolean enableLogicalTypes) {
- _enableLogicalTypes = enableLogicalTypes;
+ public void setExtractRawTimeValues(boolean extractRawTimeValues) {
+ _extractRawTimeValues = extractRawTimeValues;
}
Review Comment:
This renames the only public Avro logical-type toggle from `enableLogicalTypes` to `extractRawTimeValues` without any compatibility alias. Existing ingestion configs that set `enableLogicalTypes=false` will now be ignored and fall back to the new default, which flips those tables from raw values to converted DATE/TIME/TIMESTAMP values on upgrade.
##########
pinot-plugins/pinot-input-format/pinot-avro-base/src/main/java/org/apache/pinot/plugin/inputformat/avro/AvroRecordExtractor.java:
##########
@@ -48,87 +57,196 @@
/// - avro nested `record` → [GenericRecord] → `Map<String, Object>`
/// - avro `union[null, X]` with the `null` branch selected → `null`
///
-/// **Logical types** (applied when `enableLogicalTypes = true`, the config default; `GenericDatumReader` emits
-/// the post-conversion Java types listed below):
-/// - `decimal` → `BigDecimal` → `BigDecimal`
-/// - `uuid` → `UUID` → `String` (UUID string form via `UUID.toString()`)
-/// - `date` → `LocalDate` → `LocalDate` (passes through; TZ-independent)
-/// - `time-millis` / `time-micros` → `LocalTime` → `LocalTime` (passes through; full ns precision preserved)
-/// - `timestamp-millis` / `timestamp-micros` → `Instant` → `java.sql.Timestamp` (sub-millisecond nanos preserved
-/// via `Timestamp.getNanos()`)
+/// **Logical types** (`GenericDatumReader` emits the post-Avro-conversion Java type, then this extractor maps to the
+/// Pinot contract type):
+/// - `decimal` → `BigDecimal` → `BigDecimal` (always converted; raw bytes aren't interpretable without external
+/// precision/scale)
+/// - `timestamp-millis` → `Instant` → [Timestamp], or `Long` raw epoch millis when `extractRawTimeValues`
+/// is `true`
+/// - `timestamp-micros` → `Instant` → [Timestamp] (sub-millisecond micros preserved), or `Long` raw epoch
+/// micros when `extractRawTimeValues` is `true`
+/// - `date` → `LocalDate` → `LocalDate`, or `Integer` raw days-since-epoch when `extractRawTimeValues` is
+/// `true`
+/// - `time-millis` → `LocalTime` → `LocalTime`, or `Integer` raw ms-since-midnight when
+/// `extractRawTimeValues` is `true`
+/// - `time-micros` → `LocalTime` → `LocalTime`, or `Long` raw µs-since-midnight when `extractRawTimeValues`
+/// is `true`
+/// - `uuid` → [java.util.UUID] → [java.util.UUID] (always converted; downstream type transformer adapts to
+/// the Pinot column type — `STRING` column gets canonical UUID string, `BYTES` column gets 16-byte
+/// big-endian form)
public class AvroRecordExtractor extends BaseRecordExtractor<GenericRecord> {
- private boolean _applyLogicalTypes = true;
+
+ // Avro logical-type names (copied from org.apache.avro.LogicalTypes).
+ private static final String DECIMAL = "decimal";
+ private static final String TIMESTAMP_MILLIS = "timestamp-millis";
+ private static final String TIMESTAMP_MICROS = "timestamp-micros";
+ private static final String DATE = "date";
+ private static final String TIME_MILLIS = "time-millis";
+ private static final String TIME_MICROS = "time-micros";
+ private static final String UUID = "uuid";
+
+ private static final Map<String, Conversion<?>> CONVERSION_MAP = Map.of(
+ DECIMAL, new Conversions.DecimalConversion(),
+ TIMESTAMP_MILLIS, new TimeConversions.TimestampMillisConversion(),
+ TIMESTAMP_MICROS, new TimeConversions.TimestampMicrosConversion(),
+ DATE, new TimeConversions.DateConversion(),
+ TIME_MILLIS, new TimeConversions.TimeMillisConversion(),
+ TIME_MICROS, new TimeConversions.TimeMicrosConversion(),
+ UUID, new Conversions.UUIDConversion()
+ );
+ private static final Set<String> TEMPORAL_LOGICAL_TYPES =
+ Set.of(TIMESTAMP_MILLIS, TIMESTAMP_MICROS, DATE, TIME_MILLIS, TIME_MICROS);
+
+ protected boolean _extractRawTimeValues;
@Override
protected void initConfig(@Nullable RecordExtractorConfig config) {
if (config instanceof AvroRecordExtractorConfig) {
- _applyLogicalTypes = ((AvroRecordExtractorConfig) config).isEnableLogicalTypes();
+ _extractRawTimeValues = ((AvroRecordExtractorConfig) config).isExtractRawTimeValues();
}
}
@Override
public GenericRow extract(GenericRecord from, GenericRow to) {
+ Schema schema = from.getSchema();
if (_extractAll) {
- List<Schema.Field> fields = from.getSchema().getFields();
- for (Schema.Field field : fields) {
+ for (Schema.Field field : schema.getFields()) {
String fieldName = field.name();
- Object value = from.get(fieldName);
- if (_applyLogicalTypes) {
- value = AvroSchemaUtil.applyLogicalType(field, value);
- }
- if (value != null) {
- value = transformValue(value, field);
- }
- to.putValue(fieldName, value);
+ to.putValue(fieldName, convertValue(field.schema(), from.get(fieldName)));
}
} else {
for (String fieldName : _fields) {
- Schema.Field field = from.getSchema().getField(fieldName);
+ Schema.Field field = schema.getField(fieldName);
if (field != null) {
- Object value = from.get(field.pos());
- if (_applyLogicalTypes) {
- value = AvroSchemaUtil.applyLogicalType(field, value);
- }
- if (value != null) {
- value = transformValue(value, field);
- }
- to.putValue(fieldName, value);
+ to.putValue(fieldName, convertValue(field.schema(), from.get(field.pos())));
}
}
}
return to;
}
- protected Object transformValue(Object value, Schema.Field field) {
- return convert(value);
+ /// Schema-driven dispatch — produces a contract-compliant value in a single walk.
+ /// `null` short-circuits at the top so subclasses overriding [#convertLeaf] never see null.
+ @Nullable
+ protected Object convertValue(Schema schema, @Nullable Object value) {
+ if (value == null) {
+ return null;
+ }
+ schema = resolveUnionSchema(schema);
+ switch (schema.getType()) {
+ case ARRAY:
+ // GenericDatumReader emits array<T> as GenericData.Array, which is a List.
+ return convertArray(schema, (List<?>) value);
+ case MAP:
+ // GenericDatumReader emits map<T> as a HashMap. Avro keys are always strings; the runtime key type
+ // is `Utf8` unless the schema declares `avro.java.string = "String"`. We normalize to `String`.
+ return convertMap(schema, (Map<?, ?>) value);
+ case RECORD:
+ return convertRecord(schema, (GenericRecord) value);
+ default:
+ return convertLeaf(schema, value);
+ }
}
- @Override
- protected boolean isRecord(Object value) {
- return value instanceof GenericRecord;
+ /// Converts a leaf (non-container) Avro value to its Pinot contract type. Subclasses override to handle
+ /// format-specific extensions (e.g. parquet-avro's INT96 surfaced as a `fixed(12)` with a sentinel doc).
+ /// The default handles the Avro spec — primitives + the seven registered logical types.
+ ///
+ /// Per the Avro spec, only STRING / BYTES / FIXED / INT / LONG can carry a logical-type annotation; the
+ /// other primitive types skip the lookup entirely. When a logical-type conversion runs, `Instant`
+ /// results (`timestamp-millis` / `timestamp-micros`) are post-mapped to [Timestamp] per the Pinot
+ /// contract. When [#_extractRawTimeValues] is set, temporal logical types pass through the raw
+ /// underlying integer.
+ protected Object convertLeaf(Schema schema, Object value) {
+ Schema.Type type = schema.getType();
+ switch (type) {
+ case BOOLEAN:
+ case FLOAT:
+ case DOUBLE:
+ // The Avro spec defines no logical types for these primitives — skip the logical-type lookup.
+ return value;
+ case ENUM:
+ // No logical types; `EnumSymbol.toString()` returns the canonical enum-symbol string.
+ return value.toString();
+ default:
+ // INT / LONG / STRING / BYTES / FIXED — fall through to logical-type handling below.
+ break;
+ }
+ LogicalType logicalType = LogicalTypes.fromSchemaIgnoreInvalid(schema);
+ if (logicalType != null) {
+ String name = logicalType.getName();
+ if (!(_extractRawTimeValues && TEMPORAL_LOGICAL_TYPES.contains(name))) {
+ Conversion<?> conversion = CONVERSION_MAP.get(name);
+ if (conversion != null) {
+ Object converted = Conversions.convertToLogicalType(value, schema, logicalType, conversion);
+ return converted instanceof Instant ? Timestamp.from((Instant) converted) : converted;
+ }
+ }
+ }
+ // No logical-type conversion fired — fall through to physical-type normalization.
+ switch (type) {
+ case STRING:
+ // `Utf8.toString()` returns the decoded String; an already-`String` value is a no-op.
+ return value.toString();
+ case BYTES:
+ // ByteBuffer might be reused by the reader. Slice to avoid advancing the original buffer's position.
+ ByteBuffer slice = ((ByteBuffer) value).slice();
+ byte[] bytes = new byte[slice.limit()];
+ slice.get(bytes);
+ return bytes;
+ case FIXED:
+ return ((GenericFixed) value).bytes();
+ default:
+ // INT / LONG with no logical type, or temporal raw-mode pass-through.
+ return value;
+ }
}
- @Override
- protected Map<Object, Object> convertRecord(Object value) {
- GenericRecord record = (GenericRecord) value;
- List<Schema.Field> fields = record.getSchema().getFields();
- Map<Object, Object> convertedMap = Maps.newHashMapWithExpectedSize(fields.size());
+ private Object[] convertArray(Schema schema, List<?> list) {
+ Schema elementSchema = schema.getElementType();
+ int numElements = list.size();
+ Object[] result = new Object[numElements];
+ for (int i = 0; i < numElements; i++) {
+ result[i] = convertValue(elementSchema, list.get(i));
+ }
+ return result;
+ }
+
+ private Map<String, Object> convertMap(Schema schema, Map<?, ?> map) {
+ Schema valueSchema = schema.getValueType();
+ Map<String, Object> result = Maps.newHashMapWithExpectedSize(map.size());
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ result.put(entry.getKey().toString(), convertValue(valueSchema, entry.getValue()));
+ }
+ return result;
+ }
+
+ private Map<String, Object> convertRecord(Schema schema, GenericRecord record) {
+ List<Schema.Field> fields = schema.getFields();
+ Map<String, Object> result = Maps.newHashMapWithExpectedSize(fields.size());
for (Schema.Field field : fields) {
- String fieldName = field.name();
- Object fieldValue = record.get(fieldName);
- Object convertedValue = fieldValue != null ? transformValue(fieldValue, field) : null;
- convertedMap.put(fieldName, convertedValue);
+ result.put(field.name(), convertValue(field.schema(), record.get(field.name())));
}
- return convertedMap;
+ return result;
}
- /// Adds Avro-specific handling: [GenericFixed] (`fixed`) → `byte[]`. Everything else delegates to the base
- /// (see class Javadoc for the full Avro-source → Java-output matrix).
- @Override
- protected Object convertSingleValue(Object value) {
- if (value instanceof GenericFixed) {
- return ((GenericFixed) value).bytes();
+ private static Schema resolveUnionSchema(Schema schema) {
+ if (!schema.isUnion()) {
+ return schema;
+ }
+ // Prefer the first non-null branch carrying a logical type; otherwise the first non-null branch.
+ Schema firstNonNull = null;
+ for (Schema sub : schema.getTypes()) {
+ if (sub.getType() == Schema.Type.NULL) {
+ continue;
+ }
+ if (sub.getLogicalType() != null) {
+ return sub;
+ }
+ if (firstNonNull == null) {
+ firstNonNull = sub;
+ }
}
- return super.convertSingleValue(value);
+ return firstNonNull != null ? firstNonNull : schema;
Review Comment:
`resolveUnionSchema()` now collapses every union to the first non-null branch (or the first logical branch) before looking at the actual runtime value. That breaks Avro unions with multiple non-null members: a value from any later branch will be decoded against the wrong schema, which can leak `Utf8`/other raw objects or even throw `ClassCastException` for record-vs-scalar unions. The old extractor converted based on the runtime value and did not have this regression.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3180068754
##########
pinot-common/src/main/java/org/apache/pinot/common/utils/PinotDataType.java:
##########
@@ -1590,6 +1700,9 @@ public static PinotDataType getSingleValueType(Class<?> cls) {
if (cls == byte[].class) {
return BYTES;
}
+ if (cls == UUID.class) {
+ return UUID;
+ }
Review Comment:
Adding `UUID` only to `getSingleValueType(Class<?>)` leaves the multi-value path unchanged. `DataTypeTransformerUtils` determines MV source types via `PinotDataType.getMultiValueType(values[0].getClass())`; for `Object[]` of `java.util.UUID` this still falls back to `OBJECT_ARRAY`, and `BYTES_ARRAY.convert(...)` then fails because `OBJECT.toBytes(...)` is unsupported. As a result, ingesting a multi-value UUID logical type into a Pinot `BYTES` column now breaks even though the new single-value UUID contract says BYTES should receive the 16-byte form.
##########
pinot-plugins/pinot-input-format/pinot-parquet/src/main/java/org/apache/pinot/plugin/inputformat/parquet/ParquetNativeRecordExtractor.java:
##########
@@ -311,11 +306,26 @@ private Map<String, Object> extractKeyValueMap(Group group) {
Group keyValueGroup = group.getGroup(0, i);
Object key = extractValue(keyValueGroup, keyIndex);
Object value = extractValue(keyValueGroup, valueIndex);
- map.put(key.toString(), value);
+ map.put(stringifyMapKey(key), value);
}
return map;
}
+ /// Stringifies a map key per the Pinot `Map<String, Object>` contract. `byte[]` keys (unannotated BINARY /
+ /// FIXED) base64-encode; everything else (`String`, `Integer`, `Long`, `Float`, `Double`, `Boolean`,
+ /// `BigDecimal`, `UUID`, `LocalDate`, `LocalTime`, `Timestamp`) has a meaningful `toString()`.
+ ///
+ /// **Why base64 (not hex)**: this matches the Pinot MAP value's JSON ser/de path — Jackson serializes any
+ /// `byte[]` value as base64, so a base64-encoded key reads uniformly with the rest of a serialized map.
+ /// Pinot also uses hex via `BytesUtils.toHexString` for the BYTES→STRING column-type conversion, but the
+ /// MAP path goes through Jackson, so base64 wins on consistency here.
+ private static String stringifyMapKey(Object key) {
+ if (key instanceof byte[]) {
+ return Base64.getEncoder().encodeToString((byte[]) key);
+ }
+ return key.toString();
Review Comment:
`stringifyMapKey()` now treats `Timestamp` keys as safe to stringify with `toString()`, but this PR itself documents in `JsonUtils` that `Timestamp.toString()` is JVM-timezone-dependent. That means a Parquet MAP whose key column is a timestamp logical type will ingest different string keys on machines with different default time zones, even though the underlying Parquet value is the same.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3185724224
##########
pinot-plugins/pinot-input-format/pinot-avro-base/src/main/java/org/apache/pinot/plugin/inputformat/avro/AvroRecordExtractor.java:
##########
@@ -41,94 +55,209 @@
/// - avro `double` → `Double` → `Double`
/// - avro `string` → `Utf8` → `String` (via `Utf8.toString()`)
/// - avro `bytes` → `ByteBuffer` → `byte[]` (materialized from the buffer's remaining content)
-/// - avro `fixed` → [GenericFixed] / `GenericData.Fixed` → `byte[]`
+/// - avro `fixed` → `GenericFixed` / `GenericData.Fixed` → `byte[]`
/// - avro `enum` → `GenericData.EnumSymbol` → `String` (enum name)
/// - avro `array<T>` → `List<T>` → `Object[]` (each element recursively converted)
/// - avro `map<string, T>` → `Map<Utf8, T>` → `Map<String, Object>` (each value recursively converted)
-/// - avro nested `record` → [GenericRecord] → `Map<String, Object>`
+/// - avro nested `record` → `GenericRecord` → `Map<String, Object>`
/// - avro `union[null, X]` with the `null` branch selected → `null`
///
-/// **Logical types** (applied when `enableLogicalTypes = true`, the config default; `GenericDatumReader` emits
-/// the post-conversion Java types listed below):
-/// - `decimal` → `BigDecimal` → `BigDecimal`
-/// - `uuid` → `UUID` → `String` (UUID string form via `UUID.toString()`)
-/// - `date` → `LocalDate` → `LocalDate` (passes through; TZ-independent)
-/// - `time-millis` / `time-micros` → `LocalTime` → `LocalTime` (passes through; full ns precision preserved)
-/// - `timestamp-millis` / `timestamp-micros` → `Instant` → `java.sql.Timestamp` (sub-millisecond nanos preserved
-/// via `Timestamp.getNanos()`)
+/// **Logical types** (the reader emits the raw Avro physical type; this extractor applies the conversion via
+/// [#CONVERSION_MAP] to produce the Pinot contract type):
+/// - `decimal` / `big-decimal` → raw `ByteBuffer` → [BigDecimal] (always converted; raw bytes aren't interpretable
+/// without external precision/scale)
+/// - `timestamp-millis` → raw `Long` → [Timestamp], or `Long` raw epoch millis when `extractRawTimeValues` is `true`
+/// - `timestamp-micros` → raw `Long` → [Timestamp] (sub-millisecond micros preserved), or `Long` raw epoch micros when
+/// `extractRawTimeValues` is `true`
+/// - `timestamp-nanos` → raw `Long` → [Timestamp] (nanosecond precision preserved), or `Long` raw epoch nanos when
+/// `extractRawTimeValues` is `true`
+/// - `date` → raw `Integer` → [LocalDate], or `Integer` raw days-since-epoch when `extractRawTimeValues` is `true`
+/// - `time-millis` → raw `Integer` → [LocalTime], or `Integer` raw ms-since-midnight when `extractRawTimeValues` is
+/// `true`
+/// - `time-micros` → raw `Long` → [LocalTime], or `Long` raw µs-since-midnight when `extractRawTimeValues` is `true`
+/// - `uuid` → raw `Utf8` / `GenericFixed` → [UUID] (always converted; downstream type transformer adapts to the Pinot
+/// column type — `STRING` column gets canonical UUID string, `BYTES` column gets 16-byte big-endian form)
public class AvroRecordExtractor extends BaseRecordExtractor<GenericRecord> {
- private boolean _applyLogicalTypes = true;
+ private static final Conversion<BigDecimal> DECIMAL_CONVERSION = new Conversions.DecimalConversion();
+ private static final Conversion<BigDecimal> BIG_DECIMAL_CONVERSION = new Conversions.BigDecimalConversion();
+ private static final Conversion<Instant> TIMESTAMP_MILLIS_CONVERSION =
+ new TimeConversions.TimestampMillisConversion();
+ private static final Conversion<Instant> TIMESTAMP_MICROS_CONVERSION =
+ new TimeConversions.TimestampMicrosConversion();
+ private static final Conversion<Instant> TIMESTAMP_NANOS_CONVERSION = new TimeConversions.TimestampNanosConversion();
+ private static final Conversion<LocalDate> DATE_CONVERSION = new TimeConversions.DateConversion();
+ private static final Conversion<LocalTime> TIME_MILLIS_CONVERSION = new TimeConversions.TimeMillisConversion();
+ private static final Conversion<LocalTime> TIME_MICROS_CONVERSION = new TimeConversions.TimeMicrosConversion();
+ private static final Conversion<UUID> UUID_CONVERSION = new Conversions.UUIDConversion();
+
+ private static final Map<String, Conversion<?>> CONVERSION_MAP = Map.of(
+ DECIMAL_CONVERSION.getLogicalTypeName(), DECIMAL_CONVERSION,
+ BIG_DECIMAL_CONVERSION.getLogicalTypeName(), BIG_DECIMAL_CONVERSION,
+ TIMESTAMP_MILLIS_CONVERSION.getLogicalTypeName(), TIMESTAMP_MILLIS_CONVERSION,
+ TIMESTAMP_MICROS_CONVERSION.getLogicalTypeName(), TIMESTAMP_MICROS_CONVERSION,
+ TIMESTAMP_NANOS_CONVERSION.getLogicalTypeName(), TIMESTAMP_NANOS_CONVERSION,
+ DATE_CONVERSION.getLogicalTypeName(), DATE_CONVERSION,
+ TIME_MILLIS_CONVERSION.getLogicalTypeName(), TIME_MILLIS_CONVERSION,
+ TIME_MICROS_CONVERSION.getLogicalTypeName(), TIME_MICROS_CONVERSION,
+ UUID_CONVERSION.getLogicalTypeName(), UUID_CONVERSION
+ );
+
+ private static final Set<String> TEMPORAL_LOGICAL_TYPES = Set.of(
+ TIMESTAMP_MILLIS_CONVERSION.getLogicalTypeName(),
+ TIMESTAMP_MICROS_CONVERSION.getLogicalTypeName(),
+ TIMESTAMP_NANOS_CONVERSION.getLogicalTypeName(),
+ DATE_CONVERSION.getLogicalTypeName(),
+ TIME_MILLIS_CONVERSION.getLogicalTypeName(),
Review Comment:
`timestamp-nanos` was added to the Avro logical-type conversion path, but this file's tests still cover only millis/micros timestamps. Because nanosecond handling has its own conversion class and raw-mode behavior, a regression there would currently slip through unnoticed; please add end-to-end extractor tests for both the default `Timestamp` path and `extractRawTimeValues=true`.
##########
pinot-plugins/pinot-input-format/pinot-parquet/src/main/java/org/apache/pinot/plugin/inputformat/parquet/ParquetRecordReaderConfig.java:
##########
@@ -18,34 +18,31 @@
*/
package org.apache.pinot.plugin.inputformat.parquet;
-import org.apache.commons.configuration2.Configuration;
import org.apache.pinot.spi.data.readers.RecordReaderConfig;
-/**
- * Config for ParquetRecordReader
- */
+/// Config for [ParquetRecordReader] (and the underlying [ParquetAvroRecordReader] / [ParquetNativeRecordReader]).
+/// Three settings, all default `false`:
+/// - `useParquetAvroRecordReader` — force the parquet-avro reader.
+/// - `useParquetNativeRecordReader` — force the native parquet reader. When neither flag is set, the dispatcher
+/// auto-detects via the file's `avro.schema` metadata (Avro reader if present, native otherwise).
+/// - `extractRawTimeValues` — opt out of TIMESTAMP / DATE / TIME conversion at the extractor boundary,
+/// surfacing the raw underlying integer in the column's declared unit instead of the contract Java type.
+/// DECIMAL and UUID always convert. See [ParquetAvroRecordExtractor] / [ParquetNativeRecordExtractor] for
+/// the per-type matrix.
public class ParquetRecordReaderConfig implements RecordReaderConfig {
- private static final String USE_PARQUET_AVRO_RECORDER_READER = "useParquetAvroRecordReader";
- private static final String USE_PARQUET_NATIVE_RECORDER_READER = "useParquetNativeRecordReader";
-
private boolean _useParquetAvroRecordReader;
private boolean _useParquetNativeRecordReader;
- private Configuration _conf;
-
- public ParquetRecordReaderConfig() {
- }
-
- public ParquetRecordReaderConfig(Configuration conf) {
- _conf = conf;
- _useParquetAvroRecordReader = conf.getBoolean(USE_PARQUET_AVRO_RECORDER_READER, false);
- _useParquetNativeRecordReader = conf.getBoolean(USE_PARQUET_NATIVE_RECORDER_READER, false);
- }
+ private boolean _extractRawTimeValues;
Review Comment:
This removes the `Configuration`-accepting constructor and `getConfig()` accessor from a public record-reader config class. In-repo callers may not use them anymore, but external ingestion code that still constructs `ParquetRecordReaderConfig` from a Commons Configuration or inspects the backing config will now fail to compile on upgrade. If this break is intentional, please keep a compatibility shim or deprecate first rather than deleting the API outright in one step.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3184633126
##########
pinot-plugins/pinot-input-format/pinot-parquet/src/main/java/org/apache/pinot/plugin/inputformat/parquet/ParquetNativeRecordExtractor.java:
##########
@@ -311,11 +307,31 @@ private Map<String, Object> extractKeyValueMap(Group group) {
Group keyValueGroup = group.getGroup(0, i);
Object key = extractValue(keyValueGroup, keyIndex);
Object value = extractValue(keyValueGroup, valueIndex);
- map.put(key.toString(), value);
+ map.put(stringifyMapKey(key), value);
}
return map;
}
+ /// Stringifies a map key for the Pinot `Map<String, Object>` contract, matching the JSON-serialization
+ /// convention used elsewhere in this PR (`JsonUtils` keeps `WRITE_DATES_AS_TIMESTAMPS = true`):
+ /// - `byte[]` (unannotated BINARY / FIXED) → base64. Same form Jackson uses for `byte[]` values, so the
+ /// key reads uniformly with the rest of a serialized map. Pinot's BYTES→STRING column-type conversion
+ /// uses hex via `BytesUtils.toHexString`, but the MAP path goes through Jackson — base64 wins on
+ /// consistency here.
+ /// - `Timestamp` → numeric epoch millis as a string. Matches Jackson's Timestamp value-serialization
+ /// (`WRITE_DATES_AS_TIMESTAMPS = true`) and avoids `Timestamp#toString`'s JVM-default-TZ dependency.
+ /// - Everything else (`String`, `Integer`, `Long`, `Float`, `Double`, `Boolean`, `BigDecimal`, `UUID`,
+ /// `LocalDate`, `LocalTime`) has a stable, TZ-independent `toString`.
+ private static String stringifyMapKey(Object key) {
+ if (key instanceof byte[]) {
+ return Base64.getEncoder().encodeToString((byte[]) key);
+ }
+ if (key instanceof Timestamp) {
+ return Long.toString(((Timestamp) key).getTime());
Review Comment:
Good catch — fixed. `Timestamp` map keys now serialize via `Timestamp#toInstant().toString()` (ISO-8601 UTC with full nanosecond precision), so a Parquet `TIMESTAMP_MICROS` / `TIMESTAMP_NANOS` / `INT96` map with sub-millisecond-distinct keys no longer collapses entries.
This does diverge from the value-side JSON convention (`WRITE_DATES_AS_TIMESTAMPS=true` keeps Timestamp values as numeric epoch millis), but correctness for map keys outweighs symmetry here — Jackson itself takes the same asymmetric stance with `WRITE_DATE_KEYS_AS_TIMESTAMPS=false` defaulting Timestamp keys to ISO-string form. The result is also TZ-independent (the original concern), since `Instant.toString` is UTC.
##########
pinot-plugins/pinot-input-format/pinot-avro-base/src/main/java/org/apache/pinot/plugin/inputformat/avro/AvroRecordExtractor.java:
##########
@@ -48,87 +58,189 @@
/// - avro nested `record` → [GenericRecord] → `Map<String, Object>`
/// - avro `union[null, X]` with the `null` branch selected → `null`
///
-/// **Logical types** (applied when `enableLogicalTypes = true`, the config default; `GenericDatumReader` emits
-/// the post-conversion Java types listed below):
-/// - `decimal` → `BigDecimal` → `BigDecimal`
-/// - `uuid` → `UUID` → `String` (UUID string form via `UUID.toString()`)
-/// - `date` → `LocalDate` → `LocalDate` (passes through; TZ-independent)
-/// - `time-millis` / `time-micros` → `LocalTime` → `LocalTime` (passes through; full ns precision preserved)
-/// - `timestamp-millis` / `timestamp-micros` → `Instant` → `java.sql.Timestamp` (sub-millisecond nanos preserved
-/// via `Timestamp.getNanos()`)
+/// **Logical types** (`GenericDatumReader` emits the post-Avro-conversion Java type, then this extractor maps to the
+/// Pinot contract type):
+/// - `decimal` → `BigDecimal` → `BigDecimal` (always converted; raw bytes aren't interpretable without external
+/// precision/scale)
+/// - `timestamp-millis` → `Instant` → [Timestamp], or `Long` raw epoch millis when `extractRawTimeValues`
+/// is `true`
+/// - `timestamp-micros` → `Instant` → [Timestamp] (sub-millisecond micros preserved), or `Long` raw epoch
+/// micros when `extractRawTimeValues` is `true`
+/// - `date` → `LocalDate` → `LocalDate`, or `Integer` raw days-since-epoch when `extractRawTimeValues` is
+/// `true`
+/// - `time-millis` → `LocalTime` → `LocalTime`, or `Integer` raw ms-since-midnight when
+/// `extractRawTimeValues` is `true`
+/// - `time-micros` → `LocalTime` → `LocalTime`, or `Long` raw µs-since-midnight when `extractRawTimeValues`
+/// is `true`
+/// - `uuid` → [java.util.UUID] → [java.util.UUID] (always converted; downstream type transformer adapts to
+/// the Pinot column type — `STRING` column gets canonical UUID string, `BYTES` column gets 16-byte
+/// big-endian form)
public class AvroRecordExtractor extends BaseRecordExtractor<GenericRecord> {
- private boolean _applyLogicalTypes = true;
+
+ // Avro logical-type names (copied from org.apache.avro.LogicalTypes).
+ private static final String DECIMAL = "decimal";
+ private static final String TIMESTAMP_MILLIS = "timestamp-millis";
+ private static final String TIMESTAMP_MICROS = "timestamp-micros";
+ private static final String DATE = "date";
+ private static final String TIME_MILLIS = "time-millis";
+ private static final String TIME_MICROS = "time-micros";
+ private static final String UUID = "uuid";
+
+ private static final Map<String, Conversion<?>> CONVERSION_MAP = Map.of(
+ DECIMAL, new Conversions.DecimalConversion(),
+ TIMESTAMP_MILLIS, new TimeConversions.TimestampMillisConversion(),
+ TIMESTAMP_MICROS, new TimeConversions.TimestampMicrosConversion(),
+ DATE, new TimeConversions.DateConversion(),
+ TIME_MILLIS, new TimeConversions.TimeMillisConversion(),
+ TIME_MICROS, new TimeConversions.TimeMicrosConversion(),
+ UUID, new Conversions.UUIDConversion()
+ );
+ private static final Set<String> TEMPORAL_LOGICAL_TYPES =
+ Set.of(TIMESTAMP_MILLIS, TIMESTAMP_MICROS, DATE, TIME_MILLIS, TIME_MICROS);
+
+ protected boolean _extractRawTimeValues;
@Override
protected void initConfig(@Nullable RecordExtractorConfig config) {
if (config instanceof AvroRecordExtractorConfig) {
- _applyLogicalTypes = ((AvroRecordExtractorConfig) config).isEnableLogicalTypes();
+ _extractRawTimeValues = ((AvroRecordExtractorConfig) config).isExtractRawTimeValues();
}
}
@Override
public GenericRow extract(GenericRecord from, GenericRow to) {
+ Schema schema = from.getSchema();
if (_extractAll) {
- List<Schema.Field> fields = from.getSchema().getFields();
- for (Schema.Field field : fields) {
+ for (Schema.Field field : schema.getFields()) {
String fieldName = field.name();
- Object value = from.get(fieldName);
- if (_applyLogicalTypes) {
- value = AvroSchemaUtil.applyLogicalType(field, value);
- }
- if (value != null) {
- value = transformValue(value, field);
- }
- to.putValue(fieldName, value);
+ to.putValue(fieldName, convertValue(field.schema(), from.get(fieldName)));
}
} else {
for (String fieldName : _fields) {
- Schema.Field field = from.getSchema().getField(fieldName);
+ Schema.Field field = schema.getField(fieldName);
if (field != null) {
- Object value = from.get(field.pos());
- if (_applyLogicalTypes) {
- value = AvroSchemaUtil.applyLogicalType(field, value);
- }
- if (value != null) {
- value = transformValue(value, field);
- }
- to.putValue(fieldName, value);
+ to.putValue(fieldName, convertValue(field.schema(), from.get(field.pos())));
}
}
}
return to;
}
- protected Object transformValue(Object value, Schema.Field field) {
- return convert(value);
+ /// Schema-driven dispatch — produces a contract-compliant value in a single walk.
+ /// `null` short-circuits at the top so subclasses overriding [#convertLeaf] never see null.
+ @Nullable
+ protected Object convertValue(Schema schema, @Nullable Object value) {
+ if (value == null) {
+ return null;
+ }
+ schema = resolveUnionSchema(schema, value);
+ switch (schema.getType()) {
+ case ARRAY:
+ // GenericDatumReader emits array<T> as GenericData.Array, which is a List.
+ return convertArray(schema, (List<?>) value);
+ case MAP:
+ // GenericDatumReader emits map<T> as a HashMap. Avro keys are always strings; the runtime key type
+ // is `Utf8` unless the schema declares `avro.java.string = "String"`. We normalize to `String`.
+ return convertMap(schema, (Map<?, ?>) value);
+ case RECORD:
+ return convertRecord(schema, (GenericRecord) value);
+ default:
+ return convertLeaf(schema, value);
+ }
}
- @Override
- protected boolean isRecord(Object value) {
- return value instanceof GenericRecord;
+ /// Converts a leaf (non-container) Avro value to its Pinot contract type. Subclasses override to handle
+ /// format-specific extensions (e.g. parquet-avro's INT96 surfaced as a `fixed(12)` with a sentinel doc).
+ /// The default handles the Avro spec — primitives + the seven registered logical types.
+ ///
+ /// Per the Avro spec, only STRING / BYTES / FIXED / INT / LONG can carry a logical-type annotation; the
+ /// other primitive types skip the lookup entirely. When a logical-type conversion runs, `Instant`
+ /// results (`timestamp-millis` / `timestamp-micros`) are post-mapped to [Timestamp] per the Pinot
+ /// contract. When [#_extractRawTimeValues] is set, temporal logical types pass through the raw
+ /// underlying integer.
+ protected Object convertLeaf(Schema schema, Object value) {
+ Schema.Type type = schema.getType();
+ switch (type) {
+ case BOOLEAN:
+ case FLOAT:
+ case DOUBLE:
+ // The Avro spec defines no logical types for these primitives — skip the logical-type lookup.
+ return value;
+ case ENUM:
+ // No logical types; `EnumSymbol.toString()` returns the canonical enum-symbol string.
+ return value.toString();
+ default:
+ // INT / LONG / STRING / BYTES / FIXED — fall through to logical-type handling below.
+ break;
+ }
+ LogicalType logicalType = LogicalTypes.fromSchemaIgnoreInvalid(schema);
+ if (logicalType != null) {
+ String name = logicalType.getName();
+ if (!(_extractRawTimeValues && TEMPORAL_LOGICAL_TYPES.contains(name))) {
+ Conversion<?> conversion = CONVERSION_MAP.get(name);
+ if (conversion != null) {
+ Object converted = Conversions.convertToLogicalType(value, schema, logicalType, conversion);
+ return converted instanceof Instant ? Timestamp.from((Instant) converted) : converted;
+ }
+ }
+ }
+ // No logical-type conversion fired — fall through to physical-type normalization.
+ switch (type) {
+ case STRING:
+ // `Utf8.toString()` returns the decoded String; an already-`String` value is a no-op.
+ return value.toString();
+ case BYTES:
+ // ByteBuffer might be reused by the reader. Slice to avoid advancing the original buffer's position.
+ ByteBuffer slice = ((ByteBuffer) value).slice();
+ byte[] bytes = new byte[slice.limit()];
+ slice.get(bytes);
+ return bytes;
+ case FIXED:
+ return ((GenericFixed) value).bytes();
+ default:
+ // INT / LONG with no logical type, or temporal raw-mode pass-through.
+ return value;
+ }
}
- @Override
- protected Map<Object, Object> convertRecord(Object value) {
- GenericRecord record = (GenericRecord) value;
- List<Schema.Field> fields = record.getSchema().getFields();
- Map<Object, Object> convertedMap = Maps.newHashMapWithExpectedSize(fields.size());
+ private Object[] convertArray(Schema schema, List<?> list) {
+ Schema elementSchema = schema.getElementType();
+ int numElements = list.size();
+ Object[] result = new Object[numElements];
+ for (int i = 0; i < numElements; i++) {
+ result[i] = convertValue(elementSchema, list.get(i));
+ }
+ return result;
+ }
+
+ private Map<String, Object> convertMap(Schema schema, Map<?, ?> map) {
+ Schema valueSchema = schema.getValueType();
+ Map<String, Object> result = Maps.newHashMapWithExpectedSize(map.size());
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ result.put(entry.getKey().toString(), convertValue(valueSchema, entry.getValue()));
+ }
+ return result;
+ }
+
+ private Map<String, Object> convertRecord(Schema schema, GenericRecord record) {
+ List<Schema.Field> fields = schema.getFields();
+ Map<String, Object> result = Maps.newHashMapWithExpectedSize(fields.size());
for (Schema.Field field : fields) {
- String fieldName = field.name();
- Object fieldValue = record.get(fieldName);
- Object convertedValue = fieldValue != null ? transformValue(fieldValue, field) : null;
- convertedMap.put(fieldName, convertedValue);
+ result.put(field.name(), convertValue(field.schema(), record.get(field.name())));
}
- return convertedMap;
+ return result;
}
- /// Adds Avro-specific handling: [GenericFixed] (`fixed`) → `byte[]`. Everything else delegates to the base
- /// (see class Javadoc for the full Avro-source → Java-output matrix).
- @Override
- protected Object convertSingleValue(Object value) {
- if (value instanceof GenericFixed) {
- return ((GenericFixed) value).bytes();
+ /// Picks the union branch matching the runtime value via Avro's standard union resolution
+ /// ([GenericData#resolveUnion]) — the same code path `GenericDatumWriter` uses, dispatching by
+ /// the runtime Java type's schema name. Avro disallows duplicate primitive types in a single
+ /// union, so the resolution is unambiguous. Throws [org.apache.avro.UnresolvedUnionException]
+ /// when the value matches no branch (a real schema-vs-data mismatch).
+ private static Schema resolveUnionSchema(Schema schema, Object value) {
+ if (!schema.isUnion()) {
+ return schema;
}
- return super.convertSingleValue(value);
+ int index = GenericData.get().resolveUnion(schema, value);
Review Comment:
Good catch — fixed two things:
1. **`resolveUnionSchema`** now uses `AvroUtils.getGenericData()` (the same `GenericData` instance the reader is built with) instead of `GenericData.get()`. So a `union[null, bytes(decimal)]` field whose runtime value is `BigDecimal` (post-reader-conversion) now resolves to the bytes(decimal) branch via `conversionsByClass.get(BigDecimal.class) → DecimalConversion → matches branch with logical type "decimal"`.
2. **`convertLeaf`** also now handles pre-converted values gracefully — it checks `conversion.getConvertedType().isInstance(value)` before re-converting, so when the reader has already turned a raw `ByteBuffer` into `BigDecimal`, we don't try to convert it again (which would have CCE-thrown casting BigDecimal to ByteBuffer). The raw-input path (test-only via `encodeLogical`) and the pre-converted path (production reader) now both work.
Added `testNullableUnionWithDecimalLogicalTypeResolvesByConversion` exercising the full path: `union[null, bytes(decimal)]` field with a directly-stored `BigDecimal` value (simulating the reader's pre-conversion). Resolves to the decimal branch and returns the BigDecimal unchanged.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "xiangfu0 (via GitHub)" <gi...@apache.org>.
xiangfu0 commented on PR #18400:
URL: https://github.com/apache/pinot/pull/18400#issuecomment-4381026939
Docs follow-up opened: https://github.com/pinot-contrib/pinot-docs/pull/799
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3180329149
##########
pinot-plugins/pinot-input-format/pinot-parquet/src/main/java/org/apache/pinot/plugin/inputformat/parquet/ParquetNativeRecordExtractor.java:
##########
@@ -311,11 +307,31 @@ private Map<String, Object> extractKeyValueMap(Group group) {
Group keyValueGroup = group.getGroup(0, i);
Object key = extractValue(keyValueGroup, keyIndex);
Object value = extractValue(keyValueGroup, valueIndex);
- map.put(key.toString(), value);
+ map.put(stringifyMapKey(key), value);
}
return map;
}
+ /// Stringifies a map key for the Pinot `Map<String, Object>` contract, matching the JSON-serialization
+ /// convention used elsewhere in this PR (`JsonUtils` keeps `WRITE_DATES_AS_TIMESTAMPS = true`):
+ /// - `byte[]` (unannotated BINARY / FIXED) → base64. Same form Jackson uses for `byte[]` values, so the
+ /// key reads uniformly with the rest of a serialized map. Pinot's BYTES→STRING column-type conversion
+ /// uses hex via `BytesUtils.toHexString`, but the MAP path goes through Jackson — base64 wins on
+ /// consistency here.
+ /// - `Timestamp` → numeric epoch millis as a string. Matches Jackson's Timestamp value-serialization
+ /// (`WRITE_DATES_AS_TIMESTAMPS = true`) and avoids `Timestamp#toString`'s JVM-default-TZ dependency.
+ /// - Everything else (`String`, `Integer`, `Long`, `Float`, `Double`, `Boolean`, `BigDecimal`, `UUID`,
+ /// `LocalDate`, `LocalTime`) has a stable, TZ-independent `toString`.
+ private static String stringifyMapKey(Object key) {
+ if (key instanceof byte[]) {
+ return Base64.getEncoder().encodeToString((byte[]) key);
+ }
+ if (key instanceof Timestamp) {
+ return Long.toString(((Timestamp) key).getTime());
Review Comment:
`stringifyMapKey()` collapses every `Timestamp` key to `timestamp.getTime()`, which drops any microsecond/nanosecond part. Parquet maps whose key type is `TIMESTAMP_MICROS`, `TIMESTAMP_NANOS`, or `INT96` can therefore overwrite distinct entries that fall in the same millisecond, corrupting the extracted map.
##########
pinot-plugins/pinot-input-format/pinot-avro-base/src/main/java/org/apache/pinot/plugin/inputformat/avro/AvroRecordExtractor.java:
##########
@@ -48,87 +58,189 @@
/// - avro nested `record` → [GenericRecord] → `Map<String, Object>`
/// - avro `union[null, X]` with the `null` branch selected → `null`
///
-/// **Logical types** (applied when `enableLogicalTypes = true`, the config default; `GenericDatumReader` emits
-/// the post-conversion Java types listed below):
-/// - `decimal` → `BigDecimal` → `BigDecimal`
-/// - `uuid` → `UUID` → `String` (UUID string form via `UUID.toString()`)
-/// - `date` → `LocalDate` → `LocalDate` (passes through; TZ-independent)
-/// - `time-millis` / `time-micros` → `LocalTime` → `LocalTime` (passes through; full ns precision preserved)
-/// - `timestamp-millis` / `timestamp-micros` → `Instant` → `java.sql.Timestamp` (sub-millisecond nanos preserved
-/// via `Timestamp.getNanos()`)
+/// **Logical types** (`GenericDatumReader` emits the post-Avro-conversion Java type, then this extractor maps to the
+/// Pinot contract type):
+/// - `decimal` → `BigDecimal` → `BigDecimal` (always converted; raw bytes aren't interpretable without external
+/// precision/scale)
+/// - `timestamp-millis` → `Instant` → [Timestamp], or `Long` raw epoch millis when `extractRawTimeValues`
+/// is `true`
+/// - `timestamp-micros` → `Instant` → [Timestamp] (sub-millisecond micros preserved), or `Long` raw epoch
+/// micros when `extractRawTimeValues` is `true`
+/// - `date` → `LocalDate` → `LocalDate`, or `Integer` raw days-since-epoch when `extractRawTimeValues` is
+/// `true`
+/// - `time-millis` → `LocalTime` → `LocalTime`, or `Integer` raw ms-since-midnight when
+/// `extractRawTimeValues` is `true`
+/// - `time-micros` → `LocalTime` → `LocalTime`, or `Long` raw µs-since-midnight when `extractRawTimeValues`
+/// is `true`
+/// - `uuid` → [java.util.UUID] → [java.util.UUID] (always converted; downstream type transformer adapts to
+/// the Pinot column type — `STRING` column gets canonical UUID string, `BYTES` column gets 16-byte
+/// big-endian form)
public class AvroRecordExtractor extends BaseRecordExtractor<GenericRecord> {
- private boolean _applyLogicalTypes = true;
+
+ // Avro logical-type names (copied from org.apache.avro.LogicalTypes).
+ private static final String DECIMAL = "decimal";
+ private static final String TIMESTAMP_MILLIS = "timestamp-millis";
+ private static final String TIMESTAMP_MICROS = "timestamp-micros";
+ private static final String DATE = "date";
+ private static final String TIME_MILLIS = "time-millis";
+ private static final String TIME_MICROS = "time-micros";
+ private static final String UUID = "uuid";
+
+ private static final Map<String, Conversion<?>> CONVERSION_MAP = Map.of(
+ DECIMAL, new Conversions.DecimalConversion(),
+ TIMESTAMP_MILLIS, new TimeConversions.TimestampMillisConversion(),
+ TIMESTAMP_MICROS, new TimeConversions.TimestampMicrosConversion(),
+ DATE, new TimeConversions.DateConversion(),
+ TIME_MILLIS, new TimeConversions.TimeMillisConversion(),
+ TIME_MICROS, new TimeConversions.TimeMicrosConversion(),
+ UUID, new Conversions.UUIDConversion()
+ );
+ private static final Set<String> TEMPORAL_LOGICAL_TYPES =
+ Set.of(TIMESTAMP_MILLIS, TIMESTAMP_MICROS, DATE, TIME_MILLIS, TIME_MICROS);
+
+ protected boolean _extractRawTimeValues;
@Override
protected void initConfig(@Nullable RecordExtractorConfig config) {
if (config instanceof AvroRecordExtractorConfig) {
- _applyLogicalTypes = ((AvroRecordExtractorConfig) config).isEnableLogicalTypes();
+ _extractRawTimeValues = ((AvroRecordExtractorConfig) config).isExtractRawTimeValues();
}
}
@Override
public GenericRow extract(GenericRecord from, GenericRow to) {
+ Schema schema = from.getSchema();
if (_extractAll) {
- List<Schema.Field> fields = from.getSchema().getFields();
- for (Schema.Field field : fields) {
+ for (Schema.Field field : schema.getFields()) {
String fieldName = field.name();
- Object value = from.get(fieldName);
- if (_applyLogicalTypes) {
- value = AvroSchemaUtil.applyLogicalType(field, value);
- }
- if (value != null) {
- value = transformValue(value, field);
- }
- to.putValue(fieldName, value);
+ to.putValue(fieldName, convertValue(field.schema(), from.get(fieldName)));
}
} else {
for (String fieldName : _fields) {
- Schema.Field field = from.getSchema().getField(fieldName);
+ Schema.Field field = schema.getField(fieldName);
if (field != null) {
- Object value = from.get(field.pos());
- if (_applyLogicalTypes) {
- value = AvroSchemaUtil.applyLogicalType(field, value);
- }
- if (value != null) {
- value = transformValue(value, field);
- }
- to.putValue(fieldName, value);
+ to.putValue(fieldName, convertValue(field.schema(), from.get(field.pos())));
}
}
}
return to;
}
- protected Object transformValue(Object value, Schema.Field field) {
- return convert(value);
+ /// Schema-driven dispatch — produces a contract-compliant value in a single walk.
+ /// `null` short-circuits at the top so subclasses overriding [#convertLeaf] never see null.
+ @Nullable
+ protected Object convertValue(Schema schema, @Nullable Object value) {
+ if (value == null) {
+ return null;
+ }
+ schema = resolveUnionSchema(schema, value);
+ switch (schema.getType()) {
+ case ARRAY:
+ // GenericDatumReader emits array<T> as GenericData.Array, which is a List.
+ return convertArray(schema, (List<?>) value);
+ case MAP:
+ // GenericDatumReader emits map<T> as a HashMap. Avro keys are always strings; the runtime key type
+ // is `Utf8` unless the schema declares `avro.java.string = "String"`. We normalize to `String`.
+ return convertMap(schema, (Map<?, ?>) value);
+ case RECORD:
+ return convertRecord(schema, (GenericRecord) value);
+ default:
+ return convertLeaf(schema, value);
+ }
}
- @Override
- protected boolean isRecord(Object value) {
- return value instanceof GenericRecord;
+ /// Converts a leaf (non-container) Avro value to its Pinot contract type. Subclasses override to handle
+ /// format-specific extensions (e.g. parquet-avro's INT96 surfaced as a `fixed(12)` with a sentinel doc).
+ /// The default handles the Avro spec — primitives + the seven registered logical types.
+ ///
+ /// Per the Avro spec, only STRING / BYTES / FIXED / INT / LONG can carry a logical-type annotation; the
+ /// other primitive types skip the lookup entirely. When a logical-type conversion runs, `Instant`
+ /// results (`timestamp-millis` / `timestamp-micros`) are post-mapped to [Timestamp] per the Pinot
+ /// contract. When [#_extractRawTimeValues] is set, temporal logical types pass through the raw
+ /// underlying integer.
+ protected Object convertLeaf(Schema schema, Object value) {
+ Schema.Type type = schema.getType();
+ switch (type) {
+ case BOOLEAN:
+ case FLOAT:
+ case DOUBLE:
+ // The Avro spec defines no logical types for these primitives — skip the logical-type lookup.
+ return value;
+ case ENUM:
+ // No logical types; `EnumSymbol.toString()` returns the canonical enum-symbol string.
+ return value.toString();
+ default:
+ // INT / LONG / STRING / BYTES / FIXED — fall through to logical-type handling below.
+ break;
+ }
+ LogicalType logicalType = LogicalTypes.fromSchemaIgnoreInvalid(schema);
+ if (logicalType != null) {
+ String name = logicalType.getName();
+ if (!(_extractRawTimeValues && TEMPORAL_LOGICAL_TYPES.contains(name))) {
+ Conversion<?> conversion = CONVERSION_MAP.get(name);
+ if (conversion != null) {
+ Object converted = Conversions.convertToLogicalType(value, schema, logicalType, conversion);
+ return converted instanceof Instant ? Timestamp.from((Instant) converted) : converted;
+ }
+ }
+ }
+ // No logical-type conversion fired — fall through to physical-type normalization.
+ switch (type) {
+ case STRING:
+ // `Utf8.toString()` returns the decoded String; an already-`String` value is a no-op.
+ return value.toString();
+ case BYTES:
+ // ByteBuffer might be reused by the reader. Slice to avoid advancing the original buffer's position.
+ ByteBuffer slice = ((ByteBuffer) value).slice();
+ byte[] bytes = new byte[slice.limit()];
+ slice.get(bytes);
+ return bytes;
+ case FIXED:
+ return ((GenericFixed) value).bytes();
+ default:
+ // INT / LONG with no logical type, or temporal raw-mode pass-through.
+ return value;
+ }
}
- @Override
- protected Map<Object, Object> convertRecord(Object value) {
- GenericRecord record = (GenericRecord) value;
- List<Schema.Field> fields = record.getSchema().getFields();
- Map<Object, Object> convertedMap = Maps.newHashMapWithExpectedSize(fields.size());
+ private Object[] convertArray(Schema schema, List<?> list) {
+ Schema elementSchema = schema.getElementType();
+ int numElements = list.size();
+ Object[] result = new Object[numElements];
+ for (int i = 0; i < numElements; i++) {
+ result[i] = convertValue(elementSchema, list.get(i));
+ }
+ return result;
+ }
+
+ private Map<String, Object> convertMap(Schema schema, Map<?, ?> map) {
+ Schema valueSchema = schema.getValueType();
+ Map<String, Object> result = Maps.newHashMapWithExpectedSize(map.size());
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ result.put(entry.getKey().toString(), convertValue(valueSchema, entry.getValue()));
+ }
+ return result;
+ }
+
+ private Map<String, Object> convertRecord(Schema schema, GenericRecord record) {
+ List<Schema.Field> fields = schema.getFields();
+ Map<String, Object> result = Maps.newHashMapWithExpectedSize(fields.size());
for (Schema.Field field : fields) {
- String fieldName = field.name();
- Object fieldValue = record.get(fieldName);
- Object convertedValue = fieldValue != null ? transformValue(fieldValue, field) : null;
- convertedMap.put(fieldName, convertedValue);
+ result.put(field.name(), convertValue(field.schema(), record.get(field.name())));
}
- return convertedMap;
+ return result;
}
- /// Adds Avro-specific handling: [GenericFixed] (`fixed`) → `byte[]`. Everything else delegates to the base
- /// (see class Javadoc for the full Avro-source → Java-output matrix).
- @Override
- protected Object convertSingleValue(Object value) {
- if (value instanceof GenericFixed) {
- return ((GenericFixed) value).bytes();
+ /// Picks the union branch matching the runtime value via Avro's standard union resolution
+ /// ([GenericData#resolveUnion]) — the same code path `GenericDatumWriter` uses, dispatching by
+ /// the runtime Java type's schema name. Avro disallows duplicate primitive types in a single
+ /// union, so the resolution is unambiguous. Throws [org.apache.avro.UnresolvedUnionException]
+ /// when the value matches no branch (a real schema-vs-data mismatch).
+ private static Schema resolveUnionSchema(Schema schema, Object value) {
+ if (!schema.isUnion()) {
+ return schema;
}
- return super.convertSingleValue(value);
+ int index = GenericData.get().resolveUnion(schema, value);
Review Comment:
`resolveUnionSchema()` now uses `GenericData.get().resolveUnion(...)`, but the Avro file reader is built with `AvroUtils.GENERIC_DATA`, which registers logical-type conversions such as decimal. For a field like `union[null, bytes(decimal)]`, the runtime value coming from `GenericDatumReader` is `BigDecimal`, and the default `GenericData` cannot match that to the `bytes` branch, so extraction fails with `UnresolvedUnionException` for nullable logical-type fields that used to work.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refine RecordExtractor contract: TIMESTAMP narrows to Long, push time conversions per-format [pinot]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #18400:
URL: https://github.com/apache/pinot/pull/18400#issuecomment-4362551513
## [Codecov](https://app.codecov.io/gh/apache/pinot/pull/18400?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `95.00000%` with `1 line` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 34.98%. Comparing base ([`80fb0e8`](https://app.codecov.io/gh/apache/pinot/commit/80fb0e8932aa9b1beb40df9613111667b8b5765d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`b5a7e4e`](https://app.codecov.io/gh/apache/pinot/commit/b5a7e4e999509ac25ec343a1500ae8a3ea0fa2a3?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/pinot/pull/18400?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...he/pinot/spi/data/readers/BaseRecordExtractor.java](https://app.codecov.io/gh/apache/pinot/pull/18400?src=pr&el=tree&filepath=pinot-spi%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpinot%2Fspi%2Fdata%2Freaders%2FBaseRecordExtractor.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cGlub3Qtc3BpL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9zcGkvZGF0YS9yZWFkZXJzL0Jhc2VSZWNvcmRFeHRyYWN0b3IuamF2YQ==) | 0.00% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/pinot/pull/18400?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
> :exclamation: There is a different number of reports uploaded between BASE (80fb0e8) and HEAD (b5a7e4e). Click for more details.
>
> <details><summary>HEAD has 16 uploads less than BASE</summary>
>
>| Flag | BASE (80fb0e8) | HEAD (b5a7e4e) |
>|------|------|------|
>|java-21|5|1|
>|unittests1|1|0|
>|unittests|2|1|
>|temurin|5|1|
>|integration|3|0|
>|integration1|1|0|
>|integration2|1|0|
>|custom-integration1|1|0|
></details>
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #18400 +/- ##
=============================================
- Coverage 63.46% 34.98% -28.48%
+ Complexity 1701 841 -860
=============================================
Files 3254 3254
Lines 199104 199083 -21
Branches 30830 30824 -6
=============================================
- Hits 126354 69653 -56701
- Misses 62665 123340 +60675
+ Partials 10085 6090 -3995
```
| [Flag](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [custom-integration1](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [integration](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [integration1](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [integration2](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [java-21](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `34.98% <95.00%> (-28.48%)` | :arrow_down: |
| [temurin](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `34.98% <95.00%> (-28.48%)` | :arrow_down: |
| [unittests](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `34.98% <95.00%> (-28.48%)` | :arrow_down: |
| [unittests1](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [unittests2](https://app.codecov.io/gh/apache/pinot/pull/18400/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `34.98% <95.00%> (+<0.01%)` | :arrow_up: |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/pinot/pull/18400?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3180300573
##########
pinot-common/src/main/java/org/apache/pinot/common/utils/PinotDataType.java:
##########
@@ -1590,6 +1700,9 @@ public static PinotDataType getSingleValueType(Class<?> cls) {
if (cls == byte[].class) {
return BYTES;
}
+ if (cls == UUID.class) {
+ return UUID;
+ }
Review Comment:
Fixed — added `UUID_ARRAY`, plus the same gap was present for the other newly-introduced contract types: `DATE_ARRAY` (LocalDate) and `TIME_ARRAY` (LocalTime). All three now have:
- New enum entries (DATE_ARRAY, TIME_ARRAY, UUID_ARRAY) with `convert(...)` overrides routing through the corresponding source-type's `toLocalDateArray` / `toLocalTimeArray` / `toUuidArray`
- Three new array-conversion methods on the base (`toLocalDateArray` / `toLocalTimeArray` / `toUuidArray`) that walk the source array and per-element-convert via `DATE.convert` / `TIME.convert` / `UUID.convert`
- New cases in `getSingleValueType()` switch and `getMultiValueType(Class<?>)` for `LocalDate.class` / `LocalTime.class` / `UUID.class`
- `toInternal` overrides per array enum (Integer[] of epoch-days for DATE_ARRAY, Long[] of millis-since-midnight for TIME_ARRAY, String[] of canonical form for UUID_ARRAY)
`PinotDataTypeTest` got `testDateArray` / `testTimeArray` / `testUuidArray` covering identity, STRING_ARRAY, primitive-array and BYTES_ARRAY destination paths. `testGetMultipleValueType` now includes the new class → array-type entries.
The specific `Object[] of UUID → BYTES_ARRAY` path the bot flagged is now exact: `UUID_ARRAY.toBytesArray` walks per-element via `UUID.toBytes` → 16-byte big-endian arrays.
##########
pinot-plugins/pinot-input-format/pinot-parquet/src/main/java/org/apache/pinot/plugin/inputformat/parquet/ParquetNativeRecordExtractor.java:
##########
@@ -311,11 +306,26 @@ private Map<String, Object> extractKeyValueMap(Group group) {
Group keyValueGroup = group.getGroup(0, i);
Object key = extractValue(keyValueGroup, keyIndex);
Object value = extractValue(keyValueGroup, valueIndex);
- map.put(key.toString(), value);
+ map.put(stringifyMapKey(key), value);
}
return map;
}
+ /// Stringifies a map key per the Pinot `Map<String, Object>` contract. `byte[]` keys (unannotated BINARY /
+ /// FIXED) base64-encode; everything else (`String`, `Integer`, `Long`, `Float`, `Double`, `Boolean`,
+ /// `BigDecimal`, `UUID`, `LocalDate`, `LocalTime`, `Timestamp`) has a meaningful `toString()`.
+ ///
+ /// **Why base64 (not hex)**: this matches the Pinot MAP value's JSON ser/de path — Jackson serializes any
+ /// `byte[]` value as base64, so a base64-encoded key reads uniformly with the rest of a serialized map.
+ /// Pinot also uses hex via `BytesUtils.toHexString` for the BYTES→STRING column-type conversion, but the
+ /// MAP path goes through Jackson, so base64 wins on consistency here.
+ private static String stringifyMapKey(Object key) {
+ if (key instanceof byte[]) {
+ return Base64.getEncoder().encodeToString((byte[]) key);
+ }
+ return key.toString();
Review Comment:
Fixed — `stringifyMapKey` now special-cases `Timestamp` to `Long.toString(timestamp.getTime())`, matching the JSON-serialization convention this PR keeps for Timestamp values (`JsonUtils` preserves Jackson's default `WRITE_DATES_AS_TIMESTAMPS = true`, so Timestamp values serialize as numeric epoch millis). Map keys now use the same numeric-millis form, so a Pinot Map column with Timestamp keys + Timestamp values produces consistent JSON like `{"1700000000000": 1700000000000}` instead of mixing ISO-string keys with numeric values, and the result is JVM-TZ-independent (was the original concern with `Timestamp#toString`).
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3185794563
##########
pinot-plugins/pinot-input-format/pinot-avro-base/src/main/java/org/apache/pinot/plugin/inputformat/avro/AvroRecordExtractor.java:
##########
@@ -41,94 +55,209 @@
/// - avro `double` → `Double` → `Double`
/// - avro `string` → `Utf8` → `String` (via `Utf8.toString()`)
/// - avro `bytes` → `ByteBuffer` → `byte[]` (materialized from the buffer's remaining content)
-/// - avro `fixed` → [GenericFixed] / `GenericData.Fixed` → `byte[]`
+/// - avro `fixed` → `GenericFixed` / `GenericData.Fixed` → `byte[]`
/// - avro `enum` → `GenericData.EnumSymbol` → `String` (enum name)
/// - avro `array<T>` → `List<T>` → `Object[]` (each element recursively converted)
/// - avro `map<string, T>` → `Map<Utf8, T>` → `Map<String, Object>` (each value recursively converted)
-/// - avro nested `record` → [GenericRecord] → `Map<String, Object>`
+/// - avro nested `record` → `GenericRecord` → `Map<String, Object>`
/// - avro `union[null, X]` with the `null` branch selected → `null`
///
-/// **Logical types** (applied when `enableLogicalTypes = true`, the config default; `GenericDatumReader` emits
-/// the post-conversion Java types listed below):
-/// - `decimal` → `BigDecimal` → `BigDecimal`
-/// - `uuid` → `UUID` → `String` (UUID string form via `UUID.toString()`)
-/// - `date` → `LocalDate` → `LocalDate` (passes through; TZ-independent)
-/// - `time-millis` / `time-micros` → `LocalTime` → `LocalTime` (passes through; full ns precision preserved)
-/// - `timestamp-millis` / `timestamp-micros` → `Instant` → `java.sql.Timestamp` (sub-millisecond nanos preserved
-/// via `Timestamp.getNanos()`)
+/// **Logical types** (the reader emits the raw Avro physical type; this extractor applies the conversion via
+/// [#CONVERSION_MAP] to produce the Pinot contract type):
+/// - `decimal` / `big-decimal` → raw `ByteBuffer` → [BigDecimal] (always converted; raw bytes aren't interpretable
+/// without external precision/scale)
+/// - `timestamp-millis` → raw `Long` → [Timestamp], or `Long` raw epoch millis when `extractRawTimeValues` is `true`
+/// - `timestamp-micros` → raw `Long` → [Timestamp] (sub-millisecond micros preserved), or `Long` raw epoch micros when
+/// `extractRawTimeValues` is `true`
+/// - `timestamp-nanos` → raw `Long` → [Timestamp] (nanosecond precision preserved), or `Long` raw epoch nanos when
+/// `extractRawTimeValues` is `true`
+/// - `date` → raw `Integer` → [LocalDate], or `Integer` raw days-since-epoch when `extractRawTimeValues` is `true`
+/// - `time-millis` → raw `Integer` → [LocalTime], or `Integer` raw ms-since-midnight when `extractRawTimeValues` is
+/// `true`
+/// - `time-micros` → raw `Long` → [LocalTime], or `Long` raw µs-since-midnight when `extractRawTimeValues` is `true`
+/// - `uuid` → raw `Utf8` / `GenericFixed` → [UUID] (always converted; downstream type transformer adapts to the Pinot
+/// column type — `STRING` column gets canonical UUID string, `BYTES` column gets 16-byte big-endian form)
public class AvroRecordExtractor extends BaseRecordExtractor<GenericRecord> {
- private boolean _applyLogicalTypes = true;
+ private static final Conversion<BigDecimal> DECIMAL_CONVERSION = new Conversions.DecimalConversion();
+ private static final Conversion<BigDecimal> BIG_DECIMAL_CONVERSION = new Conversions.BigDecimalConversion();
+ private static final Conversion<Instant> TIMESTAMP_MILLIS_CONVERSION =
+ new TimeConversions.TimestampMillisConversion();
+ private static final Conversion<Instant> TIMESTAMP_MICROS_CONVERSION =
+ new TimeConversions.TimestampMicrosConversion();
+ private static final Conversion<Instant> TIMESTAMP_NANOS_CONVERSION = new TimeConversions.TimestampNanosConversion();
+ private static final Conversion<LocalDate> DATE_CONVERSION = new TimeConversions.DateConversion();
+ private static final Conversion<LocalTime> TIME_MILLIS_CONVERSION = new TimeConversions.TimeMillisConversion();
+ private static final Conversion<LocalTime> TIME_MICROS_CONVERSION = new TimeConversions.TimeMicrosConversion();
+ private static final Conversion<UUID> UUID_CONVERSION = new Conversions.UUIDConversion();
+
+ private static final Map<String, Conversion<?>> CONVERSION_MAP = Map.of(
+ DECIMAL_CONVERSION.getLogicalTypeName(), DECIMAL_CONVERSION,
+ BIG_DECIMAL_CONVERSION.getLogicalTypeName(), BIG_DECIMAL_CONVERSION,
+ TIMESTAMP_MILLIS_CONVERSION.getLogicalTypeName(), TIMESTAMP_MILLIS_CONVERSION,
+ TIMESTAMP_MICROS_CONVERSION.getLogicalTypeName(), TIMESTAMP_MICROS_CONVERSION,
+ TIMESTAMP_NANOS_CONVERSION.getLogicalTypeName(), TIMESTAMP_NANOS_CONVERSION,
+ DATE_CONVERSION.getLogicalTypeName(), DATE_CONVERSION,
+ TIME_MILLIS_CONVERSION.getLogicalTypeName(), TIME_MILLIS_CONVERSION,
+ TIME_MICROS_CONVERSION.getLogicalTypeName(), TIME_MICROS_CONVERSION,
+ UUID_CONVERSION.getLogicalTypeName(), UUID_CONVERSION
+ );
+
+ private static final Set<String> TEMPORAL_LOGICAL_TYPES = Set.of(
+ TIMESTAMP_MILLIS_CONVERSION.getLogicalTypeName(),
+ TIMESTAMP_MICROS_CONVERSION.getLogicalTypeName(),
+ TIMESTAMP_NANOS_CONVERSION.getLogicalTypeName(),
+ DATE_CONVERSION.getLogicalTypeName(),
+ TIME_MILLIS_CONVERSION.getLogicalTypeName(),
Review Comment:
Fair. Added two end-to-end tests:
- `testTimestampNanosLogicalTypeAsTimestampPreservingNanos` — default mode: builds a record with `Instant.ofEpochSecond(1649924302L, 123_456_789L)` (full nanosecond precision past the micros boundary), encodes via `TimeConversions.TimestampNanosConversion`, asserts the extractor returns `Timestamp.from(instant)` with all nanos preserved via `Timestamp.setNanos`.
- `testTimestampNanosLogicalTypeAsRawLongNanosWhenRaw` — `extractRawTimeValues=true` mode: same record, asserts the extractor passes through the raw `Long` epoch nanos (`1649924302L * 1_000_000_000L + 123_456_789L`).
Matches the existing millis/micros pairs structurally.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3185793662
##########
pinot-plugins/pinot-input-format/pinot-parquet/src/main/java/org/apache/pinot/plugin/inputformat/parquet/ParquetRecordReaderConfig.java:
##########
@@ -18,34 +18,31 @@
*/
package org.apache.pinot.plugin.inputformat.parquet;
-import org.apache.commons.configuration2.Configuration;
import org.apache.pinot.spi.data.readers.RecordReaderConfig;
-/**
- * Config for ParquetRecordReader
- */
+/// Config for [ParquetRecordReader] (and the underlying [ParquetAvroRecordReader] / [ParquetNativeRecordReader]).
+/// Three settings, all default `false`:
+/// - `useParquetAvroRecordReader` — force the parquet-avro reader.
+/// - `useParquetNativeRecordReader` — force the native parquet reader. When neither flag is set, the dispatcher
+/// auto-detects via the file's `avro.schema` metadata (Avro reader if present, native otherwise).
+/// - `extractRawTimeValues` — opt out of TIMESTAMP / DATE / TIME conversion at the extractor boundary,
+/// surfacing the raw underlying integer in the column's declared unit instead of the contract Java type.
+/// DECIMAL and UUID always convert. See [ParquetAvroRecordExtractor] / [ParquetNativeRecordExtractor] for
+/// the per-type matrix.
public class ParquetRecordReaderConfig implements RecordReaderConfig {
- private static final String USE_PARQUET_AVRO_RECORDER_READER = "useParquetAvroRecordReader";
- private static final String USE_PARQUET_NATIVE_RECORDER_READER = "useParquetNativeRecordReader";
-
private boolean _useParquetAvroRecordReader;
private boolean _useParquetNativeRecordReader;
- private Configuration _conf;
-
- public ParquetRecordReaderConfig() {
- }
-
- public ParquetRecordReaderConfig(Configuration conf) {
- _conf = conf;
- _useParquetAvroRecordReader = conf.getBoolean(USE_PARQUET_AVRO_RECORDER_READER, false);
- _useParquetNativeRecordReader = conf.getBoolean(USE_PARQUET_NATIVE_RECORDER_READER, false);
- }
+ private boolean _extractRawTimeValues;
Review Comment:
Acknowledged as a deliberate API change, in the same family as the `BaseRecordExtractor.shouldExtract` and `JsonUtils.jsonNodeToStringMap` removals already discussed in this PR. The `Configuration`-based constructor and `getConfig()` accessor were a thin convenience over `commons-configuration` access; in-tree usage was zero, and external callers can switch to the property-based constructor or call `setX(...)` directly. Trading the small breakage now for a cleaner config surface that doesn't pull a `commons-configuration` Configuration into the SPI.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3180030237
##########
pinot-plugins/pinot-input-format/pinot-avro-base/src/main/java/org/apache/pinot/plugin/inputformat/avro/AvroRecordReaderConfig.java:
##########
@@ -20,17 +20,16 @@
import org.apache.pinot.spi.data.readers.RecordReaderConfig;
-/**
- * Config for {@link AvroRecordReader}
- */
+
+/// Config for [AvroRecordReader]. See [AvroRecordExtractorConfig] for the meaning of `extractRawTimeValues`.
public class AvroRecordReaderConfig implements RecordReaderConfig {
- private boolean _enableLogicalTypes = true;
+ private boolean _extractRawTimeValues;
- public boolean isEnableLogicalTypes() {
- return _enableLogicalTypes;
+ public boolean isExtractRawTimeValues() {
+ return _extractRawTimeValues;
}
- public void setEnableLogicalTypes(boolean enableLogicalTypes) {
- _enableLogicalTypes = enableLogicalTypes;
+ public void setExtractRawTimeValues(boolean extractRawTimeValues) {
+ _extractRawTimeValues = extractRawTimeValues;
}
Review Comment:
Acknowledged as a deliberate breaking change. The old `enableLogicalTypes=false` was a global switch that turned off DECIMAL and UUID along with TIMESTAMP / DATE / TIME — but DECIMAL is meaningless without scale/precision-driven conversion (raw bytes can't be interpreted) and UUID is meaningless without canonical-form decoding. So `enableLogicalTypes=false` was never really a usable mode for those types; users who set it generally meant "give me raw timestamp/date/time integers," not "break my decimals."
The new `extractRawTimeValues` flag is finer-grained — it opts out of TIMESTAMP / DATE / TIME only, with DECIMAL and UUID always converted. Adding a compat alias from `enableLogicalTypes=false` to `extractRawTimeValues=true` would silently flip DECIMAL/UUID behavior for any existing user who set the old flag, which is its own surprise. A clean rename forces an explicit migration decision rather than papering over the semantic difference.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3180035533
##########
pinot-plugins/pinot-input-format/pinot-parquet/src/main/java/org/apache/pinot/plugin/inputformat/parquet/ParquetNativeRecordExtractor.java:
##########
@@ -148,95 +164,74 @@ private Object extractValue(Group from, int fieldIndex, Type fieldType, int inde
return BigDecimal.valueOf(longValue, decimalLogicalTypeAnnotation.getScale());
}
if (logicalTypeAnnotation instanceof LogicalTypeAnnotation.TimeLogicalTypeAnnotation) {
- // `TIME_MICROS` / `TIME_NANOS` → [LocalTime] preserving full nanosecond precision.
+ // `TIME_MICROS` / `TIME_NANOS` → [LocalTime] preserving full nanosecond precision, or raw value
+ // (in the column's declared unit) when configured.
+ if (_extractRawTimeValues) {
+ return longValue;
+ }
LogicalTypeAnnotation.TimeUnit timeUnit =
((LogicalTypeAnnotation.TimeLogicalTypeAnnotation) logicalTypeAnnotation).getUnit();
return LocalTime.ofNanoOfDay(timeUnit == LogicalTypeAnnotation.TimeUnit.MICROS ? longValue * 1_000L
: longValue);
}
if (logicalTypeAnnotation instanceof LogicalTypeAnnotation.TimestampLogicalTypeAnnotation) {
- // `TIMESTAMP_MILLIS` / `TIMESTAMP_MICROS` / `TIMESTAMP_NANOS` → `java.sql.Timestamp` preserving
- // sub-millisecond precision via `setNanos`.
- return timestampFromLong(longValue,
+ // `TIMESTAMP_MILLIS` / `TIMESTAMP_MICROS` / `TIMESTAMP_NANOS` → [Timestamp] preserving sub-millisecond
+ // nanos via `setNanos`. Raw mode returns the value as stored in the column's declared unit.
+ // TODO: `isAdjustedToUTC()` is ignored — a `timestamp-* adjustToUTC=false` field is local-clock
+ // time, not a UTC instant, but we treat all values as UTC instants per the Pinot TIMESTAMP
+ // contract. For local-datetime data the produced `Timestamp` will be off by the JVM TZ offset.
+ if (_extractRawTimeValues) {
+ return longValue;
+ }
+ return ParquetUtils.convertLongToTimestamp(longValue,
((LogicalTypeAnnotation.TimestampLogicalTypeAnnotation) logicalTypeAnnotation).getUnit());
Review Comment:
Acknowledged, but out of scope for this PR. The `isAdjustedToUTC=false` mishandling is pre-existing — the prior code (before this PR) decoded both variants identically as UTC instants too. This PR keeps that behavior unchanged and adds an explicit TODO at the call site (`isAdjustedToUTC() is ignored — a 'timestamp-* adjustToUTC=false' field is local-clock time, not a UTC instant, but we treat all values as UTC instants per the Pinot TIMESTAMP contract`). Fixing it is itself a user-visible behavior change for anyone whose data is `adjustToUTC=false` — their TIMESTAMP column values would shift by the JVM TZ offset on upgrade — so it deserves its own PR with a release note rather than being folded into the contract-refinement scope here.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refine RecordExtractor contract: TIMESTAMP narrows to Long, push time conversions per-format [pinot]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18400:
URL: https://github.com/apache/pinot/pull/18400#discussion_r3175820076
##########
pinot-spi/src/main/java/org/apache/pinot/spi/data/readers/BaseRecordExtractor.java:
##########
@@ -211,22 +194,18 @@ protected Map<Object, Object> convertRecord(Object value) {
getClass().getSimpleName() + " does not support nested records; override convertRecord() to enable.");
}
- /// Converts a single value per the [RecordExtractor] contract:
+ /// Universal normalizations for types that any format extractor might produce:
/// - `Byte` / `Short` widen to `Integer` so all small ints unify behind a single Pinot type
/// - [BigInteger] widens to [BigDecimal] (Pinot has no `BigInteger` data type; downstream transforms handle
/// `BigDecimal` natively)
/// - other `Number` (`Integer` / `Long` / `Float` / `Double` / `BigDecimal`) passes through
/// - `Boolean` passes through
/// - `byte[]` passes through
- /// - [Timestamp] passes through
/// - `ByteBuffer` materializes to `byte[]` (sliced so the source buffer's position is not advanced)
///
- /// [Temporal] family (`java.time`):
- /// - [LocalDate] / [LocalTime] pass through (TZ-independent date / time-of-day)
- /// - [Instant] / [OffsetDateTime] / [ZonedDateTime] bridge to [Timestamp] via [Timestamp#from] — all three are
- /// unambiguously TZ-anchored, so the conversion is lossless (sub-second nanos preserved)
- /// - [LocalDateTime] bridges to [Timestamp] interpreting the wall-clock as UTC
- /// - other [Temporal] types fall through to `value.toString()`
+ /// Date / time types (DATE / TIME / TIMESTAMP) are NOT handled here — see [RecordExtractor] for the contract
+ /// and the format-specific extractor (`convertSingleValue` override or direct construction in `extractValue`)
+ /// for the native-to-contract conversion.
Review Comment:
This change silently alters the default SPI behavior for third-party `BaseRecordExtractor` subclasses: any extractor that relied on the base implementation to normalize `Timestamp`/`Instant`/`LocalDate`/`LocalTime` now falls through to `toString()`. That is a breaking contract change for external formats unless every downstream subclass is updated in lockstep.
##########
pinot-plugins/pinot-input-format/pinot-arrow/src/main/java/org/apache/pinot/plugin/inputformat/arrow/ArrowToGenericRowConverter.java:
##########
@@ -246,12 +245,10 @@ private Object convertArrowTypeToPinotCompatible(@Nullable Object value) {
return value.toString();
}
- // Handle Arrow LocalDateTime -> java.sql.Timestamp conversion
+ // Handle Arrow LocalDateTime -> Long epoch millis (per RecordExtractor contract: TIMESTAMP → Long).
if (value instanceof LocalDateTime) {
- // Arrow TimeStampMilliVector.getObject() returns LocalDateTime, but Pinot expects
- // java.sql.Timestamp objects for proper timestamp handling and native support
LocalDateTime dateTime = (LocalDateTime) value;
- return Timestamp.from(dateTime.toInstant(ZoneOffset.UTC));
+ return dateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
Review Comment:
The new `LocalDateTime -> epochMillis` conversion is only covered by a test that checks the result is a positive `Long`, so it would not catch a wrong epoch calculation or a timezone/offset regression. Since this file already has Arrow decoder tests, please add an assertion for the exact expected millis value (ideally including a non-midnight case) for the new UTC interpretation.
##########
pinot-spi/src/main/java/org/apache/pinot/spi/data/readers/BaseRecordExtractor.java:
##########
@@ -77,14 +68,6 @@ public void init(@Nullable Set<String> fields, @Nullable RecordExtractorConfig c
protected void initConfig(@Nullable RecordExtractorConfig config) {
}
Review Comment:
Removing this protected helper is a source-compatible breaking change for external `pinot-spi` consumers that subclass `BaseRecordExtractor`. Even if the method is unused inside this repository, third-party extractors can still call `shouldExtract(...)`, so deleting it from a published SPI will break their builds on upgrade.
##########
pinot-plugins/pinot-input-format/pinot-orc/src/main/java/org/apache/pinot/plugin/inputformat/orc/ORCRecordExtractor.java:
##########
@@ -206,13 +206,12 @@ private static Object extractSingleValue(String field, ColumnVector columnVector
}
case TIMESTAMP:
case TIMESTAMP_INSTANT: {
- // `time[rowId]` is epoch millis truncated to second precision; sub-second nanos (0..999_999_999)
+ // `time[rowId]` is epoch millis (truncated to second precision); sub-second nanos (0..999_999_999)
// live in `nanos[rowId]`. `TIMESTAMP_INSTANT` (UTC instant) shares the same vector layout as
- // `TIMESTAMP` (local). Construct a `Timestamp` and set the full nanos field to preserve precision.
+ // `TIMESTAMP` (local). Per the contract, output is `Long` epoch millis; sub-millisecond precision is
+ // dropped here to match Pinot's TIMESTAMP physical storage.
TimestampColumnVector tsv = (TimestampColumnVector) columnVector;
- Timestamp ts = new Timestamp(tsv.time[rowId]);
- ts.setNanos(tsv.nanos[rowId]);
- return ts;
+ return tsv.time[rowId] + tsv.nanos[rowId] / 1_000_000L;
Review Comment:
This new manual epoch-millis calculation is only exercised with positive timestamps in `ORCRecordExtractorTest`. Since the code now combines `time` and `nanos` directly instead of delegating to `Timestamp`, it needs at least one pre-epoch test case as well to catch sign/rounding regressions for negative timestamps.
##########
pinot-spi/src/main/java/org/apache/pinot/spi/utils/MapUtils.java:
##########
@@ -50,11 +49,13 @@ private MapUtils() {
}
private static final Logger LOGGER = LoggerFactory.getLogger(MapUtils.class);
- private static final ObjectMapper SORTED_MAPPER =
- new ObjectMapper().configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
- private static final ObjectMapper UNSORTED_MAPPER = new ObjectMapper();
- private static final TypeReference<Map<String, Object>> MAP_TYPE_REFERENCE = new TypeReference<>() {
- };
+
+ // Pinot's standard ObjectMapper config (JSR-310 / ISO-8601 for LocalDate / LocalTime — see JsonUtils),
+ // plus key-ordered output for the sorted variant so byte output is a pure function of the logical map.
+ // Writes only — read paths delegate to JsonUtils, whose DEFAULT_READER is already JSR-310-aware.
+ private static final ObjectWriter SORTED_WRITER = JsonUtils.newObjectMapperWithJavaTime()
+ .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true).writer();
+ private static final ObjectWriter UNSORTED_WRITER = JsonUtils.newObjectMapperWithJavaTime().writer();
Review Comment:
This switches all `MapUtils` serialization paths to the new JSR-310-aware mapper, but none of the existing `MapUtilsTest` cases cover `LocalDate`/`LocalTime` values or nested maps/lists containing them. Because this file already has round-trip tests for other value types, please add analogous coverage here so regressions in the new mapper configuration are caught in the code path that actually serializes `MAP` columns.
##########
pinot-spi/src/main/java/org/apache/pinot/spi/utils/JsonUtils.java:
##########
@@ -157,11 +188,6 @@ public static JsonNode stringToJsonNode(String jsonString)
return DEFAULT_READER.readTree(jsonString);
}
Review Comment:
Deleting `jsonNodeToStringMap(...)` is a backward-incompatible change in the published `pinot-spi` API. There are no in-repo callers anymore, but external code can still call this public helper, so removing it will break upgrades for downstream consumers even though the replacement is only an internal call-site change here.
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
Re: [PR] Refactor Avro/Parquet RecordExtractor; finalize logical-type contract [pinot]
Posted by "Jackie-Jiang (via GitHub)" <gi...@apache.org>.
Jackie-Jiang merged PR #18400:
URL: https://github.com/apache/pinot/pull/18400
--
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@pinot.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org