:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(hogql): extract UUIDT and uuid7 to standalone module (#71112)
George Munyoroc9860083bacb
diff --git a/posthog/hogql/database/schema/test/test_channel_type.py b/posthog/hogql/database/schema/test/test_channel_type.pyindex 2986d9a25bf3..c97e6072ae3e 100644--- a/posthog/hogql/database/schema/test/test_channel_type.py+++ b/posthog/hogql/database/schema/test/test_channel_type.py@@ -9,7 +9,7 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query-from posthog.models.utils import uuid7+from posthog.uuidt import uuid7class TestReferringDomainType(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/hogql/database/schema/test/test_events.py b/posthog/hogql/database/schema/test/test_events.pyindex 9d35a1310c76..05a97346ee31 100644--- a/posthog/hogql/database/schema/test/test_events.py+++ b/posthog/hogql/database/schema/test/test_events.py@@ -3,7 +3,7 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_eventfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query-from posthog.models.utils import uuid7+from posthog.uuidt import uuid7class TestEvents(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/hogql/database/schema/test/test_persons.py b/posthog/hogql/database/schema/test/test_persons.pyindex fbf882dd9247..25ab7a6e946b 100644--- a/posthog/hogql/database/schema/test/test_persons.py+++ b/posthog/hogql/database/schema/test/test_persons.py@@ -39,7 +39,7 @@ from posthog.clickhouse.client.execute import sync_executefrom posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunnerfrom posthog.models.person.util import create_person-from posthog.models.utils import UUIDT+from posthog.uuidt import UUIDTfrom products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.util import recalculate_cohortpeoplediff --git a/posthog/hogql/database/schema/test/test_session_replay_events.py b/posthog/hogql/database/schema/test/test_session_replay_events.pyindex 8909081415a2..5841801eac15 100644--- a/posthog/hogql/database/schema/test/test_session_replay_events.py+++ b/posthog/hogql/database/schema/test/test_session_replay_events.py@@ -22,9 +22,9 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client import sync_executefrom posthog.models.event.sql import TRUNCATE_EVENTS_TABLE_SQL-from posthog.models.utils import uuid7from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL+from posthog.uuidt import uuid7@freeze_time("2021-01-01T13:46:23")diff --git a/posthog/hogql/database/schema/test/test_sessions_v1.py b/posthog/hogql/database/schema/test/test_sessions_v1.pyindex 42f631bf8645..98c36f2dc1c5 100644--- a/posthog/hogql/database/schema/test/test_sessions_v1.py+++ b/posthog/hogql/database/schema/test/test_sessions_v1.py@@ -17,7 +17,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.models import Organization, Teamfrom posthog.models.sessions.sql import ALLOWED_TEAM_IDS-from posthog.models.utils import uuid7+from posthog.uuidt import uuid7from products.event_definitions.backend.models.property_definition import PropertyTypediff --git a/posthog/hogql/database/schema/test/test_sessions_v2.py b/posthog/hogql/database/schema/test/test_sessions_v2.pyindex 52c10cfa4ffa..93e27ed21377 100644--- a/posthog/hogql/database/schema/test/test_sessions_v2.py+++ b/posthog/hogql/database/schema/test/test_sessions_v2.py@@ -22,7 +22,7 @@ from posthog.hogql.database.schema.sessions_v2 import (from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query-from posthog.models.utils import uuid7+from posthog.uuidt import uuid7from products.event_definitions.backend.models.property_definition import PropertyTypediff --git a/posthog/hogql/database/schema/test/test_sessions_v3.py b/posthog/hogql/database/schema/test/test_sessions_v3.pyindex 3b8d3a11f78d..f7c06be66cfc 100644--- a/posthog/hogql/database/schema/test/test_sessions_v3.py+++ b/posthog/hogql/database/schema/test/test_sessions_v3.py@@ -20,7 +20,7 @@ from posthog.hogql.database.schema.sessions_v3 import (from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query-from posthog.models.utils import uuid7+from posthog.uuidt import uuid7from products.event_definitions.backend.models.property_definition import PropertyTypediff --git a/posthog/hogql/escape_sql.py b/posthog/hogql/escape_sql.pyindex fea9ffdf359c..dca8c3fd28ee 100644--- a/posthog/hogql/escape_sql.py+++ b/posthog/hogql/escape_sql.py@@ -7,7 +7,7 @@ from zoneinfo import ZoneInfofrom posthog.hogql.errors import QueryError, ResolutionError-from posthog.models.utils import UUIDT+from posthog.uuidt import UUIDT# Copied from clickhouse_driver.util.escape, adapted only from single quotes to backquotes.escape_chars_map = {diff --git a/posthog/hogql/functions/test/test_action.py b/posthog/hogql/functions/test/test_action.pyindex 007c12d7ce9a..abebcb4c2a4d 100644--- a/posthog/hogql/functions/test/test_action.py+++ b/posthog/hogql/functions/test/test_action.py@@ -4,7 +4,7 @@ from posthog.test.base import BaseTest, _create_action, _create_event, _create_pfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.test.utils import pretty_print_response_in_tests-from posthog.models.utils import UUIDT+from posthog.uuidt import UUIDTfrom products.actions.backend.models.action import Actiondiff --git a/posthog/hogql/functions/test/test_cohort.py b/posthog/hogql/functions/test/test_cohort.pyindex 25dd536978c9..081d1484af12 100644--- a/posthog/hogql/functions/test/test_cohort.py+++ b/posthog/hogql/functions/test/test_cohort.py@@ -19,7 +19,7 @@ from posthog.hogql.test.utils import pretty_print_response_in_testsfrom posthog.clickhouse.client.execute import sync_executefrom posthog.models.team.team import Team-from posthog.models.utils import UUIDT+from posthog.uuidt import UUIDTfrom products.cohorts.backend.models.calculation_history import CohortCalculationHistoryfrom products.cohorts.backend.models.cohort import Cohortdiff --git a/posthog/hogql/parser.py b/posthog/hogql/parser.pyindex af18ef493597..ed3ea0993597 100644--- a/posthog/hogql/parser.py+++ b/posthog/hogql/parser.py@@ -1,3 +1,4 @@+import osimport sysimport copyimport random@@ -9,6 +10,7 @@ from types import FrameTypefrom typing import Any, castfrom django.conf import settings+from django.core.exceptions import ImproperlyConfiguredfrom cachetools import LRUCachefrom hogql_parser import (@@ -185,11 +187,25 @@ _PARSER_MODE_BACKENDS: dict[ParserMode, tuple[HogQLParserBackend, HogQLParserBac_SHADOW_SAMPLE_RATE = 0.001+def _is_test_mode() -> bool:+ """Whether we're running under the test settings, without requiring Django to be configured.++ Reads Django's `settings.TEST` when settings are available; falls back to the `TEST` env var+ (then `False`) so the parser can run in environments that never boot Django (CLIs, workers,+ fuzzing scripts). Test mode only tightens parser behavior (100% shadow sampling, raise-on-+ divergence), so defaulting to non-test when settings are absent is safe for production paths.+ """+ try:+ return bool(settings.TEST)+ except ImproperlyConfigured:+ return os.environ.get("TEST", "").lower() in ("1", "true", "t")++def _shadow_sample_rate() -> float:"""Shadow sampling fraction: 100% in tests (an explicitly requested shadow mode compares every parse, soregressions fail loud and deterministically), `_SHADOW_SAMPLE_RATE` in prod. Divergence behavior also differsby env (TEST raises, prod records) in `_run_shadow_comparison`."""- return 1.0 if settings.TEST else _SHADOW_SAMPLE_RATE+ return 1.0 if _is_test_mode() else _SHADOW_SAMPLE_RATEdef _resolve_parser_mode(@@ -235,7 +251,7 @@ def _resolve_parser_mode(if backend is not None:return backend, Noneif _RUST_PARSER_AVAILABLE:- if settings.TEST:+ if _is_test_mode():return _PARSER_MODE_BACKENDS[ParserMode.RUST_PY_ONLY]return _PARSER_MODE_BACKENDS[ParserMode.RUST_PY_WITH_CPP_SHADOW]return DEFAULT_BACKEND, None@@ -282,7 +298,7 @@ def _run_shadow_comparison("""if random.random() >= _shadow_sample_rate():return- test_mode = settings.TEST+ test_mode = _is_test_mode()rule_label = str(rule)primary_version = _BACKEND_VERSION.get(primary_backend, "unknown")shadow_version = _BACKEND_VERSION.get(shadow_backend, "unknown")diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.pyindex 522855fa48cf..b338fceae7e5 100644--- a/posthog/hogql/printer/base.py+++ b/posthog/hogql/printer/base.py@@ -35,8 +35,8 @@ from posthog.hogql.visitor import Visitor, clone_exprfrom posthog.clickhouse.kafka_engine import json_extract_trim_quotesfrom posthog.models.team.team import WeekStartDay-from posthog.models.utils import UUIDTfrom posthog.schema_enums import PersonsOnEventsMode+from posthog.uuidt import UUIDTMAX_PLACEHOLDER_MACRO_EXPANSION_DEPTH = 8diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.pyindex 61d63873a33c..e1a83c88e4a2 100644--- a/posthog/hogql/printer/clickhouse.py+++ b/posthog/hogql/printer/clickhouse.py@@ -25,7 +25,7 @@ from posthog.hogql.visitor import GetFieldsTraverser, clone_exprfrom posthog.models.exchange_rate.sql import EXCHANGE_RATE_DECIMAL_PRECISION, EXCHANGE_RATE_DICTIONARY_NAMEfrom posthog.models.team.team import WeekStartDay-from posthog.models.utils import UUIDT+from posthog.uuidt import UUIDTdef _table_filter_type(table_type: ast.TableOrSelectType) -> ast.TableOrSelectType:diff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.pyindex 43daf904e2d4..9eb42abcea37 100644--- a/posthog/hogql/printer/postgres.py+++ b/posthog/hogql/printer/postgres.py@@ -20,7 +20,7 @@ from posthog.hogql.printer.postgres_functions import (POSTGRES_PASSTHROUGH_FUNCTIONS,)-from posthog.models.utils import UUIDT+from posthog.uuidt import UUIDT# Regex for validating function names — only alphanumeric and underscores allowed.# Prevents SQL injection via backtick-quoted identifiers in HogQL.diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex a2237bd3e69d..8dd23af523f4 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -62,7 +62,7 @@ from posthog.hogql.type_system import (from posthog.hogql.utils import map_virtual_propertiesfrom posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr-from posthog.models.utils import UUIDT+from posthog.uuidt import UUIDT# https://github.com/ClickHouse/ClickHouse/issues/23194 - "Describe how identifiers in SELECT queries are resolved"diff --git a/posthog/hogql/scripts/_diagnostic_common.py b/posthog/hogql/scripts/_diagnostic_common.pyindex 32f175257e8e..289909e5078b 100644--- a/posthog/hogql/scripts/_diagnostic_common.py+++ b/posthog/hogql/scripts/_diagnostic_common.py@@ -20,8 +20,8 @@ Holds the cross-script vocabulary:- **Backend probe** — `_probe_backend` fails fast on an unusable`--oracle` / `--candidate`.-Importing this module pulls `posthog.hogql.*` — callers must have run-`django.setup()` first (every script here does, before its imports).+Importing this module pulls in the HogQL parser and AST layer only, which+run without Django — no `django.setup()` required."""from __future__ import annotationsdiff --git a/posthog/hogql/scripts/hog_corpus_diagnostic.py b/posthog/hogql/scripts/hog_corpus_diagnostic.pyindex f360f43881a0..07efd0eb7a5f 100644--- a/posthog/hogql/scripts/hog_corpus_diagnostic.py+++ b/posthog/hogql/scripts/hog_corpus_diagnostic.py@@ -57,10 +57,8 @@ import tracebackimport subprocessfrom pathlib import Path-import django-+# Skip django.setup(): parser core only reads settings.TEST, so settings alone avoids ready()-hook DB/redis init.os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")-django.setup()from posthog.hogql.scripts._diagnostic_common import (_probe_backend,diff --git a/posthog/hogql/scripts/parser_bench.py b/posthog/hogql/scripts/parser_bench.pyindex 49760325e1ed..3c3c8186a9f7 100644--- a/posthog/hogql/scripts/parser_bench.py+++ b/posthog/hogql/scripts/parser_bench.py@@ -1,6 +1,5 @@-# ruff: noqa: T201, E402, I001-# CLI benchmark tool: print() is the report channel, and the imports-# are deferred until after `django.setup()` so the order is intentional.+# ruff: noqa: T201, I001+# CLI benchmark tool: print() is the report channel."""Side-by-side parser performance benchmark — backend-agnostic.`--oracle` defaults to `cpp-json`. `--candidate` is REQUIRED (no@@ -60,11 +59,6 @@ import timeitfrom pathlib import Pathfrom typing import Any-import django--os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")-django.setup()-from posthog.hogql.parser import HogQLParserShadowMismatch, clear_parse_caches, parse_expr, parse_selectfrom posthog.hogql.scripts._diagnostic_common import _abort_on_shadow_mismatch, _probe_backenddiff --git a/posthog/hogql/scripts/pbt_corpus.py b/posthog/hogql/scripts/pbt_corpus.pyindex 28454a210148..28757afd66a7 100644--- a/posthog/hogql/scripts/pbt_corpus.py+++ b/posthog/hogql/scripts/pbt_corpus.py@@ -36,21 +36,14 @@ Typical workflow:"""# ruff: noqa: T201 (CLI script — print is the report channel)-# ruff: noqa: E402 (django.setup() ordering)from __future__ import annotations-import osimport sysimport jsonimport argparsefrom collections import Counter-import django--os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")-django.setup()-from posthog.hogql.scripts._diagnostic_common import (DivergenceShape,_ast_mismatch_shape,diff --git a/posthog/hogql/scripts/shrink_query.py b/posthog/hogql/scripts/shrink_query.pyindex ed6ff588585b..3ddf1a827759 100644--- a/posthog/hogql/scripts/shrink_query.py+++ b/posthog/hogql/scripts/shrink_query.py@@ -33,15 +33,10 @@ import osimport sysimport argparse-import django--# Keep stdout pristine (only the shrunk query, for `$(...)` capture): django setup/settings print chatter there, so point stdout at stderr before django.setup() — early enough that logging config binds to stderr too — and write the result to the saved real stdout.+# Keep stdout pristine (only the shrunk query, for `$(...)` capture): settings/import chatter can print there, so point stdout at stderr before importing the parser — early enough that logging config binds to stderr too — and write the result to the saved real stdout._REAL_STDOUT = sys.stdoutsys.stdout = sys.stderr-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")-django.setup()-from posthog.hogql.scripts._diagnostic_common import _probe_backend, _safe_parse, _shape_for, shrink_to_shapediff --git a/posthog/hogql/test/test_escape_sql.py b/posthog/hogql/test/test_escape_sql.pyindex 7eb63697113e..ef8c40d400cf 100644--- a/posthog/hogql/test/test_escape_sql.py+++ b/posthog/hogql/test/test_escape_sql.py@@ -16,7 +16,7 @@ from posthog.hogql.escape_sql import (from posthog.hogql.parser import parse_exprfrom posthog.clickhouse.client.execute import sync_execute-from posthog.models.utils import UUIDT+from posthog.uuidt import UUIDT_ROUNDTRIP_IDENTIFIER_SAMPLES = ["back`tick",diff --git a/posthog/hogql/test/test_no_django_imports.py b/posthog/hogql/test/test_no_django_imports.pynew file mode 100644index 000000000000..f8fd353cf151--- /dev/null+++ b/posthog/hogql/test/test_no_django_imports.py@@ -0,0 +1,52 @@+import os+import sys+import subprocess++# The HogQL parser and AST layer must import and run without django.setup() — no Django ORM+# or app-model coupling. That is what lets these modules (and the corpus/fuzzing scripts built+# on them) run standalone in workers, CLIs, and tooling without paying the Django startup tax.+# If someone adds a `from posthog.models import ...` (or any ORM import) into one of these,+# importing it in a fresh interpreter raises AppRegistryNotReady and this test fails.+DJANGO_FREE_MODULES = [+ "posthog.uuidt",+ "posthog.hogql.ast",+ "posthog.hogql.base",+ "posthog.hogql.visitor",+ "posthog.hogql.errors",+ "posthog.hogql.timings",+ "posthog.hogql.placeholders",+ "posthog.hogql.escape_sql",+ "posthog.hogql.functions.mapping",+ "posthog.hogql.database.models",+ "posthog.hogql.parser",+]++_CHILD = f"""+import importlib+for mod in {DJANGO_FREE_MODULES!r}:+ importlib.import_module(mod)+from posthog.hogql import ast+from posthog.hogql.parser import parse_expr, parse_select+assert isinstance(parse_select("select 1"), ast.SelectQuery)+assert isinstance(parse_expr("1 + 1"), ast.Expr)+print("DJANGO_FREE_OK")+"""+++def test_hogql_parser_and_ast_import_without_django() -> None:+ # Fresh interpreter, no django.setup(), and DJANGO_SETTINGS_MODULE stripped so we also+ # exercise the parser's settings-free fallback. Any Django-app/ORM import surfaces as+ # AppRegistryNotReady in the child.+ env = {k: v for k, v in os.environ.items() if k != "DJANGO_SETTINGS_MODULE"}+ proc = subprocess.run(+ [sys.executable, "-c", _CHILD],+ env=env,+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert proc.returncode == 0 and "DJANGO_FREE_OK" in proc.stdout, (+ "HogQL parser/AST layer no longer imports without django.setup().\n"+ f"stdout:\n{proc.stdout}\nstderr:\n{proc.stderr}"+ )+ assert "AppRegistryNotReady" not in proc.stderr, proc.stderrdiff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.pyindex 778f6d33d7b9..1adcd96d5e79 100644--- a/posthog/hogql/test/test_query.py+++ b/posthog/hogql/test/test_query.py@@ -37,9 +37,9 @@ from posthog.hogql.test.utils import (from posthog.errors import CHQueryErrorS3Error, InternalCHQueryErrorfrom posthog.models.exchange_rate.currencies import SUPPORTED_CURRENCY_CODES-from posthog.models.utils import UUIDT, uuid7from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME+from posthog.uuidt import UUIDT, uuid7from products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.util import recalculate_cohortpeoplediff --git a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py b/posthog/hogql/transforms/test/test_events_predicate_pushdown.pyindex ec88e0ce2208..ea85bf01feaa 100644--- a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py+++ b/posthog/hogql/transforms/test/test_events_predicate_pushdown.py@@ -48,7 +48,7 @@ from posthog.hogql.visitor import TraversingVisitorfrom posthog.clickhouse.client import sync_executefrom posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition-from posthog.models.utils import uuid7+from posthog.uuidt import uuid7from products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.util import recalculate_cohortpeoplediff --git a/posthog/hogql/transforms/test/test_in_cohort.py b/posthog/hogql/transforms/test/test_in_cohort.pyindex 0613c13dba5d..f2c00dde67fa 100644--- a/posthog/hogql/transforms/test/test_in_cohort.py+++ b/posthog/hogql/transforms/test/test_in_cohort.py@@ -12,7 +12,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.test.utils import pretty_print_response_in_testsfrom posthog.clickhouse.client.execute import sync_execute-from posthog.models.utils import UUIDT+from posthog.uuidt import UUIDTfrom products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.util import recalculate_cohortpeoplediff --git a/posthog/models/utils.py b/posthog/models/utils.pyindex 18c23be8f78c..d4f92d9225e9 100644--- a/posthog/models/utils.py+++ b/posthog/models/utils.py@@ -1,15 +1,13 @@import reimport json-import uuidimport stringimport hashlibimport secretsimport datetime-from collections import defaultdict, namedtuple+from collections import namedtuplefrom collections.abc import Callable, Iterable, Iteratorfrom contextlib import contextmanagerfrom decimal import Decimal-from time import time, time_nsfrom typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, Unionfrom uuid import UUID@@ -23,10 +21,9 @@ from django.db.models.constraints import BaseConstraintfrom django.utils.text import slugifyfrom posthog.constants import MAX_SLUG_LENGTH+from posthog.uuidt import UUIDT, uuid7if TYPE_CHECKING:- from random import Random-from posthog.hogql import astT = TypeVar("T")@@ -38,124 +35,6 @@ EncryptionModeType = Literal["sha256", "pbkdf2"]SHA256_HASH_PREFIX = "sha256$"-class UUIDT(uuid.UUID):- """- Deprecated, you probably want to use UUIDv7 instead. As of May 2024 the latest RFC with the UUIv7 spec is at- Proposed Standard (see RFC9562 https://www.rfc-editor.org/rfc/rfc9562#name-uuid-version-7). This class was written- well before that, is still in use in PostHog, but should not be used for new columns / models / features / etc.-- UUID (mostly) sortable by generation time.-- This doesn't adhere to any official UUID version spec, but it is superior as a primary key:- to incremented integers (as they can reveal sensitive business information about usage volumes and patterns),- to UUID v4 (as the complete randomness of v4 makes its indexing performance suboptimal),- and to UUID v1 (as despite being time-based it can't be used practically for sorting by generation time).-- Order can be messed up if system clock is changed or if more than 65 536 IDs are generated per millisecond- (that's over 5 trillion events per day), but it should be largely safe to assume that these are time-sortable.-- Anatomy:- - 6 bytes - Unix time milliseconds unsigned integer- - 2 bytes - autoincremented series unsigned integer (per millisecond, rolls over to 0 after reaching 65 535 UUIDs in one ms)- - 8 bytes - securely random gibberish-- Loosely based on Segment's KSUID (https://github.com/segmentio/ksuid) and on Twitter's snowflake ID- (https://blog.twitter.com/engineering/en_us/a/2010/announcing-snowflake.html).- """-- current_series_per_ms: dict[int, int] = defaultdict(int)-- def __init__(- self,- unix_time_ms: Optional[int] = None,- uuid_str: Optional[str] = None,- *,- seeded_random: Optional["Random"] = None,- ) -> None:- if uuid_str and self.is_valid_uuid(uuid_str):- super().__init__(uuid_str)- return-- if unix_time_ms is None:- unix_time_ms = int(time() * 1000)- time_component = unix_time_ms.to_bytes(6, "big", signed=False) # 48 bits for time, WILL FAIL in 10 895 CE- series_component = self.get_series(unix_time_ms).to_bytes(2, "big", signed=False) # 16 bits for series- if seeded_random is not None:- random_component = bytes(seeded_random.getrandbits(8) for _ in range(8)) # 64 bits for random gibberish- else:- random_component = secrets.token_bytes(8) # 64 bits for random gibberish- input_bytes = time_component + series_component + random_component- assert len(input_bytes) == 16- super().__init__(bytes=input_bytes)-- @classmethod- def get_series(cls, unix_time_ms: int) -> int:- """Get per-millisecond series integer in range [0-65536)."""- series = cls.current_series_per_ms[unix_time_ms]- if len(cls.current_series_per_ms) > 10_000: # Clear class dict periodically- cls.current_series_per_ms.clear()- cls.current_series_per_ms[unix_time_ms] = series- cls.current_series_per_ms[unix_time_ms] += 1- cls.current_series_per_ms[unix_time_ms] %= 65_536- return series-- @classmethod- def is_valid_uuid(cls, candidate: Any) -> bool:- if not isinstance(candidate, str):- return False- hex_str = candidate.replace("urn:", "").replace("uuid:", "")- hex_str = hex_str.strip("{}").replace("-", "")- if len(hex_str) != 32:- return False- try:- return 0 <= int(hex_str, 16) < (1 << 128)- except ValueError:- return False---# Delete this when we can use the version from the stdlib directly, see https://github.com/python/cpython/issues/102461-def uuid7(unix_ms_time: Optional[Union[int, str]] = None, random: Optional[Union["Random", int]] = None) -> uuid.UUID:- # timestamp part- unix_ms_time_int: int- if isinstance(unix_ms_time, str):- # parse the ISO format string, use the timestamp from that- date = datetime.datetime.fromisoformat(unix_ms_time)- unix_ms_time_int = int(date.timestamp() * 1000)- elif unix_ms_time is None:- # use the current system time- unix_ms_time_int = time_ns() // (10**6)- else:- # use the provided timestamp directly- unix_ms_time_int = unix_ms_time-- # random part- if isinstance(random, int):- # use the integer directly as the random component- rand_a = random & 0x0FFF- rand_b = random >> 12 & 0x03FFFFFFFFFFFFFFF- elif random is not None:- # use the provided random generator- rand_a = random.getrandbits(12)- rand_b = random.getrandbits(56)- else:- # use the system random generator- rand_bytes = int.from_bytes(secrets.token_bytes(10), byteorder="little")- rand_a = rand_bytes & 0x0FFF- rand_b = (rand_bytes >> 12) & 0x03FFFFFFFFFFFFFFF-- # fixed constants- ver = 7- var = 0b10-- # construct the UUID int- uuid_int = (unix_ms_time_int & 0x0FFFFFFFFFFFF) << 80- uuid_int |= ver << 76- uuid_int |= rand_a << 64- uuid_int |= var << 62- uuid_int |= rand_b- return uuid.UUID(int=uuid_int)--class CreatedMetaFields(models.Model):created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)diff --git a/posthog/uuidt.py b/posthog/uuidt.pynew file mode 100644index 000000000000..baa04682d204--- /dev/null+++ b/posthog/uuidt.py@@ -0,0 +1,131 @@+import uuid+import secrets+import datetime+from collections import defaultdict+from time import time, time_ns+from typing import TYPE_CHECKING, Any, Optional, Union++# Django-free UUID helpers. Kept out of posthog.models.utils (which imports the Django ORM at+# module level) so the HogQL engine can use them without booting Django. posthog.models.utils+# re-exports these names for existing callers.++if TYPE_CHECKING:+ from random import Random+++class UUIDT(uuid.UUID):+ """+ Deprecated, you probably want to use UUIDv7 instead. As of May 2024 the latest RFC with the UUIDv7 spec is at+ Proposed Standard (see RFC9562 https://www.rfc-editor.org/rfc/rfc9562#name-uuid-version-7). This class was written+ well before that, is still in use in PostHog, but should not be used for new columns / models / features / etc.++ UUID (mostly) sortable by generation time.++ This doesn't adhere to any official UUID version spec, but it is superior as a primary key:+ to incremented integers (as they can reveal sensitive business information about usage volumes and patterns),+ to UUID v4 (as the complete randomness of v4 makes its indexing performance suboptimal),+ and to UUID v1 (as despite being time-based it can't be used practically for sorting by generation time).++ Order can be messed up if system clock is changed or if more than 65 536 IDs are generated per millisecond+ (that's over 5 trillion events per day), but it should be largely safe to assume that these are time-sortable.++ Anatomy:+ - 6 bytes - Unix time milliseconds unsigned integer+ - 2 bytes - autoincremented series unsigned integer (per millisecond, rolls over to 0 after reaching 65 535 UUIDs in one ms)+ - 8 bytes - securely random gibberish++ Loosely based on Segment's KSUID (https://github.com/segmentio/ksuid) and on Twitter's snowflake ID+ (https://blog.twitter.com/engineering/en_us/a/2010/announcing-snowflake.html).+ """++ current_series_per_ms: dict[int, int] = defaultdict(int)++ def __init__(+ self,+ unix_time_ms: Optional[int] = None,+ uuid_str: Optional[str] = None,+ *,+ seeded_random: Optional["Random"] = None,+ ) -> None:+ if uuid_str and self.is_valid_uuid(uuid_str):+ super().__init__(uuid_str)+ return++ if unix_time_ms is None:+ unix_time_ms = int(time() * 1000)+ time_component = unix_time_ms.to_bytes(6, "big", signed=False) # 48 bits for time, WILL FAIL in 10 895 CE+ series_component = self.get_series(unix_time_ms).to_bytes(2, "big", signed=False) # 16 bits for series+ if seeded_random is not None:+ random_component = bytes(seeded_random.getrandbits(8) for _ in range(8)) # 64 bits for random gibberish+ else:+ random_component = secrets.token_bytes(8) # 64 bits for random gibberish+ input_bytes = time_component + series_component + random_component+ assert len(input_bytes) == 16+ super().__init__(bytes=input_bytes)++ @classmethod+ def get_series(cls, unix_time_ms: int) -> int:+ """Get per-millisecond series integer in range [0-65536)."""+ series = cls.current_series_per_ms[unix_time_ms]+ if len(cls.current_series_per_ms) > 10_000: # Clear class dict periodically+ cls.current_series_per_ms.clear()+ cls.current_series_per_ms[unix_time_ms] = series+ cls.current_series_per_ms[unix_time_ms] += 1+ cls.current_series_per_ms[unix_time_ms] %= 65_536+ return series++ @classmethod+ def is_valid_uuid(cls, candidate: Any) -> bool:+ if not isinstance(candidate, str):+ return False+ hex_str = candidate.replace("urn:", "").replace("uuid:", "")+ hex_str = hex_str.strip("{}").replace("-", "")+ if len(hex_str) != 32:+ return False+ try:+ return 0 <= int(hex_str, 16) < (1 << 128)+ except ValueError:+ return False+++# Delete this when we can use the version from the stdlib directly, see https://github.com/python/cpython/issues/102461+def uuid7(unix_ms_time: Optional[Union[int, str]] = None, random: Optional[Union["Random", int]] = None) -> uuid.UUID:+ # timestamp part+ unix_ms_time_int: int+ if isinstance(unix_ms_time, str):+ # parse the ISO format string, use the timestamp from that+ date = datetime.datetime.fromisoformat(unix_ms_time)+ unix_ms_time_int = int(date.timestamp() * 1000)+ elif unix_ms_time is None:+ # use the current system time+ unix_ms_time_int = time_ns() // (10**6)+ else:+ # use the provided timestamp directly+ unix_ms_time_int = unix_ms_time++ # random part+ if isinstance(random, int):+ # use the integer directly as the random component+ rand_a = random & 0x0FFF+ rand_b = random >> 12 & 0x03FFFFFFFFFFFFFFF+ elif random is not None:+ # use the provided random generator+ rand_a = random.getrandbits(12)+ rand_b = random.getrandbits(56)+ else:+ # use the system random generator+ rand_bytes = int.from_bytes(secrets.token_bytes(10), byteorder="little")+ rand_a = rand_bytes & 0x0FFF+ rand_b = (rand_bytes >> 12) & 0x03FFFFFFFFFFFFFFF++ # fixed constants+ ver = 7+ var = 0b10++ # construct the UUID int+ uuid_int = (unix_ms_time_int & 0x0FFFFFFFFFFFF) << 80+ uuid_int |= ver << 76+ uuid_int |= rand_a << 64+ uuid_int |= var << 62+ uuid_int |= rand_b+ return uuid.UUID(int=uuid_int)