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.

chore(devex): move django-stubs to 6.1 ahead of the django bump (#123952)

Julian Bez71d9e04d0192
diff --git a/ee/api/vercel/test/test_error_mixin_bug.py b/ee/api/vercel/test/test_error_mixin_bug.py
index 30b5db95449c..a894327945d6 100644
--- a/ee/api/vercel/test/test_error_mixin_bug.py
+++ b/ee/api/vercel/test/test_error_mixin_bug.py
@@ -26,7 +26,7 @@ class TestVercelErrorMixin(VercelTestBase):
viewset = _TestViewSet()
viewset.action = "test_action"
viewset.format_kwarg = None
- viewset.request = Request(django_request) # ty: ignore[invalid-assignment]
+ viewset.request = Request(django_request)
return viewset
def test_non_drf_exception_returns_vercel_error_format(self):
diff --git a/ee/billing/salesforce_enrichment/conversations_signals.py b/ee/billing/salesforce_enrichment/conversations_signals.py
index bd75b032359b..9d8073c7e914 100644
--- a/ee/billing/salesforce_enrichment/conversations_signals.py
+++ b/ee/billing/salesforce_enrichment/conversations_signals.py
@@ -3,6 +3,7 @@
import datetime as dt
from dataclasses import dataclass
from itertools import batched
+from typing import Any
from django.conf import settings
from django.contrib.postgres.aggregates import ArrayAgg
@@ -133,6 +134,11 @@ def fetch_slack_channel_user_count(team_id: int, slack_channel_id: str, slack_te
return None
+def _row_dicts(queryset: QuerySet[Any, Any]) -> list[dict[str, object]]:
+ # `.values()` rows are plain dicts at runtime, but the stubs type them as TypedDicts.
+ return list(queryset)
+
+
def _activity_at() -> Coalesce:
"""Most recent activity timestamp for a ticket, preferring the newest available signal."""
return Coalesce("last_message_at", "updated_at", "created_at", output_field=DateTimeField())
@@ -175,7 +181,7 @@ def _fetch_slack_channel_aggregate_rows(org_ids: list[str]) -> list[dict[str, ob
if not org_ids:
return []
- return list(
+ return _row_dicts(
_tickets_with_verified_org()
.filter(
channel_source=Channel.SLACK,
@@ -222,7 +228,7 @@ def _fetch_trusted_slack_channel_activity_rows(
if not channel_filters:
return []
- return list(
+ return _row_dicts(
Ticket.objects.filter(channel_filters, channel_source=Channel.SLACK, identity_verified=True)
.annotate(activity_at=_activity_at())
# Group by team as well as (workspace, channel): a team's Slack connection
@@ -254,7 +260,7 @@ def _fetch_latest_support_ticket_rows(org_ids: list[str]) -> list[dict[str, obje
if not org_ids:
return []
- return list(
+ return _row_dicts(
_tickets_with_verified_org()
.filter(organization_id__in=org_ids)
.annotate(activity_at=_activity_at())
diff --git a/ee/hogai/django_checkpoint/checkpointer.py b/ee/hogai/django_checkpoint/checkpointer.py
index ff61f78b0c98..b1aa21d48eae 100644
--- a/ee/hogai/django_checkpoint/checkpointer.py
+++ b/ee/hogai/django_checkpoint/checkpointer.py
@@ -362,7 +362,9 @@ class DjangoCheckpointer(BaseCheckpointSaver[str]):
# Thread.lock() will prevent race conditions though to the same checkpoints within a single pod.
# nosemgrep: idor-lookup-without-team (internal LangGraph checkpoint)
checkpoint, _ = ConversationCheckpoint.objects.get_or_create(
- id=checkpoint_id, thread_id=thread_id, checkpoint_ns=checkpoint_ns
+ id=checkpoint_id, # type: ignore[misc] # LangGraph passes the config from put(), which sets checkpoint_id
+ thread_id=thread_id,
+ checkpoint_ns=checkpoint_ns,
)
writes_to_create = []
diff --git a/posthog/admin/admins/user_admin.py b/posthog/admin/admins/user_admin.py
index c55b02b61266..f6f7dd0f7de7 100644
--- a/posthog/admin/admins/user_admin.py
+++ b/posthog/admin/admins/user_admin.py
@@ -16,6 +16,7 @@ from django.db.models import CASCADE, PROTECT, RESTRICT, Model
from django.db.models.deletion import get_candidate_relations_to_delete
from django.db.models.fields.related import ForeignObject
from django.db.models.fields.reverse_related import ForeignObjectRel
+from django.db.models.options import Options
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.urls import reverse
@@ -379,8 +380,8 @@ class UserAdmin(DjangoUserAdmin):
impersonated = get_impersonated_user(request)
return impersonated is not None and obj.pk == impersonated.pk
- def get_actions(self, request):
- actions = super().get_actions(request)
+ def get_actions(self, request: HttpRequest, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ actions = super().get_actions(request, *args, **kwargs)
# Bulk delete has nowhere to ask for a reason, and it would collect the cascade for every
# selected account into one page.
actions.pop("delete_selected", None)
@@ -406,7 +407,9 @@ class UserAdmin(DjangoUserAdmin):
# cascade one step further, through a relation of a relation, means joining back through
# every parent table, which is the unbounded work this page exists to avoid. The
# confirmation page says the counts stop at the account's own rows.
- relations = cast(Iterable[ForeignObjectRel], get_candidate_relations_to_delete(User._meta))
+ relations = cast(
+ Iterable[ForeignObjectRel], get_candidate_relations_to_delete(cast("Options[Model]", User._meta))
+ )
for related in relations:
field = related.field
related_model = field.model
diff --git a/posthog/api/advanced_activity_logs/filters.py b/posthog/api/advanced_activity_logs/filters.py
index e50476039670..9d322aec4370 100644
--- a/posthog/api/advanced_activity_logs/filters.py
+++ b/posthog/api/advanced_activity_logs/filters.py
@@ -15,7 +15,7 @@ _ALLOWED_DETAIL_FILTER_OPERATIONS = {"exact", "contains", "in"}
# and `name.regex` becomes `(detail ->> 'name')::text ~ <value>`, which evaluates an arbitrary
# Postgres regular expression against every row. Computed from Django's registries so the set
# stays correct when Django adds lookups.
-_DJANGO_LOOKUP_NAMES = frozenset(JSONField().get_lookups()) | frozenset(KeyTransform.get_lookups())
+_DJANGO_LOOKUP_NAMES = frozenset(JSONField().get_lookups()) | frozenset(KeyTransform.get_class_lookups())
_MAX_DETAIL_FILTERS = 100
_MAX_FIELD_PATH_LENGTH = 500
diff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.py
index 365a657b7ef6..21a943e3d2af 100644
--- a/posthog/api/my_notifications.py
+++ b/posthog/api/my_notifications.py
@@ -1,7 +1,7 @@
import operator
from datetime import datetime, timedelta
from functools import reduce
-from typing import Any, Optional
+from typing import Any, Optional, cast
from django.db.models import Q
from django.utils import timezone
@@ -251,5 +251,7 @@ class MyNotificationsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if bookmark_date is None:
raise ValidationError("must provide a bookmark date")
- NotificationViewed.objects.update_or_create(user=user, defaults={"last_viewed_activity_date": bookmark_date})
+ NotificationViewed.objects.update_or_create(
+ user=cast(User, user), defaults={"last_viewed_activity_date": bookmark_date}
+ )
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/posthog/api/search.py b/posthog/api/search.py
index cf5d471ad3cb..0df02cc43964 100644
--- a/posthog/api/search.py
+++ b/posthog/api/search.py
@@ -244,7 +244,7 @@ def search_entities(
# happens here when workflows were the one entity requested.
if entities or not workflows_requested:
if query:
- qs = qs.order_by("-rank")
+ qs = qs.order_by(F("rank").desc())
else:
qs = qs.order_by("type", F("_sort_name").asc(nulls_first=True))
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 76da48f305a1..b1af001ee410 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -1692,7 +1692,7 @@ class TestPasswordResetAPI(APIBaseTest):
self.assertEqual(mail.outbox[0].subject, "Reset your PostHog password")
self.assertEqual(mail.outbox[0].body, "") # no plain-text version support yet
- html_message = mail.outbox[0].alternatives[0][0] # type: ignore
+ html_message = cast(str, mail.outbox[0].alternatives[0][0]) # type: ignore
self.validate_basic_html(
html_message,
"https://my.posthog.net",
@@ -1764,7 +1764,7 @@ class TestPasswordResetAPI(APIBaseTest):
self.assertSetEqual({",".join(outmail.to) for outmail in mail.outbox}, {self.CONFIG_EMAIL})
- html_message = mail.outbox[0].alternatives[0][0] # type: ignore
+ html_message = cast(str, mail.outbox[0].alternatives[0][0]) # type: ignore
self.validate_basic_html(
html_message,
"https://my.posthog.net",
@@ -1912,7 +1912,7 @@ class TestPasswordResetAPI(APIBaseTest):
# check password was changed
self.user.refresh_from_db()
self.assertTrue(self.user.check_password(VALID_TEST_PASSWORD))
- self.assertFalse(self.user.check_password(self.CONFIG_PASSWORD)) # type: ignore
+ self.assertFalse(self.user.check_password(self.CONFIG_PASSWORD))
self.assertEqual(self.user.requested_password_reset_at, None)
# old password is gone
@@ -1966,7 +1966,7 @@ class TestPasswordResetAPI(APIBaseTest):
# password was not changed
self.user.refresh_from_db()
- self.assertTrue(self.user.check_password(self.CONFIG_PASSWORD)) # type: ignore
+ self.assertTrue(self.user.check_password(self.CONFIG_PASSWORD))
self.assertFalse(self.user.check_password("123"))
def test_cant_reset_password_with_no_token(self):
@@ -1988,7 +1988,7 @@ class TestPasswordResetAPI(APIBaseTest):
# password was not changed
self.user.refresh_from_db()
- self.assertTrue(self.user.check_password(self.CONFIG_PASSWORD)) # type: ignore
+ self.assertTrue(self.user.check_password(self.CONFIG_PASSWORD))
self.assertFalse(self.user.check_password("a12345678"))
def test_cant_reset_password_with_invalid_token(self):
@@ -2025,7 +2025,7 @@ class TestPasswordResetAPI(APIBaseTest):
# password was not changed
self.user.refresh_from_db()
- self.assertTrue(self.user.check_password(self.CONFIG_PASSWORD)) # type: ignore
+ self.assertTrue(self.user.check_password(self.CONFIG_PASSWORD))
self.assertFalse(self.user.check_password("a12345678"))
def test_cant_reset_password_with_invalid_user_id(self):
@@ -2049,7 +2049,7 @@ class TestPasswordResetAPI(APIBaseTest):
# password was not changed
self.user.refresh_from_db()
- self.assertTrue(self.user.check_password(self.CONFIG_PASSWORD)) # type: ignore
+ self.assertTrue(self.user.check_password(self.CONFIG_PASSWORD))
self.assertFalse(self.user.check_password("a12345678"))
def test_cant_reset_password_with_non_uuid_user_id(self):
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 45364a954759..9cadf4d34701 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -3368,7 +3368,7 @@ class TestEmailVerificationAPI(APIBaseTest):
self.assertEqual(mail.outbox[0].subject, "Verify your email address")
self.assertEqual(mail.outbox[0].body, "") # no plain-text version support yet
- html_message = mail.outbox[0].alternatives[0][0] # type: ignore
+ html_message = cast(str, mail.outbox[0].alternatives[0][0]) # type: ignore
code = re.search(r"(\d{6}) is your code\.", html_message).group(1) # type: ignore[union-attr]
self.validate_basic_html(html_message, "https://my.posthog.net", preheader=f"{code} is your code.")
diff --git a/posthog/management/commands/test/test_audit_encrypted_field_keys.py b/posthog/management/commands/test/test_audit_encrypted_field_keys.py
index 017b4b5d8dba..603ada9b3c95 100644
--- a/posthog/management/commands/test/test_audit_encrypted_field_keys.py
+++ b/posthog/management/commands/test/test_audit_encrypted_field_keys.py
@@ -260,7 +260,7 @@ class TestAuditCommandEndToEnd(BaseTest):
# cast to Any: sensitive_config is wrapped in field_access_control, so the django-stubs
# plugin doesn't see it as a model field and rejects the get_field string literal.
column = quote(cast(Any, Integration)._meta.get_field("sensitive_config").column)
- pk_column = quote(Integration._meta.pk.column)
+ pk_column = quote(cast(str, Integration._meta.pk.column))
with connection.cursor() as cursor:
cursor.execute(
f"UPDATE {table} SET {column} = %s::jsonb WHERE {pk_column} = %s",
diff --git a/posthog/management/commands/update_hog_function_code.py b/posthog/management/commands/update_hog_function_code.py
index df5ca9e7adbc..e356a63ce3ea 100644
--- a/posthog/management/commands/update_hog_function_code.py
+++ b/posthog/management/commands/update_hog_function_code.py
@@ -1,5 +1,5 @@
import time
-from typing import NotRequired, TypedDict
+from typing import NotRequired, TypedDict, cast
from django.core.management.base import BaseCommand
from django.core.paginator import Paginator
@@ -200,7 +200,8 @@ class Command(BaseCommand):
# A single destination with uncompilable (e.g. hand-edited) hog must not abort the whole run.
try:
- new_bytecode = compile_hog(new_hog, destination.type)
+ # The queryset filters on type="destination", so the type is set.
+ new_bytecode = compile_hog(new_hog, cast(str, destination.type))
except Exception as e:
failed.append((str(destination.id), destination.team_id, destination.enabled, str(e)))
continue
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 6939f7074915..1cf65a3a9cff 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -1216,7 +1216,8 @@ def safely_get_field_value(instance: models.Model | None, field: str):
if hasattr(field_id, "pk"):
field_id = field_id.pk
# Only fetch the actual object if we have a valid ID
- related_model = field_obj.related_model
+ # Widen the stub type to keep the guard against an unresolved lazy "app.Model" reference.
+ related_model: type[models.Model] | str = field_obj.related_model
if isinstance(related_model, type) and issubclass(related_model, models.Model):
return related_model.objects.get(pk=field_id) # type: ignore[attr-defined]
else:
diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.py
index e4cf46639379..ca751c18ecb2 100644
--- a/posthog/models/data_deletion_request.py
+++ b/posthog/models/data_deletion_request.py
@@ -1,8 +1,8 @@
import re
-from collections.abc import Callable
+from collections.abc import Callable, Collection
from dataclasses import dataclass
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any, Self
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
@@ -666,8 +666,8 @@ class DataDeletionRequest(UUIDModel):
return f"DataDeletionRequest({self.request_type}, team={self.team_id}, status={self.status})"
@classmethod
- def from_db(cls, db, field_names, values):
- instance = super().from_db(db, field_names, values)
+ def from_db(cls, db: str | None, field_names: Collection[str], values: Collection[Any], **kwargs: Any) -> Self:
+ instance = super().from_db(db, field_names, values, **kwargs)
instance._loaded_team_id = instance.team_id
return instance
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 378f010b7b0a..7149cd525017 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -440,7 +440,9 @@ class GitHubIntegrationBase:
.annotate(count=Count("id"))
)
for row in grouped:
- counts[row["integration_id"]] = counts.get(row["integration_id"], 0) + row["count"]
+ # The integration_id__in filter excludes rows without an installation id.
+ installation_id = cast(str, row["integration_id"])
+ counts[installation_id] = counts.get(installation_id, 0) + row["count"]
return counts
@classmethod
diff --git a/posthog/models/identity_provider_config.py b/posthog/models/identity_provider_config.py
index 177ca37d5aae..783e85bbf54c 100644
--- a/posthog/models/identity_provider_config.py
+++ b/posthog/models/identity_provider_config.py
@@ -124,9 +124,11 @@ class IdentityProviderConfigManager(models.Manager["IdentityProviderConfig"]):
matching: list[tuple[IdentityProviderConfig, OrganizationDomain]] = []
if "@" in email:
domain = email.rsplit("@", 1)[-1]
- for config in issuer_configs:
- verified_domains = config.organization_domains.filter(domain__iexact=domain, verified_at__isnull=False)
- matching.extend((config, organization_domain) for organization_domain in verified_domains)
+ for issuer_config in issuer_configs:
+ verified_domains = issuer_config.organization_domains.filter(
+ domain__iexact=domain, verified_at__isnull=False
+ )
+ matching.extend((issuer_config, organization_domain) for organization_domain in verified_domains)
if not matching:
return IDJagIdentityProviderResolution(
diff --git a/posthog/models/integration/model.py b/posthog/models/integration/model.py
index a6152ce35653..2e5e0b2cb7ec 100644
--- a/posthog/models/integration/model.py
+++ b/posthog/models/integration/model.py
@@ -61,8 +61,7 @@ def _decrypted_sensitive_value(integration: "Integration", field_name: str) -> s
if not isinstance(value, str) or not value.startswith(FERNET_TOKEN_PREFIX):
return value
- # django-stubs can't see through `field_access_control`, so it doesn't know this field name.
- field = cast(EncryptedJSONField, integration._meta.get_field("sensitive_config")) # type: ignore[misc]
+ field = cast(EncryptedJSONField, integration._meta.get_field("sensitive_config"))
recovered = field.decrypt_all_layers(value)
if recovered is None:
diff --git a/posthog/models/integration_repository_cache.py b/posthog/models/integration_repository_cache.py
index 4fb75659f78c..e58fe49225d6 100644
--- a/posthog/models/integration_repository_cache.py
+++ b/posthog/models/integration_repository_cache.py
@@ -18,7 +18,7 @@ import asyncio
import contextlib
from collections.abc import AsyncIterator, Awaitable, Callable
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, cast
from urllib.parse import quote
from django.db import models
@@ -317,7 +317,7 @@ class GitHubRepositoryFullCache:
else:
entry, _ = IntegrationRepositoryCacheEntry.objects.update_or_create(
full_name=full_name,
- integration=self.integration,
+ integration=cast(Integration, self.integration),
defaults=defaults,
)
return entry
diff --git a/posthog/models/messaging.py b/posthog/models/messaging.py
index 9e8d4b4de375..c7cdcefc7212 100644
--- a/posthog/models/messaging.py
+++ b/posthog/models/messaging.py
@@ -1,4 +1,6 @@
import hashlib
+from collections.abc import Mapping
+from typing import Any
from django.conf import settings
from django.db import models
@@ -28,9 +30,11 @@ def get_email_hashes(email: str) -> list[str]:
return [_hash_email(email, salt) for salt in salts if salt]
-class MessagingRecordManager(models.Manager):
- def get_or_create(self, defaults=None, **kwargs):
- raw_email = kwargs.pop("raw_email", None)
+class MessagingRecordManager(models.Manager["MessagingRecord"]):
+ # Keyword-only `raw_email` keeps the django-stubs plugin from checking it as a field lookup.
+ def get_or_create(
+ self, defaults: Mapping[str, Any] | None = None, *, raw_email: str | None = None, **kwargs: Any
+ ) -> tuple["MessagingRecord", bool]:
if raw_email is None:
return super().get_or_create(defaults, **kwargs)
@@ -44,8 +48,9 @@ class MessagingRecordManager(models.Manager):
kwargs["email_hash"] = get_email_hash(raw_email)
return super().get_or_create(defaults, **kwargs)
- async def aget_or_create(self, defaults=None, **kwargs):
- raw_email = kwargs.pop("raw_email", None)
+ async def aget_or_create(
+ self, defaults: Mapping[str, Any] | None = None, *, raw_email: str | None = None, **kwargs: Any
+ ) -> tuple["MessagingRecord", bool]:
if raw_email is None:
return await super().aget_or_create(defaults, **kwargs)
@@ -56,12 +61,11 @@ class MessagingRecordManager(models.Manager):
kwargs["email_hash"] = get_email_hash(raw_email)
return await super().aget_or_create(defaults, **kwargs)
- def filter(self, *args, **kwargs):
+ def filter(self, *args: Any, raw_email: str | None = None, **kwargs: Any) -> models.QuerySet["MessagingRecord"]:
# A raw_email maps to multiple hashes across salt rotations, so we only remap it
# on filter() — never get(), which would raise MultipleObjectsReturned if both a
# pre- and post-rotation record exist. Callers needing one row use
# filter(raw_email=...).first()/.exists().
- raw_email = kwargs.pop("raw_email", None)
if raw_email is not None:
kwargs["email_hash__in"] = get_email_hashes(raw_email)
return super().filter(*args, **kwargs)
diff --git a/posthog/models/organization.py b/posthog/models/organization.py
index 92ca9095a052..2cc39d49d630 100644
--- a/posthog/models/organization.py
+++ b/posthog/models/organization.py
@@ -1,7 +1,8 @@
import sys
+from collections.abc import Collection
from datetime import datetime, timedelta
from functools import cache as functools_cache
-from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict, Union
+from typing import TYPE_CHECKING, Any, Literal, Optional, Self, TypedDict, Union
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
@@ -378,8 +379,8 @@ class Organization(ModelActivityMixin, UUIDTModel):
__repr__ = sane_repr("name")
@classmethod
- def from_db(cls, db: Any, field_names: Any, values: Any) -> "Organization":
- instance = super().from_db(db, field_names, values)
+ def from_db(cls, db: str | None, field_names: Collection[str], values: Collection[Any], **kwargs: Any) -> Self:
+ instance = super().from_db(db, field_names, values, **kwargs)
instance._loaded_name = instance.__dict__.get("name")
return instance
diff --git a/posthog/models/tagged_item.py b/posthog/models/tagged_item.py
index 692732b96cf5..757c9b251b24 100644
--- a/posthog/models/tagged_item.py
+++ b/posthog/models/tagged_item.py
@@ -1,5 +1,5 @@
from collections.abc import Iterable
-from typing import Any
+from typing import Any, cast
from django.contrib.contenttypes.fields import GenericForeignKey
from django.core.exceptions import ValidationError
@@ -43,7 +43,8 @@ class TaggedItemQuerySet(models.QuerySet):
# nosemgrep: orm-field-injection -- the name comes from the closed TAGGABLE_MODELS registry, never from input
return self.for_model(model).filter(**{object_column_for(model): OuterRef(outer_field)})
- def bulk_create(self, objs: Iterable["TaggedItem"], *args: Any, **kwargs: Any) -> list["TaggedItem"]:
+ # The django-stubs plugin rebinds this subclass to its own TypeVar, so a concrete signature cannot match.
+ def bulk_create(self, objs: Iterable["TaggedItem"], *args: Any, **kwargs: Any) -> list["TaggedItem"]: # type: ignore[override]
"""Fill the generic pointer on each row, because bulk_create never calls save()."""
objs = list(objs)
uncached_tag_ids = {obj.tag_id for obj in objs if not TaggedItem.tag.is_cached(obj)}
@@ -52,7 +53,7 @@ class TaggedItemQuerySet(models.QuerySet):
if obj.tag_id in tags:
obj.tag = tags[obj.tag_id]
obj.sync_team()
- return super().bulk_create(objs, *args, **kwargs)
+ return cast(list[TaggedItem], super().bulk_create(cast(Iterable[Any], objs), *args, **kwargs))
class TaggedItem(ModelActivityMixin, UUIDTModel):
diff --git a/posthog/models/test/integration/test_model.py b/posthog/models/test/integration/test_model.py
index 558d88ee1c49..0f82a69fb511 100644
--- a/posthog/models/test/integration/test_model.py
+++ b/posthog/models/test/integration/test_model.py
@@ -94,7 +94,7 @@ class TestIntegrationModel(BaseTest):
# stored value ends up with an extra layer and one decrypt still leaves ciphertext behind.
# The secret is intact underneath, so the connection must keep working.
integration = self.create_integration("stripe", sensitive_config={field_name: "a-real-token"})
- field = cast(EncryptedJSONField, Integration._meta.get_field("sensitive_config")) # type: ignore[misc]
+ field = cast(EncryptedJSONField, Integration._meta.get_field("sensitive_config"))
stored = json.loads(get_db_field_value("sensitive_config", integration.id))
update_db_field_value(
"sensitive_config",
diff --git a/posthog/models/user.py b/posthog/models/user.py
index dd7556fc1c3e..1da48b0615cf 100644
--- a/posthog/models/user.py
+++ b/posthog/models/user.py
@@ -1,6 +1,6 @@
-from collections.abc import Callable
+from collections.abc import Callable, Collection
from functools import cached_property
-from typing import TYPE_CHECKING, Any, NoReturn, Optional, TypedDict, cast
+from typing import TYPE_CHECKING, Any, NoReturn, Optional, Self, TypedDict, cast
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.core.management.base import CommandError
@@ -376,8 +376,8 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignore
_original_is_active: bool
@classmethod
- def from_db(cls, db, field_names, values):
- instance = super().from_db(db, field_names, values)
+ def from_db(cls, db: str | None, field_names: Collection[str], values: Collection[Any], **kwargs: Any) -> Self:
+ instance = super().from_db(db, field_names, values, **kwargs)
instance._original_is_active = instance.is_active
return instance
diff --git a/posthog/session_recordings/test/test_session_recording_throttle.py b/posthog/session_recordings/test/test_session_recording_throttle.py
index ed20d21c865b..e54bbcdf3fc9 100644
--- a/posthog/session_recordings/test/test_session_recording_throttle.py
+++ b/posthog/session_recordings/test/test_session_recording_throttle.py
@@ -440,7 +440,7 @@ class TestSessionRecordingViewSetThrottleSelection(BaseTest):
viewset.action = action
request = Request(APIRequestFactory().get("/"))
request._authenticator = authenticator # type: ignore[attr-defined] # backs read-only @property
- viewset.request = request # ty: ignore[invalid-assignment]
+ viewset.request = request
return viewset
@parameterized.expand(
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index 4844cc6bd89b..432716deea66 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -447,7 +447,7 @@ def enqueue_cohorts_to_calculate(parallel_count: int) -> None:
for cohort in (
get_cohort_calculation_candidates_queryset()
.filter(
- Q(last_error_at__lte=timezone.now() - backoff_duration) # type: ignore
+ Q(last_error_at__lte=timezone.now() - backoff_duration)
| Q(last_error_at__isnull=True) # backwards compatability cohorts before last_error_at was introduced
)
.order_by(F("last_calculation").asc(nulls_first=True))[0:parallel_count]
diff --git a/posthog/temporal/cleanup_property_definitions/activities.py b/posthog/temporal/cleanup_property_definitions/activities.py
index 8d2af4ec70f2..252b7fc1b1e6 100644
--- a/posthog/temporal/cleanup_property_definitions/activities.py
+++ b/posthog/temporal/cleanup_property_definitions/activities.py
@@ -45,9 +45,9 @@ def _definitions_matching(project_id: int, property_type: int, pattern: str) ->
_project_definitions(project_id, property_type)
.filter(name__regex=pattern)
.order_by(
- "effective_project_id",
+ F("effective_project_id"),
"type",
- "group_type_index_key",
+ F("group_type_index_key"),
F("query_usage_30_day").desc(nulls_last=True),
"name",
)
diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.py
index 59beb4f2acf8..d925c2b71c63 100644
--- a/posthog/temporal/usage_report/queries.py
+++ b/posthog/temporal/usage_report/queries.py
@@ -41,7 +41,7 @@ canonical reference.
import dataclasses
from collections.abc import Callable
from datetime import datetime
-from typing import Any, Literal
+from typing import Any, Literal, cast
from django.db.models import Count
@@ -108,7 +108,9 @@ def _group_types_total() -> list[dict[str, int]]:
def _dashboard_count() -> list[dict[str, int]]:
- return list(Dashboard.objects.values("team_id").annotate(total=Count("id")).order_by("team_id"))
+ return cast(
+ list[dict[str, int]], list(Dashboard.objects.values("team_id").annotate(total=Count("id")).order_by("team_id"))
+ )
def _dashboard_template_count() -> list[dict[str, int]]:
@@ -139,7 +141,10 @@ def _dashboard_tagged_count() -> list[dict[str, int]]:
def _ff_count() -> list[dict[str, int]]:
- return list(FeatureFlag.objects.values("team_id").annotate(total=Count("id")).order_by("team_id"))
+ return cast(
+ list[dict[str, int]],
+ list(FeatureFlag.objects.values("team_id").annotate(total=Count("id")).order_by("team_id")),
+ )
def _ff_active_count() -> list[dict[str, int]]:
@@ -149,16 +154,24 @@ def _ff_active_count() -> list[dict[str, int]]:
def _survey_count() -> list[dict[str, int]]:
- return list(Survey.objects.values("team_id").annotate(total=Count("id")).order_by("team_id"))
+ return cast(
+ list[dict[str, int]], list(Survey.objects.values("team_id").annotate(total=Count("id")).order_by("team_id"))
+ )
def _replay_vision_scanner_count() -> list[dict[str, int]]:
- return list(ReplayScanner.objects.values("team_id").annotate(total=Count("id")).order_by("team_id"))
+ return cast(
+ list[dict[str, int]],
+ list(ReplayScanner.objects.values("team_id").annotate(total=Count("id")).order_by("team_id")),
+ )
def _replay_vision_scanner_active_count() -> list[dict[str, int]]:
- return list(
- ReplayScanner.objects.filter(enabled=True).values("team_id").annotate(total=Count("id")).order_by("team_id")
+ return cast(
+ list[dict[str, int]],
+ list(
+ ReplayScanner.objects.filter(enabled=True).values("team_id").annotate(total=Count("id")).order_by("team_id")
+ ),
)
diff --git a/posthog/test/test_conftest_cache_canaries.py b/posthog/test/test_conftest_cache_canaries.py
index 63a396c819f0..2d174a488ed0 100644
--- a/posthog/test/test_conftest_cache_canaries.py
+++ b/posthog/test/test_conftest_cache_canaries.py
@@ -13,6 +13,9 @@
# the corresponding `_cache_*` function in conftest.py, and if it no longer holds,
# delete that patch — do not "fix" the test.
+from functools import cached_property
+from typing import Any, cast
+
import pytest
from django.db.models.fields.reverse_related import ForeignObjectRel
@@ -58,13 +61,13 @@ def test_rel_identity_cache_matches_unpatched_django():
orig_eq = _unpatched(ForeignObjectRel.__eq__)
for rel in rels[:5]:
# identity is an undocumented Django internal, absent from django-stubs.
- cached_identity = rel.identity # type: ignore[attr-defined] # via the cached_property installed by conftest
+ cached_identity = rel.identity # via the cached_property installed by conftest
cached_hash = hash(rel)
# Recompute from the original property fget (cached_property.func). Subclass fgets
# (ManyToOneRel etc.) internally do `super().identity`, which routes through the
# base class's cached_property and leaves the partial base tuple in the instance
# dict — so clear the instance cache before and after to keep the rel pristine.
- descriptor = type(rel).identity # type: ignore[attr-defined]
+ descriptor = cast("cached_property[tuple[Any, ...]]", type(rel).identity)
rel.__dict__.pop("identity", None)
try:
fresh_identity = descriptor.func(rel)
diff --git a/posthog/test/test_email.py b/posthog/test/test_email.py
index a465820cf1f0..8b95080a0b30 100644
--- a/posthog/test/test_email.py
+++ b/posthog/test/test_email.py
@@ -255,7 +255,7 @@ class TestEmail(BaseTest):
first = MessagingRecord.objects.filter(
email_hash__in=get_email_hashes("[email protected]"), campaign_key="batch_transient"
).first()
- self.assertIsNotNone(first)
+ assert first is not None
self.assertIsNotNone(first.sent_at) # committed before the failure → a retry skips it
second = MessagingRecord.objects.filter(
email_hash__in=get_email_hashes("[email protected]"), campaign_key="batch_transient"
@@ -1242,9 +1242,7 @@ class TestMessagingHashSalt(BaseTest):
with self.settings(MESSAGING_HASH_SALT="new_salt", MESSAGING_HASH_SALT_FALLBACKS=["old_salt"]):
self.assertTrue(
- # django-stubs' mypy plugin resolves filter() kwargs against model fields
- # and can't follow the manager's raw_email→email_hash__in remap.
- MessagingRecord.objects.filter( # type: ignore[misc]
+ MessagingRecord.objects.filter(
raw_email="[email protected]", campaign_key="c", sent_at__isnull=False
).exists()
)
diff --git a/posthog/test/test_scoped_service_jwt.py b/posthog/test/test_scoped_service_jwt.py
index bb4864003e55..e2248abf129b 100644
--- a/posthog/test/test_scoped_service_jwt.py
+++ b/posthog/test/test_scoped_service_jwt.py
@@ -125,7 +125,7 @@ class TestScopedServiceJWTAuthentication(APIBaseTest):
django_request = self.factory.get(path)
if url_team_id is not None:
django_request.resolver_match = resolve(path)
- return Request(django_request) # ty: ignore[invalid-return-type]
+ return Request(django_request)
def _authenticate(self, authentication: ScopedServiceJWTAuthentication, request: Request) -> tuple[Any, Any]:
result = authentication.authenticate(request)
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index 7e82ba0b3cd4..f0a4fa934413 100644
--- a/posthog/test/test_utils.py
+++ b/posthog/test/test_utils.py
@@ -14,7 +14,7 @@ from unittest.mock import call, patch
from django.contrib.auth.models import AnonymousUser
from django.core.cache import cache
from django.core.handlers.wsgi import WSGIRequest
-from django.http import HttpRequest
+from django.http import HttpRequest, QueryDict
from django.test import SimpleTestCase, TestCase, override_settings
from django.test.client import RequestFactory
from django.utils.timezone import now
@@ -214,7 +214,7 @@ class TestFormatUrls(SimpleTestCase):
"HTTP_HOST": "www.testserver",
"HTTP_X_FORWARDED_PROTO": "https",
}
- request: Request = Request(build_req) # ty: ignore[invalid-assignment]
+ request: Request = Request(build_req)
self.assertEqual("https://www.testserver", format_query_params_absolute_url(request))
@@ -817,22 +817,22 @@ class TestLoadDataFromRequest(TestCase):
class TestShouldRefresh(SimpleTestCase):
def test_refresh_requested_by_client_with_refresh_true(self):
request = HttpRequest()
- request.GET["refresh"] = "true"
+ request.GET = QueryDict("refresh=true")
self.assertTrue(refresh_requested_by_client(Request(request)))
def test_refresh_requested_by_client_with_refresh_empty(self):
request = HttpRequest()
- request.GET["refresh"] = ""
+ request.GET = QueryDict("refresh=")
self.assertTrue(refresh_requested_by_client(Request(request)))
def test_should_not_refresh_with_refresh_false(self):
request = HttpRequest()
- request.GET["refresh"] = "false"
+ request.GET = QueryDict("refresh=false")
self.assertFalse(refresh_requested_by_client(Request(request)))
def test_should_not_refresh_with_refresh_gibberish(self):
request = HttpRequest()
- request.GET["refresh"] = "2132klkl"
+ request.GET = QueryDict("refresh=2132klkl")
self.assertFalse(refresh_requested_by_client(Request(request)))
def test_refresh_requested_by_client_with_data_true(self):
diff --git a/posthog/utils.py b/posthog/utils.py
index be7e79818099..c17ae26a81c7 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -2572,8 +2572,7 @@ def to_json(obj: dict) -> bytes:
def opt_slash_path(route: str, view: Callable, name: Optional[str] = None) -> URLPattern:
"""Catches path with or without trailing slash, taking into account query param and hash."""
- # Ignoring the type because while name can be optional on re_path, mypy doesn't agree
- return re_path(rf"^{route}/?(?:[?#].*)?$", view, name=name) # type: ignore
+ return re_path(rf"^{route}/?(?:[?#].*)?$", view, name=name)
def get_current_user_from_thread() -> Optional["User"]:
diff --git a/products/access_control/backend/facade/api.py b/products/access_control/backend/facade/api.py
index 29a98cb1e01b..3d7c3d8e73e2 100644
--- a/products/access_control/backend/facade/api.py
+++ b/products/access_control/backend/facade/api.py
@@ -520,7 +520,7 @@ def upsert_property_access_control(
team_id=team_id,
property_definition=prop_def,
organization_member_id=input.organization_member_id,
- role_id=input.role_id,
+ role_id=input.role_id, # type: ignore[misc] # nullable FK; django-stubs drops None from *_id lookups
defaults={
"access_level": input.access_level.value,
},
diff --git a/products/aeo/backend/facade/api.py b/products/aeo/backend/facade/api.py
index 3b759994f85d..2e8b51a80297 100644
--- a/products/aeo/backend/facade/api.py
+++ b/products/aeo/backend/facade/api.py
@@ -194,15 +194,6 @@ def get_prompt_stats(team_id: int, prompt_id: str, *, timezone_name: str, days:
prompt = _get_prompt_row(team_id, prompt_id)
target_domains: list[str] = settings.AEO_TARGET_DOMAINS
checks = AEOCitationCheck.objects.for_team(team_id).filter(prompt_id=prompt.id)
- # `mentioned` filters on the `cited` column, and an annotation named `cited` would shadow that
- # column for every later annotation in the same call, so it must come first.
- counts = {
- "checks": Count("id"),
- "mentioned": Count("id", filter=Q(check_failed=False) & mention_filter(target_domains)),
- "cited": Count("id", filter=Q(cited=True)),
- "failed": Count("id", filter=Q(check_failed=True)),
- }
-
engines = tuple(
PromptEngineStats(
engine=row["engine"],
@@ -214,7 +205,16 @@ def get_prompt_stats(team_id: int, prompt_id: str, *, timezone_name: str, days:
last_checked_at=row["last_checked_at"],
)
for row in checks.values("engine")
- .annotate(**counts, first_checked_at=Min("created_at"), last_checked_at=Max("created_at"))
+ # `mentioned` filters on the `cited` column, and an annotation named `cited` would shadow that
+ # column for every later annotation in the same call, so it must come first.
+ .annotate(
+ checks=Count("id"),
+ mentioned=Count("id", filter=Q(check_failed=False) & mention_filter(target_domains)),
+ cited=Count("id", filter=Q(cited=True)),
+ failed=Count("id", filter=Q(check_failed=True)),
+ first_checked_at=Min("created_at"),
+ last_checked_at=Max("created_at"),
+ )
.order_by("engine")
)
@@ -234,7 +234,12 @@ def get_prompt_stats(team_id: int, prompt_id: str, *, timezone_name: str, days:
)
for row in in_window.annotate(date=TruncDate("created_at", tzinfo=tz))
.values("date", "engine")
- .annotate(**counts)
+ .annotate(
+ checks=Count("id"),
+ mentioned=Count("id", filter=Q(check_failed=False) & mention_filter(target_domains)),
+ cited=Count("id", filter=Q(cited=True)),
+ failed=Count("id", filter=Q(check_failed=True)),
+ )
.order_by("date", "engine")
)
answered = in_window.filter(check_failed=False)
diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.py
index a6a1c6a76886..9e75b5b47fa7 100644
--- a/products/ai_observability/backend/models/evaluations.py
+++ b/products/ai_observability/backend/models/evaluations.py
@@ -1,4 +1,5 @@
-from typing import Any
+from collections.abc import Collection
+from typing import Any, Self
from django.db import models, transaction
from django.db.models.signals import post_save
@@ -156,8 +157,8 @@ class Evaluation(ModelActivityMixin, UUIDTModel):
self._initial_status = self.status
@classmethod
- def from_db(cls, db, field_names, values):
- instance = super().from_db(db, field_names, values)
+ def from_db(cls, db: str | None, field_names: Collection[str], values: Collection[Any], **kwargs: Any) -> Self:
+ instance = super().from_db(db, field_names, values, **kwargs)
instance._initial_enabled = instance.enabled
instance._initial_status = instance.status
return instance
diff --git a/products/approvals/backend/experiment_policy_sync.py b/products/approvals/backend/experiment_policy_sync.py
index 30e2cef0bd61..4f22de9d918f 100644
--- a/products/approvals/backend/experiment_policy_sync.py
+++ b/products/approvals/backend/experiment_policy_sync.py
@@ -105,7 +105,7 @@ def sync_experiment_policies() -> None:
mirror, was_created = ApprovalPolicy.objects.get_or_create(
organization_id=source.organization_id,
- team_id=source.team_id,
+ team_id=source.team_id, # type: ignore[misc] # nullable FK; django-stubs drops None from *_id lookups
action_key=target_action,
defaults=fields,
)
diff --git a/products/cohorts/backend/backfill/observe.py b/products/cohorts/backend/backfill/observe.py
index 626f5b5f61a1..ca51e5d9b58a 100644
--- a/products/cohorts/backend/backfill/observe.py
+++ b/products/cohorts/backend/backfill/observe.py
@@ -97,7 +97,7 @@ def _observe() -> ObservationPass:
result.active_runs[key] = row["runs"]
result.oldest_active_age_seconds[key] = max(0.0, (now - row["oldest"]).total_seconds())
- for row in (
+ for chunk_row in (
CohortBackfillChunk.objects.unscoped()
.filter(
status=CohortBackfillChunkStatus.FAILED,
@@ -106,15 +106,15 @@ def _observe() -> ObservationPass:
.values("run__backfill_kind")
.annotate(chunks=Count("id"))
):
- result.failed_chunks[row["run__backfill_kind"]] = row["chunks"]
+ result.failed_chunks[chunk_row["run__backfill_kind"]] = chunk_row["chunks"]
- for row in (
+ for recent_row in (
CohortBackfillRun.objects.unscoped()
.filter(status__in=TERMINAL_COHORT_BACKFILL_RUN_STATUSES, finished_at__gte=now - RECENT_WINDOW)
.values("status", "backfill_kind")
.annotate(runs=Count("id"))
):
- result.recent_runs[(row["status"], row["backfill_kind"])] = row["runs"]
+ result.recent_runs[(recent_row["status"], recent_row["backfill_kind"])] = recent_row["runs"]
return result
diff --git a/products/cohorts/backend/realtime_state.py b/products/cohorts/backend/realtime_state.py
index 8fec2e0693da..8f22be691178 100644
--- a/products/cohorts/backend/realtime_state.py
+++ b/products/cohorts/backend/realtime_state.py
@@ -17,7 +17,7 @@ filters changing is not evidence that anything is rebuilding.
"""
from collections import defaultdict
-from collections.abc import Iterable, Sequence
+from collections.abc import Iterable, Mapping, Sequence
from datetime import datetime
from typing import Any, TypeGuard
from uuid import UUID
@@ -149,7 +149,7 @@ def _required_backfill_kinds(cohort: Cohort) -> set[str]:
return set(cohort._required_backfill_stamps())
-def _percent_complete(chunks: dict[str, Any] | None) -> int | None:
+def _percent_complete(chunks: Mapping[str, Any] | None) -> int | None:
"""Scan progress as a whole percent, or None while the run has planned no chunks.
Rounded down, so 100 means every chunk is confirmed rather than 199 of 200.
@@ -230,7 +230,7 @@ def _queued_triggers(pairs: Sequence[tuple[int, str]]) -> dict[tuple[int, str],
}
-def _chunk_tallies(team_id: int, run_ids: Sequence[UUID]) -> dict[UUID, dict[str, Any]]:
+def _chunk_tallies(team_id: int, run_ids: Sequence[UUID]) -> dict[UUID, Mapping[str, Any]]:
if not run_ids:
return {}
tallies = (
diff --git a/products/conversations/backend/api/ticket_actions.py b/products/conversations/backend/api/ticket_actions.py
index 6b9a116eae52..e6bb944b75d0 100644
--- a/products/conversations/backend/api/ticket_actions.py
+++ b/products/conversations/backend/api/ticket_actions.py
@@ -636,7 +636,7 @@ def handle_ticket_patch(request: Request, team: Team, ticket_id: str | uuid.UUID
# delete would skip it. The trigger context attributes every resulting entry
# to the workflow that made the change.
# Only a removed TaggedItem can orphan a tag, so the cleanup checks just those tags.
- removed_tag_ids: set[int] = set()
+ removed_tag_ids: set[uuid.UUID] = set()
with ActivityTriggerContext(workflow_trigger):
if tags_mode == "remove":
for tagged_item in (
diff --git a/products/dashboards/backend/admin/dashboard_admin.py b/products/dashboards/backend/admin/dashboard_admin.py
index cc524b2880c2..b2a08bc40265 100644
--- a/products/dashboards/backend/admin/dashboard_admin.py
+++ b/products/dashboards/backend/admin/dashboard_admin.py
@@ -55,9 +55,9 @@ class DashboardAdmin(admin.ModelAdmin):
def get_queryset(self, request):
return Dashboard.objects_including_soft_deleted.all()
- def get_actions(self, request: HttpRequest) -> dict[str, Any]:
+ def get_actions(self, request: HttpRequest, *args: Any, **kwargs: Any) -> dict[str, Any]:
# Drop the built-in hard-delete: dashboards are soft-deleted product-side.
- actions = super().get_actions(request)
+ actions = super().get_actions(request, *args, **kwargs)
actions.pop("delete_selected", None)
return actions
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index c5af91445e74..375c5303752b 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -2536,7 +2536,7 @@ class DashboardSerializer(DashboardMetadataSerializer):
tile_defaults = DashboardSerializer._extract_display_defaults(tile_data)
# nosemgrep: idor-lookup-without-team -- dashboard=instance constrains to team
return DashboardTile.objects_including_soft_deleted.update_or_create(
- id=tile_data.get("id", None),
+ id=tile_data.get("id", None), # type: ignore[misc] # id=None matches no row, so a new tile is created
dashboard=instance,
defaults={**tile_defaults, **extra_defaults, "dashboard": instance},
)
diff --git a/products/data_modeling/backend/logic/usage.py b/products/data_modeling/backend/logic/usage.py
index bbbbe0446a31..7e1851bad76a 100644
--- a/products/data_modeling/backend/logic/usage.py
+++ b/products/data_modeling/backend/logic/usage.py
@@ -1,3 +1,4 @@
+from collections.abc import Mapping
from datetime import UTC, date, datetime, time, timedelta
from typing import TypedDict, cast
from uuid import UUID
@@ -80,7 +81,7 @@ class ModelUsage:
}
@classmethod
- def engine_usage(cls, row: dict[str, object], engines: tuple[DataModelingJobEngine, ...]) -> list[EngineUsage]:
+ def engine_usage(cls, row: Mapping[str, object], engines: tuple[DataModelingJobEngine, ...]) -> list[EngineUsage]:
return [
EngineUsage(
engine=engine,
@@ -146,7 +147,7 @@ class ModelUsage:
status_jobs = cls.all_jobs(team_id, start, end, engines).filter(saved_query_id__in=saved_query_ids)
overview = jobs.aggregate(**cls.aggregates())
usage_updated_at = jobs.aggregate(latest=Max("usage_updated_at"))["latest"]
- daily = {
+ daily: dict[date, Mapping[str, object]] = {
row["day"]: row
for row in jobs.annotate(day=TruncDate("last_run_at", tzinfo=UTC))
.values("day")
@@ -179,7 +180,7 @@ class ModelUsage:
)
count = models.count()
offset = (page - 1) * page_size
- rows = list(
+ rows: list[Mapping[str, object]] = list(
models.order_by(F("read_bytes").desc(nulls_last=True), "saved_query_id")[offset : offset + page_size]
)
return {
diff --git a/products/data_quality/backend/admin.py b/products/data_quality/backend/admin.py
index ee89058a45ab..56da1fd83ff9 100644
--- a/products/data_quality/backend/admin.py
+++ b/products/data_quality/backend/admin.py
@@ -1,4 +1,4 @@
-from typing import cast
+from typing import Any, cast
from django import forms
from django.contrib import admin
@@ -65,7 +65,7 @@ class _DataQualityAdmin(admin.ModelAdmin):
return queryset.order_by(*ordering) if ordering else queryset
def formfield_for_foreignkey(
- self, db_field: models.ForeignKey, request: HttpRequest, **kwargs: object
+ self, db_field: models.ForeignKey, request: HttpRequest, **kwargs: Any
) -> forms.ModelChoiceField | None:
manager = db_field.remote_field.model._default_manager
if not isinstance(manager, TeamScopedManager):
diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.py
index b642fcf02929..3b76968a6185 100644
--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py
+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py
@@ -870,17 +870,17 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
)
- external_lookup = {result["day"]: result for result in external_by_day}
- modeling_lookup = {result["day"]: result for result in modeling_by_day}
+ external_day_lookup = {result["day"]: result for result in external_by_day}
+ modeling_day_lookup = {result["day"]: result for result in modeling_by_day}
for i in range(days):
day_date = (now - timedelta(days=i)).date()
- external_data = external_lookup.get(day_date, {"successful": 0, "failed": 0})
- modeling_data = modeling_lookup.get(day_date, {"successful": 0, "failed": 0})
+ external_day = external_day_lookup.get(day_date, {"successful": 0, "failed": 0})
+ modeling_day = modeling_day_lookup.get(day_date, {"successful": 0, "failed": 0})
breakdown[str(day_date)] = {
- "successful": external_data["successful"] + modeling_data["successful"],
- "failed": external_data["failed"] + modeling_data["failed"],
+ "successful": external_day["successful"] + modeling_day["successful"],
+ "failed": external_day["failed"] + modeling_day["failed"],
}
running_external_data_jobs = ExternalDataJob.objects.filter(
diff --git a/products/event_definitions/backend/migrations/0014_drop_taxonomy_project_id_fk_idx.py b/products/event_definitions/backend/migrations/0014_drop_taxonomy_project_id_fk_idx.py
index 2c13b62e1c68..3197e41b1283 100644
--- a/products/event_definitions/backend/migrations/0014_drop_taxonomy_project_id_fk_idx.py
+++ b/products/event_definitions/backend/migrations/0014_drop_taxonomy_project_id_fk_idx.py
@@ -1,10 +1,12 @@
+from typing import Any
+
import django.db.models.deletion
from django.db import migrations, models
from posthog.migration_helpers import DropIndexConcurrently
-def _project_field() -> models.ForeignKey:
+def _project_field() -> "models.ForeignKey[Any, Any]":
return models.ForeignKey(
db_index=False,
null=True,
diff --git a/products/growth/backend/tests/test_enrichment_admin.py b/products/growth/backend/tests/test_enrichment_admin.py
index 1d538ce4355c..963d9c06bd35 100644
--- a/products/growth/backend/tests/test_enrichment_admin.py
+++ b/products/growth/backend/tests/test_enrichment_admin.py
@@ -241,9 +241,9 @@ class TestEnrichmentLabelResultAdminFilters(_GrowthAdminTestCase):
self._result(self._config(name="other_label", version="v1-other"), fetch)
request = RequestFactory().get("/admin/growth/enrichmentlabelresult/", {"label_name": "ai_pilled"})
- queryset = EnrichmentLabelNameFilter(request, request.GET.copy(), EnrichmentLabelResult, self.admin).queryset(
- request, EnrichmentLabelResult.objects.all()
- )
+ queryset = EnrichmentLabelNameFilter(
+ request, dict(request.GET.lists()), EnrichmentLabelResult, self.admin
+ ).queryset(request, EnrichmentLabelResult.objects.all())
assert list(queryset) == [matching]
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index ced24bd7a9e6..81532408bed1 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -679,7 +679,7 @@ def _as_configured_now(
platform's, so it is evaluated as stored. It still needs its logs row on the copy's team. A row in
a child environment has its logs there, and the query would read the project's instead.
"""
- legacy_ids = [check.legacy_configuration_id for check in checks]
+ legacy_ids = [check.legacy_configuration_id for check in checks if check.legacy_configuration_id is not None]
alerts = {alert.id: alert for alert in LogsAlertConfiguration.objects.filter(team_id=team_id, id__in=legacy_ids)}
current: list[PlatformAlertCheckInput] = []
stopped: list[Decision] = []
diff --git a/products/managed_warehouse/backend/model_observability.py b/products/managed_warehouse/backend/model_observability.py
index 89e5d53153c8..95dd6d476a00 100644
--- a/products/managed_warehouse/backend/model_observability.py
+++ b/products/managed_warehouse/backend/model_observability.py
@@ -123,7 +123,8 @@ class DuckgresServerQuerySet(models.QuerySet["DuckgresServer"]):
record_duckgres_server_access("read")
return super().exists()
- def iterator(self, chunk_size: int | None = None) -> Iterator[DuckgresServer]:
+ # The django-stubs plugin rebinds this subclass to its own row TypeVar, so a concrete row type cannot match.
+ def iterator(self, chunk_size: int | None = None) -> Iterator[DuckgresServer]: # type: ignore[override]
record_duckgres_server_access("read")
return super().iterator(chunk_size=chunk_size)
diff --git a/products/marketing_analytics/backend/services/conversion_recommendations.py b/products/marketing_analytics/backend/services/conversion_recommendations.py
index 6d8a2c399f2d..444f12184326 100644
--- a/products/marketing_analytics/backend/services/conversion_recommendations.py
+++ b/products/marketing_analytics/backend/services/conversion_recommendations.py
@@ -566,7 +566,9 @@ class ConversionRecommendationService:
return ConversionRecommendationResults()
result = ConversionRecommendationResults.model_validate(run.results)
action_ids = [
- item.candidate.action_id for item in result.recommendations if item.candidate.kind == "ActionsNode"
+ item.candidate.action_id
+ for item in result.recommendations
+ if item.candidate.kind == "ActionsNode" and item.candidate.action_id is not None
]
allowed = set(
UserAccessControl(self.user, team=self.team)
diff --git a/products/mcp_registry/backend/logic.py b/products/mcp_registry/backend/logic.py
index 7b9e5c7fbd43..cb6a32b366f4 100644
--- a/products/mcp_registry/backend/logic.py
+++ b/products/mcp_registry/backend/logic.py
@@ -10,7 +10,7 @@ task-facing business layer.
import re
from dataclasses import dataclass
-from typing import Any
+from typing import Any, cast
from uuid import UUID
from django.db.models import (
@@ -276,9 +276,12 @@ def score_for_run(run: MCPRankingRun | None, server: MCPRegistryServer) -> MCPRa
def measured_project_rollup() -> list[dict[str, Any]]:
"""Per-project contribution to the measured layer (staff fleet view)."""
- return list(
- MCPMeasuredStats.objects.unscoped()
- .values("team_id")
- .annotate(servers=Count("server", distinct=True), total_calls=Sum("calls"))
- .order_by("-total_calls")
+ return cast(
+ list[dict[str, Any]],
+ list(
+ MCPMeasuredStats.objects.unscoped()
+ .values("team_id")
+ .annotate(servers=Count("server", distinct=True), total_calls=Sum("calls"))
+ .order_by("-total_calls")
+ ),
)
diff --git a/products/notifications/backend/logic.py b/products/notifications/backend/logic.py
index d761aedcd1ae..b32d01c57a0a 100644
--- a/products/notifications/backend/logic.py
+++ b/products/notifications/backend/logic.py
@@ -267,7 +267,7 @@ def create_notification(data: NotificationData) -> NotificationEvent | None:
if data.idempotency_key:
event, created = NotificationEvent.objects.get_or_create(
organization_id=organization.id,
- team_id=data.team_id,
+ team_id=data.team_id, # type: ignore[misc] # nullable FK; django-stubs drops None from *_id lookups
idempotency_key=data.idempotency_key,
defaults=event_data,
)
diff --git a/products/product_analytics/backend/admin.py b/products/product_analytics/backend/admin.py
index a54ce6c0dfb4..0b4c6abde7c5 100644
--- a/products/product_analytics/backend/admin.py
+++ b/products/product_analytics/backend/admin.py
@@ -96,9 +96,9 @@ class InsightAdmin(admin.ModelAdmin):
def get_queryset(self, request):
return Insight.objects_including_soft_deleted.all()
- def get_actions(self, request: HttpRequest) -> dict[str, Any]:
+ def get_actions(self, request: HttpRequest, *args: Any, **kwargs: Any) -> dict[str, Any]:
# Drop the built-in hard-delete: insights are soft-deleted product-side.
- actions = super().get_actions(request)
+ actions = super().get_actions(request, *args, **kwargs)
actions.pop("delete_selected", None)
return actions
diff --git a/products/product_analytics/backend/logic.py b/products/product_analytics/backend/logic.py
index 93105ff7b165..c7108867baea 100644
--- a/products/product_analytics/backend/logic.py
+++ b/products/product_analytics/backend/logic.py
@@ -50,7 +50,7 @@ def lock_insight_for_evaluation(*, team_id: int, insight_id: int) -> bool:
def record_insight_view(*, insight_id: int, team_id: int | None, user_id: int | None) -> None:
- InsightViewed.objects.update_or_create(
+ InsightViewed.objects.update_or_create( # type: ignore[misc] # nullable FKs; django-stubs drops None from *_id lookups
insight_id=insight_id, team_id=team_id, user_id=user_id, defaults={"last_viewed_at": now()}
)
diff --git a/products/reminders/backend/api/reminder.py b/products/reminders/backend/api/reminder.py
index 02d7ef284e26..bb18ddd583a2 100644
--- a/products/reminders/backend/api/reminder.py
+++ b/products/reminders/backend/api/reminder.py
@@ -173,11 +173,12 @@ class ReminderSerializer(serializers.ModelSerializer):
if scoped_organizations is not None:
organization_ids = [id for id in organization_ids if str(id) in scoped_organizations]
organization_field = cast(serializers.PrimaryKeyRelatedField, self.fields["organization"])
- organization_field.queryset = Organization.objects.filter(id__in=organization_ids)
+ organization_field.queryset = Organization.objects.filter(id__in=organization_ids) # type: ignore[arg-type] # DRF stubs type queryset as a Manager, which django-stubs treats as a descriptor
teams = Team.objects.filter(organization_id__in=organization_ids)
if scoped_teams is not None:
teams = teams.filter(id__in=scoped_teams)
- cast(serializers.PrimaryKeyRelatedField, self.fields["team"]).queryset = teams
+ team_field = cast(serializers.PrimaryKeyRelatedField, self.fields["team"])
+ team_field.queryset = teams # type: ignore[arg-type] # DRF stubs type queryset as a Manager, which django-stubs treats as a descriptor
class Meta:
model = Reminder
diff --git a/products/replay_vision/backend/api/observation_stats.py b/products/replay_vision/backend/api/observation_stats.py
index 99a4622d0a2c..2570df0e526d 100644
--- a/products/replay_vision/backend/api/observation_stats.py
+++ b/products/replay_vision/backend/api/observation_stats.py
@@ -130,7 +130,7 @@ def _version_markers(queryset: QuerySet[ReplayObservation]) -> list[dict[str, An
implying nothing changed."""
rows = (
queryset.annotate(snapshot_version=KeyTextTransform("scanner_version", "scanner_snapshot"))
- .exclude(snapshot_version=None)
+ .exclude(snapshot_version__isnull=True)
.annotate(
day=TruncDate("created_at"),
# The whole snapshot, not just scanner_config, so every version-tracked field can be diffed.
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 6cc4bb420d54..54608330fdf1 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -1260,7 +1260,7 @@ class ReplayObservationViewSet(
"""Record that the calling user opened this observation. Idempotent."""
observation = self.get_object()
ReplayObservationView.objects.get_or_create(
- team_id=observation.team_id, observation=observation, user=request.user
+ team_id=observation.team_id, observation=observation, user=cast(User, request.user)
)
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 82367a3cb850..a6c521c723bf 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -1294,7 +1294,7 @@ class ReplayScannerFilter(django_filters.FilterSet):
invalid = sorted(t for t in tokens if not t.isdecimal())
if invalid:
raise ValidationError({"created_by": f"Non-numeric value(s) {invalid}; user IDs must be integers."})
- return queryset.filter(created_by_id__in=tokens)
+ return queryset.filter(created_by_id__in=[int(t) for t in tokens])
def _filter_experiment_id(
self, queryset: QuerySet[ReplayScanner], _name: str, value: str
@@ -1701,11 +1701,16 @@ def select_watch_feed_candidates(
rows: list[dict[str, Any]] = []
for start in range(0, len(newest_first), WATCH_FEED_CANDIDATE_CAP):
chunk = newest_first[start : start + WATCH_FEED_CANDIDATE_CAP]
- rows += list(
- accessible_observations(access, team_id, ReplayObservation.objects.filter(team_id=team_id, id__in=chunk))
- .annotate(feed_viewed=viewed)
- .order_by("-created_at", "-id")
- .values("id", "scanner_id", "session_id", "created_at", "watch_rank", "feed_viewed")
+ rows += cast(
+ list[dict[str, Any]],
+ list(
+ accessible_observations(
+ access, team_id, ReplayObservation.objects.filter(team_id=team_id, id__in=chunk)
+ )
+ .annotate(feed_viewed=viewed)
+ .order_by("-created_at", "-id")
+ .values("id", "scanner_id", "session_id", "created_at", "watch_rank", "feed_viewed")
+ ),
)
if len(rows) >= WATCH_FEED_CANDIDATE_CAP:
break
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index 28c714d4fee8..739b1a243872 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -5,6 +5,7 @@ from collections import Counter
from collections.abc import Callable
from dataclasses import dataclass, replace
from datetime import UTC, date, datetime, timedelta
+from typing import cast
from uuid import UUID
from django.db.models import Count, IntegerField, QuerySet, Sum, Value
@@ -379,7 +380,8 @@ def compute_scanner_budgets(
# is then counted by both (a transient over-count that fails toward capped), never by neither.
in_flight = _scanner_in_flight_credits(organization_id, capped_ids, period)
settled = {
- row["scanner_id"]: row["total_credits"] or 0
+ # The scanner_id__in filter excludes rows without a scanner.
+ cast(UUID, row["scanner_id"]): row["total_credits"] or 0
for row in scanner_period_receipts(organization_id, period)
.filter(scanner_id__in=capped_ids)
.values("scanner_id")
diff --git a/products/replay_vision/backend/tests/test_observation_media.py b/products/replay_vision/backend/tests/test_observation_media.py
index 05fd54ad2d0f..dd080b60c918 100644
--- a/products/replay_vision/backend/tests/test_observation_media.py
+++ b/products/replay_vision/backend/tests/test_observation_media.py
@@ -215,9 +215,13 @@ class TestObservationMedia(BaseTest):
assert (m.small_asset.content_location or "").endswith("-small.webp")
assert m.small_asset.expires_after == m.asset.expires_after
unlinked = [
- prepared.frames[2].small_media_asset_id,
- prepared.frames[3].media_asset_id,
- prepared.frames[3].small_media_asset_id,
+ asset_id
+ for asset_id in (
+ prepared.frames[2].small_media_asset_id,
+ prepared.frames[3].media_asset_id,
+ prepared.frames[3].small_media_asset_id,
+ )
+ if asset_id is not None
]
for asset in ExportedAsset.objects_including_ttl_deleted.filter(pk__in=unlinked):
assert asset.expires_after is not None and asset.expires_after <= timezone.now()
diff --git a/products/replay_vision/backend/watch_rank.py b/products/replay_vision/backend/watch_rank.py
index 0da6576a3940..ff5fd3ff4884 100644
--- a/products/replay_vision/backend/watch_rank.py
+++ b/products/replay_vision/backend/watch_rank.py
@@ -10,9 +10,10 @@ errors all the time does not fill the feed.
import math
import asyncio
from collections import Counter
+from collections.abc import Mapping
from dataclasses import asdict
from datetime import timedelta
-from typing import Any, Literal
+from typing import Any, Literal, cast
from django.core.cache import cache
from django.core.exceptions import EmptyResultSet
@@ -412,16 +413,19 @@ def select_embedding_picks(
.annotate(sessions=Count("id"), people=Count(person, distinct=True))
}
# The row-gate reads each row's snapshot JSON, so it runs on the picks only.
- rows = list(
- accessible_observations(
- access, team_id, ReplayObservation.objects.filter(team_id=team_id, id__in=list(window_values))
- )
- .annotate(feed_viewed=viewed)
- .values("id", "scanner_id", "session_id", "created_at", "watch_rank", "feed_viewed")
+ rows = cast(
+ list[dict[str, Any]],
+ list(
+ accessible_observations(
+ access, team_id, ReplayObservation.objects.filter(team_id=team_id, id__in=list(window_values))
+ )
+ .annotate(feed_viewed=viewed)
+ .values("id", "scanner_id", "session_id", "created_at", "watch_rank", "feed_viewed")
+ ),
)
for row in rows:
window = window_values[row["id"]]
- reach = group_reach.get(window["watch_group_root"], {})
+ reach: Mapping[str, Any] = group_reach.get(window["watch_group_root"], {})
row["watch_percentile"] = window["watch_percentile"]
row["watch_group_root"] = window["watch_group_root"]
row["watch_group_size"] = reach.get("sessions", 1)
diff --git a/products/review_hog/backend/reviewer/progress.py b/products/review_hog/backend/reviewer/progress.py
index 6ec172087231..fdbc98d21bf4 100644
--- a/products/review_hog/backend/reviewer/progress.py
+++ b/products/review_hog/backend/reviewer/progress.py
@@ -9,11 +9,11 @@ comment, so the two surfaces can never disagree.
import logging
import operator
-from collections.abc import Sequence
+from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
from functools import reduce
-from typing import Any, Final, Literal
+from typing import Any, Final, Literal, cast
from django.db.models import (
Case,
@@ -219,8 +219,8 @@ def turn_stats(team_id: int, heads: dict[str, str | None]) -> dict[str, TurnStat
.order_by("created_at", "id")
.values("report_id", "chunk_count")
)
- for row in chunk_rows: # oldest-first, so the turn's latest chunking wins
- stats[str(row["report_id"])].chunk_count = row["chunk_count"]
+ for chunk_row in chunk_rows: # oldest-first, so the turn's latest chunking wins
+ stats[str(chunk_row["report_id"])].chunk_count = chunk_row["chunk_count"]
result_rows = (
ReviewReportArtefact.objects.for_team(team_id)
@@ -313,7 +313,8 @@ def turn_markers(team_id: int, report_ids: list[str]) -> dict[tuple[str, int], T
)
)
markers: dict[tuple[str, int], TurnMarker] = {}
- for row in rows:
+ # KeyTextTransform returns NULL for a missing key, but the stubs type the annotation as str.
+ for row in cast(Iterable[Mapping[str, Any]], rows):
if row["marker_run_index"] is None or row["marker_review_mode"] is None:
continue
# Markers written before the explicit field carry the design only in a single-agent
diff --git a/products/signals/backend/scout_harness/skill_loader.py b/products/signals/backend/scout_harness/skill_loader.py
index 88f047487e66..ae67fbea8d46 100644
--- a/products/signals/backend/scout_harness/skill_loader.py
+++ b/products/signals/backend/scout_harness/skill_loader.py
@@ -1,8 +1,9 @@
from __future__ import annotations
+from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
-from typing import TYPE_CHECKING, Literal
+from typing import TYPE_CHECKING, Any, Literal
from django.db.models import Max, Min, QuerySet
@@ -303,7 +304,7 @@ def resolve_skill_authors(team: Team, skill_name: str) -> list[SkillAuthor]:
if not people:
return []
- def to_author(person: dict, role: Literal["creator", "editor"]) -> SkillAuthor:
+ def to_author(person: Mapping[str, Any], role: Literal["creator", "editor"]) -> SkillAuthor:
# Collapse whitespace so a multi-line display name can't break out of the prompt's
# one-line list-item structure.
name = " ".join(f"{person['created_by__first_name']} {person['created_by__last_name']}".split())
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 33f7ef1ebfde..127708c58e38 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -2766,8 +2766,8 @@ def _upsert_scout_config(
skill_name=skill_name,
defaults={
**defaults,
- "created_by": request.user,
- "enabled_by": request.user if tunables.get("enabled", True) else None,
+ "created_by": cast(User, request.user),
+ "enabled_by": cast(User, request.user) if tunables.get("enabled", True) else None,
},
)
if created or not tunables:
diff --git a/products/signals/backend/spend.py b/products/signals/backend/spend.py
index 48333693a0ae..4d19e7e6fa50 100644
--- a/products/signals/backend/spend.py
+++ b/products/signals/backend/spend.py
@@ -129,7 +129,9 @@ def _locked_ad_hoc_spend(*, team_id: int, signal_id: str) -> SignalSpend:
team_id=team_id,
signal_id=signal_id,
kind=SignalSpend.Kind.AD_HOC,
- defaults={"billing_exempt": lambda: trial_spend_exempt(team_id)},
+ # get_or_create calls callable defaults only when it creates the row, so the trial lookup is
+ # skipped for existing rows. django-stubs types defaults as plain field values.
+ defaults={"billing_exempt": lambda: trial_spend_exempt(team_id)}, # type: ignore[misc]
)
return SignalSpend.objects.for_team(team_id).select_for_update().get(id=spend.id)
diff --git a/products/signals/backend/test/test_report_admin.py b/products/signals/backend/test/test_report_admin.py
index f9c39a2a18d8..990cf45635af 100644
--- a/products/signals/backend/test/test_report_admin.py
+++ b/products/signals/backend/test/test_report_admin.py
@@ -13,7 +13,7 @@ class TestReportAdmin(SimpleTestCase):
model_admin = SignalReportAdmin(SignalReport, admin.site)
filter_type = model_admin.get_list_filter(request)[0]
assert isinstance(filter_type, type) and issubclass(filter_type, SignalReportStatusFilter)
- status_filter = filter_type(request, request.GET.copy(), SignalReport, model_admin)
+ status_filter = filter_type(request, dict(request.GET.lists()), SignalReport, model_admin)
choices = list(status_filter.choices(Mock(add_facets=False)))
assert "Monitoring" not in [choice["display"] for choice in choices]
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index f8a8c48916c1..cdb7272c2048 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -2089,6 +2089,7 @@ async def test_trial_runs_keep_runtime_and_state_separate_from_the_production_sc
assert isinstance(prompt, str)
assert "Report follow-up checks are limited in this private trial" in prompt
assert "scout-report-check-create" not in prompt
+ assert outcome.run_id is not None
bridge = await SignalScoutRun.objects.aget(id=outcome.run_id)
if task_cancelled:
assert bridge.summary == ""
diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.py
index e4c88bbc2e22..eb92f31d88a1 100644
--- a/products/signals/dags/inbox_ranking/dataset/dag.py
+++ b/products/signals/dags/inbox_ranking/dataset/dag.py
@@ -644,10 +644,10 @@ def server_action_rows(report_ids: list[str], snapshot_end: datetime.datetime) -
.values("report_id")
.annotate(row_count=Count("id"), earliest_at=Min("first_at"))
)
- for row in discussions.iterator(chunk_size=2000):
- values = entry(row["report_id"])
- values["slack_discussion_count"] = row["row_count"]
- values["first_slack_discussed_at"] = row["earliest_at"]
+ for discussion_row in discussions.iterator(chunk_size=2000):
+ values = entry(discussion_row["report_id"])
+ values["slack_discussion_count"] = discussion_row["row_count"]
+ values["first_slack_discussed_at"] = discussion_row["earliest_at"]
return [
(report_id, *(values[column] for column in SERVER_ACTIONS_COLUMNS)) for report_id, values in entries.items()
]
diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.py
index 70272ecb1b36..13ffca7e04ff 100644
--- a/products/slack_app/backend/tests/test_followup_forwarding.py
+++ b/products/slack_app/backend/tests/test_followup_forwarding.py
@@ -253,7 +253,9 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
None,
)
- state = self.Task.objects.get(team=self.team).latest_run.state
+ latest_run = self.Task.objects.get(team=self.team).latest_run
+ assert latest_run is not None
+ state = latest_run.state
assert state["runtime_adapter"] == "codex"
assert state["codex_model_access"] == "own-subscription"
assert state["codex_subscription_user_id"] == self.user.id
@@ -283,19 +285,19 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
task = self.Task.objects.get(team=self.team)
assert task.repository is None
assert task.origin_product == self.Task.OriginProduct.SLACK
- assert task.latest_run.state["interaction_origin"] == "slack"
- assert task.latest_run.state["pr_authorship_mode"] == "bot"
+ latest_run = task.latest_run
+ assert latest_run is not None
+ assert latest_run.state["interaction_origin"] == "slack"
+ assert latest_run.state["pr_authorship_mode"] == "bot"
# Mention-dispatch debug pointer persisted on the new run.
# No explicit envelope event_id → falls back to "<channel>:<ts>".
- assert (
- task.latest_run.state["slack_mention_workflow_id"] == "slack-app-mention-processing-T_SLACK:C123:1234.5678"
- )
+ assert latest_run.state["slack_mention_workflow_id"] == "slack-app-mention-processing-T_SLACK:C123:1234.5678"
mock_execute_workflow.assert_called_once()
call_kwargs = mock_execute_workflow.call_args.kwargs
assert call_kwargs["task_id"] == str(task.id)
- assert call_kwargs["run_id"] == str(task.latest_run.id)
+ assert call_kwargs["run_id"] == str(latest_run.id)
assert call_kwargs["create_pr"] is True
assert call_kwargs["posthog_mcp_scopes"] == "full"
@@ -303,7 +305,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
integration=self.integration, channel="C123", thread_ts="1234.5678"
)
assert mapping.task_id == task.id
- assert mapping.task_run_id == task.latest_run.id
+ assert mapping.task_run_id == latest_run.id
@parameterized.expand(
[
@@ -596,7 +598,9 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
)
task = self.Task.objects.get(team=self.team)
- assert task.latest_run.state["slack_mention_workflow_id"] == "slack-app-mention-processing-T_SLACK:Ev01234567"
+ latest_run = task.latest_run
+ assert latest_run is not None
+ assert latest_run.state["slack_mention_workflow_id"] == "slack-app-mention-processing-T_SLACK:Ev01234567"
@patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
@@ -623,7 +627,9 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
)
task = self.Task.objects.get(team=self.team)
- state = task.latest_run.state
+ latest_run = task.latest_run
+ assert latest_run is not None
+ state = latest_run.state
assert state["repo_research_task_id"] == "11111111-1111-1111-1111-111111111111"
assert state["repo_research_run_id"] == "22222222-2222-2222-2222-222222222222"
@@ -652,8 +658,10 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
)
task = self.Task.objects.get(team=self.team)
- assert "repo_research_task_id" not in task.latest_run.state
- assert "repo_research_run_id" not in task.latest_run.state
+ latest_run = task.latest_run
+ assert latest_run is not None
+ assert "repo_research_task_id" not in latest_run.state
+ assert "repo_research_run_id" not in latest_run.state
@patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
@@ -682,7 +690,9 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert task.repository is None
assert task.github_integration is not None
assert task.github_user_integration is None
- assert task.latest_run.state["pr_authorship_mode"] == "bot"
+ latest_run = task.latest_run
+ assert latest_run is not None
+ assert latest_run.state["pr_authorship_mode"] == "bot"
mock_execute_workflow.assert_called_once()
@patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")
@@ -721,7 +731,9 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert task.repository is None
assert task.github_integration is not None
assert task.github_user_integration is None
- assert task.latest_run.state["pr_authorship_mode"] == "bot"
+ latest_run = task.latest_run
+ assert latest_run is not None
+ assert latest_run.state["pr_authorship_mode"] == "bot"
mock_execute_workflow.assert_called_once()
@patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")
@@ -756,7 +768,9 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
task = self.Task.objects.get(team=self.team)
assert task.repository is None
assert task.github_user_integration is not None
- assert task.latest_run.state["pr_authorship_mode"] == "user"
+ latest_run = task.latest_run
+ assert latest_run is not None
+ assert latest_run.state["pr_authorship_mode"] == "user"
mock_execute_workflow.assert_called_once()
# Description-format coverage (labeled mentions, indentation, role annotations,
diff --git a/products/subscriptions/backend/logic/visibility.py b/products/subscriptions/backend/logic/visibility.py
index d4b43c2dfd2a..d1f40a56e3be 100644
--- a/products/subscriptions/backend/logic/visibility.py
+++ b/products/subscriptions/backend/logic/visibility.py
@@ -5,21 +5,11 @@ so a user who cannot view one of those may not see the subscription either. The
subqueries over the target tables, so the access filter stays a single query.
"""
+from typing import Any, Protocol
+
from django.contrib.postgres.expressions import ArraySubquery
from django.contrib.postgres.fields import ArrayField
-from django.db.models import (
- BigIntegerField,
- BooleanField,
- CharField,
- F,
- Func,
- JSONField,
- Manager,
- Q,
- QuerySet,
- TextField,
- Value,
-)
+from django.db.models import BigIntegerField, BooleanField, CharField, F, Func, JSONField, Q, QuerySet, TextField, Value
from django.db.models.functions import Cast, Concat
from posthog.dataclasses import frozen
@@ -32,6 +22,11 @@ from products.product_analytics.backend.facade.models import Insight
from products.subscriptions.backend.facade.contracts import SubscriptionRequestInvalidError
+class _Filterable(Protocol):
+ # A Protocol, not Manager, because type checkers read a Manager-typed field as a descriptor.
+ def filter(self, *args: Any, **kwargs: Any) -> QuerySet[Any]: ...
+
+
@frozen
class _TargetLookups:
insight: str
@@ -42,9 +37,9 @@ class _TargetLookups:
rendered_snapshot: str | None
exported_insights: str
no_selection: str
- insights: Manager
- dashboards: Manager
- tiles: Manager
+ insights: _Filterable
+ dashboards: _Filterable
+ tiles: _Filterable
_SUBSCRIPTION_TARGETS = _TargetLookups(
@@ -150,7 +145,8 @@ def _target_filter(user_access_control: UserAccessControl, team_id: int, targets
return Q()
team_dashboards = targets.dashboards.filter(team_id=team_id)
- blocked_insights = blocked_target_ids(user_access_control, targets.insights.filter(team_id=team_id), "insight")
+ target_insights = targets.insights.filter(team_id=team_id)
+ blocked_insights = blocked_target_ids(user_access_control, target_insights, "insight")
blocked_dashboards = blocked_target_ids(user_access_control, team_dashboards, "dashboard")
# Distinct so the context-ref array below holds one entry per dashboard, not one per blocked tile.
dashboards_with_blocked_tiles = (
diff --git a/products/tasks/backend/logic/user_task_summaries.py b/products/tasks/backend/logic/user_task_summaries.py
index 84cd2471b33c..dad2bddd3357 100644
--- a/products/tasks/backend/logic/user_task_summaries.py
+++ b/products/tasks/backend/logic/user_task_summaries.py
@@ -6,7 +6,8 @@ state, so the query pulls those keys out in Postgres instead of loading whole st
"""
import datetime
-from collections.abc import Collection
+from collections.abc import Collection, Mapping
+from typing import Any
from django.db.models.fields.json import KeyTextTransform, KeyTransform
@@ -93,7 +94,7 @@ def list_user_task_summaries(
}
summaries: list[UserTaskSummary] = []
for task in tasks:
- run = latest_runs.get(task["id"], {})
+ run: Mapping[str, Any] = latest_runs.get(task["id"], {})
summary = (run.get("summary") or run.get("prior_summary") or "").strip() or None
# An explicit tag list on the run wins, even an empty one, as in `task_tags_from_state`.
tags = run.get("run_tags") if isinstance(run.get("run_tags"), list) else run.get("prior_tags")
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index a1ee3cc4dfcb..0d4a43bba5f2 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -950,10 +950,10 @@ class TaskWriteSerializer(serializers.Serializer):
super().__init__(*args, **kwargs)
# SignalReport is scoped to the request team by the field; bind its queryset lazily so
# importing this module never touches the signals model at import time.
- cast(
- serializers.PrimaryKeyRelatedField, self.fields["signal_report"]
- ).queryset = tasks_facade.signal_report_queryset()
- cast(serializers.PrimaryKeyRelatedField, self.fields["channel"]).queryset = tasks_facade.channel_queryset()
+ signal_report_field = cast(serializers.PrimaryKeyRelatedField, self.fields["signal_report"])
+ signal_report_field.queryset = tasks_facade.signal_report_queryset() # type: ignore[arg-type] # DRF stubs type queryset as a Manager, which django-stubs treats as a descriptor
+ channel_field = cast(serializers.PrimaryKeyRelatedField, self.fields["channel"])
+ channel_field.queryset = tasks_facade.channel_queryset() # type: ignore[arg-type] # DRF stubs type queryset as a Manager, which django-stubs treats as a descriptor
def validate_channel(self, value):
request = self.context.get("request")
@@ -4158,9 +4158,8 @@ class WarmTaskRequestSerializer(serializers.Serializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- cast(
- serializers.PrimaryKeyRelatedField, self.fields["signal_report"]
- ).queryset = tasks_facade.signal_report_queryset()
+ signal_report_field = cast(serializers.PrimaryKeyRelatedField, self.fields["signal_report"])
+ signal_report_field.queryset = tasks_facade.signal_report_queryset() # type: ignore[arg-type] # DRF stubs type queryset as a Manager, which django-stubs treats as a descriptor
def validate_repository(self, value: str | None) -> str | None:
if value is None:
diff --git a/products/tasks/backend/repository_resolver.py b/products/tasks/backend/repository_resolver.py
index 7d1e64190149..1ceb4a31a896 100644
--- a/products/tasks/backend/repository_resolver.py
+++ b/products/tasks/backend/repository_resolver.py
@@ -47,13 +47,13 @@ async def resolve_repositories_for_issue(issue) -> list[RepositoryContext]:
"""
Task = apps.get_model("tasks", "Task")
- if issue.repository_scope == Task.RepositoryScope.SINGLE:
+ if issue.repository_scope == Task.RepositoryScope.SINGLE: # type: ignore[attr-defined] # Task has no RepositoryScope; nothing calls this module
return await resolve_single_repository(issue)
- elif issue.repository_scope == Task.RepositoryScope.MULTIPLE:
+ elif issue.repository_scope == Task.RepositoryScope.MULTIPLE: # type: ignore[attr-defined] # Task has no RepositoryScope; nothing calls this module
return await resolve_multiple_repositories(issue)
- elif issue.repository_scope == Task.RepositoryScope.SMART_SELECT:
+ elif issue.repository_scope == Task.RepositoryScope.SMART_SELECT: # type: ignore[attr-defined] # Task has no RepositoryScope; nothing calls this module
return await resolve_smart_select_repositories(issue)
# Fallback to legacy behavior
@@ -251,7 +251,7 @@ async def _update_issue_selected_repositories(issue, selected_repos: list[Reposi
# Update the issue's repository config
issue.repository_config = {**issue.repository_config, "available_repositories": available_repositories}
- await Task.objects.filter(id=issue.id).aupdate(repository_config=issue.repository_config)
+ await Task.objects.filter(id=issue.id).aupdate(repository_config=issue.repository_config) # type: ignore[misc] # Task has no repository_config; nothing calls this module
# Smart selection AI helpers (placeholder for future implementation)
diff --git a/products/warehouse_sources/backend/stalled_schedules.py b/products/warehouse_sources/backend/stalled_schedules.py
index b305abab98bc..b56d70ecf8de 100644
--- a/products/warehouse_sources/backend/stalled_schedules.py
+++ b/products/warehouse_sources/backend/stalled_schedules.py
@@ -187,7 +187,7 @@ def find_stalled_schemas(
if source_type is not None:
queryset = queryset.filter(source__source_type__iexact=source_type)
- queryset = queryset.select_related("source").order_by("latest_run_at")
+ queryset = queryset.select_related("source").order_by(F("latest_run_at"))
if limit is not None:
queryset = queryset[:limit]
diff --git a/products/web_analytics/backend/achievements/tasks.py b/products/web_analytics/backend/achievements/tasks.py
index 999bc2598d7a..cd6fca4b4480 100644
--- a/products/web_analytics/backend/achievements/tasks.py
+++ b/products/web_analytics/backend/achievements/tasks.py
@@ -164,7 +164,7 @@ def get_or_create_progress(ctx: EvalContext, track: TrackDefinition) -> WebAnaly
canonical_team_id = ctx.team.parent_team_id or ctx.team.id
progress, _ = WebAnalyticsAchievementProgress.objects.for_team(canonical_team_id, canonical=True).get_or_create(
team_id=canonical_team_id,
- user_id=user_id,
+ user_id=user_id, # type: ignore[misc] # nullable FK; django-stubs drops None from *_id lookups
track_key=str(track.key),
defaults={"current_stage": 0, "progress_value": 0, "state": {}},
)
diff --git a/products/wizard/backend/tests/runs/test_cloud_activities.py b/products/wizard/backend/tests/runs/test_cloud_activities.py
index a9ae54e4a5ca..b8e65737d368 100644
--- a/products/wizard/backend/tests/runs/test_cloud_activities.py
+++ b/products/wizard/backend/tests/runs/test_cloud_activities.py
@@ -183,6 +183,7 @@ def test_provision_worker_uses_persisted_run_identity(team, user) -> None:
worker_record = apps.get_model("wizard", "WizardWorker").objects.for_team(team.id).get(run_id=run.id)
assert worker_record.sandbox_id == "worker-id"
assert worker_record.cleanup_status == "active"
+ assert worker_record.resource_usage is not None
assert worker_record.resource_usage["cpu_cores"] == 2.0
provision.reset_mock()
@@ -466,5 +467,6 @@ def test_create_run_artifacts_persists_git_diff_and_pull_request(_write: MagicMo
assert pull_request_artifact.number == pull_request.number
assert wizard_facade.get_run(team.id, run.id).status == WizardRunStatus.COMPLETED
worker = apps.get_model("wizard", "WizardWorker").objects.for_team(team.id).get(run_id=run.id)
+ assert worker.resource_usage is not None
assert worker.resource_usage["provider_cpu_usage_usec"] == 1_000_000
assert worker.resource_usage["provider_billed_cpu_usage_usec"] == 2_000_000
diff --git a/pyproject.toml b/pyproject.toml
index bd5cc3d66dd5..ca6884e22660 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -236,10 +236,10 @@ dev = [
"import-linter~=2.11",
"deepdiff~=8.6.1",
"django-linear-migrations~=2.19.0",
- "django-stubs~=5.2.0",
+ "django-stubs~=6.1.0",
# django-stubs requires this unbounded, so an upgrade run drifts it to a version
# that models a different Django. Hold it on the line django-stubs is on.
- "django-stubs-ext~=5.2.5",
+ "django-stubs-ext~=6.1.0",
"djangorestframework-stubs~=3.16.0",
"faker==17.5.0",
"fakeredis[lua]==2.23.3",
diff --git a/uv.lock b/uv.lock
index 68238894db6e..c83253f2bf54 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2166,7 +2166,7 @@ celery = [
[[package]]
name = "django-stubs"
-version = "5.2.5"
+version = "6.1.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "django" },
@@ -2174,22 +2174,22 @@ dependencies = [
{ name = "types-pyyaml" },
{ name = "typing-extensions" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/e1/8e/286150f593481c33f54d14efb58d72178f159d57d31043529d38bbc98e2f/django_stubs-5.2.5.tar.gz", hash = "sha256:fc78384e28d8c5292d60983075a5934f644f7c304c25ae2793fc57aa66d5018b", size = 247794, upload-time = "2025-09-12T19:29:49.636Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/56/d0/00a9af43bf65ee54706e29b1c41b3a00d7a97157fbf97ed3038dcc73d584/django_stubs-6.1.2.tar.gz", hash = "sha256:d62b15fa5cbae79b1922d015e1454d299959d230221dadb23f65c749480b97ec", size = 295860, upload-time = "2026-10-05T06:47:17.595Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/2f/02/cdbf7652ef2c9a7a1fed7c279484b7f3806f15b1bb34aec9fef8e8cfacbf/django_stubs-5.2.5-py3-none-any.whl", hash = "sha256:223c1a3324cd4873b7629dec6e9adbe224a94508284c1926b25fddff7a92252b", size = 490196, upload-time = "2025-09-12T19:29:47.954Z" },
+ { url = "https://files.pythonhosted.org/packages/96/36/206be00ba6aaf21c72cf61fd38cee492c7dcf51eac72fd61a9f7ddd0f916/django_stubs-6.1.2-py3-none-any.whl", hash = "sha256:ffb6e74f54b8c1f9b2f3bc4852c5abbaa2324b2a7cb1c51854c5f95abe67165c", size = 559846, upload-time = "2026-10-05T06:47:15.889Z" },
]
[[package]]
name = "django-stubs-ext"
-version = "5.2.5"
+version = "6.1.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "django" },
{ name = "typing-extensions" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/16/94/c9b8f4c47084a0fa666da9066c36771098101932688adf2c17a40fab79c2/django_stubs_ext-5.2.5.tar.gz", hash = "sha256:ecc628df29d36cede638567c4e33ff485dd7a99f1552ad0cece8c60e9c3a8872", size = 6489, upload-time = "2025-09-12T19:29:06.008Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/d9/62/de532d58736d671b9ac0c0467909a9429758ae579d636e868ce74519566b/django_stubs_ext-6.1.2.tar.gz", hash = "sha256:2142da7fffbbe897ccecf9b4c97e09ea1a2e9291760b0a824b4c402b375ce6f9", size = 7221, upload-time = "2026-10-05T06:46:43.717Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/e0/fe/a85a105fddffadb4a8d50e500caeee87d836b679d51a19d52dfa0cc6c660/django_stubs_ext-5.2.5-py3-none-any.whl", hash = "sha256:9b4b8ac9d32f7e6c304fd05477f8688fae6ed57f6a0f9f4d074f9e55b5a3da14", size = 9310, upload-time = "2025-09-12T19:29:04.62Z" },
+ { url = "https://files.pythonhosted.org/packages/21/bb/393c3c1e24aaf37d62918ea50f3ea22e30d5f3162fc62f4c3bf3275e5ed3/django_stubs_ext-6.1.2-py3-none-any.whl", hash = "sha256:7334e687ab6dc78a6c3da90ab1ccb0e412efd827ea11de8d3f85adbad948abb1", size = 10850, upload-time = "2026-10-05T06:46:42.647Z" },
]
[[package]]
@@ -6387,8 +6387,8 @@ dev = [
{ name = "debugpy", specifier = "~=1.8.0" },
{ name = "deepdiff", specifier = "~=8.6.1" },
{ name = "django-linear-migrations", specifier = "~=2.19.0" },
- { name = "django-stubs", specifier = "~=5.2.0" },
- { name = "django-stubs-ext", specifier = "~=5.2.5" },
+ { name = "django-stubs", specifier = "~=6.1.0" },
+ { name = "django-stubs-ext", specifier = "~=6.1.0" },
{ name = "djangorestframework-stubs", specifier = "~=3.16.0" },
{ name = "faker", specifier = "==17.5.0" },
{ name = "fakeredis", extras = ["lua"], specifier = "==2.23.3" },