You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "claudevdm (via GitHub)" <gi...@apache.org> on 2025/11/02 22:22:05 UTC

[PR] Timestam logicaltype [beam]

claudevdm opened a new pull request, #36705:
URL: https://github.com/apache/beam/pull/36705

   **Please** add a meaningful description for your change here
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/actions/workflows/build_wheels.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/actions/workflows/python_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/actions/workflows/java_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/actions/workflows/go_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add timestamp logicaltype [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #36705:
URL: https://github.com/apache/beam/pull/36705#discussion_r2494970103


##########
sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/Timestamp.java:
##########
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+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.Instant;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.values.Row;
+import org.checkerframework.checker.nullness.qual.NonNull;
+
+/**
+ * A timestamp represented with configurable precision.
+ *
+ * <p>This logical type stores timestamps as a Row with two fields:
+ *
+ * <ul>
+ *   <li>seconds: INT64 - seconds since Unix epoch (can be negative)
+ *   <li>subseconds: INT16 or INT32 - always non-negative (0 to 10^precision - 1)
+ * </ul>
+ *
+ * <p>The subseconds field is always non-negative, even for timestamps before the epoch. For
+ * example, -1.5 seconds is represented as {seconds: -2, subseconds: 500000} for microsecond
+ * precision. This matches Java's {@link java.time.Instant} internal representation.
+ *
+ * <p><b>Note for users converting from single-integer timestamp representations:</b> If you have
+ * timestamps stored as a single long value (e.g., microseconds since epoch), you must handle
+ * negative modulo correctly when converting:
+ *
+ * <pre>{@code
+ * long timestampMicros = -1_500_000;
+ * long seconds = timestampMicros / 1_000_000;
+ * long micros = timestampMicros % 1_000_000;
+ * if (micros < 0) {
+ *   micros += 1_000_000;
+ *   seconds -= 1;
+ * }
+ * Instant instant = Instant.ofEpochSecond(seconds, micros * 1000);
+ * }</pre>
+ */
+public class Timestamp implements Schema.LogicalType<Instant, Row> {
+  public static final String IDENTIFIER = "beam:logical_type:timestamp:v1";
+  static final int MIN_PRECISION = 0;
+  static final int MAX_PRECISION = 9;
+
+  private final int precision;
+  private final int scalingFactor;
+  private final Schema timestampSchema;
+
+  public static Timestamp of(int precision) {
+    return new Timestamp(precision);
+  }
+
+  public static final Timestamp MILLIS = Timestamp.of(3);
+  public static final Timestamp MICROS = Timestamp.of(6);
+  public static final Timestamp NANOS = Timestamp.of(9);
+
+  public Timestamp(int precision) {
+    checkArgument(
+        precision <= MAX_PRECISION && precision >= MIN_PRECISION,
+        "Timestamp precision must be between %s and %s (inclusive), but was %s.",
+        MIN_PRECISION,
+        MAX_PRECISION,
+        precision);
+    this.precision = precision;
+    this.scalingFactor = (int) Math.pow(10, MAX_PRECISION - precision);
+    if (precision < 5) {
+      this.timestampSchema =
+          Schema.builder().addInt64Field("seconds").addInt16Field("subseconds").build();
+    } else {
+      this.timestampSchema =
+          Schema.builder().addInt64Field("seconds").addInt32Field("subseconds").build();
+    }
+  }
+
+  @Override
+  public String getIdentifier() {
+    return IDENTIFIER;
+  }
+
+  @Override
+  public Schema.FieldType getArgumentType() {
+    return Schema.FieldType.INT32;
+  }
+
+  @Override
+  public Integer getArgument() {
+    return precision;
+  }
+
+  @Override
+  public Schema.FieldType getBaseType() {
+    return Schema.FieldType.row(timestampSchema);
+  }
+
+  @Override
+  public Row toBaseType(Instant input) {
+    // Avoid silent data loss
+    checkState(
+        input.getNano() % scalingFactor == 0,
+        "Timestamp logical type was configured with precision %s, but encountered "
+            + "a Java Instant with %s nanoseconds (not evenly divisible by scaling factor %s).",
+        precision,
+        input.getNano(),
+        scalingFactor);
+
+    int subseconds = input.getNano() / scalingFactor;
+
+    Row.Builder rowBuilder = Row.withSchema(timestampSchema).addValue(input.getEpochSecond());
+    if (precision < 5) {
+      rowBuilder.addValue((short) subseconds); // Explicitly add as short
+    } else {
+      rowBuilder.addValue(subseconds); // Add as int
+    }
+    return rowBuilder.build();
+  }
+
+  @Override
+  public Instant toInputType(@NonNull Row base) {
+    long subseconds =
+        (precision < 5)
+            ? checkArgumentNotNull(
+                base.getInt16(1),
+                "While trying to convert to Instant: Row missing subseconds field")
+            : checkArgumentNotNull(
+                base.getInt32(1),
+                "While trying to convert to Instant: Row missing subseconds field");
+
+    checkArgument(
+        subseconds >= 0,
+        "While trying to convert to Instant: subseconds field must be non-negative, "
+            + "but was %s. This likely indicates data corruption.",
+        subseconds);
+
+    int maxSubseconds = (int) (Math.pow(10, precision) - 1);
+    checkArgument(
+        subseconds <= maxSubseconds,
+        "While trying to convert to Instant: subseconds field must be <= %s for precision %s, "
+            + "but was %s. This likely indicates data corruption or precision mismatch.",
+        maxSubseconds,
+        precision,
+        subseconds);
+
+    return Instant.ofEpochSecond(
+        checkArgumentNotNull(
+            base.getInt64(0), "While trying to convert to Instant: Row missing seconds field"),
+        subseconds * scalingFactor);
+  }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   This method can be improved for readability, maintainability, and performance.
   
   1.  **Access fields by name**: Using indices like `0` and `1` is fragile. Accessing fields by name (`"seconds"`, `"subseconds"`) is more robust.
   2.  **Simplify subseconds retrieval**: You can get the `subseconds` value as a `Number` and call `longValue()`, which works for both `Short` and `Integer` types, simplifying the conditional logic.
   3.  **Avoid `Math.pow`**: As mentioned for the constructor, using a pre-computed array for powers of 10 is better than `Math.pow`.
   
   Here is a suggested refactoring that incorporates these points. Note that this assumes you've added the `POWERS_OF_10` array as suggested in the other comment.
   
   ```java
     public Instant toInputType(@NonNull Row base) {
       Number subsecondsNum = (Number) base.getValue("subseconds");
       checkArgumentNotNull(
           subsecondsNum, "While trying to convert to Instant: Row missing subseconds field");
       long subseconds = subsecondsNum.longValue();
   
       checkArgument(
           subseconds >= 0,
           "While trying to convert to Instant: subseconds field must be non-negative, "
               + "but was %s. This likely indicates data corruption.",
           subseconds);
   
       int maxSubseconds = POWERS_OF_10[precision] - 1;
       checkArgument(
           subseconds <= maxSubseconds,
           "While trying to convert to Instant: subseconds field must be <= %s for precision %s, "
               + "but was %s. This likely indicates data corruption or precision mismatch.",
           maxSubseconds,
           precision,
           subseconds);
   
       Long seconds =
           checkArgumentNotNull(
               base.getInt64("seconds"), "While trying to convert to Instant: Row missing seconds field");
   
       return Instant.ofEpochSecond(seconds, subseconds * scalingFactor);
     }
   ```



##########
sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/logicaltypes/Timestamp.java:
##########
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+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.Instant;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.values.Row;
+import org.checkerframework.checker.nullness.qual.NonNull;
+
+/**
+ * A timestamp represented with configurable precision.
+ *
+ * <p>This logical type stores timestamps as a Row with two fields:
+ *
+ * <ul>
+ *   <li>seconds: INT64 - seconds since Unix epoch (can be negative)
+ *   <li>subseconds: INT16 or INT32 - always non-negative (0 to 10^precision - 1)
+ * </ul>
+ *
+ * <p>The subseconds field is always non-negative, even for timestamps before the epoch. For
+ * example, -1.5 seconds is represented as {seconds: -2, subseconds: 500000} for microsecond
+ * precision. This matches Java's {@link java.time.Instant} internal representation.
+ *
+ * <p><b>Note for users converting from single-integer timestamp representations:</b> If you have
+ * timestamps stored as a single long value (e.g., microseconds since epoch), you must handle
+ * negative modulo correctly when converting:
+ *
+ * <pre>{@code
+ * long timestampMicros = -1_500_000;
+ * long seconds = timestampMicros / 1_000_000;
+ * long micros = timestampMicros % 1_000_000;
+ * if (micros < 0) {
+ *   micros += 1_000_000;
+ *   seconds -= 1;
+ * }
+ * Instant instant = Instant.ofEpochSecond(seconds, micros * 1000);
+ * }</pre>
+ */
+public class Timestamp implements Schema.LogicalType<Instant, Row> {
+  public static final String IDENTIFIER = "beam:logical_type:timestamp:v1";
+  static final int MIN_PRECISION = 0;
+  static final int MAX_PRECISION = 9;
+
+  private final int precision;
+  private final int scalingFactor;
+  private final Schema timestampSchema;
+
+  public static Timestamp of(int precision) {
+    return new Timestamp(precision);
+  }
+
+  public static final Timestamp MILLIS = Timestamp.of(3);
+  public static final Timestamp MICROS = Timestamp.of(6);
+  public static final Timestamp NANOS = Timestamp.of(9);
+
+  public Timestamp(int precision) {
+    checkArgument(
+        precision <= MAX_PRECISION && precision >= MIN_PRECISION,
+        "Timestamp precision must be between %s and %s (inclusive), but was %s.",
+        MIN_PRECISION,
+        MAX_PRECISION,
+        precision);
+    this.precision = precision;
+    this.scalingFactor = (int) Math.pow(10, MAX_PRECISION - precision);

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Using `Math.pow` for integer powers can be inefficient and can sometimes lead to precision issues with floating-point arithmetic. It's better to use pre-calculated integer powers of 10 for clarity, performance, and to avoid potential floating-point inaccuracies.
   
   Consider adding a static final array of powers of 10 to the class:
   ```java
   private static final int[] POWERS_OF_10 = {
     1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000, 1_000_000_000
   };
   ```
   Then you can replace this line with:
   `this.scalingFactor = POWERS_OF_10[MAX_PRECISION - precision];`
   
   And in `toInputType`, `(int) (Math.pow(10, precision) - 1)` can be replaced with `POWERS_OF_10[precision] - 1`.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add timestamp logicaltype [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #36705:
URL: https://github.com/apache/beam/pull/36705#issuecomment-3491614400

   Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment `assign set of reviewers`


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add timestamo logicaltype [beam]

Posted by "claudevdm (via GitHub)" <gi...@apache.org>.
claudevdm commented on PR #36705:
URL: https://github.com/apache/beam/pull/36705#issuecomment-3491606972

   R: @ahmedabu98 
   R: @Abacn 
   R: @damccorm 


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add timestamp logicaltype [beam]

Posted by "claudevdm (via GitHub)" <gi...@apache.org>.
claudevdm commented on PR #36705:
URL: https://github.com/apache/beam/pull/36705#issuecomment-3491729308

   /gemini review


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add timestamp logicaltype [beam]

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm merged PR #36705:
URL: https://github.com/apache/beam/pull/36705


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org