Skip to content

[Uid] Add microsecond precision to UUIDv7 and optimize on x64 #60898

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Symfony/Component/Uid/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.4
---

* Add microsecond precision to UUIDv7

7.3
---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ public function testV7()
toBase32 01FWHE4YDGFK1SHH6W1G60EECF
toHex 0x017f22e279b07cc398c4dc0c0c07398f
----------------------- --------------------------------------
Time 2022-02-22 19:22:22.000000 UTC
Time 2022-02-22 19:22:22.000816 UTC
----------------------- --------------------------------------
Expand Down
12 changes: 12 additions & 0 deletions src/Symfony/Component/Uid/Tests/UuidTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -546,4 +546,16 @@ public function testToString()
{
$this->assertSame('a45a8538-77a9-4335-bd30-236f59b81b81', (new UuidV4('a45a8538-77a9-4335-bd30-236f59b81b81'))->toString());
}

/**
* @testWith ["1645557742.000001"]
* ["1645557742.123456"]
* ["1645557742.999999"]
*/
public function testV7MicrosecondPrecision(string $time)
{
$uuid = UuidV7::fromString(UuidV7::generate(\DateTimeImmutable::createFromFormat('U.u', $time)));

$this->assertSame($time, $uuid->getDateTime()->format('U.u'));
}
}
84 changes: 53 additions & 31 deletions src/Symfony/Component/Uid/UuidV7.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
use Symfony\Component\Uid\Exception\InvalidArgumentException;

/**
* A v7 UUID is lexicographically sortable and contains a 48-bit timestamp and 74 extra unique bits.
* A v7 UUID is lexicographically sortable and contains a 58-bit timestamp and 64 extra unique bits.
*
* Within the same millisecond, monotonicity is ensured by incrementing the random part by a random increment.
* Within the same millisecond, the unique bits are incremented by a 24-bit random number.
* This method provides microsecond precision for the timestamp, and minimizes both the
* risk of collisions and the consumption of the OS' entropy pool.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
Expand All @@ -25,6 +27,7 @@
protected const TYPE = 7;

private static string $time = '';
private static int $subMs = 0;
private static array $rand = [];
private static string $seed;
private static array $seedParts;
Expand All @@ -47,23 +50,27 @@
if (4 > \strlen($time)) {
$time = '000'.$time;
}
$time .= substr(1000 + (hexdec(substr($this->uid, 14, 4)) >> 2 & 0x3FF), -3);

return \DateTimeImmutable::createFromFormat('U.v', substr_replace($time, '.', -3, 0));
return \DateTimeImmutable::createFromFormat('U.u', substr_replace($time, '.', -6, 0));

Check failure on line 55 in src/Symfony/Component/Uid/UuidV7.php

View workflow job for this annotation

GitHub Actions / Psalm

FalsableReturnStatement

src/Symfony/Component/Uid/UuidV7.php:55:16: FalsableReturnStatement: The declared return type 'DateTimeImmutable' for Symfony\Component\Uid\UuidV7::getDateTime does not allow false, but the function returns 'DateTimeImmutable|false' (see https://psalm.dev/137)

Check failure on line 55 in src/Symfony/Component/Uid/UuidV7.php

View workflow job for this annotation

GitHub Actions / Psalm

FalsableReturnStatement

src/Symfony/Component/Uid/UuidV7.php:55:16: FalsableReturnStatement: The declared return type 'DateTimeImmutable' for Symfony\Component\Uid\UuidV7::getDateTime does not allow false, but the function returns 'DateTimeImmutable|false' (see https://psalm.dev/137)
}

public static function generate(?\DateTimeInterface $time = null): string
{
if (null === $mtime = $time) {
$time = microtime(false);
$subMs = (int) substr($time, 5, 3);
$time = substr($time, 11).substr($time, 2, 3);
} elseif (0 > $time = $time->format('Uv')) {
} elseif (0 > $time = $time->format('Uu')) {
throw new InvalidArgumentException('The timestamp must be positive.');
} else {
$subMs = (int) substr($time, -3);

Check failure on line 67 in src/Symfony/Component/Uid/UuidV7.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Component/Uid/UuidV7.php:67:35: InvalidArgument: Argument 1 of substr expects string, but DateTimeInterface|null provided (see https://psalm.dev/004)

Check failure on line 67 in src/Symfony/Component/Uid/UuidV7.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Component/Uid/UuidV7.php:67:35: InvalidArgument: Argument 1 of substr expects string, but DateTimeInterface|null provided (see https://psalm.dev/004)
$time = substr($time, 0, -3);

Check failure on line 68 in src/Symfony/Component/Uid/UuidV7.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Component/Uid/UuidV7.php:68:28: InvalidArgument: Argument 1 of substr expects string, but DateTimeInterface|null provided (see https://psalm.dev/004)

Check failure on line 68 in src/Symfony/Component/Uid/UuidV7.php

View workflow job for this annotation

GitHub Actions / Psalm

InvalidArgument

src/Symfony/Component/Uid/UuidV7.php:68:28: InvalidArgument: Argument 1 of substr expects string, but DateTimeInterface|null provided (see https://psalm.dev/004)
}

if ($time > self::$time || (null !== $mtime && $time !== self::$time)) {
randomize:
self::$rand = unpack('n*', isset(self::$seed) ? random_bytes(10) : self::$seed = random_bytes(16));
self::$rand[1] &= 0x03FF;
self::$rand = unpack(\PHP_INT_SIZE >= 8 ? 'L*' : 'S*', isset(self::$seed) ? random_bytes(8) : self::$seed = random_bytes(16));
self::$time = $time;
} else {
// Within the same ms, we increment the rand part by a random 24-bit number.
Expand All @@ -73,12 +80,12 @@
// them into 16 x 32-bit numbers; we take the first byte of each of these
// numbers to get 5 extra 24-bit numbers. Then, we consume those numbers
// one-by-one and run this logic every 21 iterations.
// self::$rand holds the random part of the UUID, split into 5 x 16-bit
// numbers for x86 portability. We increment this random part by the next
// self::$rand holds the random part of the UUID, split into 2 x 32-bit numbers
// or 4 x 16-bit for x86 portability. We increment this random part by the next
// 24-bit number in the self::$seedParts list and decrement self::$seedIndex.

if (!self::$seedIndex) {
$s = unpack('l*', self::$seed = hash('sha512', self::$seed, true));
$s = unpack(\PHP_INT_SIZE >= 8 ? 'L*' : 'l*', self::$seed = hash('sha512', self::$seed, true));
$s[] = ($s[1] >> 8 & 0xFF0000) | ($s[2] >> 16 & 0xFF00) | ($s[3] >> 24 & 0xFF);
$s[] = ($s[4] >> 8 & 0xFF0000) | ($s[5] >> 16 & 0xFF00) | ($s[6] >> 24 & 0xFF);
$s[] = ($s[7] >> 8 & 0xFF0000) | ($s[8] >> 16 & 0xFF00) | ($s[9] >> 24 & 0xFF);
Expand All @@ -88,40 +95,55 @@
self::$seedIndex = 21;
}

self::$rand[5] = 0xFFFF & $carry = self::$rand[5] + 1 + (self::$seedParts[self::$seedIndex--] & 0xFFFFFF);
self::$rand[4] = 0xFFFF & $carry = self::$rand[4] + ($carry >> 16);
self::$rand[3] = 0xFFFF & $carry = self::$rand[3] + ($carry >> 16);
self::$rand[2] = 0xFFFF & $carry = self::$rand[2] + ($carry >> 16);
self::$rand[1] += $carry >> 16;

if (0xFC00 & self::$rand[1]) {
if (\PHP_INT_SIZE >= 8 || 10 > \strlen($time = self::$time)) {
$time = (string) (1 + $time);
} elseif ('999999999' === $mtime = substr($time, -9)) {
$time = (1 + substr($time, 0, -9)).'000000000';
} else {
$time = substr_replace($time, str_pad(++$mtime, 9, '0', \STR_PAD_LEFT), -9);
}
if (\PHP_INT_SIZE >= 8) {
self::$rand[2] = 0xFFFFFFFF & $carry = self::$rand[2] + 1 + (self::$seedParts[self::$seedIndex--] & 0xFFFFFF);
self::$rand[1] = 0xFFFFFFFF & $carry = self::$rand[1] + ($carry >> 32);
$carry >>= 32;
} else {
self::$rand[4] = 0xFFFF & $carry = self::$rand[4] + 1 + (self::$seedParts[self::$seedIndex--] & 0xFFFFFF);
self::$rand[3] = 0xFFFF & $carry = self::$rand[3] + ($carry >> 16);
self::$rand[2] = 0xFFFF & $carry = self::$rand[2] + ($carry >> 16);
self::$rand[1] = 0xFFFF & $carry = self::$rand[1] + ($carry >> 16);
$carry >>= 16;
}

if ($carry && $subMs <= self::$subMs) {
usleep(1);

goto randomize;
if (1024 <= ++$subMs) {
if (\PHP_INT_SIZE >= 8 || 10 > \strlen($time = self::$time)) {
$time = (string) (1 + $time);
} elseif ('999999999' === $mtime = substr($time, -9)) {
$time = (1 + substr($time, 0, -9)).'000000000';
} else {
$time = substr_replace($time, str_pad(++$mtime, 9, '0', \STR_PAD_LEFT), -9);
}

goto randomize;
}
}

$time = self::$time;
}
self::$subMs = $subMs;

if (\PHP_INT_SIZE >= 8) {
$time = dechex($time);
} else {
$time = bin2hex(BinaryUtil::fromBase($time, BinaryUtil::BASE10));
return substr_replace(\sprintf('%012x-%04x-%04x-%04x%08x',
$time,
0x7000 | ($subMs << 2) | (self::$rand[1] >> 30),
0x8000 | (self::$rand[1] >> 16 & 0x3FFF),
self::$rand[1] & 0xFFFF,
self::$rand[2],
), '-', 8, 0);
}

return substr_replace(\sprintf('%012s-%04x-%04x-%04x%04x%04x',
$time,
0x7000 | (self::$rand[1] << 2) | (self::$rand[2] >> 14),
0x8000 | (self::$rand[2] & 0x3FFF),
bin2hex(BinaryUtil::fromBase($time, BinaryUtil::BASE10)),
0x7000 | ($subMs << 2) | (self::$rand[1] >> 14),
0x8000 | (self::$rand[1] & 0x3FFF),
self::$rand[2],
self::$rand[3],
self::$rand[4],
self::$rand[5],
), '-', 8, 0);
}
}
Loading