Skip to content

: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.

refactor(devex): share integer column bounds for facade serializers (#127200)

Julian Bezaa01fc919393
diff --git a/posthog/models/integer_field_bounds.py b/posthog/models/integer_field_bounds.py
new file mode 100644
index 000000000000..cda8ab3fe1a9
--- /dev/null
+++ b/posthog/models/integer_field_bounds.py
@@ -0,0 +1,5 @@
+from django.db import connection
+
+# Presentation serializers cannot import models, so they restate the column bounds from here.
+INTEGER_FIELD_MIN, INTEGER_FIELD_MAX = connection.ops.integer_field_range("IntegerField")
+BIG_INTEGER_FIELD_MIN, BIG_INTEGER_FIELD_MAX = connection.ops.integer_field_range("BigIntegerField")
diff --git a/products/ai_observability/backend/api/offline_experiment_serializers.py b/products/ai_observability/backend/api/offline_experiment_serializers.py
index 01667456e233..17bffc58d83d 100644
--- a/products/ai_observability/backend/api/offline_experiment_serializers.py
+++ b/products/ai_observability/backend/api/offline_experiment_serializers.py
@@ -8,6 +8,8 @@ from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from rest_framework_dataclasses.serializers import DataclassSerializer
+from posthog.models.integer_field_bounds import BIG_INTEGER_FIELD_MAX
+
from products.ai_observability.backend.models.offline_evaluations import OfflineEvaluationResult, OfflineExperiment
from products.ai_observability.backend.offline_evaluation_types import (
ExperimentSubmission,
@@ -218,14 +220,14 @@ class ExperimentSubmissionSerializer(_StrictDataclassSerializer[ExperimentSubmis
required=False,
allow_null=True,
min_value=0,
- max_value=2**63 - 1,
+ max_value=BIG_INTEGER_FIELD_MAX,
help_text="Expected number of distinct items. Completion must match this count when supplied.",
)
expected_result_count = _CountField(
required=False,
allow_null=True,
min_value=0,
- max_value=2**63 - 1,
+ max_value=BIG_INTEGER_FIELD_MAX,
help_text="Expected number of distinct item/scorer-version results, including non-success statuses.",
)
suite_key = _identifier_field("Stable identifier for comparing executions of the same evaluation suite.")
diff --git a/products/ai_observability/backend/api/score_definitions.py b/products/ai_observability/backend/api/score_definitions.py
index 4fbcd98b72fa..ae81f9a9ded8 100644
--- a/products/ai_observability/backend/api/score_definitions.py
+++ b/products/ai_observability/backend/api/score_definitions.py
@@ -22,6 +22,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import report_user_action
from posthog.models import User
+from posthog.models.integer_field_bounds import INTEGER_FIELD_MAX
from posthog.permissions import AccessControlPermission
from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
@@ -125,7 +126,7 @@ class ScoreDefinitionVersionQuerySerializer(StrictQuerySerializer):
try:
version, version_id = decode_cursor(value, 2)
number = int(version)
- if not 1 <= number <= 2147483647:
+ if not 1 <= number <= INTEGER_FIELD_MAX:
raise ValueError
return number, UUID(version_id)
except ValueError as error:
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 79904ec90e3b..f14c80716b4a 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -11,6 +11,7 @@ from rest_framework.request import Request
from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.api.shared import UserBasicSerializer
+from posthog.models.integer_field_bounds import INTEGER_FIELD_MAX, INTEGER_FIELD_MIN
from posthog.permissions import get_authenticator_scopes
from products.autoresearch.backend.facade import api
@@ -641,14 +642,14 @@ class AutoresearchPipelineSerializer(DataclassSerializer):
help_text='Resolved target definition: {"type": "event"} or {"type": "action", "action_id": N}.'
)
horizon_days = serializers.IntegerField(
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
required=False,
help_text="Prediction horizon in days. The model predicts whether the target event occurs within this window.",
)
training_lookback_days = serializers.IntegerField(
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
required=False,
help_text="How far back to look for training examples. Larger windows give more data but may include stale behavior.",
)
@@ -659,14 +660,14 @@ class AutoresearchPipelineSerializer(DataclassSerializer):
help_text="Population scored daily. Typically broader than the training population."
)
cadence_days = serializers.IntegerField(
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
required=False,
help_text="Re-score the inference population every N days.",
)
iteration_budget = serializers.IntegerField(
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
required=False,
help_text="Deprecated: scheduled training no longer reads it. Use iterations_per_run.",
)
@@ -734,8 +735,8 @@ class AutoresearchPipelineSerializer(DataclassSerializer):
help_text="Target AUC threshold. Training stops early if this score is reached.",
)
plateau_iterations = serializers.IntegerField(
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
required=False,
help_text="Stop training if no AUC improvement is seen in this many consecutive iterations.",
)
@@ -997,7 +998,7 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):
plateau_iterations = serializers.IntegerField(
required=False,
min_value=1,
- max_value=2147483647,
+ max_value=INTEGER_FIELD_MAX,
help_text="Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.",
)
output_person_property = serializers.CharField(
@@ -1338,7 +1339,9 @@ class IterationTrailSerializer(DataclassSerializer):
"""Compact, read-only view of one iteration for the cross-run history feed and the Training tab."""
iteration_number = serializers.IntegerField(
- min_value=-2147483648, max_value=2147483647, help_text="Order of this attempt within its run (0-based)."
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
+ help_text="Order of this attempt within its run (0-based).",
)
status = serializers.ChoiceField(
choices=ITERATION_STATUS_CHOICES,
@@ -1447,8 +1450,8 @@ class AutoresearchTrainingRunSerializer(DataclassSerializer):
help_text="Reasoning effort the training agent ran at. Null for older runs, runs with no task, and models with no effort setting.",
)
iteration_budget = serializers.IntegerField(
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
required=False,
help_text="Maximum iterations allowed for this run.",
)
@@ -1529,8 +1532,8 @@ class AutoresearchIterationSerializer(DataclassSerializer):
pipeline = serializers.UUIDField()
training_run = serializers.UUIDField()
iteration_number = serializers.IntegerField(
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
)
recipe_hash = serializers.CharField(max_length=64)
recipe_snapshot = IterationRecipeField(
@@ -1861,8 +1864,8 @@ class AutoresearchRunSerializer(DataclassSerializer):
help_text="Run status: pending, running, completed, or failed.",
)
rows_scored = serializers.IntegerField(
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
required=False,
allow_null=True,
help_text="Number of users scored in this inference run.",
@@ -2041,7 +2044,7 @@ class RecordIterationSerializer(serializers.Serializer):
iteration_number = serializers.IntegerField(
min_value=0,
- max_value=2147483647,
+ max_value=INTEGER_FIELD_MAX,
help_text="Zero-based index of this iteration within the run. Re-sending the same number updates that iteration (idempotent).",
)
recipe_snapshot = IterationRecipeField(
diff --git a/products/batch_exports/backend/presentation/views/batch_export/backfills.py b/products/batch_exports/backend/presentation/views/batch_export/backfills.py
index b2bc00a9db88..4c7bc85efe09 100644
--- a/products/batch_exports/backend/presentation/views/batch_export/backfills.py
+++ b/products/batch_exports/backend/presentation/views/batch_export/backfills.py
@@ -15,6 +15,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.event_usage import groups
from posthog.models import User
+from posthog.models.integer_field_bounds import BIG_INTEGER_FIELD_MAX, BIG_INTEGER_FIELD_MIN
from products.batch_exports.backend.facade import (
api as batch_exports_api,
@@ -22,7 +23,7 @@ from products.batch_exports.backend.facade import (
)
from products.batch_exports.backend.facade.enums import BatchExportBackfillStatus
from products.batch_exports.backend.presentation.views.batch_export.pagination import FacadeCursorPagination
-from products.batch_exports.backend.presentation.views.utils import BIG_INTEGER_MAX, BIG_INTEGER_MIN, parse_path_uuid
+from products.batch_exports.backend.presentation.views.utils import parse_path_uuid
logger = structlog.get_logger(__name__)
@@ -58,8 +59,8 @@ class BatchExportBackfillSerializer(serializers.Serializer):
total_records_count = serializers.IntegerField(
required=False,
allow_null=True,
- min_value=BIG_INTEGER_MIN,
- max_value=BIG_INTEGER_MAX,
+ min_value=BIG_INTEGER_FIELD_MIN,
+ max_value=BIG_INTEGER_FIELD_MAX,
help_text="The total number of records to export. Initially estimated, updated with actual count after completion.",
)
adjusted_start_at = serializers.DateTimeField(
diff --git a/products/batch_exports/backend/presentation/views/batch_export/runs.py b/products/batch_exports/backend/presentation/views/batch_export/runs.py
index 849018839500..2acf780fe8bc 100644
--- a/products/batch_exports/backend/presentation/views/batch_export/runs.py
+++ b/products/batch_exports/backend/presentation/views/batch_export/runs.py
@@ -13,6 +13,12 @@ from rest_framework.exceptions import NotFound, ValidationError
from posthog.api.log_entries import LogEntryMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
+from posthog.models.integer_field_bounds import (
+ BIG_INTEGER_FIELD_MAX,
+ BIG_INTEGER_FIELD_MIN,
+ INTEGER_FIELD_MAX,
+ INTEGER_FIELD_MIN,
+)
from posthog.utils import relative_date_parse
from products.batch_exports.backend.facade import (
@@ -21,13 +27,7 @@ from products.batch_exports.backend.facade import (
)
from products.batch_exports.backend.facade.enums import BatchExportRunStatus
from products.batch_exports.backend.presentation.views.batch_export.pagination import FacadeCursorPagination
-from products.batch_exports.backend.presentation.views.utils import (
- BIG_INTEGER_MAX,
- BIG_INTEGER_MIN,
- INTEGER_MAX,
- INTEGER_MIN,
- parse_path_uuid,
-)
+from products.batch_exports.backend.presentation.views.utils import parse_path_uuid
# The viewset declares no queryset, so drf-spectacular cannot read the type of the ids from a model.
RUN_ID_PARAMETER = OpenApiParameter(
@@ -52,15 +52,15 @@ class BatchExportRunSerializer(serializers.Serializer):
records_completed = serializers.IntegerField(
required=False,
allow_null=True,
- min_value=INTEGER_MIN,
- max_value=INTEGER_MAX,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
help_text="The number of records that have been exported.",
)
records_failed = serializers.IntegerField(
required=False,
allow_null=True,
- min_value=INTEGER_MIN,
- max_value=INTEGER_MAX,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
help_text="The number of records that failed downstream processing (e.g. hog function execution errors).",
)
latest_error = serializers.CharField(
@@ -86,15 +86,15 @@ class BatchExportRunSerializer(serializers.Serializer):
records_total_count = serializers.IntegerField(
required=False,
allow_null=True,
- min_value=INTEGER_MIN,
- max_value=INTEGER_MAX,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
help_text="The total count of records that should be exported in this BatchExportRun.",
)
bytes_exported = serializers.IntegerField(
required=False,
allow_null=True,
- min_value=BIG_INTEGER_MIN,
- max_value=BIG_INTEGER_MAX,
+ min_value=BIG_INTEGER_FIELD_MIN,
+ max_value=BIG_INTEGER_FIELD_MAX,
help_text="The number of bytes that have been exported in this BatchExportRun.",
)
batch_export = serializers.UUIDField(
diff --git a/products/batch_exports/backend/presentation/views/utils.py b/products/batch_exports/backend/presentation/views/utils.py
index ddbc247133c8..3b880d603f5d 100644
--- a/products/batch_exports/backend/presentation/views/utils.py
+++ b/products/batch_exports/backend/presentation/views/utils.py
@@ -16,12 +16,6 @@ from posthog.models import Team
from products.batch_exports.backend.facade.api import drop_unknown_hogql_modifiers
-# The bounds of the integer columns, which a model serializer reads off the model.
-# TODO: Nothing here is specific to batch exports, and other products hard-code the same numbers.
-# Move these to core, for example derived from django.db.connection.ops.integer_field_range.
-INTEGER_MIN, INTEGER_MAX = -(2**31), 2**31 - 1
-BIG_INTEGER_MIN, BIG_INTEGER_MAX = -(2**63), 2**63 - 1
-
HOGQL_MODIFIERS_HELP_TEXT = (
"HogQL modifiers to use when the query runs, as an object keyed by modifier name, for example "
"{\"convertToProjectTimezone\": true}. Only supported when 'model' is 'hogql'. Each modifier set here "
diff --git a/products/customer_analytics/backend/presentation/views/customer_tasks.py b/products/customer_analytics/backend/presentation/views/customer_tasks.py
index 18a41e0c73dd..87dad1b49710 100644
--- a/products/customer_analytics/backend/presentation/views/customer_tasks.py
+++ b/products/customer_analytics/backend/presentation/views/customer_tasks.py
@@ -18,6 +18,7 @@ from rest_framework.views import APIView
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models import Team, User
+from posthog.models.integer_field_bounds import INTEGER_FIELD_MAX
from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
from products.access_control.backend.facade.user_access_control import UserAccessControl
@@ -27,9 +28,6 @@ from products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYT
_ASSIGNED_TO_ERROR = "assigned_to must be me, unassigned, a project member ID, or role:<role UUID>."
# pinned: the frontend writes the same prefix into links and API calls
_ROLE_ASSIGNEE_PREFIX = "role:"
-# posthog_user.id is an int4 column, and DRF never runs full_clean, so an ID past this bound would
-# fail in Postgres with a 500 rather than being rejected here.
-_MAX_MEMBER_ID = 2147483647
_ORDERING_CHOICES = [
"name",
@@ -274,7 +272,8 @@ class CustomerTaskListQuerySerializer(serializers.Serializer):
member_id = int(value)
except ValueError:
raise serializers.ValidationError(_ASSIGNED_TO_ERROR) from None
- if not 1 <= member_id <= _MAX_MEMBER_ID:
+ # posthog_user.id is an int4 column and DRF never runs full_clean, so a larger ID would fail in Postgres with a 500.
+ if not 1 <= member_id <= INTEGER_FIELD_MAX:
raise serializers.ValidationError(_ASSIGNED_TO_ERROR)
return str(member_id)
diff --git a/products/customer_analytics/backend/presentation/views/workflow_customer_tasks.py b/products/customer_analytics/backend/presentation/views/workflow_customer_tasks.py
index e1ac7e17ce2a..e786ac297613 100644
--- a/products/customer_analytics/backend/presentation/views/workflow_customer_tasks.py
+++ b/products/customer_analytics/backend/presentation/views/workflow_customer_tasks.py
@@ -10,6 +10,7 @@ from rest_framework.response import Response
from posthog.auth import InternalAPIUser, ScopedServiceJWTAuthentication
from posthog.jwt import PosthogJwtAudience
+from posthog.models.integer_field_bounds import INTEGER_FIELD_MAX
from posthog.scoped_service_jwt import ScopedServiceJwtPurpose
from products.customer_analytics.backend.facade import contracts
@@ -39,7 +40,7 @@ class WorkflowCustomerTaskCreateSerializer(serializers.Serializer):
required=False,
allow_null=True,
min_value=1,
- max_value=2147483647,
+ max_value=INTEGER_FIELD_MAX,
help_text="PostHog user ID of the assigned project member.",
)
due_at = serializers.DateTimeField(required=False, allow_null=True, help_text="ISO 8601 task deadline.")
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index c7df64259a3f..5c50b68da0f5 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -46,6 +46,7 @@ from posthog.api.tagged_item import TaggedItemSerializerMixin, set_tags_on_objec
from posthog.event_usage import EventSource, get_event_source, get_request_analytics_properties, report_user_action
from posthog.exceptions import QuotaLimitExceeded
from posthog.exceptions_capture import capture_exception
+from posthog.models.integer_field_bounds import BIG_INTEGER_FIELD_MAX, INTEGER_FIELD_MAX
from posthog.models.product_intent.product_intent import ProductIntent
from posthog.models.tag import tagify
from posthog.models.tagged_item import TaggedItem
@@ -559,7 +560,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
allow_null=True,
min_value=1,
# int4 bound: DRF never runs full_clean, so an over-int4 value would 500 in Postgres, not 400.
- max_value=2147483647,
+ max_value=INTEGER_FIELD_MAX,
help_text=(
"Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level "
"cap. When reached, this scanner stops scanning until the period resets. It stays enabled and "
@@ -1410,7 +1411,7 @@ class ReplayScannerFilter(django_filters.FilterSet):
# Cap at the Postgres bigint max the id column can hold: a larger value can't be a real PK,
# and feeding it to the id lookup below raises NumericValueOutOfRange (a 500) instead of a 400.
stripped = value.strip()
- if not stripped.isdecimal() or not 1 <= int(stripped) <= 9223372036854775807:
+ if not stripped.isdecimal() or not 1 <= int(stripped) <= BIG_INTEGER_FIELD_MAX:
raise ValidationError({"experiment_id": "Must be a positive integer."})
experiment_id = int(stripped)
# Gate on the caller's experiment access, mirroring validate_experiment_targeting and
@@ -2053,7 +2054,7 @@ class DraftScannerRequestSerializer(serializers.Serializer):
experiment_id = serializers.IntegerField(
required=False,
min_value=1,
- max_value=9223372036854775807,
+ max_value=BIG_INTEGER_FIELD_MAX,
help_text=(
"A launched experiment the person picked for the scanner to watch. "
"The draft is then an `experiment` scanner on it."
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index ec76f0a9b773..5dbbafe640e3 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -22,6 +22,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.integrations import IntegrationKind, IntegrationRecord
from posthog.integrations.fields import IntegrationReferenceField
from posthog.models import Team, User
+from posthog.models.integer_field_bounds import INTEGER_FIELD_MAX
from posthog.models.integration import SUPPORTED_EXTERNAL_ISSUE_PROVIDERS
from products.signals.backend import contracts
@@ -471,7 +472,7 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
allow_null=True,
min_value=1,
# Ceiling at the int4 column max so an out-of-range value returns 400, not a DB write error.
- max_value=2147483647,
+ max_value=INTEGER_FIELD_MAX,
help_text=(
"Daily cap on new reports surfacing to the inbox, counted per calendar day in the "
"project's timezone. Once reached, signal ingestion, scout runs, and report research "
diff --git a/products/subscriptions/backend/presentation/views.py b/products/subscriptions/backend/presentation/views.py
index dfd2f22f2406..67778321cebc 100644
--- a/products/subscriptions/backend/presentation/views.py
+++ b/products/subscriptions/backend/presentation/views.py
@@ -33,6 +33,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import get_request_analytics_properties, groups
from posthog.exceptions import QuotaLimitExceeded
+from posthog.models.integer_field_bounds import INTEGER_FIELD_MAX, INTEGER_FIELD_MIN
from posthog.models.user import User
from posthog.permissions import is_service_auth
from posthog.rate_limit import SubscriptionTestDeliveryThrottle
@@ -424,7 +425,7 @@ class SubscriptionWriteSerializer(serializers.Serializer):
interval = serializers.IntegerField(
required=True,
min_value=1,
- max_value=2147483647,
+ max_value=INTEGER_FIELD_MAX,
help_text=(
"Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). "
"Required on create; must be 1 or greater."
@@ -439,15 +440,15 @@ class SubscriptionWriteSerializer(serializers.Serializer):
bysetpos = serializers.IntegerField(
allow_null=True,
required=False,
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
help_text="Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).",
)
count = serializers.IntegerField(
allow_null=True,
required=False,
- min_value=-2147483648,
- max_value=2147483647,
+ min_value=INTEGER_FIELD_MIN,
+ max_value=INTEGER_FIELD_MAX,
help_text="Total number of deliveries before the subscription stops. Null for unlimited.",
)
start_date = serializers.DateTimeField(
@@ -1257,7 +1258,7 @@ class SubscriptionDeliverySerializer(serializers.Serializer):
),
)
exported_asset_ids = serializers.ListField(
- child=serializers.IntegerField(min_value=-2147483648, max_value=2147483647),
+ child=serializers.IntegerField(min_value=INTEGER_FIELD_MIN, max_value=INTEGER_FIELD_MAX),
allow_empty=False,
read_only=True,
help_text="ExportedAsset ids generated for this send.",