]> git.ipfire.org Git - thirdparty/postgresql.git/commitdiff
Reject infinite and out-of-range interval shifts in uuidv7().
authorMasahiko Sawada <msawada@postgresql.org>
Thu, 16 Jul 2026 18:50:16 +0000 (11:50 -0700)
committerMasahiko Sawada <msawada@postgresql.org>
Thu, 16 Jul 2026 18:50:16 +0000 (11:50 -0700)
uuidv7(interval) shifts the current time by the given interval before
encoding it into the 48-bit Unix-millisecond timestamp field of the
generated UUID. Two cases were mishandled:

An infinite interval ('infinity' or '-infinity') produced an infinite
timestamp, which overflowed during the conversion to Unix-epoch
microseconds and yielded a garbage UUID. Reject infinite intervals up
front, before any timestamp arithmetic.

A shift that moved the timestamp outside the range representable by
the 48-bit field was silently accepted. Timestamps before the Unix
epoch wrapped when cast to unsigned, and timestamps beyond
approximately year 10889 overflowed the field; both produced UUIDs
with bogus timestamps that break sort ordering. Reject any shifted
timestamp outside the supported range.

Also document that infinite intervals and out-of-range shifts are
rejected.

Although raising a new error changes behavior in a stable branch, this
is back-patched to 18 (where uuidv7(interval) was introduced) because
the previous behavior can silently corrupt data. Failing loudly is far
safer than silently accepting the wraparound; otherwise users may not
discover that their UUIDv7 values are no longer sortable until years
later, when recovery is painful. It also matches how PostgreSQL
already handles timestamp + interval overflow, which raises an
error. The change only affects applications passing an interval large
enough to push the result outside the representable range.

Backpatch to 18, where uuidv7(interval) was introduced.

Reported-by: Christophe Pettus <xof@thebuild.com>
Author: Baji Shaik <baji.pgdev@gmail.com>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com>
Reviewed-by: Tristan Partin <tristan@partin.io>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Discussion: https://www.postgresql.org/message-id/799A70FA-6E5C-4118-99EB-2FBBE1CBAC54@thebuild.com
Backpatch-through: 18

doc/src/sgml/func/func-uuid.sgml
src/backend/utils/adt/uuid.c
src/test/regress/expected/uuid.out
src/test/regress/sql/uuid.sql

index 2638e2bf855f259f18cc8ac9c8f8bc12586ec367..89fd5781bccf06e944902f91a8bef5110308959b 100644 (file)
         sub-millisecond timestamp + random. The optional
         parameter <parameter>shift</parameter> will shift the computed
         timestamp by the given <type>interval</type>.
+        Infinite interval values are not accepted.
+        The shifted timestamp must fall within the range supported by
+        UUID version 7's 48-bit millisecond timestamp field: from
+        1970-01-01 00:00:00 UTC to approximately year 10889.
+        An error is raised if the resulting timestamp is outside this
+        range.
        </para>
        <para>
         <literal>uuidv7()</literal>
index 6ee3752ac78a78b8bd079ad75dd39f6e9f90eb3f..4b9a75ce217bb259f7e00c02ecad27f96017bd1c 100644 (file)
 #define NS_PER_US      INT64CONST(1000)
 #define US_PER_MS      INT64CONST(1000)
 
+/*
+ * The offset between the PostgreSQL epoch (2000-01-01) and the Unix epoch
+ * (1970-01-01) in microseconds. Subtract this from a Unix-epoch microseconds
+ * to get a TimestampTz.
+ */
+#define PG_UNIX_EPOCH_OFFSET_US \
+       ((int64) (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY * USECS_PER_SEC)
+
+/*
+ * Valid timestamp range for UUID version 7, expressed in PostgreSQL-epoch
+ * microseconds. UUIDv7 uses a 48-bit unsigned millisecond field relative
+ * to the Unix epoch, so the representable window is [1970-01-01, ~10889].
+ */
+#define UUIDV7_MIN_TIMESTAMP   (-PG_UNIX_EPOCH_OFFSET_US)
+#define UUIDV7_MAX_TIMESTAMP \
+       (((INT64CONST(1) << 48) - 1) * US_PER_MS - PG_UNIX_EPOCH_OFFSET_US)
+
 /*
  * UUID version 7 uses 12 bits in "rand_a" to store  1/4096 (or 2^12) fractions of
  * sub-millisecond. While most Unix-like platforms provide nanosecond-precision
@@ -672,6 +689,13 @@ uuidv7_interval(PG_FUNCTION_ARGS)
        int64           ns = get_real_time_ns_ascending();
        int64           us;
 
+       /* Reject infinite intervals before any arithmetic */
+       if (INTERVAL_NOT_FINITE(shift))
+               ereport(ERROR,
+                               (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+                                errmsg("interval out of range for UUID version 7"),
+                                errdetail("UUID version 7 does not support infinite intervals.")));
+
        /*
         * Shift the current timestamp by the given interval. To calculate time
         * shift correctly, we convert the UNIX epoch to TimestampTz and use
@@ -679,16 +703,26 @@ uuidv7_interval(PG_FUNCTION_ARGS)
         * precision.
         */
 
-       ts = (TimestampTz) (ns / NS_PER_US) -
-               (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY * USECS_PER_SEC;
+       ts = (TimestampTz) (ns / NS_PER_US) - PG_UNIX_EPOCH_OFFSET_US;
 
        /* Compute time shift */
        ts = DatumGetTimestampTz(DirectFunctionCall2(timestamptz_pl_interval,
                                                                                                 TimestampTzGetDatum(ts),
                                                                                                 IntervalPGetDatum(shift)));
 
-       /* Convert a TimestampTz value back to an UNIX epoch timestamp */
-       us = ts + (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY * USECS_PER_SEC;
+       /*
+        * Reject timestamps outside the range representable by UUID version 7's
+        * 48-bit millisecond field. We compare in PostgreSQL-epoch units so that
+        * the subsequent conversion to Unix-epoch microseconds cannot overflow.
+        */
+       if (ts < UUIDV7_MIN_TIMESTAMP || ts > UUIDV7_MAX_TIMESTAMP)
+               ereport(ERROR,
+                               (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+                                errmsg("timestamp out of range for UUID version 7"),
+                                errdetail("UUID version 7 supports timestamps from 1970-01-01 to approximately year 10889.")));
+
+       /* Convert the TimestampTz value to a Unix-epoch timestamp in usec */
+       us = ts + PG_UNIX_EPOCH_OFFSET_US;
 
        /* Generate an UUIDv7 */
        uuid = generate_uuidv7(us / US_PER_MS, (us % US_PER_MS) * NS_PER_US + ns % NS_PER_US);
@@ -748,8 +782,7 @@ uuid_extract_timestamp(PG_FUNCTION_ARGS)
                        + (((uint64) uuid->data[0]) << 40);
 
                /* convert ms to us, then adjust */
-               ts = (TimestampTz) (tms * US_PER_MS) -
-                       (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY * USECS_PER_SEC;
+               ts = (TimestampTz) (tms * US_PER_MS) - PG_UNIX_EPOCH_OFFSET_US;
 
                PG_RETURN_TIMESTAMPTZ(ts);
        }
index 9c5dda9e9abb1db7872b455091ed3a6f2d9fbe9c..e10cacbd6b91d720da4176d9d95c77dc884ff865 100644 (file)
@@ -261,6 +261,28 @@ SELECT y, ts, prev_ts FROM uuidts WHERE ts < prev_ts;
 ---+----+---------
 (0 rows)
 
+-- uuidv7: infinite intervals are rejected
+SELECT uuidv7('infinity'::interval);
+ERROR:  interval out of range for UUID version 7
+DETAIL:  UUID version 7 does not support infinite intervals.
+SELECT uuidv7('-infinity'::interval);
+ERROR:  interval out of range for UUID version 7
+DETAIL:  UUID version 7 does not support infinite intervals.
+-- uuidv7: timestamps before Unix epoch are rejected
+SELECT uuidv7('-1000 years'::interval);
+ERROR:  timestamp out of range for UUID version 7
+DETAIL:  UUID version 7 supports timestamps from 1970-01-01 to approximately year 10889.
+-- uuidv7: timestamps beyond 48-bit ms field (~year 10889) are rejected
+SELECT uuidv7('9000 years'::interval);
+ERROR:  timestamp out of range for UUID version 7
+DETAIL:  UUID version 7 supports timestamps from 1970-01-01 to approximately year 10889.
+-- uuidv7: a large but in-range forward shift is accepted
+SELECT uuid_extract_timestamp(uuidv7('1000 years'::interval)) > now() + '999 years'::interval;
+ ?column? 
+----------
+ t
+(1 row)
+
 -- extract functions
 -- version
 SELECT uuid_extract_version('11111111-1111-5111-8111-111111111111');  -- 5
index 8cc2ad40614ae1873c6edca0a068f38212b5ec46..debf84d93491d0d2156fe2b0d0549198ed249a85 100644 (file)
@@ -140,6 +140,19 @@ WITH uuidts AS (
 )
 SELECT y, ts, prev_ts FROM uuidts WHERE ts < prev_ts;
 
+-- uuidv7: infinite intervals are rejected
+SELECT uuidv7('infinity'::interval);
+SELECT uuidv7('-infinity'::interval);
+
+-- uuidv7: timestamps before Unix epoch are rejected
+SELECT uuidv7('-1000 years'::interval);
+
+-- uuidv7: timestamps beyond 48-bit ms field (~year 10889) are rejected
+SELECT uuidv7('9000 years'::interval);
+
+-- uuidv7: a large but in-range forward shift is accepted
+SELECT uuid_extract_timestamp(uuidv7('1000 years'::interval)) > now() + '999 years'::interval;
+
 -- extract functions
 
 -- version