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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
* [Beam SQL] Added a live view to the SQL shell. A streaming (unbounded) SELECT shows its rows as they arrive, with an `op` column for each row's change kind ([#41313](https://github.com/apache/beam/issues/41313)).
* (Python) `BatchElements` can group elements by key across workers (`key_fn`, `num_shards`), and RunInference model handlers can use it through `batch_key_fn` / `batch_key_num_shards`. `apache_beam.ml.inference.prefix_batching` adds a `PrefixBatchingConfig` and prompt/chat prefix extractors so LLM handlers can batch requests that share a prompt prefix and hit the server's prefix cache ([#40905](https://github.com/apache/beam/pull/40905)).
* (Go) Added pass-through registration for fixed and variable length string and bytes logical types ([#39684](https://github.com/apache/beam/issues/39684)).
* (Java/Python) Added DateTime as a new portable logical type (`datetime:v1`). Java `DateTime` takes a precision (`DateTime.of(p)`, `MILLIS`, `MICROS`, `NANOS`), which defaults to 6. Python maps it to the new `apache_beam.utils.timestamp.DateTime` ([#41550](https://github.com/apache/beam/pull/41550)).

### Performance

Expand All @@ -128,6 +129,7 @@

[comment]: # "generic breaking changes if not covered in following sections."
* (Java) Flink runner: batch pipelines now assign source splits to readers statically by default instead of lazily. Set `--sourceStaticSplitThresholdMb=0` to restore lazy assignment ([#40607](https://github.com/apache/beam/issues/40607)).
* (Java) `SqlTypes.DATETIME` is now `DateTime` with precision 6, so a `LocalDateTime` with digits below a microsecond throws instead of being stored. Use `DateTime.NANOS` for those values ([#41550](https://github.com/apache/beam/pull/41550)).
* X behavior was changed ([#X](https://github.com/apache/beam/issues/X)).

### Package upgrades
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -657,3 +657,35 @@ coder:
examples:
"\x01\x00\x02\x00\xb6\x95\xd5\xf9\x05\x95\x9a\xef:": {f_timestamp: {seconds: 1597328054, subseconds: 123456789}}
"\x01\x00\x02\x00\xfe\xff\xff\xff\xff\xff\xff\xff\xff\x01\xff\x93\xeb\xdc\x03": {f_timestamp: {seconds: -2, subseconds: 999999999}}

---

coder:
urn: "beam:coder:row:v1"
# f_datetime: logical(datetime:v1, precision=3, representation row<Date:int64, Time:int64>)
payload: "\x0a}\x0a\x0af_datetime\x1ao:m\x0a\x1dbeam:logical_type:datetime:v1\x1aB2@\x0a>\x0a\x0a\x0a\x04Date\x1a\x02\x10\x04\x0a\x0a\x0a\x04Time\x1a\x02\x10\x04\x12$83a4147a-2f70-4c01-bb68-1e864ad6990c\"\x02\x10\x03*\x04\x0a\x02\x18\x03\x12$4fc4774e-37df-400a-8f31-7ef2a0dff64d"
examples:
"\x01\x00\x02\x00\xb7\x90\x01\xc0\xe1\xad\xbe\xd8\xd3\x0b": {f_datetime: {Date: 18487, Time: 51254123000000}}
"\x01\x00\x02\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\xc0\xfb\xfe\x89\xc9\xd2\x13": {f_datetime: {Date: -1, Time: 86399999000000}}

---

coder:
urn: "beam:coder:row:v1"
# f_datetime: logical(datetime:v1, precision=6, representation row<Date:int64, Time:int64>)
payload: "\x0a}\x0a\x0af_datetime\x1ao:m\x0a\x1dbeam:logical_type:datetime:v1\x1aB2@\x0a>\x0a\x0a\x0a\x04Date\x1a\x02\x10\x04\x0a\x0a\x0a\x04Time\x1a\x02\x10\x04\x12$2b59abb6-4d5c-46e5-8ba7-7bac2152e710\"\x02\x10\x03*\x04\x0a\x02\x18\x06\x12$9a6dd2eb-068c-48c4-bd35-08dda524b154"
examples:
"\x01\x00\x02\x00\xb7\x90\x01\x80\xcc\xc9\xbe\xd8\xd3\x0b": {f_datetime: {Date: 18487, Time: 51254123456000}}
"\x01\x00\x02\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x98\xf8\xbb\x8a\xc9\xd2\x13": {f_datetime: {Date: -1, Time: 86399999999000}}
"\x01\x00\x02\x00\xc6\x8d\xd4\xff\xff\xff\xff\xff\xff\x01\x00": {f_datetime: {Date: -719162, Time: 0}}
"\x01\x00\x02\x00\xa0\x81\xb3\x01\x98\xf8\xbb\x8a\xc9\xd2\x13": {f_datetime: {Date: 2932896, Time: 86399999999000}}

---

coder:
urn: "beam:coder:row:v1"
# f_datetime: logical(datetime:v1, precision=9, representation row<Date:int64, Time:int64>)
payload: "\x0a}\x0a\x0af_datetime\x1ao:m\x0a\x1dbeam:logical_type:datetime:v1\x1aB2@\x0a>\x0a\x0a\x0a\x04Date\x1a\x02\x10\x04\x0a\x0a\x0a\x04Time\x1a\x02\x10\x04\x12$50fa1e41-87ca-49c2-bbf9-2213fda455df\"\x02\x10\x03*\x04\x0a\x02\x18\x09\x12$2528740c-f08c-4259-af4b-4feb13ff0d07"
examples:
"\x01\x00\x02\x00\xb7\x90\x01\x95\xd2\xc9\xbe\xd8\xd3\x0b": {f_datetime: {Date: 18487, Time: 51254123456789}}
"\x01\x00\x02\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\xff\xff\xbb\x8a\xc9\xd2\x13": {f_datetime: {Date: -1, Time: 86399999999999}}
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,16 @@ message LogicalTypes {
// e.g. -1.5s at precision 6 is {seconds: -2, subseconds: 500000}.
TIMESTAMP = 9 [(org.apache.beam.model.pipeline.v1.beam_urn) =
"beam:logical_type:timestamp:v1"];

// A URN for DateTime type
// - Representation type: ROW<Date: INT64, Time: INT64>
// - Argument type: INT32, the precision, which defaults to 6.
// A date and wall-clock time without a timezone. Date counts days
// since the epoch, and Time counts nanoseconds since midnight at every
// precision. The precision is the number of decimal digits of the
// fraction of a second, and every finer digit is zero.
DATETIME = 10 [(org.apache.beam.model.pipeline.v1.beam_urn) =
"beam:logical_type:datetime:v1"];
}
}

Expand Down
1 change: 1 addition & 0 deletions sdks/go/test/regression/coders/fromyaml/fromyaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ var unimplementedCoders = map[string]bool{
var filteredCases = []struct{ filter, reason string }{
{"30ea5a25-dcd8-4cdb-abeb-5332d15ab4b9", "https://github.com/apache/beam/issues/21206: Support encoding position."},
{"beam:logical_type:timestamp:v1", "https://github.com/apache/beam/issues/39684: Support timestamp."},
{"beam:logical_type:datetime:v1", "https://github.com/apache/beam/issues/39684: Support datetime."},
}

// Coder is a representation a serialized beam coder.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import org.apache.beam.sdk.schemas.Schema.LogicalType;
import org.apache.beam.sdk.schemas.Schema.TypeName;
import org.apache.beam.sdk.schemas.logicaltypes.Date;
import org.apache.beam.sdk.schemas.logicaltypes.DateTime;
import org.apache.beam.sdk.schemas.logicaltypes.FixedBytes;
import org.apache.beam.sdk.schemas.logicaltypes.FixedPrecisionNumeric;
import org.apache.beam.sdk.schemas.logicaltypes.FixedString;
Expand Down Expand Up @@ -117,6 +118,7 @@ private static String getLogicalTypeUrn(String identifier) {
.put(VariableString.IDENTIFIER, VariableString.class)
.put(Date.IDENTIFIER, Date.class)
.put(Timestamp.IDENTIFIER, Timestamp.class)
.put(DateTime.IDENTIFIER, DateTime.class)
.build();

public static SchemaApi.Schema schemaToProto(Schema schema, boolean serializeLogicalType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@
package org.apache.beam.sdk.schemas.logicaltypes;

import static org.apache.beam.sdk.util.Preconditions.checkArgumentNotNull;
import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument;
import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.model.pipeline.v1.SchemaApi;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.values.Row;

Expand All @@ -36,29 +40,72 @@
* that represents incrementing count of days where day 0 is 1970-01-01 (ISO). Time field is the
* same as the base type of {@link Time}, which is a Long that represents a count of time in
* nanoseconds.
*
* <p>The precision is the number of digits in the fraction of a second, from 0 to 9, and defaults
* to 6. {@link #toBaseType} refuses a value with finer digits.
*/
public class DateTime implements Schema.LogicalType<LocalDateTime, Row> {
public static final String IDENTIFIER = "beam:logical_type:datetime:v1";
// The UID from before DateTime had a precision, so instances that earlier versions serialized
// still deserialize.
private static final long serialVersionUID = -3033263475478247643L;

public static final String IDENTIFIER =
SchemaApi.LogicalTypes.Enum.DATETIME
.getValueDescriptor()
.getOptions()
.getExtension(RunnerApi.beamUrn);
public static final String DATE_FIELD_NAME = "Date";
public static final String TIME_FIELD_NAME = "Time";
public static final Schema DATETIME_SCHEMA =
Schema.builder().addInt64Field(DATE_FIELD_NAME).addInt64Field(TIME_FIELD_NAME).build();

static final int MAX_PRECISION = 9;
static final int DEFAULT_PRECISION = 6;

public static final DateTime MILLIS = DateTime.of(3);
public static final DateTime MICROS = DateTime.of(6);
public static final DateTime NANOS = DateTime.of(9);

private final int precision;
private final int scalingFactor;

/** A DateTime with the default precision, 6. */
public DateTime() {
this(DEFAULT_PRECISION);
}

private DateTime(int precision) {
checkArgument(
precision >= 0 && precision <= MAX_PRECISION,
"DateTime precision must be between 0 and %s (inclusive), but was %s.",
MAX_PRECISION,
precision);
this.precision = precision;
this.scalingFactor = (int) Math.pow(10, MAX_PRECISION - precision);
}

public static DateTime of(int precision) {
return new DateTime(precision);
}

// Instances that earlier versions serialized have neither field set, and they meant micros.
private Object readResolve() {
return scalingFactor == 0 ? MICROS : this;
}

@Override
public String getIdentifier() {
return IDENTIFIER;
}

// unused
@Override
public Schema.FieldType getArgumentType() {
return Schema.FieldType.STRING;
return Schema.FieldType.INT32;
}

// unused
@Override
public String getArgument() {
return "";
public Integer getArgument() {
return precision;
}

@Override
Expand All @@ -68,21 +115,35 @@ public Schema.FieldType getBaseType() {

@Override
public Row toBaseType(LocalDateTime input) {
long nanoOfDay = input.toLocalTime().toNanoOfDay();
checkState(
nanoOfDay % scalingFactor == 0,
"DateTime logical type was configured with precision %s, but encountered %s, which has "
+ "finer digits.",
precision,
input);
return Row.withSchema(DATETIME_SCHEMA)
.addValues(input.toLocalDate().toEpochDay(), input.toLocalTime().toNanoOfDay())
.addValues(input.toLocalDate().toEpochDay(), nanoOfDay)
.build();
}

@Override
public LocalDateTime toInputType(Row base) {
long nanoOfDay =
checkArgumentNotNull(
base.getInt64(TIME_FIELD_NAME),
"While trying to convert to LocalDateTime: Row missing time field");
checkArgument(
nanoOfDay % scalingFactor == 0,
"While trying to convert to LocalDateTime: time field %s has digits finer than precision "
+ "%s. This likely indicates data corruption or a precision mismatch.",
nanoOfDay,
precision);
return LocalDateTime.of(
LocalDate.ofEpochDay(
checkArgumentNotNull(
base.getInt64(DATE_FIELD_NAME),
"While trying to convert to LocalDateTime: Row missing date field")),
LocalTime.ofNanoOfDay(
checkArgumentNotNull(
base.getInt64(TIME_FIELD_NAME),
"While trying to convert to LocalDateTime: Row missing time field")));
LocalTime.ofNanoOfDay(nanoOfDay));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,8 @@ public static Iterable<Schema.FieldType> data() {
// INT16/INT32 subseconds representation boundary.
.add(FieldType.logicalType(Timestamp.of(4)))
.add(FieldType.logicalType(Timestamp.of(5)))
.add(FieldType.logicalType(DateTime.MILLIS))
.add(FieldType.logicalType(DateTime.NANOS))
.add(FieldType.logicalType(new PortableNullArgLogicalType()))
.add(FieldType.logicalType(new NullArgumentLogicalType()))
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import org.apache.beam.sdk.schemas.Schema;
Expand Down Expand Up @@ -508,4 +512,39 @@ public void testTimestampExtremeValues() {
Row maxRow = Row.withSchema(schema).addValue(nearMax).build();
assertEquals(nearMax, maxRow.getLogicalTypeValue(0, Instant.class));
}

@Test
public void testDateTimePrecision() {
LocalDateTime nanos = LocalDateTime.of(2020, 8, 13, 14, 14, 14, 123_456_789);
assertEquals(nanos, DateTime.NANOS.toInputType(DateTime.NANOS.toBaseType(nanos)));
// SqlTypes.DATETIME is micros, so it refuses finer digits, as Timestamp does.
assertEquals(6, (int) SqlTypes.DATETIME.getArgument());
assertThrows(IllegalStateException.class, () -> SqlTypes.DATETIME.toBaseType(nanos));
Row micros = SqlTypes.DATETIME.toBaseType(nanos.withNano(123_456_000));
assertEquals(51_254_123_456_000L, (long) micros.getInt64(DateTime.TIME_FIELD_NAME));
// Finer digits arriving to decode mean corrupt data.
Row corrupt =
Row.withSchema(DateTime.DATETIME_SCHEMA).addValues(18487L, 51_254_123_456_001L).build();
assertThrows(IllegalArgumentException.class, () -> SqlTypes.DATETIME.toInputType(corrupt));
assertThrows(IllegalArgumentException.class, () -> DateTime.of(10));
assertThrows(IllegalArgumentException.class, () -> DateTime.of(-1));
}

@Test
public void testDateTimeReadsPreviouslySerializedForm() throws Exception {
// A DateTime that Beam 2.77 Java-serialized, before DateTime had a precision. Flink savepoints
// and serialized coders hold this form.
byte[] serialized =
Base64.getDecoder()
.decode(
"rO0ABXNyADFvcmcuYXBhY2hlLmJlYW0uc2RrLnNjaGVtYXMubG9naWNhbHR5cGVzLkRhdGVUaW1l"
+ "1eeu8KHzxyUCAAB4cA==");
DateTime dateTime;
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serialized))) {
dateTime = (DateTime) in.readObject();
}
assertEquals(6, (int) dateTime.getArgument());
LocalDateTime micros = LocalDateTime.of(2020, 8, 13, 14, 14, 14, 123_456_000);
assertEquals(micros, dateTime.toInputType(dateTime.toBaseType(micros)));
}
}
54 changes: 54 additions & 0 deletions sdks/python/apache_beam/coders/row_coder_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from apache_beam.typehints.schemas import _static_encoding_option_pb2
from apache_beam.typehints.schemas import named_tuple_from_schema
from apache_beam.typehints.schemas import typing_to_runner_api
from apache_beam.utils.timestamp import DateTime
from apache_beam.utils.timestamp import Timestamp

Person = typing.NamedTuple(
Expand Down Expand Up @@ -259,6 +260,59 @@ def test_create_row_coder_from_schema_with_parameterized_timestamp(self):
self.assertEqual(test_case, decoded)
self.assertEqual(decoded.event_time.precision(), precision)

def test_java_datetime_bytes(self):
# Bytes from the Java SDK's RowCoder for a SqlTypes.DATETIME field, read
# with the schema older SDKs send, minus the Java-serialized payload. Their
# STRING "" argument means micros.
schema = schema_pb2.Schema(
id="java_datetime",
fields=[
schema_pb2.Field(
name="f_datetime",
type=schema_pb2.FieldType(
logical_type=schema_pb2.LogicalType(
urn="beam:logical_type:datetime:v1",
representation=schema_pb2.FieldType(
row_type=schema_pb2.RowType(
schema=schema_pb2.Schema(
id="java_datetime_repr",
fields=[
schema_pb2.Field(
name="Date",
type=schema_pb2.FieldType(
atomic_type=schema_pb2.INT64)),
schema_pb2.Field(
name="Time",
type=schema_pb2.FieldType(
atomic_type=schema_pb2.INT64)),
]))),
argument_type=schema_pb2.FieldType(
atomic_type=schema_pb2.STRING),
argument=schema_pb2.FieldValue(
atomic_value=schema_pb2.AtomicTypeValue(
string=''))))),
])
coder = RowCoder(schema)
for encoded, expected in [
# 2020-08-13T14:14:14.123456
(b'\x01\x00\x02\x00\xb7\x90\x01\x80\xcc\xc9\xbe\xd8\xd3\x0b',
DateTime(18487, 51254123456, 6)),
# 1969-12-31T23:59:59.999999
(
b'\x01\x00\x02\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01'
b'\x98\xf8\xbb\x8a\xc9\xd2\x13',
DateTime(-1, 86399999999, 6)),
# 0001-01-01T00:00
(b'\x01\x00\x02\x00\xc6\x8d\xd4\xff\xff\xff\xff\xff\xff\x01\x00',
DateTime(-719162, 0, 6)),
# +10000-01-01T00:00, past what datetime.datetime can hold
(b'\x01\x00\x02\x00\xa1\x81\xb3\x01\x00', DateTime(2932897, 0, 6)),
]:
decoded = coder.decode(encoded)
self.assertEqual(decoded.f_datetime, expected)
self.assertEqual(decoded.f_datetime.precision(), expected.precision())
self.assertEqual(coder.encode(decoded), encoded)

def test_row_coder_negative_varint(self):
schema = schema_pb2.Schema(
id="negative",
Expand Down
1 change: 1 addition & 0 deletions sdks/python/apache_beam/portability/common_urns.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,4 @@
var_char = LogicalTypes.Enum.VAR_CHAR
date = LogicalTypes.Enum.DATE
timestamp = LogicalTypes.Enum.TIMESTAMP
datetime = LogicalTypes.Enum.DATETIME
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
from apache_beam.utils.timestamp import DateTime
from apache_beam.utils.timestamp import Timestamp


Expand Down Expand Up @@ -53,7 +54,10 @@ def _create_row(self, num: int):
float_=(num + float(num) / 100),
arr_=[num, num, num],
date_=datetime.date.today() - datetime.timedelta(days=num),
timestamp_=Timestamp(123 * num, 456 * num))
timestamp_=Timestamp(123 * num, 456 * num),
datetime_=DateTime.from_datetime(
datetime.datetime(2020, 8, 13, 14, 14, 14) +
datetime.timedelta(days=num, microseconds=num)))

def test_write_read_pipeline(self):
biglake_catalog_props = {
Expand Down
Loading
Loading