"""Row ids for tables that grow by time. A random uuid4 primary key puts every new row on a random page of the key's index; once that index outgrows memory, each insert waits for a disk read. Measured on the live instance (#5149): plugin_metrics took ~9 ms a row, about 110 rows/s, so a host agent's post could not finish inside its 10 s timeout. A time-ordered id lands every new row at the index's right edge instead. """ from __future__ import annotations import os import time import uuid def time_ordered_id() -> str: """A UUIDv7-layout id (RFC 9562) as a 36-character string: a 48-bit millisecond timestamp, then 74 random bits. Same shape and column type as the uuid4 ids already stored, so no table changes; Python's own uuid7() arrives only in 3.14.""" ms = time.time_ns() // 1_000_000 value = (ms & 0xFFFF_FFFF_FFFF) << 80 | int.from_bytes(os.urandom(10), "big") value = (value & ~(0xF << 76)) | (0x7 << 76) # version 7 value = (value & ~(0x3 << 62)) | (0x2 << 62) # RFC 9562 variant return str(uuid.UUID(int=value))