From 2deed80fbd15edeff04f9c5925b7897715cfe437 Mon Sep 17 00:00:00 2001
From: Andrey Borodin <amborodin@acm.org>
Date: Tue, 19 Nov 2024 22:41:32 +0500
Subject: [PATCH v34 2/2] Mix in 2 bits of entropy into timestampt of UUID on
 MacOS

---
 src/backend/utils/adt/uuid.c | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/src/backend/utils/adt/uuid.c b/src/backend/utils/adt/uuid.c
index f8b8b59021..b251f2b10d 100644
--- a/src/backend/utils/adt/uuid.c
+++ b/src/backend/utils/adt/uuid.c
@@ -503,6 +503,17 @@ generate_uuidv7(uint64 ns)
 				(errcode(ERRCODE_INTERNAL_ERROR),
 				 errmsg("could not generate random values")));
 
+#if defined(__darwin__)
+	/*
+	 * On MacOS real time is truncted to microseconds. Thus, 2 least
+	 * significant bits of increased_clock_precision are neither random
+	 * (CSPRNG), nor time-dependent (in a sense - truly random). These 2 bits
+	 * are dependent on other time-specific bits, thus they do not contribute
+	 * to uniqueness. To make these bit random we mix in two bits from CSPRNG.
+	 */
+	uuid->data[7] = uuid->data[7] ^ (uuid->data[8] >> 6);
+#endif
+
 	/*
 	 * Set magic numbers for a "version 7" (pseudorandom) UUID, see
 	 * https://www.rfc-editor.org/rfc/rfc9562#name-version-field
-- 
2.39.5 (Apple Git-154)

