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(python): apply 3.13 typing sweep (UP043/UP035/B911) (#60440)

Raúl Negrón-Otero5f63d134ed6f
diff --git a/ee/api/conversation.py b/ee/api/conversation.py
index 322364ce9058..c76038e993f3 100644
--- a/ee/api/conversation.py
+++ b/ee/api/conversation.py
@@ -451,7 +451,7 @@ class ConversationViewSet(
async def async_stream(
workflow_inputs: ChatAgentWorkflowInputs | ResearchAgentWorkflowInputs,
- ) -> AsyncGenerator[bytes, None]:
+ ) -> AsyncGenerator[bytes]:
SSE_KEEPALIVE_COMMENT = b": keepalive\n\n"
SSE_KEEPALIVE_INTERVAL = 15 # seconds — well under typical LB idle timeouts (60s)
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.py
index 2e32e4bce14d..99f30d9b1a24 100644
--- a/ee/api/session_summaries.py
+++ b/ee/api/session_summaries.py
@@ -519,7 +519,7 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
session_ids=session_ids,
)
- async def async_stream() -> AsyncGenerator[bytes, None]:
+ async def async_stream() -> AsyncGenerator[bytes]:
SSE_KEEPALIVE_COMMENT = b": keepalive\n\n"
SSE_KEEPALIVE_INTERVAL = 15 # seconds — well under typical LB idle timeouts (60s)
diff --git a/ee/hogai/chat_agent/runner.py b/ee/hogai/chat_agent/runner.py
index 2f6f57d0859c..d7ce6872c4e6 100644
--- a/ee/hogai/chat_agent/runner.py
+++ b/ee/hogai/chat_agent/runner.py
@@ -150,7 +150,7 @@ class ChatAgentRunner(BaseAgentRunner):
stream_subgraphs: bool = True,
stream_first_message: bool = True,
stream_only_assistant_messages: bool = False,
- ) -> AsyncGenerator[AssistantOutput, None]:
+ ) -> AsyncGenerator[AssistantOutput]:
if self._selected_agent_mode and self._user:
with _tracer.start_as_current_span("posthoganalytics.capture"):
await database_sync_to_async(posthoganalytics.capture)(
diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.py
index 488601fb3601..26cc4bcb4e51 100644
--- a/ee/hogai/core/runner.py
+++ b/ee/hogai/core/runner.py
@@ -255,7 +255,7 @@ class BaseAgentRunner(ABC):
stream_subgraphs: bool = True,
stream_first_message: bool = True,
stream_only_assistant_messages: bool = False,
- ) -> AsyncGenerator[AssistantOutput, None]:
+ ) -> AsyncGenerator[AssistantOutput]:
state = await self._init_or_update_state()
config = self._get_config()
diff --git a/ee/hogai/eval/ci/conftest.py b/ee/hogai/eval/ci/conftest.py
index db896ee803c9..0c75e053e62e 100644
--- a/ee/hogai/eval/ci/conftest.py
+++ b/ee/hogai/eval/ci/conftest.py
@@ -111,19 +111,19 @@ def call_root_for_insight_generation(demo_org_team_user):
def demo_org_team_user(
set_up_evals, # noqa: F811
django_db_blocker,
-) -> Generator[tuple[Organization, Team, User], None, None]:
+) -> Generator[tuple[Organization, Team, User]]:
yield create_demo_org_team_user(django_db_blocker)
@pytest.fixture(scope="session", autouse=True)
-def core_memory(demo_org_team_user, django_db_blocker) -> Generator[CoreMemory, None, None]:
+def core_memory(demo_org_team_user, django_db_blocker) -> Generator[CoreMemory]:
yield create_core_memory(demo_org_team_user[1], django_db_blocker)
@pytest.fixture
def dashboard_with_insights(
demo_org_team_user,
-) -> Generator[DashboardWithInsightsFixture, None, None]:
+) -> Generator[DashboardWithInsightsFixture]:
"""Creates a dashboard with 3 insights and 1 replacement insight for testing UpsertDashboardTool."""
yield create_dashboard_with_insights(*demo_org_team_user)
# No manual cleanup needed - Django's test framework handles rollback automatically
diff --git a/ee/hogai/eval/offline/conftest.py b/ee/hogai/eval/offline/conftest.py
index 54fdab91da24..3cbde29f15b0 100644
--- a/ee/hogai/eval/offline/conftest.py
+++ b/ee/hogai/eval/offline/conftest.py
@@ -31,7 +31,7 @@ from ee.hogai.eval.schema import DatasetInput, EvalsDockerImageConfig
@pytest.fixture(scope="session")
-def dagster_context() -> Generator[PipesContext, None, None]:
+def dagster_context() -> Generator[PipesContext]:
with open_dagster_pipes() as context:
yield context
@@ -120,7 +120,7 @@ def eval_ctx(
set_up_evals, # noqa: F811
dagster_context: PipesContext,
django_db_blocker,
-) -> Generator[EvaluationContext, None, None]:
+) -> Generator[EvaluationContext]:
"""
Script that restores dumped Django models and patches AI query runners.
Creates teams with team_id=project_id for the same single user and organization,
diff --git a/ee/hogai/eval/offline/snapshot_loader.py b/ee/hogai/eval/offline/snapshot_loader.py
index 57b3971b94bd..3e2aa79ab3d7 100644
--- a/ee/hogai/eval/offline/snapshot_loader.py
+++ b/ee/hogai/eval/offline/snapshot_loader.py
@@ -116,7 +116,7 @@ class SnapshotLoader:
content = await response["Body"].read()
return BytesIO(content)
- def _parse_snapshot_to_schema(self, schema: type[T], buffer: BytesIO) -> Generator[T, None, None]:
+ def _parse_snapshot_to_schema(self, schema: type[T], buffer: BytesIO) -> Generator[T]:
for record in reader(buffer):
yield schema.model_validate(record)
diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.py
index 093c748c4a36..41c0a255d24f 100644
--- a/ee/hogai/eval/sandboxed/conftest.py
+++ b/ee/hogai/eval/sandboxed/conftest.py
@@ -90,7 +90,7 @@ def django_db_setup(
django_db_keepdb: bool,
django_db_createdb: bool,
django_db_modify_db_settings: None,
-) -> Generator[None, None, None]:
+) -> Generator[None]:
"""Create the eval test DB even though eval items have no django_db marker."""
from django.test.utils import setup_databases, teardown_databases
@@ -116,7 +116,7 @@ def django_db_setup(
@pytest.fixture(scope="session", autouse=True)
-def _sandboxed_eval_database_access(set_up_evals, django_db_blocker) -> Generator[None, None, None]: # noqa: F811
+def _sandboxed_eval_database_access(set_up_evals, django_db_blocker) -> Generator[None]: # noqa: F811
"""Use one committed eval database instead of per-test transactions."""
django_db_blocker.unblock()
yield
@@ -208,7 +208,7 @@ def _django_live_server(_sandboxed_eval_database_access):
@pytest.fixture(scope="session", autouse=True)
-def _sandboxed_local_skills(_sandbox_settings) -> Generator[Path, None, None]:
+def _sandboxed_local_skills(_sandbox_settings) -> Generator[Path]:
"""Build local skills once per session; bind-mount into every sandbox.
Uses a content-hash cache so repeat runs skip the build when nothing has
@@ -234,7 +234,7 @@ def _sandboxed_local_skills(_sandbox_settings) -> Generator[Path, None, None]:
@pytest.fixture(scope="session", autouse=True)
-def _temporal_test_server() -> Generator[tuple[str, str, str], None, None]:
+def _temporal_test_server() -> Generator[tuple[str, str, str]]:
"""Start an isolated Temporal dev server for sandboxed eval workflows."""
loop = asyncio.new_event_loop()
temporal_namespace = settings.TEMPORAL_NAMESPACE
@@ -265,7 +265,7 @@ def _sandbox_settings(
_django_live_server: object,
_llm_gateway: object,
_temporal_test_server: tuple[str, str, str],
-) -> Generator[None, None, None]:
+) -> Generator[None]:
"""Configure Django settings required by the sandbox/temporal activities.
All URLs use ``host.docker.internal`` so they're reachable from inside
diff --git a/ee/hogai/eval/schema.py b/ee/hogai/eval/schema.py
index 2ec739da243b..d3a8f25b5be3 100644
--- a/ee/hogai/eval/schema.py
+++ b/ee/hogai/eval/schema.py
@@ -20,12 +20,12 @@ T = TypeVar("T", bound=Model)
class BaseSnapshot(AvroBase, ABC, Generic[T]):
@classmethod
@abstractmethod
- def serialize_for_team(cls, *, team_id: int) -> Generator[Self, None, None]:
+ def serialize_for_team(cls, *, team_id: int) -> Generator[Self]:
raise NotImplementedError
@classmethod
@abstractmethod
- def deserialize_for_team(cls, models: Sequence[Self], *, team_id: int, project_id: int) -> Generator[T, None, None]:
+ def deserialize_for_team(cls, models: Sequence[Self], *, team_id: int, project_id: int) -> Generator[T]:
raise NotImplementedError
@@ -40,9 +40,7 @@ class TeamSnapshot(BaseSnapshot[Team]):
yield TeamSnapshot(name=team.name, test_account_filters=json.dumps(team.test_account_filters))
@classmethod
- def deserialize_for_team(
- cls, models: Sequence[Self], *, team_id: int, project_id: int
- ) -> Generator[Team, None, None]:
+ def deserialize_for_team(cls, models: Sequence[Self], *, team_id: int, project_id: int) -> Generator[Team]:
for model in models:
yield Team(
id=team_id,
diff --git a/ee/hogai/insights_assistant.py b/ee/hogai/insights_assistant.py
index cb4f8a8389e9..7b3fc57519bc 100644
--- a/ee/hogai/insights_assistant.py
+++ b/ee/hogai/insights_assistant.py
@@ -97,7 +97,7 @@ class InsightsAssistant(BaseAgentRunner):
stream_subgraphs: bool = True,
stream_first_message: bool = False,
stream_only_assistant_messages: bool = False,
- ) -> AsyncGenerator[AssistantOutput, None]:
+ ) -> AsyncGenerator[AssistantOutput]:
last_ai_message: AssistantMessage | None = None
last_artifact_content: VisualizationArtifactContent | None = None
diff --git a/ee/hogai/llm_traces_summaries/utils/load_from_csv.py b/ee/hogai/llm_traces_summaries/utils/load_from_csv.py
index 295fff1ae31e..d80dfdd07e2d 100644
--- a/ee/hogai/llm_traces_summaries/utils/load_from_csv.py
+++ b/ee/hogai/llm_traces_summaries/utils/load_from_csv.py
@@ -13,7 +13,7 @@ logger = structlog.get_logger(__name__)
csv.field_size_limit(sys.maxsize)
-def load_traces_from_csv_files(csv_paths: list[str]) -> Generator[LLMTrace, None, None]:
+def load_traces_from_csv_files(csv_paths: list[str]) -> Generator[LLMTrace]:
"""Load traces from CSV files, useful for local development."""
# The assumption is that the CSV was exported through default Traces query runner query
fields_to_column_mapping = {
diff --git a/ee/hogai/research_agent/runner.py b/ee/hogai/research_agent/runner.py
index 0f7f7f2cff27..9b37282740b4 100644
--- a/ee/hogai/research_agent/runner.py
+++ b/ee/hogai/research_agent/runner.py
@@ -110,7 +110,7 @@ class ResearchAgentRunner(BaseAgentRunner):
stream_subgraphs: bool = True,
stream_first_message: bool = True,
stream_only_assistant_messages: bool = False,
- ) -> AsyncGenerator[AssistantOutput, None]:
+ ) -> AsyncGenerator[AssistantOutput]:
if self._user:
with _tracer.start_as_current_span("posthoganalytics.capture"):
await database_sync_to_async(posthoganalytics.capture)(
diff --git a/ee/hogai/sandbox/executor.py b/ee/hogai/sandbox/executor.py
index 3462e381c499..ee6b5d1ecf31 100644
--- a/ee/hogai/sandbox/executor.py
+++ b/ee/hogai/sandbox/executor.py
@@ -186,7 +186,7 @@ def handle_sandbox_message(
def _make_streaming_response(
- async_generator_factory: Callable[[], AsyncGenerator[bytes, None]],
+ async_generator_factory: Callable[[], AsyncGenerator[bytes]],
) -> StreamingHttpResponse:
"""Create a StreamingHttpResponse that works under both ASGI and WSGI."""
return StreamingHttpResponse(
@@ -243,7 +243,7 @@ async def _sandbox_stream(
conversation_id: str | None = None,
user_content: str | None = None,
team_id: int | None = None,
-) -> AsyncGenerator[bytes, None]:
+) -> AsyncGenerator[bytes]:
"""Stream sandbox events from Redis to the browser as SSE.
Reads events in a background task and funnels them through an
diff --git a/ee/hogai/stream/redis_stream.py b/ee/hogai/stream/redis_stream.py
index 3cd1645a23b5..0af81867452e 100644
--- a/ee/hogai/stream/redis_stream.py
+++ b/ee/hogai/stream/redis_stream.py
@@ -282,7 +282,7 @@ class ConversationRedisStream:
start_id: str = "0",
block_ms: int = 50, # Block for 50ms waiting for new messages
count: Optional[int] = CONVERSATION_STREAM_CONCURRENT_READ_COUNT,
- ) -> AsyncGenerator[StreamEvent, None]:
+ ) -> AsyncGenerator[StreamEvent]:
"""
Read updates from Redis stream.
@@ -377,7 +377,7 @@ class ConversationRedisStream:
async def write_to_stream(
self,
- generator: AsyncGenerator[AssistantOutput, None],
+ generator: AsyncGenerator[AssistantOutput],
callback: Callable[[], None] | None = None,
emit_completion: bool = True,
) -> None:
diff --git a/ee/hogai/utils/aio.py b/ee/hogai/utils/aio.py
index f2b5ede41f6b..c51fdb314366 100644
--- a/ee/hogai/utils/aio.py
+++ b/ee/hogai/utils/aio.py
@@ -9,7 +9,7 @@ import structlog
logger = structlog.get_logger(__name__)
-def async_to_sync(async_handler: Callable[[], AsyncGenerator[Any, None]]) -> Generator[Any, None, None]:
+def async_to_sync(async_handler: Callable[[], AsyncGenerator[Any]]) -> Generator[Any]:
"""Converts an async iterator to a sync generator."""
q: Queue[Any] = Queue(maxsize=5000)
diff --git a/ee/hogai/utils/embeddings.py b/ee/hogai/utils/embeddings.py
index 0c296a0b632f..b4a630c5bd13 100644
--- a/ee/hogai/utils/embeddings.py
+++ b/ee/hogai/utils/embeddings.py
@@ -38,7 +38,7 @@ def get_async_azure_embeddings_client() -> EmbeddingsClientAsync:
)
-async def aembed_documents(client: EmbeddingsClientAsync, texts: list[str]) -> Generator[list[float], None, None]:
+async def aembed_documents(client: EmbeddingsClientAsync, texts: list[str]) -> Generator[list[float]]:
"""Embed documents for storing in a vector database."""
response = await client.embed(
input=texts,
diff --git a/posthog/caching/warming.py b/posthog/caching/warming.py
index d482b47ac1c7..2c2e08dd8fd5 100644
--- a/posthog/caching/warming.py
+++ b/posthog/caching/warming.py
@@ -81,7 +81,7 @@ def teams_enabled_for_cache_warming() -> list[int]:
return enabled_team_ids
-def insights_to_keep_fresh(team: Team, shared_only: bool = False) -> Generator[tuple[int, Optional[int]], None, None]:
+def insights_to_keep_fresh(team: Team, shared_only: bool = False) -> Generator[tuple[int, Optional[int]]]:
"""
This is the place to decide which insights should be kept warm for the provided team.
The reasoning is that this will be a yes or no decision. If we need to keep it warm, we try our best
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 74454f54e30b..67a6bd1af76c 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -670,7 +670,7 @@ class QueryCounter:
@contextmanager
-def tags_context(**tags_to_set: Any) -> Generator[None, None, None]:
+def tags_context(**tags_to_set: Any) -> Generator[None]:
"""
Context manager that saves all query tags on enter and restores them on exit.
Optionally accepts key-value pairs to set after saving the original tags.
diff --git a/posthog/clickhouse/system_status.py b/posthog/clickhouse/system_status.py
index 0820410de0be..565d6b1c70c4 100644
--- a/posthog/clickhouse/system_status.py
+++ b/posthog/clickhouse/system_status.py
@@ -23,7 +23,7 @@ FLAMEGRAPH_PL = abspath(join(dirname(__file__), "bin", "flamegraph.pl"))
SystemStatusRow = dict
-def system_status() -> Generator[SystemStatusRow, None, None]:
+def system_status() -> Generator[SystemStatusRow]:
alive = is_alive()
yield {
"key": "clickhouse_alive",
diff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.py
index bed2263f8e24..21af9a0c77a3 100644
--- a/posthog/dags/common/resources.py
+++ b/posthog/dags/common/resources.py
@@ -242,7 +242,7 @@ class PostgresURLResource(dagster.ConfigurableResource):
@dagster.resource
-def kafka_producer_resource(context: dagster.InitResourceContext) -> Generator[_KafkaProducer, None, None]:
+def kafka_producer_resource(context: dagster.InitResourceContext) -> Generator[_KafkaProducer]:
"""Yield a singleton Kafka producer bound to the INGESTION (WarpStream) profile; flush on teardown.
Every existing consumer of this resource (`detach_distinct_id_op`,
diff --git a/posthog/demo/matrix/models.py b/posthog/demo/matrix/models.py
index 93b04b1b5016..2c84b904ce1f 100644
--- a/posthog/demo/matrix/models.py
+++ b/posthog/demo/matrix/models.py
@@ -217,7 +217,7 @@ class SimServerClient(SimClient):
distinct_id: str,
input_state: Any,
trace_id: Optional[str] = None,
- ) -> Generator[tuple[str, Callable], None, None]:
+ ) -> Generator[tuple[str, Callable]]:
"""Capture an AI generation event."""
trace_id = trace_id or str(uuid4())
output_state = None
diff --git a/posthog/hogql/resolver_utils.py b/posthog/hogql/resolver_utils.py
index 9306d0cccdec..b9e5be3a2381 100644
--- a/posthog/hogql/resolver_utils.py
+++ b/posthog/hogql/resolver_utils.py
@@ -251,7 +251,7 @@ def expand_hogqlx_query(node: ast.HogQLXTag, team_id: Optional[int]):
raise ResolutionError(f"Error parsing query tag: {e}", start=node.start, end=node.end)
-def extract_select_queries(select: ast.SelectSetQuery | ast.SelectQuery) -> Generator[ast.SelectQuery, None, None]:
+def extract_select_queries(select: ast.SelectSetQuery | ast.SelectQuery) -> Generator[ast.SelectQuery]:
if isinstance(select, ast.SelectQuery):
yield select
else:
diff --git a/posthog/hogql_queries/insights/funnels/utils.py b/posthog/hogql_queries/insights/funnels/utils.py
index 948de935342c..46d1fb4b5bc3 100644
--- a/posthog/hogql_queries/insights/funnels/utils.py
+++ b/posthog/hogql_queries/insights/funnels/utils.py
@@ -1,5 +1,6 @@
+from typing import TypeIs
+
from rest_framework.exceptions import ValidationError
-from typing_extensions import TypeIs
from posthog.schema import (
ActionsNode,
diff --git a/posthog/hogql_queries/query_cache.py b/posthog/hogql_queries/query_cache.py
index fa05ad47a4d2..cab777565df2 100644
--- a/posthog/hogql_queries/query_cache.py
+++ b/posthog/hogql_queries/query_cache.py
@@ -131,7 +131,7 @@ def _get_cache_metrics(registry: Optional[CollectorRegistry] = None) -> CacheMet
@contextmanager
-def get_cache_metrics_context(registry_name: str) -> Generator[CacheMetrics, None, None]:
+def get_cache_metrics_context(registry_name: str) -> Generator[CacheMetrics]:
"""Context manager that yields the appropriate cache metrics based on execution context."""
if _is_short_lived_context():
with pushed_metrics_registry(registry_name) as registry:
diff --git a/posthog/hogql_queries/utils/time_sliced_query.py b/posthog/hogql_queries/utils/time_sliced_query.py
index 3e92227995bb..17c0cc698ae9 100644
--- a/posthog/hogql_queries/utils/time_sliced_query.py
+++ b/posthog/hogql_queries/utils/time_sliced_query.py
@@ -30,7 +30,7 @@ def time_sliced_results(
order_by_earliest: bool,
make_runner: Callable[[DateRange], TimeSliceableRunner],
analytics_props: Any = None,
-) -> Generator[Any, None, None]:
+) -> Generator[Any]:
"""
A generator that yields results by splitting the query into progressive time slices.
diff --git a/posthog/models/resource_transfer/inter_project_transferer.py b/posthog/models/resource_transfer/inter_project_transferer.py
index 955daabf465b..286962a85f14 100644
--- a/posthog/models/resource_transfer/inter_project_transferer.py
+++ b/posthog/models/resource_transfer/inter_project_transferer.py
@@ -210,7 +210,7 @@ def dag_sort_duplication_graph(graph: Iterable[ResourceTransferVertex]) -> tuple
def build_resource_duplication_graph(
resource: Any, exclude_set: set[ResourceTransferKey], depth: int = 1
-) -> Generator[ResourceTransferVertex, None, None]:
+) -> Generator[ResourceTransferVertex]:
"""
This function builds a graph representing the relations in the connected component that `resource` is a member of.
diff --git a/posthog/models/scoping/__init__.py b/posthog/models/scoping/__init__.py
index fd1f20849c03..08b1034e4d64 100644
--- a/posthog/models/scoping/__init__.py
+++ b/posthog/models/scoping/__init__.py
@@ -56,7 +56,7 @@ def reset_current_team_id(token: Token[int | None]) -> None:
@contextmanager
-def team_scope(team_id: int, *, canonical: bool = False) -> Generator[None, None, None]:
+def team_scope(team_id: int, *, canonical: bool = False) -> Generator[None]:
"""
Context manager to set the current team_id for a block of code.
@@ -92,7 +92,7 @@ def team_scope(team_id: int, *, canonical: bool = False) -> Generator[None, None
@contextmanager
-def unscoped() -> Generator[None, None, None]:
+def unscoped() -> Generator[None]:
"""
Context manager to temporarily disable automatic team scoping.
diff --git a/posthog/personhog_client/proto/generated/personhog/types/v1/cohort_pb2.pyi b/posthog/personhog_client/proto/generated/personhog/types/v1/cohort_pb2.pyi
index d8ddc2a12f42..f72a57344e41 100644
--- a/posthog/personhog_client/proto/generated/personhog/types/v1/cohort_pb2.pyi
+++ b/posthog/personhog_client/proto/generated/personhog/types/v1/cohort_pb2.pyi
@@ -1,7 +1,9 @@
-from typing import (
- ClassVar as _ClassVar,
+from collections.abc import (
Iterable as _Iterable,
Mapping as _Mapping,
+)
+from typing import (
+ ClassVar as _ClassVar,
Optional as _Optional,
Union as _Union,
)
diff --git a/posthog/personhog_client/proto/generated/personhog/types/v1/common_pb2.pyi b/posthog/personhog_client/proto/generated/personhog/types/v1/common_pb2.pyi
index e93292970472..30dda91c6770 100644
--- a/posthog/personhog_client/proto/generated/personhog/types/v1/common_pb2.pyi
+++ b/posthog/personhog_client/proto/generated/personhog/types/v1/common_pb2.pyi
@@ -1,6 +1,6 @@
+from collections.abc import Iterable as _Iterable
from typing import (
ClassVar as _ClassVar,
- Iterable as _Iterable,
Optional as _Optional,
Union as _Union,
)
diff --git a/posthog/personhog_client/proto/generated/personhog/types/v1/feature_flag_pb2.pyi b/posthog/personhog_client/proto/generated/personhog/types/v1/feature_flag_pb2.pyi
index 5a2158e35d2f..09197075307d 100644
--- a/posthog/personhog_client/proto/generated/personhog/types/v1/feature_flag_pb2.pyi
+++ b/posthog/personhog_client/proto/generated/personhog/types/v1/feature_flag_pb2.pyi
@@ -1,7 +1,9 @@
-from typing import (
- ClassVar as _ClassVar,
+from collections.abc import (
Iterable as _Iterable,
Mapping as _Mapping,
+)
+from typing import (
+ ClassVar as _ClassVar,
Optional as _Optional,
Union as _Union,
)
diff --git a/posthog/personhog_client/proto/generated/personhog/types/v1/group_pb2.pyi b/posthog/personhog_client/proto/generated/personhog/types/v1/group_pb2.pyi
index ce6960c3bb0f..6872027161f3 100644
--- a/posthog/personhog_client/proto/generated/personhog/types/v1/group_pb2.pyi
+++ b/posthog/personhog_client/proto/generated/personhog/types/v1/group_pb2.pyi
@@ -1,7 +1,9 @@
-from typing import (
- ClassVar as _ClassVar,
+from collections.abc import (
Iterable as _Iterable,
Mapping as _Mapping,
+)
+from typing import (
+ ClassVar as _ClassVar,
Optional as _Optional,
Union as _Union,
)
diff --git a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi
index af816e3be8fc..8a1f72146690 100644
--- a/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi
+++ b/posthog/personhog_client/proto/generated/personhog/types/v1/person_pb2.pyi
@@ -1,7 +1,9 @@
-from typing import (
- ClassVar as _ClassVar,
+from collections.abc import (
Iterable as _Iterable,
Mapping as _Mapping,
+)
+from typing import (
+ ClassVar as _ClassVar,
Optional as _Optional,
Union as _Union,
)
diff --git a/posthog/queries/column_optimizer/foss_column_optimizer.py b/posthog/queries/column_optimizer/foss_column_optimizer.py
index 70d06ea5c2c8..98728a4f75af 100644
--- a/posthog/queries/column_optimizer/foss_column_optimizer.py
+++ b/posthog/queries/column_optimizer/foss_column_optimizer.py
@@ -168,7 +168,7 @@ class FOSSColumnOptimizer:
}
)
- def entities_used_in_filter(self) -> Generator[Entity, None, None]:
+ def entities_used_in_filter(self) -> Generator[Entity]:
yield from self.filter.entities
yield from cast(list[Entity], self.filter.exclusions)
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 3dc62df345a2..ceb03bf6485d 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -582,7 +582,7 @@ def ensure_not_weak(etag: str) -> str:
@contextmanager
-def stream_from(url: str, headers: dict | None = None) -> Generator[requests.Response, None, None]:
+def stream_from(url: str, headers: dict | None = None) -> Generator[requests.Response]:
"""
Stream data from a URL using optional headers.
@@ -1535,7 +1535,7 @@ class SessionRecordingViewSet(
product_context: str | None = None,
custom_tags: dict[str, str] | None = None,
force_restart: bool = False,
- ) -> AsyncGenerator[str, None]:
+ ) -> AsyncGenerator[str]:
"""Stream video-based summarization progress events and final summary to the client.
Progress events (``session-summary-progress``) carry the workflow's
diff --git a/posthog/session_recordings/session_recording_helpers.py b/posthog/session_recordings/session_recording_helpers.py
index 6838f296a24c..bc909fa1305f 100644
--- a/posthog/session_recordings/session_recording_helpers.py
+++ b/posthog/session_recordings/session_recording_helpers.py
@@ -125,8 +125,8 @@ def snapshot_library_fallback_from(user_agent: str | None) -> str | None:
def preprocess_replay_events(
- _events: list[Event] | Generator[Event, None, None], max_size_bytes=1024 * 1024, user_agent: str | None = None
-) -> Generator[Event, None, None]:
+ _events: list[Event] | Generator[Event], max_size_bytes=1024 * 1024, user_agent: str | None = None
+) -> Generator[Event]:
"""
The events going to blob ingestion are uncompressed (the compression happens in the Kafka producer)
1. Since posthog-js {version} we are grouping events on the frontend in a batch and passing their size in $snapshot_bytes
@@ -259,9 +259,7 @@ def preprocess_replay_events(
yield event
-def _process_windowed_events(
- events: list[Event], fn: Callable[[list[Any]], Generator[Event, None, None]]
-) -> list[Event]:
+def _process_windowed_events(events: list[Event], fn: Callable[[list[Any]], Generator[Event]]) -> list[Event]:
"""
Helper method to simplify grouping events by window_id and session_id, processing them with the given function,
and then returning the flattened list
diff --git a/posthog/tasks/test/test_pushgateway_task.py b/posthog/tasks/test/test_pushgateway_task.py
index ba53156d599d..3cb5833f5e8d 100644
--- a/posthog/tasks/test/test_pushgateway_task.py
+++ b/posthog/tasks/test/test_pushgateway_task.py
@@ -16,7 +16,7 @@ class TestPushGatewayTask:
return CollectorRegistry()
@pytest.fixture
- def mock_push_context(self, mock_registry: CollectorRegistry) -> Generator[MagicMock, None, None]:
+ def mock_push_context(self, mock_registry: CollectorRegistry) -> Generator[MagicMock]:
with patch("posthog.tasks.utils.pushed_metrics_registry") as mock:
mock_context = MagicMock()
mock_context.__enter__ = MagicMock(return_value=mock_registry)
diff --git a/posthog/temporal/ai/chat_agent.py b/posthog/temporal/ai/chat_agent.py
index 4b585e3e63b7..c0829c3006b7 100644
--- a/posthog/temporal/ai/chat_agent.py
+++ b/posthog/temporal/ai/chat_agent.py
@@ -177,7 +177,7 @@ async def process_chat_agent_activity(inputs: ChatAgentWorkflowInputs) -> None:
return True
return False
- async def stream_runner(runner: ChatAgentRunner) -> AsyncGenerator[AssistantOutput, None]:
+ async def stream_runner(runner: ChatAgentRunner) -> AsyncGenerator[AssistantOutput]:
nonlocal should_stop_queue
async for event_type, message in runner.astream():
if event_type == AssistantEventType.APPROVAL:
@@ -185,7 +185,7 @@ async def process_chat_agent_activity(inputs: ChatAgentWorkflowInputs) -> None:
should_stop_queue = True
yield cast(AssistantOutput, (event_type, message))
- async def queue_stream() -> AsyncGenerator[AssistantOutput, None]:
+ async def queue_stream() -> AsyncGenerator[AssistantOutput]:
assistant = ChatAgentRunner(
team,
conversation,
@@ -293,7 +293,7 @@ async def process_chat_agent_activity(inputs: ChatAgentWorkflowInputs) -> None:
)
redis_stream = ConversationRedisStream(inputs.stream_key)
- stream = cast(AsyncGenerator[AssistantOutput, None], queue_stream())
+ stream = cast(AsyncGenerator[AssistantOutput], queue_stream())
await redis_stream.write_to_stream(stream, activity.heartbeat, emit_completion=False)
if should_stop_queue:
diff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.py
index 308c7e05f805..f543fe740b97 100644
--- a/posthog/temporal/common/clickhouse.py
+++ b/posthog/temporal/common/clickhouse.py
@@ -747,7 +747,7 @@ class ClickHouseClient:
query_parameters=None,
query_id: str | None = None,
line_separator=b"\n",
- ) -> typing.AsyncGenerator[dict[typing.Any, typing.Any], None]:
+ ) -> typing.AsyncGenerator[dict[typing.Any, typing.Any]]:
"""Execute the given query in ClickHouse and stream back the response as one JSON per line.
This method makes sense when running with FORMAT JSONEachRow, although we currently do not enforce this.
@@ -770,7 +770,7 @@ class ClickHouseClient:
*data,
query_parameters=None,
query_id: str | None = None,
- ) -> typing.Generator[pa.RecordBatch, None, None]:
+ ) -> typing.Generator[pa.RecordBatch]:
"""Execute the given query in ClickHouse and stream back the response as Arrow record batches.
This method makes sense when running with FORMAT ArrowStreaming, although we currently do not enforce this.
@@ -786,7 +786,7 @@ class ClickHouseClient:
*data,
query_parameters=None,
query_id: str | None = None,
- ) -> typing.AsyncGenerator[pa.RecordBatch, None]:
+ ) -> typing.AsyncGenerator[pa.RecordBatch]:
"""Execute the given query in ClickHouse and stream back the response as Arrow record batches.
This method makes sense when running with FORMAT ArrowStream, although we currently do not enforce this.
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py
index 0ba1c75c70c4..b3e9c52798d0 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py
@@ -30,7 +30,7 @@ def _lock_key(team_id: int, schema_id: str) -> str:
@contextmanager
-def _get_redis_client() -> Generator[redis.Redis | None, None, None]:
+def _get_redis_client() -> Generator[redis.Redis | None]:
redis_client = None
try:
if not settings.DATA_WAREHOUSE_REDIS_HOST or not settings.DATA_WAREHOUSE_REDIS_PORT:
diff --git a/posthog/temporal/data_imports/sources/bing_ads/client.py b/posthog/temporal/data_imports/sources/bing_ads/client.py
index d2c031bfcd1f..90cb1d43442b 100644
--- a/posthog/temporal/data_imports/sources/bing_ads/client.py
+++ b/posthog/temporal/data_imports/sources/bing_ads/client.py
@@ -70,7 +70,7 @@ class BingAdsClient:
return self._customer_id
- def get_campaigns(self, account_id: int, customer_id: int) -> Generator[list[dict[str, Any]], None, None]:
+ def get_campaigns(self, account_id: int, customer_id: int) -> Generator[list[dict[str, Any]]]:
self.authorization_data.account_id = account_id
self.authorization_data.customer_id = customer_id
@@ -150,7 +150,7 @@ class BingAdsClient:
account_id: int,
start_date: datetime | None = None,
end_date: datetime | None = None,
- ) -> Generator[list[dict[str, Any]], None, None]:
+ ) -> Generator[list[dict[str, Any]]]:
customer_id = self.get_customer_id()
if resource == BingAdsResource.CAMPAIGNS:
diff --git a/posthog/temporal/data_imports/sources/common/mixins.py b/posthog/temporal/data_imports/sources/common/mixins.py
index 34ef4273dea0..a77141d883f8 100644
--- a/posthog/temporal/data_imports/sources/common/mixins.py
+++ b/posthog/temporal/data_imports/sources/common/mixins.py
@@ -1,7 +1,6 @@
import socket
from collections.abc import Callable, Generator
from contextlib import _GeneratorContextManager, contextmanager
-from typing import Any
import structlog
@@ -97,7 +96,7 @@ def _is_host_safe(host: str, team_id: int) -> tuple[bool, str | None]:
@contextmanager
-def open_ssh_tunnel(config) -> Generator[tuple[str, int], Any, None]:
+def open_ssh_tunnel(config) -> Generator[tuple[str, int]]:
"""Yield `(host, port)` for a database connection, going through an SSH tunnel if configured."""
if hasattr(config, "ssh_tunnel") and config.ssh_tunnel and config.ssh_tunnel.enabled:
ssh_tunnel = SSHTunnel.from_config(config.ssh_tunnel)
diff --git a/posthog/temporal/data_imports/sources/google_ads/google_ads.py b/posthog/temporal/data_imports/sources/google_ads/google_ads.py
index ea44e52f86ab..27a9be615ae0 100644
--- a/posthog/temporal/data_imports/sources/google_ads/google_ads.py
+++ b/posthog/temporal/data_imports/sources/google_ads/google_ads.py
@@ -417,7 +417,7 @@ def _search_as_arrow_tables(
query: str,
table: GoogleAdsTable,
resumable_source_manager: ResumableSourceManager[GoogleAdsResumeConfig],
-) -> collections.abc.Generator[pa.Table, None, None]:
+) -> collections.abc.Generator[pa.Table]:
"""Paginate ``GoogleAdsService.search`` and yield each page as a ``pyarrow.Table``.
Resumption contract:
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/client.py b/posthog/temporal/data_imports/sources/linkedin_ads/client.py
index a8b44cbac1b6..0d79a8bf0c79 100644
--- a/posthog/temporal/data_imports/sources/linkedin_ads/client.py
+++ b/posthog/temporal/data_imports/sources/linkedin_ads/client.py
@@ -119,7 +119,7 @@ class LinkedinAdsClient:
def get_campaigns(
self, account_id: str, starting_page_token: Optional[str] = None
- ) -> Generator[tuple[list[dict[str, Any]], Optional[str]], None, None]:
+ ) -> Generator[tuple[list[dict[str, Any]], Optional[str]]]:
"""Get campaigns with pagination, yielding each page with its nextPageToken."""
account_endpoint = LINKEDIN_ADS_ENDPOINTS[LinkedinAdsResource.Accounts]
campaigns_endpoint = LINKEDIN_ADS_ENDPOINTS[LinkedinAdsResource.Campaigns]
@@ -131,7 +131,7 @@ class LinkedinAdsClient:
def get_campaign_groups(
self, account_id: str, starting_page_token: Optional[str] = None
- ) -> Generator[tuple[list[dict[str, Any]], Optional[str]], None, None]:
+ ) -> Generator[tuple[list[dict[str, Any]], Optional[str]]]:
"""Get campaign groups with pagination, yielding each page with its nextPageToken."""
account_endpoint = LINKEDIN_ADS_ENDPOINTS[LinkedinAdsResource.Accounts]
groups_endpoint = LINKEDIN_ADS_ENDPOINTS[LinkedinAdsResource.CampaignGroups]
@@ -143,7 +143,7 @@ class LinkedinAdsClient:
def get_creatives(
self, account_id: str, starting_page_token: Optional[str] = None
- ) -> Generator[tuple[list[dict[str, Any]], Optional[str]], None, None]:
+ ) -> Generator[tuple[list[dict[str, Any]], Optional[str]]]:
"""Get creatives with pagination. Uses `q=criteria` and reduced page size
(the creatives backend 500s on heavier requests)."""
account_endpoint = LINKEDIN_ADS_ENDPOINTS[LinkedinAdsResource.Accounts]
@@ -162,7 +162,7 @@ class LinkedinAdsClient:
pivot: LinkedinAdsPivot = LinkedinAdsPivot.CAMPAIGN,
date_start: Optional[str] = None,
date_end: Optional[str] = None,
- ) -> Generator[tuple[list[dict[str, Any]], None], None, None]:
+ ) -> Generator[tuple[list[dict[str, Any]], None]]:
"""Fetch analytics in adaptive date-range chunks sized to stay under the 15k-element
response cap. The window starts wide and shrinks (halving) only when a response comes
back truncated, then carries the learned size forward. A truncated response is silently
@@ -240,7 +240,7 @@ class LinkedinAdsClient:
date_start: Optional[str] = None,
date_end: Optional[str] = None,
starting_page_token: Optional[str] = None,
- ) -> Generator[tuple[list[dict[str, Any]], Optional[str]], None, None]:
+ ) -> Generator[tuple[list[dict[str, Any]], Optional[str]]]:
"""Get data by resource, yielding each page and its nextPageToken (if any).
`starting_page_token` applies to the paginated entity endpoints (campaigns,
@@ -332,7 +332,7 @@ class LinkedinAdsClient:
finder: str = "search",
page_size: int = MAX_PAGE_SIZE,
extra_params: Optional[dict[str, Any]] = None,
- ) -> Generator[tuple[list[dict[str, Any]], Optional[str]], None, None]:
+ ) -> Generator[tuple[list[dict[str, Any]], Optional[str]]]:
"""Yield each page as `(elements, next_page_token)` (None on the last page).
Callers persist `next_page_token` to resume without re-fetching."""
page_token = starting_page_token
diff --git a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
index 900f16da49f3..409905736a2b 100644
--- a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
+++ b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
@@ -259,7 +259,7 @@ def _iter_simple_pagination(
params: dict,
resume_config: MetaAdsResumeConfig | None,
resumable_source_manager: ResumableSourceManager[MetaAdsResumeConfig],
-) -> collections.abc.Generator[list[dict], None, None]:
+) -> collections.abc.Generator[list[dict]]:
"""Iterate a non-time-range Graph API request via ``paging.next`` URLs.
On resume, the saved ``next_url`` is re-issued with a fresh ``access_token``
@@ -297,7 +297,7 @@ def _iter_time_range_pagination(
time_range: dict,
resume_config: MetaAdsResumeConfig | None,
resumable_source_manager: ResumableSourceManager[MetaAdsResumeConfig],
-) -> collections.abc.Generator[list[dict], None, None]:
+) -> collections.abc.Generator[list[dict]]:
"""Iterate an insights-style request by chunked date ranges.
The outer loop walks adaptive date chunks (30/7/1 days). The inner loop
@@ -424,7 +424,7 @@ def _make_paginated_api_request(
access_token: str,
time_range: dict | None,
resumable_source_manager: ResumableSourceManager[MetaAdsResumeConfig],
-) -> collections.abc.Generator[list[dict], None, None]:
+) -> collections.abc.Generator[list[dict]]:
"""Make paginated requests to the Meta Graph API.
This function handles two types of pagination:
1. Standard pagination: Uses Meta's paging.next URLs to fetch all pages of results
diff --git a/posthog/temporal/health_checks/activities.py b/posthog/temporal/health_checks/activities.py
index 10922b43ecb8..918a07b8247a 100644
--- a/posthog/temporal/health_checks/activities.py
+++ b/posthog/temporal/health_checks/activities.py
@@ -67,7 +67,7 @@ def _get_team_id_batches_sync(inputs: HealthCheckWorkflowInputs) -> list[list[in
team_ids = filter_ids_for_rollout(team_ids, inputs.rollout_percentage)
logger.info("after rollout filtering", rollout_pct=inputs.rollout_percentage, count=len(team_ids))
- batches = [list(b) for b in batched(team_ids, inputs.batch_size)]
+ batches = [list(b) for b in batched(team_ids, inputs.batch_size, strict=False)]
logger.info("created team batches", batch_count=len(batches), batch_size=inputs.batch_size)
return batches
diff --git a/posthog/temporal/salesforce_enrichment/stripe_workflow.py b/posthog/temporal/salesforce_enrichment/stripe_workflow.py
index d42c9ca73996..c528834ed7cc 100644
--- a/posthog/temporal/salesforce_enrichment/stripe_workflow.py
+++ b/posthog/temporal/salesforce_enrichment/stripe_workflow.py
@@ -212,7 +212,7 @@ async def enrich_stripe_page_activity(inputs: EnrichStripePageInputs) -> EnrichS
sf = await asyncio.to_thread(get_salesforce_client)
org_to_account_id: dict[str, str] = {}
- for lookup_chunk in batched(all_org_ids, _SFDC_LOOKUP_CHUNK_SIZE):
+ for lookup_chunk in batched(all_org_ids, _SFDC_LOOKUP_CHUNK_SIZE, strict=False):
# POSTHOG_ORG_ID_FIELD is a trusted constant; simple_salesforce quotes the IN values.
query = format_soql(
f"SELECT Id, {POSTHOG_ORG_ID_FIELD} FROM Account WHERE {POSTHOG_ORG_ID_FIELD} IN {{}}",
diff --git a/posthog/temporal/salesforce_enrichment/usage_workflow.py b/posthog/temporal/salesforce_enrichment/usage_workflow.py
index 5bd5bae15541..fa418b23b455 100644
--- a/posthog/temporal/salesforce_enrichment/usage_workflow.py
+++ b/posthog/temporal/salesforce_enrichment/usage_workflow.py
@@ -171,7 +171,7 @@ async def enrich_org_page_activity(offset: int, limit: int, batch_size: int) ->
errors: list[str] = []
sf = get_salesforce_client()
- for batch_tuple in batched(all_org_ids, batch_size):
+ for batch_tuple in batched(all_org_ids, batch_size, strict=False):
batch_org_ids = list(batch_tuple)
try:
# Aggregate usage signals
@@ -185,7 +185,7 @@ async def enrich_org_page_activity(offset: int, limit: int, batch_size: int) ->
]
if update_records:
- for sf_batch in batched(update_records, SALESFORCE_UPDATE_BATCH_SIZE):
+ for sf_batch in batched(update_records, SALESFORCE_UPDATE_BATCH_SIZE, strict=False):
response = await asyncio.to_thread(sf.bulk.Account.update, list(sf_batch)) # type: ignore[union-attr,arg-type]
for result in response:
if result.get("success"):
diff --git a/posthog/temporal/session_replay/delete_recordings/object_storage.py b/posthog/temporal/session_replay/delete_recordings/object_storage.py
index 9879816175a6..b2e03a8c4b11 100644
--- a/posthog/temporal/session_replay/delete_recordings/object_storage.py
+++ b/posthog/temporal/session_replay/delete_recordings/object_storage.py
@@ -45,7 +45,7 @@ def store_session_id_chunks(
prefix = generate_prefix(workflow_id)
total_chunks = math.ceil(len(session_ids) / chunk_size)
- for i, chunk in enumerate(batched(session_ids, chunk_size)):
+ for i, chunk in enumerate(batched(session_ids, chunk_size, strict=False)):
key = generate_chunk_key(prefix, i)
content = "\n".join(chunk)
object_storage.write(key, content)
diff --git a/posthog/temporal/session_replay/delete_recordings/workflow.py b/posthog/temporal/session_replay/delete_recordings/workflow.py
index 96d86300e227..eb8454ebd85d 100644
--- a/posthog/temporal/session_replay/delete_recordings/workflow.py
+++ b/posthog/temporal/session_replay/delete_recordings/workflow.py
@@ -47,7 +47,7 @@ async def _delete_page(
if page.session_ids:
progress.total_found += len(page.session_ids)
- for batch in batched(page.session_ids, config.batch_size):
+ for batch in batched(page.session_ids, config.batch_size, strict=False):
batch_start = workflow.now()
result: DeleteRecordingsResult = await workflow.execute_activity(
delete_recordings,
diff --git a/posthog/temporal/session_replay/session_summary/workflow.py b/posthog/temporal/session_replay/session_summary/workflow.py
index b032d0829117..6be841dd6f59 100644
--- a/posthog/temporal/session_replay/session_summary/workflow.py
+++ b/posthog/temporal/session_replay/session_summary/workflow.py
@@ -816,7 +816,7 @@ async def execute_summarize_session_video_stream(
custom_tags: dict[str, str] | None = None,
local_reads_prod: bool = False,
force_restart: bool = False,
-) -> AsyncGenerator[str, None]:
+) -> AsyncGenerator[str]:
"""Start the video-based summarization workflow and stream progress events.
Yields SSE-formatted ``session-summary-progress`` events every few seconds
diff --git a/posthog/temporal/session_replay/session_summary_group/workflow.py b/posthog/temporal/session_replay/session_summary_group/workflow.py
index 99dd079e168b..704bc6df6a9b 100644
--- a/posthog/temporal/session_replay/session_summary_group/workflow.py
+++ b/posthog/temporal/session_replay/session_summary_group/workflow.py
@@ -516,8 +516,7 @@ async def _start_session_group_summary_workflow(
tuple[
SessionSummaryStreamUpdate,
tuple[EnrichedSessionGroupSummaryPatternsList, str, list[FailedSessionInfo]] | str | SessionProgressStreamData,
- ],
- None,
+ ]
]:
"""Start the workflow and yield status updates until completion."""
client = await async_connect()
@@ -666,8 +665,7 @@ async def execute_summarize_session_group(
tuple[
SessionSummaryStreamUpdate,
tuple[EnrichedSessionGroupSummaryPatternsList, str, list[FailedSessionInfo]] | str | SessionProgressStreamData,
- ],
- None,
+ ]
]:
"""
Start the workflow and yield status updates and final summary for the group of sessions.
diff --git a/posthog/temporal/tests/data_imports/test_bigquery_source.py b/posthog/temporal/tests/data_imports/test_bigquery_source.py
index 10433c95e2e0..0e65fc12b89d 100644
--- a/posthog/temporal/tests/data_imports/test_bigquery_source.py
+++ b/posthog/temporal/tests/data_imports/test_bigquery_source.py
@@ -51,7 +51,7 @@ def bigquery_config() -> dict[str, str]:
@pytest.fixture
-def bigquery_client() -> collections.abc.Generator[bigquery.Client, None, None]:
+def bigquery_client() -> collections.abc.Generator[bigquery.Client]:
"""Manage a bigquery.Client for testing."""
client = bigquery.Client()
@@ -61,7 +61,7 @@ def bigquery_client() -> collections.abc.Generator[bigquery.Client, None, None]:
@pytest.fixture
-def bigquery_dataset(bigquery_config, bigquery_client) -> collections.abc.Generator[bigquery.Dataset, None, None]:
+def bigquery_dataset(bigquery_config, bigquery_client) -> collections.abc.Generator[bigquery.Dataset]:
"""Manage a bigquery dataset for testing.
We clean up the dataset after every test. Could be quite time expensive, but guarantees a clean slate.
@@ -93,7 +93,7 @@ def bigquery_table_primary_key(request) -> str:
@pytest.fixture
def bigquery_table_integer(
bigquery_config, bigquery_client, bigquery_dataset, bigquery_table_primary_key
-) -> collections.abc.Generator[bigquery.Table, None, None]:
+) -> collections.abc.Generator[bigquery.Table]:
"""Manage a bigquery table for testing.
We clean up the table after every test. Could be quite time expensive, but guarantees a clean slate.
@@ -129,7 +129,7 @@ def bigquery_table_integer(
@pytest.fixture
def bigquery_table_timestamp(
bigquery_config, bigquery_client, bigquery_dataset, bigquery_table_primary_key
-) -> collections.abc.Generator[bigquery.Table, None, None]:
+) -> collections.abc.Generator[bigquery.Table]:
"""Manage a bigquery table for testing.
We clean up the table after every test. Could be quite time expensive, but guarantees a clean slate.
@@ -172,7 +172,7 @@ def bigquery_table_timestamp(
@pytest.fixture
def bigquery_view_integer(
bigquery_config, bigquery_client, bigquery_dataset, bigquery_table_integer
-) -> collections.abc.Generator[bigquery.Table, None, None]:
+) -> collections.abc.Generator[bigquery.Table]:
"""Manage a BigQuery view for testing.
We clean up the view after every test. Could be quite time expensive, but guarantees a clean slate.
diff --git a/posthog/temporal/tests/data_imports/test_mssql_source.py b/posthog/temporal/tests/data_imports/test_mssql_source.py
index 018f0711860a..6f9fd55729e7 100644
--- a/posthog/temporal/tests/data_imports/test_mssql_source.py
+++ b/posthog/temporal/tests/data_imports/test_mssql_source.py
@@ -114,7 +114,7 @@ def mssql_config() -> dict[str, Any]:
@pytest.fixture
-def mssql_connection(mssql_config: dict[str, Any]) -> Generator[pymssql.Connection, None, None]:
+def mssql_connection(mssql_config: dict[str, Any]) -> Generator[pymssql.Connection]:
with pymssql.connect(
server=mssql_config["host"],
port=mssql_config["port"],
@@ -136,9 +136,7 @@ def _insert_test_data(cursor: pymssql.Cursor, table_name: str, data: list[tuple[
@pytest.fixture
-def mssql_source_table(
- mssql_connection: pymssql.Connection, mssql_config: dict[str, Any]
-) -> Generator[pymssql.Cursor, None, None]:
+def mssql_source_table(mssql_connection: pymssql.Connection, mssql_config: dict[str, Any]) -> Generator[pymssql.Cursor]:
"""Create a MS SQL Server table with test data and clean it up after the test."""
with mssql_connection.cursor() as cursor:
full_table_name = f"[{mssql_config['schema']}].[{MSSQL_TABLE_NAME}]"
@@ -503,7 +501,7 @@ class TestGetTableAverageRowSize:
self,
mssql_connection: pymssql.Connection,
mssql_config: dict[str, Any],
- ) -> Generator[pymssql.Cursor, None, None]:
+ ) -> Generator[pymssql.Cursor]:
"""Create a MS SQL Server table with deterministic row size and clean it up after the test."""
with mssql_connection.cursor() as cursor:
full_table_name = f"[{mssql_config['schema']}].[{MSSQL_TABLE_NAME}]"
@@ -577,7 +575,7 @@ class TestGetTableStats:
self,
mssql_connection: pymssql.Connection,
mssql_config: dict[str, Any],
- ) -> Generator[pymssql.Cursor, None, None]:
+ ) -> Generator[pymssql.Cursor]:
"""Create a small test table with known size and row count."""
with mssql_connection.cursor() as cursor:
full_table_name = f"[{mssql_config['schema']}].[test_small]"
@@ -628,7 +626,7 @@ class TestGetTableStats:
self,
mssql_connection: pymssql.Connection,
mssql_config: dict[str, Any],
- ) -> Generator[pymssql.Cursor, None, None]:
+ ) -> Generator[pymssql.Cursor]:
"""Create an empty test table."""
with mssql_connection.cursor() as cursor:
full_table_name = f"[{mssql_config['schema']}].[test_empty]"
diff --git a/posthog/temporal/tests/data_imports/test_postgres_source.py b/posthog/temporal/tests/data_imports/test_postgres_source.py
index 72517feb0249..922828b7483b 100644
--- a/posthog/temporal/tests/data_imports/test_postgres_source.py
+++ b/posthog/temporal/tests/data_imports/test_postgres_source.py
@@ -95,7 +95,7 @@ def postgres_config() -> dict[str, Any]:
@pytest_asyncio.fixture
async def postgres_connection(
postgres_config: dict[str, Any], setup_postgres_test_db: None
-) -> AsyncGenerator[AsyncConnection, None]:
+) -> AsyncGenerator[AsyncConnection]:
connection = await psycopg.AsyncConnection.connect(
host=postgres_config["host"],
port=postgres_config["port"],
@@ -113,7 +113,7 @@ async def postgres_connection(
@pytest_asyncio.fixture
async def postgres_source_table(
postgres_connection: AsyncConnection, postgres_config: dict[str, Any]
-) -> AsyncGenerator[AsyncCursor[TupleRow], None]:
+) -> AsyncGenerator[AsyncCursor[TupleRow]]:
"""Create a Postgres table with test data and clean it up after the test."""
async with postgres_connection.cursor() as cursor:
full_table_name = sql.Identifier(postgres_config["schema"], POSTGRES_TABLE_NAME)
diff --git a/posthog/temporal/tests/ingestion_acceptance_test/test_client.py b/posthog/temporal/tests/ingestion_acceptance_test/test_client.py
index 00b39eeae6d1..fb30c01959f2 100644
--- a/posthog/temporal/tests/ingestion_acceptance_test/test_client.py
+++ b/posthog/temporal/tests/ingestion_acceptance_test/test_client.py
@@ -28,7 +28,7 @@ def mock_posthog_sdk() -> MagicMock:
@pytest.fixture
-def client(config: Config, mock_posthog_sdk: MagicMock) -> Generator[PostHogClient, None, None]:
+def client(config: Config, mock_posthog_sdk: MagicMock) -> Generator[PostHogClient]:
client = PostHogClient(config, mock_posthog_sdk)
yield client
client.shutdown()
diff --git a/posthog/temporal/tests/session_replay/session_summary/conftest.py b/posthog/temporal/tests/session_replay/session_summary/conftest.py
index 52374c86184f..ac5bfee31110 100644
--- a/posthog/temporal/tests/session_replay/session_summary/conftest.py
+++ b/posthog/temporal/tests/session_replay/session_summary/conftest.py
@@ -202,7 +202,7 @@ class AsyncRedisTestContext(RedisTestContextBase):
@pytest_asyncio.fixture
-async def redis_test_setup() -> AsyncGenerator[AsyncRedisTestContext, None]:
+async def redis_test_setup() -> AsyncGenerator[AsyncRedisTestContext]:
"""Async context manager for Redis test setup and cleanup."""
context = AsyncRedisTestContext()
try:
diff --git a/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py b/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py
index 446a0ab27ea1..23bdc6553ed0 100644
--- a/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py
+++ b/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py
@@ -179,7 +179,7 @@ class TestExecuteSummarizeSessionVideoStream:
@staticmethod
async def _collect(
- generator: AsyncGenerator[str, None],
+ generator: AsyncGenerator[str],
) -> list[str]:
return [event async for event in generator]
diff --git a/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py b/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py
index add7c8eea118..f5859341c9f3 100644
--- a/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py
+++ b/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py
@@ -922,7 +922,7 @@ class TestSummarizeSessionGroupWorkflow:
mock_patterns_assignment_yaml_response: str,
mock_cached_session_batch_events_query_response_factory: Callable,
custom_content: str | None = None, # noqa: ARG002
- ) -> AsyncGenerator[tuple[WorkflowEnvironment, Worker], None]:
+ ) -> AsyncGenerator[tuple[WorkflowEnvironment, Worker]]:
"""Test environment for Temporal workflow"""
with self.execute_test_environment(
session_ids,
diff --git a/posthog/test/base.py b/posthog/test/base.py
index fb00f952fd17..5242cb871643 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -722,7 +722,7 @@ class PostHogTestCase(SimpleTestCase):
yield value
@contextmanager
- def retry_assertion(self, max_retries=5, delay=0.1) -> Generator[None, None, None]:
+ def retry_assertion(self, max_retries=5, delay=0.1) -> Generator[None]:
for attempt in range(max_retries):
try:
yield # Only yield once per context manager instance
diff --git a/posthog/test/db_context_capturing.py b/posthog/test/db_context_capturing.py
index 959bfc7e7aaf..d5371cf96bba 100644
--- a/posthog/test/db_context_capturing.py
+++ b/posthog/test/db_context_capturing.py
@@ -6,7 +6,7 @@ from django.test.utils import CaptureQueriesContext
@contextmanager
-def capture_db_queries() -> Generator[CaptureQueriesContext, None, None]:
+def capture_db_queries() -> Generator[CaptureQueriesContext]:
db_connection = connections[DEFAULT_DB_ALIAS]
with CaptureQueriesContext(db_connection) as capture_query_context:
yield capture_query_context
diff --git a/posthog/utils.py b/posthog/utils.py
index 76e4f7441293..51dc36b5de76 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -1824,7 +1824,7 @@ def get_week_start_for_country_code(country_code: str) -> int:
return 1 # Monday
-def sleep_time_generator() -> Generator[float, None, None]:
+def sleep_time_generator() -> Generator[float]:
# a generator that yield an exponential back off between 0.1 and 3 seconds
for _ in range(10):
yield 0.1 # 1 second in total
diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.py
index 44ff416fc14f..730400694ac0 100644
--- a/products/ai_observability/backend/api/proxy.py
+++ b/products/ai_observability/backend/api/proxy.py
@@ -169,7 +169,7 @@ class LLMProxyViewSet(viewsets.ViewSet):
http_request,
on_complete: Callable[[float], None] | None = None,
on_error: Callable[[Exception, float], None] | None = None,
- ) -> Generator[bytes, None, None]:
+ ) -> Generator[bytes]:
"""Creates a generator that handles client disconnects and encodes responses"""
started = perf_counter()
try:
@@ -191,7 +191,7 @@ class LLMProxyViewSet(viewsets.ViewSet):
except Exception:
logger.exception("llm_proxy_on_complete_callback_error")
- def _create_streaming_response(self, stream: Generator[bytes, None, None]) -> StreamingHttpResponse:
+ def _create_streaming_response(self, stream: Generator[bytes]) -> StreamingHttpResponse:
"""Creates a properly configured SSE streaming response"""
if SERVER_GATEWAY_INTERFACE == "ASGI":
astream = SyncIterableToAsync(stream)
diff --git a/products/ai_observability/backend/llm/client.py b/products/ai_observability/backend/llm/client.py
index 1e2b1922ef43..df2c114daf83 100644
--- a/products/ai_observability/backend/llm/client.py
+++ b/products/ai_observability/backend/llm/client.py
@@ -63,7 +63,7 @@ class Client:
api_key, base_url = self._resolve_credentials()
return provider.complete(request, api_key, self.analytics, base_url)
- def stream(self, request: CompletionRequest) -> Generator[StreamChunk, None, None]:
+ def stream(self, request: CompletionRequest) -> Generator[StreamChunk]:
"""Streaming completion."""
self._validate_provider(request.provider)
provider = _get_provider(request.provider, self.provider_key)
diff --git a/products/ai_observability/backend/llm/providers/anthropic.py b/products/ai_observability/backend/llm/providers/anthropic.py
index ab9e108400cd..8566a5dfedd8 100644
--- a/products/ai_observability/backend/llm/providers/anthropic.py
+++ b/products/ai_observability/backend/llm/providers/anthropic.py
@@ -185,7 +185,7 @@ class AnthropicAdapter:
api_key: str | None,
analytics: AnalyticsContext,
_base_url: str | None = None,
- ) -> Generator[StreamChunk, None, None]:
+ ) -> Generator[StreamChunk]:
"""Streaming completion."""
effective_api_key = api_key or self._get_default_api_key()
model_id = request.model
diff --git a/products/ai_observability/backend/llm/providers/base.py b/products/ai_observability/backend/llm/providers/base.py
index 7a0a0e6733c7..fa3571204a19 100644
--- a/products/ai_observability/backend/llm/providers/base.py
+++ b/products/ai_observability/backend/llm/providers/base.py
@@ -33,7 +33,7 @@ class Provider(Protocol):
api_key: str | None,
analytics: AnalyticsContext,
base_url: str | None = None,
- ) -> Generator[StreamChunk, None, None]:
+ ) -> Generator[StreamChunk]:
"""Streaming completion"""
...
diff --git a/products/ai_observability/backend/llm/providers/fireworks.py b/products/ai_observability/backend/llm/providers/fireworks.py
index 4b1130c32e98..af5abacf2dac 100644
--- a/products/ai_observability/backend/llm/providers/fireworks.py
+++ b/products/ai_observability/backend/llm/providers/fireworks.py
@@ -42,7 +42,7 @@ class FireworksAdapter(OpenAIAdapter):
api_key: str | None,
analytics: AnalyticsContext,
base_url: str | None = None,
- ) -> Generator[StreamChunk, None, None]:
+ ) -> Generator[StreamChunk]:
yield from super().stream(request, api_key, analytics, base_url=FIREWORKS_BASE_URL)
@staticmethod
diff --git a/products/ai_observability/backend/llm/providers/gemini.py b/products/ai_observability/backend/llm/providers/gemini.py
index acf4c2da6224..b04fe70cae73 100644
--- a/products/ai_observability/backend/llm/providers/gemini.py
+++ b/products/ai_observability/backend/llm/providers/gemini.py
@@ -150,7 +150,7 @@ class GeminiAdapter:
api_key: str | None,
analytics: AnalyticsContext,
_base_url: str | None = None,
- ) -> Generator[StreamChunk, None, None]:
+ ) -> Generator[StreamChunk]:
"""Streaming completion."""
effective_api_key = api_key or self._get_default_api_key()
model_id = request.model
@@ -309,7 +309,7 @@ class GeminiAdapter:
assert result is not None, "tools must be non-empty when calling _convert_tools"
return result
- def _extract_chunks_from_response(self, chunk) -> Generator[StreamChunk, None, None]:
+ def _extract_chunks_from_response(self, chunk) -> Generator[StreamChunk]:
"""Extract StreamChunks from a Gemini response chunk."""
if hasattr(chunk, "text") and chunk.text:
yield StreamChunk(type="text", data={"text": chunk.text})
diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.py
index acd070f5022b..d1aa124441bd 100644
--- a/products/ai_observability/backend/llm/providers/openai.py
+++ b/products/ai_observability/backend/llm/providers/openai.py
@@ -259,7 +259,7 @@ Return ONLY the JSON object, no other text or markdown formatting."""
api_key: str | None,
analytics: AnalyticsContext,
base_url: str | None = None,
- ) -> Generator[StreamChunk, None, None]:
+ ) -> Generator[StreamChunk]:
"""Streaming completion."""
effective_api_key = api_key or self._get_default_api_key()
effective_base_url = base_url or settings.OPENAI_BASE_URL
@@ -445,7 +445,7 @@ Return ONLY the JSON object, no other text or markdown formatting."""
cache_read_tokens=cache_read,
)
- def _yield_usage_chunks(self, usage: CompletionUsage) -> Generator[StreamChunk, None, None]:
+ def _yield_usage_chunks(self, usage: CompletionUsage) -> Generator[StreamChunk]:
input_tokens = usage.prompt_tokens or 0
output_tokens = usage.completion_tokens or 0
cache_read_tokens = (
diff --git a/products/ai_observability/backend/llm/providers/openrouter.py b/products/ai_observability/backend/llm/providers/openrouter.py
index 6358ce6abca7..e47b63810e69 100644
--- a/products/ai_observability/backend/llm/providers/openrouter.py
+++ b/products/ai_observability/backend/llm/providers/openrouter.py
@@ -53,7 +53,7 @@ class OpenRouterAdapter(OpenAIAdapter):
api_key: str | None,
analytics: AnalyticsContext,
base_url: str | None = None,
- ) -> Generator[StreamChunk, None, None]:
+ ) -> Generator[StreamChunk]:
yield from super().stream(request, api_key, analytics, base_url=OPENROUTER_BASE_URL)
@staticmethod
diff --git a/products/ai_observability/backend/llm/providers/together.py b/products/ai_observability/backend/llm/providers/together.py
index feb7a725b422..30452a571940 100644
--- a/products/ai_observability/backend/llm/providers/together.py
+++ b/products/ai_observability/backend/llm/providers/together.py
@@ -70,7 +70,7 @@ class TogetherAdapter(OpenAIAdapter):
api_key: str | None,
analytics: AnalyticsContext,
base_url: str | None = None,
- ) -> Generator[StreamChunk, None, None]:
+ ) -> Generator[StreamChunk]:
yield from super().stream(request, api_key, analytics, base_url=TOGETHER_BASE_URL)
@staticmethod
diff --git a/products/ai_observability/backend/providers/inkeep.py b/products/ai_observability/backend/providers/inkeep.py
index ee308c470c19..31e7b504b239 100644
--- a/products/ai_observability/backend/providers/inkeep.py
+++ b/products/ai_observability/backend/providers/inkeep.py
@@ -44,7 +44,7 @@ class InkeepProvider:
trace_id: str | None = None,
properties: dict | None = None,
groups: dict | None = None,
- ) -> Generator[str, None, None]:
+ ) -> Generator[str]:
"""
Generator function that yields SSE formatted data
"""
diff --git a/products/batch_exports/backend/api/destination_tests/databricks.py b/products/batch_exports/backend/api/destination_tests/databricks.py
index ee8ec183adfe..dd6df47ca005 100644
--- a/products/batch_exports/backend/api/destination_tests/databricks.py
+++ b/products/batch_exports/backend/api/destination_tests/databricks.py
@@ -50,7 +50,7 @@ class DatabricksTestStep(DestinationTestStep):
self.table_name = table_name
@contextlib.asynccontextmanager
- async def connect(self) -> AsyncGenerator[DatabricksClient, None]:
+ async def connect(self) -> AsyncGenerator[DatabricksClient]:
assert self.server_hostname is not None
assert self.http_path is not None
assert self.client_id is not None
diff --git a/products/batch_exports/backend/debug/debugger.py b/products/batch_exports/backend/debug/debugger.py
index 0530a9709520..634fd0304760 100644
--- a/products/batch_exports/backend/debug/debugger.py
+++ b/products/batch_exports/backend/debug/debugger.py
@@ -291,7 +291,7 @@ class BatchExportsDebugger:
order_by: str = "last_updated_at",
descending: bool = True,
offset: int = 0,
- ) -> collections.abc.Generator[BatchExportRun, None, None]:
+ ) -> collections.abc.Generator[BatchExportRun]:
"""Iterate over batch export runs."""
batch_export = self.batch_export
sign = "-" if descending else ""
@@ -341,7 +341,7 @@ class BatchExportsDebugger:
def iter_run_record_batches_from_s3(
self, batch_export_run: BatchExportRun
- ) -> collections.abc.Generator[pa.RecordBatch, None, None]:
+ ) -> collections.abc.Generator[pa.RecordBatch]:
folder = get_base_s3_staging_folder(
batch_export_run.parent.id,
batch_export_run.data_interval_start.isoformat() if batch_export_run.data_interval_start else None,
@@ -389,7 +389,7 @@ class BatchExportsDebugger:
def iter_run_record_batches_from_clickhouse(
self,
batch_export_run: BatchExportRun,
- ) -> collections.abc.Generator[pa.RecordBatch, None, None]:
+ ) -> collections.abc.Generator[pa.RecordBatch]:
team_id = batch_export_run.parent.team.id
full_range = (batch_export_run.data_interval_start, batch_export_run.data_interval_end)
parameters = {"team_id": team_id, "interval_end": full_range[1].strftime("%Y-%m-%d %H:%M:%S.%f")}
diff --git a/products/batch_exports/backend/temporal/backfill_batch_export.py b/products/batch_exports/backend/temporal/backfill_batch_export.py
index e1d73be516eb..28aee2c573f8 100644
--- a/products/batch_exports/backend/temporal/backfill_batch_export.py
+++ b/products/batch_exports/backend/temporal/backfill_batch_export.py
@@ -813,7 +813,7 @@ def backfill_range(
end_at: dt.datetime | None,
step: dt.timedelta,
timezone: str | None = None,
-) -> typing.Generator[tuple[dt.datetime | None, dt.datetime], None, None]:
+) -> typing.Generator[tuple[dt.datetime | None, dt.datetime]]:
"""Generate range of dates between start_at and end_at.
Args:
diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.py
index d547e25fc54d..63106edfbea0 100644
--- a/products/batch_exports/backend/temporal/batch_exports.py
+++ b/products/batch_exports/backend/temporal/batch_exports.py
@@ -61,11 +61,11 @@ from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, list_l
LOGGER = get_write_only_logger(__name__)
EXTERNAL_LOGGER = get_logger("EXTERNAL")
-BytesGenerator = collections.abc.Generator[bytes, None, None]
-RecordsGenerator = collections.abc.Generator[pa.RecordBatch, None, None]
+BytesGenerator = collections.abc.Generator[bytes]
+RecordsGenerator = collections.abc.Generator[pa.RecordBatch]
-AsyncBytesGenerator = collections.abc.AsyncGenerator[bytes, None]
-AsyncRecordsGenerator = collections.abc.AsyncGenerator[pa.RecordBatch, None]
+AsyncBytesGenerator = collections.abc.AsyncGenerator[bytes]
+AsyncRecordsGenerator = collections.abc.AsyncGenerator[pa.RecordBatch]
def _notify_run_failure(batch_export_run_id: str | UUIDT) -> None:
diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
index 002746295c89..b363da83506f 100644
--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
@@ -743,7 +743,7 @@ class BigQueryClient:
not_found_ok: bool = True,
delete: bool = True,
create: bool = True,
- ) -> collections.abc.AsyncGenerator[BigQueryTable, None]:
+ ) -> collections.abc.AsyncGenerator[BigQueryTable]:
"""Manage a table in BigQuery by ensuring it exists while in context."""
if create is True:
managed_table = await self.create_table(table, exists_ok)
diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
index 304ecbc9ec0f..bb5a4990884f 100644
--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
@@ -962,7 +962,7 @@ def _is_insufficient_permissions_error(err: DatabaseError) -> bool:
@contextlib.asynccontextmanager
-async def handle_common_errors(operation: str, timeout: float) -> AsyncGenerator[None, None]:
+async def handle_common_errors(operation: str, timeout: float) -> AsyncGenerator[None]:
"""Map common Databricks client errors to non-retryable typed exceptions.
Operation-specific exceptions (catalog-not-found, schema-not-found, etc.) should be
@@ -1086,7 +1086,7 @@ async def manage_resources(
fields: list[DatabricksField],
table_name: str,
stage_table_name: str | None = None,
-) -> AsyncGenerator[tuple[str, str, str | None], None]:
+) -> AsyncGenerator[tuple[str, str, str | None]]:
"""Manage resources in Databricks by ensuring they exist while in context."""
async with client.managed_volume(volume_name) as volume:
async with client.managed_table(table_name, fields, delete=False) as table:
diff --git a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py
index 71a4068c98ae..5e3ed27bfcb0 100644
--- a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py
@@ -453,7 +453,7 @@ class PostgreSQLClient:
delete: bool = True,
create: bool = True,
log_statements: bool = False,
- ) -> collections.abc.AsyncGenerator[str, None]:
+ ) -> collections.abc.AsyncGenerator[str]:
"""Manage a table in PostgreSQL by ensure it exists while in context.
Managing a table implies two operations: creation of a table, which happens upon entering the
diff --git a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
index 26bc0f503f7a..ed149333efb1 100644
--- a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
@@ -900,7 +900,7 @@ class SnowflakeClient:
exists_ok: bool = True,
delete: bool = True,
not_found_ok: bool = True,
- ) -> collections.abc.AsyncGenerator[SnowflakeTable, None]:
+ ) -> collections.abc.AsyncGenerator[SnowflakeTable]:
"""Manage a table in Snowflake by ensure it exists while in context."""
if create is True:
await self.create_table(table)
diff --git a/products/batch_exports/backend/temporal/utils.py b/products/batch_exports/backend/temporal/utils.py
index 889d8caa676f..ffa3497c0d2a 100644
--- a/products/batch_exports/backend/temporal/utils.py
+++ b/products/batch_exports/backend/temporal/utils.py
@@ -21,8 +21,8 @@ LOGGER = get_write_only_logger(__name__)
def peek_first_and_rewind(
- gen: collections.abc.Generator[T, None, None],
-) -> tuple[T | None, collections.abc.Generator[T, None, None]]:
+ gen: collections.abc.Generator[T],
+) -> tuple[T | None, collections.abc.Generator[T]]:
"""Peek into the first element in a generator and rewind the advance.
The generator is advanced and cannot be reversed, so we create a new one that first
@@ -36,7 +36,7 @@ def peek_first_and_rewind(
except StopIteration:
first = None
- def rewind_gen() -> collections.abc.Generator[T, None, None]:
+ def rewind_gen() -> collections.abc.Generator[T]:
"""Yield the item we popped to rewind the generator.
Return early if the generator is empty.
@@ -51,8 +51,8 @@ def peek_first_and_rewind(
async def apeek_first_and_rewind(
- gen: collections.abc.AsyncGenerator[T, None],
-) -> tuple[T | None, collections.abc.AsyncGenerator[T, None]]:
+ gen: collections.abc.AsyncGenerator[T],
+) -> tuple[T | None, collections.abc.AsyncGenerator[T]]:
"""Peek into the first element in a generator and rewind the advance.
The generator is advanced and cannot be reversed, so we create a new one that first
@@ -66,7 +66,7 @@ async def apeek_first_and_rewind(
except StopAsyncIteration:
first = None
- async def rewind_gen() -> collections.abc.AsyncGenerator[T, None]:
+ async def rewind_gen() -> collections.abc.AsyncGenerator[T]:
"""Yield the item we popped to rewind the generator.
Return early if the generator is empty.
@@ -83,7 +83,7 @@ async def apeek_first_and_rewind(
@contextlib.asynccontextmanager
-async def set_status_to_running_task(run_id: str | None) -> collections.abc.AsyncGenerator[asyncio.Task | None, None]:
+async def set_status_to_running_task(run_id: str | None) -> collections.abc.AsyncGenerator[asyncio.Task | None]:
"""Manage a background task to set a batch export run status to 'RUNNING'.
This is intended to be used within a batch export's 'insert_*' activity. These activities cannot afford
diff --git a/products/batch_exports/backend/tests/api/destination_tests/test_bigquery_destination_tests.py b/products/batch_exports/backend/tests/api/destination_tests/test_bigquery_destination_tests.py
index 19aa8c6d12c6..7bf1ad518e96 100644
--- a/products/batch_exports/backend/tests/api/destination_tests/test_bigquery_destination_tests.py
+++ b/products/batch_exports/backend/tests/api/destination_tests/test_bigquery_destination_tests.py
@@ -54,7 +54,7 @@ def bigquery_config() -> dict[str, str]:
@pytest.fixture
-def bigquery_client() -> typing.Generator[bigquery.Client, None, None]:
+def bigquery_client() -> typing.Generator[bigquery.Client]:
"""Manage a bigquery.Client for testing."""
client = bigquery.Client()
@@ -64,7 +64,7 @@ def bigquery_client() -> typing.Generator[bigquery.Client, None, None]:
@pytest.fixture
-def bigquery_dataset(bigquery_config, bigquery_client) -> typing.Generator[bigquery.Dataset, None, None]:
+def bigquery_dataset(bigquery_config, bigquery_client) -> typing.Generator[bigquery.Dataset]:
"""Manage a bigquery dataset for testing.
We clean up the dataset after every test. Could be quite time expensive, but guarantees a clean slate.
diff --git a/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py b/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py
index d7cdc84ae86c..cffab19063f6 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py
@@ -413,7 +413,7 @@ class CommonWorkflowTests:
@pytest.fixture
async def batch_export_for_destination(
self, ateam, temporal_client, interval, integration, destination_test, exclude_events
- ) -> AsyncGenerator[BatchExport, None]:
+ ) -> AsyncGenerator[BatchExport]:
"""Manage BatchExport model (and associated Temporal Schedule) for tests"""
destination_config = {**destination_test.get_destination_config(ateam.pk), "exclude_events": exclude_events}
destination_data = {
diff --git a/products/batch_exports/backend/tests/temporal/destinations/bigquery/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/bigquery/conftest.py
index ec1e866ea4de..fae6b4da89e3 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/bigquery/conftest.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/bigquery/conftest.py
@@ -38,7 +38,7 @@ def bigquery_config() -> dict[str, str]:
@pytest.fixture
-def bigquery_client() -> typing.Generator[bigquery.Client, None, None]:
+def bigquery_client() -> typing.Generator[bigquery.Client]:
"""Manage a bigquery.Client for testing."""
client = bigquery.Client()
@@ -48,7 +48,7 @@ def bigquery_client() -> typing.Generator[bigquery.Client, None, None]:
@pytest.fixture
-def bigquery_dataset(bigquery_config, bigquery_client) -> typing.Generator[bigquery.Dataset, None, None]:
+def bigquery_dataset(bigquery_config, bigquery_client) -> typing.Generator[bigquery.Dataset]:
"""Manage a bigquery dataset for testing.
We clean up the dataset after every test. Could be quite time expensive, but guarantees a clean slate.
diff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/conftest.py
index bb75c06121ad..3ffe2c67fa42 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/conftest.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/conftest.py
@@ -69,7 +69,7 @@ def snowflake_config(database, schema) -> dict[str, str | None]:
@pytest_asyncio.fixture
async def snowflake_batch_export(
ateam, table_name, snowflake_config, interval, exclude_events, temporal_client
-) -> AsyncGenerator[BatchExport, None]:
+) -> AsyncGenerator[BatchExport]:
"""Manage BatchExport model (and associated Temporal Schedule) for tests"""
destination_data = {
"type": "Snowflake",
diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
index fb7cd4526791..48082a7a7116 100644
--- a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
@@ -227,7 +227,7 @@ async def minio_client():
async def _generate_record_batches_from_internal_stage(
batch_export_id: str, data_interval_start: dt.datetime, data_interval_end: dt.datetime, stage_folder: str
-) -> AsyncGenerator[pa.RecordBatch, None]:
+) -> AsyncGenerator[pa.RecordBatch]:
"""Generate record batches from the internal stage."""
queue = RecordBatchQueue()
producer = Producer()
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index c4bdb47ddbd6..a330a0bffa73 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -2062,7 +2062,7 @@ class DashboardsViewSet(
)
# Async generator that handles progressive tile serialization and streaming
- async def async_tile_stream_generator() -> AsyncGenerator[bytes, None]:
+ async def async_tile_stream_generator() -> AsyncGenerator[bytes]:
renderer = SafeJSONRenderer()
try:
diff --git a/products/experiments/backend/experiment_summary_data_service.py b/products/experiments/backend/experiment_summary_data_service.py
index c84da98fe4bf..16463719b746 100644
--- a/products/experiments/backend/experiment_summary_data_service.py
+++ b/products/experiments/backend/experiment_summary_data_service.py
@@ -1,14 +1,13 @@
import asyncio
from dataclasses import dataclass
from datetime import datetime
-from typing import Any, Union
+from typing import Any, TypeIs, Union
from zoneinfo import ZoneInfo
from django.conf import settings
import posthoganalytics
from posthoganalytics import capture_exception
-from typing_extensions import TypeIs
from posthog.schema import (
CacheMissResponse,
diff --git a/products/exports/backend/tasks/csv_exporter.py b/products/exports/backend/tasks/csv_exporter.py
index f5a30b0ca6ad..2e9a748a32f9 100644
--- a/products/exports/backend/tasks/csv_exporter.py
+++ b/products/exports/backend/tasks/csv_exporter.py
@@ -233,7 +233,7 @@ def _format_breakdown_value(breakdown_value: Any) -> str:
return "::".join(breakdown_value)
-def _convert_response_to_csv_data(data: Any, breakdown_filter: Optional[dict] = None) -> Generator[Any, None, None]:
+def _convert_response_to_csv_data(data: Any, breakdown_filter: Optional[dict] = None) -> Generator[Any]:
if isinstance(data.get("results"), list):
results = data.get("results")
if len(results) > 0 and (isinstance(results[0], list) or isinstance(results[0], tuple)) and data.get("types"):
@@ -397,7 +397,7 @@ class UnexpectedEmptyJsonResponse(Exception):
pass
-def get_from_insights_api(exported_asset: ExportedAsset, limit: int, resource: dict) -> Generator[Any, None, None]:
+def get_from_insights_api(exported_asset: ExportedAsset, limit: int, resource: dict) -> Generator[Any]:
path: str = resource["path"]
method: str = resource.get("method", "GET")
body = resource.get("body", None)
@@ -465,7 +465,7 @@ def _query_supports_limit(query: dict) -> bool:
def get_from_query(
exported_asset: ExportedAsset, limit: int, resource: dict, analytics_props: Optional[AnalyticsProps] = None
-) -> Generator[Any, None, None]:
+) -> Generator[Any]:
query = resource.get("source")
assert query is not None
@@ -534,7 +534,7 @@ def get_from_query(
def _iter_rows(
exported_asset: ExportedAsset, limit: int, analytics_props: Optional[AnalyticsProps] = None
-) -> Generator[Any, None, None]:
+) -> Generator[Any]:
resource = exported_asset.export_context or {}
if resource.get("source"):
diff --git a/products/exports/backend/tasks/test/test_csv_exporter.py b/products/exports/backend/tasks/test/test_csv_exporter.py
index 89558ee3b704..b4ac7a908434 100644
--- a/products/exports/backend/tasks/test/test_csv_exporter.py
+++ b/products/exports/backend/tasks/test/test_csv_exporter.py
@@ -57,7 +57,7 @@ regression_11204 = "api/projects/6642/insights/trend/?events=%5B%7B%22id%22%3A%2
@override_settings(SITE_URL="http://testserver")
class TestCSVExporter(APIBaseTest):
@pytest.fixture(autouse=True)
- def patched_request(self) -> Generator[Any, None, None]:
+ def patched_request(self) -> Generator[Any]:
with patch("products.exports.backend.tasks.csv_exporter.requests.request") as patched_request:
mock_response = Mock()
mock_response.status_code = 200
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index da95c7f9c245..97d65075d7e3 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -86,7 +86,7 @@ HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER = Counter(
def _get_properties_from_filters(
filters: Union[dict, FlagFilters], property_type: str | None = None
-) -> Generator[FlagProperty, None, None]:
+) -> Generator[FlagProperty]:
"""
Extract properties from filters by iterating through groups.
@@ -116,7 +116,7 @@ def _extract_cohort_ids_from_filters(filters: Union[dict, FlagFilters]) -> set[i
return cohort_ids
-def _get_flag_properties_from_filters(filters: Union[dict, FlagFilters]) -> Generator[FlagProperty, None, None]:
+def _get_flag_properties_from_filters(filters: Union[dict, FlagFilters]) -> Generator[FlagProperty]:
"""Extract flag properties from filters."""
return _get_properties_from_filters(filters, PropertyFilterType.FLAG)
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index 3084b598af61..7478cee0ea1c 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -490,7 +490,7 @@ def _cohort_manifests_from_alerts(
manifests: list[CohortManifest] = []
for (team_id, _wm, _ep, _cim, projection_eligible, date_to), alert_ids in grouped.items():
- for chunk in batched(alert_ids, MAX_ALERT_COHORT_SIZE):
+ for chunk in batched(alert_ids, MAX_ALERT_COHORT_SIZE, strict=False):
manifests.append(
CohortManifest(
team_id=team_id,
diff --git a/products/logs/backend/temporal/workflow.py b/products/logs/backend/temporal/workflow.py
index 33687bf93c1f..754d811c8725 100644
--- a/products/logs/backend/temporal/workflow.py
+++ b/products/logs/backend/temporal/workflow.py
@@ -67,7 +67,7 @@ class LogsAlertCheckWorkflow(PostHogWorkflow):
# module-level env reads are non-deterministic across workflow replay.
batches = [
EvaluateCohortBatchInput(manifests=list(chunk))
- for chunk in batched(discovery.manifests, discovery.batch_size)
+ for chunk in batched(discovery.manifests, discovery.batch_size, strict=False)
]
# `return_exceptions=True` isolates per-batch retry-exhaustion: one
@@ -112,7 +112,7 @@ class LogsAlertCheckWorkflow(PostHogWorkflow):
# Off the eval critical path. Best-effort: signal emission must never fail
# the alert cycle, so retry-exhaustion is swallowed. Chunked because the
# input crosses the workflow->activity boundary as a single Temporal payload.
- for chunk in batched(notified, EMIT_SIGNAL_BATCH_SIZE):
+ for chunk in batched(notified, EMIT_SIGNAL_BATCH_SIZE, strict=False):
try:
await workflow.execute_activity(
emit_alert_signals_activity,
diff --git a/products/notebooks/backend/collab.py b/products/notebooks/backend/collab.py
index 1c4edf08aed4..5f3ea96c95e5 100644
--- a/products/notebooks/backend/collab.py
+++ b/products/notebooks/backend/collab.py
@@ -165,7 +165,7 @@ async def stream_collab_sse(
notebook_id: str,
*,
last_event_id: str | None,
-) -> AsyncGenerator[bytes, None]:
+) -> AsyncGenerator[bytes]:
"""
Tail this notebook's Redis stream from last_event_id (or from now if None).
Yields one SSE frame per step, plus a keepalive comment during idle gaps.
diff --git a/products/posthog_ai/scripts/pydantic_schema/test/test_pydantic_schema.py b/products/posthog_ai/scripts/pydantic_schema/test/test_pydantic_schema.py
index bc2608b48cf2..5ca4111eba3f 100644
--- a/products/posthog_ai/scripts/pydantic_schema/test/test_pydantic_schema.py
+++ b/products/posthog_ai/scripts/pydantic_schema/test/test_pydantic_schema.py
@@ -42,7 +42,7 @@ def test_json_schema_type_label(prop: dict, expected: str) -> None:
@pytest.fixture()
-def register_fake_module() -> Generator[Callable[..., None], None, None]:
+def register_fake_module() -> Generator[Callable[..., None]]:
"""Factory fixture that registers a Pydantic model as a fake module for import.
Returns a callable: register(module_name, class_name, model_cls).
diff --git a/products/replay_vision/backend/api/observation_progress.py b/products/replay_vision/backend/api/observation_progress.py
index f7442ff6d044..88e2ff708367 100644
--- a/products/replay_vision/backend/api/observation_progress.py
+++ b/products/replay_vision/backend/api/observation_progress.py
@@ -88,7 +88,7 @@ async def _query_progress(client: Any, workflow_id: str) -> dict[str, Any] | Non
return payload
-async def stream_observation_progress(observation: ReplayObservation) -> AsyncGenerator[str, None]:
+async def stream_observation_progress(observation: ReplayObservation) -> AsyncGenerator[str]:
"""SSE generator: live phase + rendering frame progress for one observation until it reaches a terminal state.
Emits `observation-progress` ticks, then a single `observation-complete` (carrying the terminal status) once the
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index 01ac3e2bbe77..75c4210c072f 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -2793,7 +2793,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
format_sse_event = self._format_sse_event
origin_product = origin_product_label(task_run)
- async def async_stream() -> AsyncGenerator[bytes, None]:
+ async def async_stream() -> AsyncGenerator[bytes]:
redis_stream = TaskRunRedisStream(stream_key, use_dedicated_stream)
connection_started_at = asyncio.get_running_loop().time()
# Default to client_disconnect: any exit that isn't an explicit
diff --git a/products/tasks/backend/stream/event_ingest.py b/products/tasks/backend/stream/event_ingest.py
index 546346c77ba4..314e398dddaa 100644
--- a/products/tasks/backend/stream/event_ingest.py
+++ b/products/tasks/backend/stream/event_ingest.py
@@ -196,7 +196,7 @@ async def _ingest_event_lines(
return result
-async def _iter_request_lines(receive: ASGIReceive) -> AsyncGenerator[str, None]:
+async def _iter_request_lines(receive: ASGIReceive) -> AsyncGenerator[str]:
"""Yield NDJSON request lines with bounded event-loop work per request."""
buffer = b""
request_size = 0
diff --git a/products/tasks/backend/stream/redis_stream.py b/products/tasks/backend/stream/redis_stream.py
index 1f6a363a436c..927aca310dd7 100644
--- a/products/tasks/backend/stream/redis_stream.py
+++ b/products/tasks/backend/stream/redis_stream.py
@@ -197,7 +197,7 @@ class TaskRunRedisStream:
block_ms: int = 100,
count: Optional[int] = TASK_RUN_STREAM_READ_COUNT,
keepalive_interval_seconds: float | None = None,
- ) -> AsyncGenerator[dict, None]:
+ ) -> AsyncGenerator[dict]:
async for item in self.read_stream_entries(
start_id=start_id,
block_ms=block_ms,
@@ -215,7 +215,7 @@ class TaskRunRedisStream:
block_ms: int = 100,
count: Optional[int] = TASK_RUN_STREAM_READ_COUNT,
keepalive_interval_seconds: float | None = None,
- ) -> AsyncGenerator[TaskRunStreamEntryOrKeepalive, None]:
+ ) -> AsyncGenerator[TaskRunStreamEntryOrKeepalive]:
"""Read events from the Redis stream.
Yields Redis stream IDs and parsed JSON dicts.
diff --git a/products/web_analytics/backend/temporal/weekly_digest/activities.py b/products/web_analytics/backend/temporal/weekly_digest/activities.py
index f37cd8e5abb1..68b00c3ff1b7 100644
--- a/products/web_analytics/backend/temporal/weekly_digest/activities.py
+++ b/products/web_analytics/backend/temporal/weekly_digest/activities.py
@@ -108,7 +108,7 @@ def _get_org_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:
page_org_ids, next_cursor = _paginate_keyset(qs, input.cursor, input.page_size)
source = "keyset"
- batches = [list(b) for b in batched(page_org_ids, workflow_input.batch_size)]
+ batches = [list(b) for b in batched(page_org_ids, workflow_input.batch_size, strict=False)]
logger.info(
"wa digest org batch page",
source=source,
diff --git a/pyproject.toml b/pyproject.toml
index a5dd6e1a4980..74b54a836bf6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -327,9 +327,6 @@ ignore = [
"UP045", # ~3064: Optional[X] → X | None (auto-fixable)
"UP046", # ~39: generic class → PEP 695 (unsafe)
"UP047", # ~37: generic func → PEP 695 (unsafe)
- "UP043", # ~162: Generator[X, None, None] → Generator[X] (defer 3.13 sweep)
- "UP035", # ~2: typing_extensions.TypeIs → typing.TypeIs (defer 3.13 sweep)
- "B911", # ~9: itertools.batched without explicit strict (defer 3.13 sweep)
]
select = [
"B",
diff --git a/services/llm-gateway/pyproject.toml b/services/llm-gateway/pyproject.toml
index 6a8d2385354b..da638b3ef5ac 100644
--- a/services/llm-gateway/pyproject.toml
+++ b/services/llm-gateway/pyproject.toml
@@ -78,9 +78,6 @@ select = [
]
ignore = [
"E501",
- "UP043", # Generator[X, None, None] → Generator[X] (defer 3.13 sweep)
- "B911", # itertools.batched without explicit strict (defer 3.13 sweep)
- "UP035", # typing_extensions.TypeIs → typing.TypeIs (defer 3.13 sweep)
]
# PLC0415 exemptions.
diff --git a/services/llm-gateway/src/llm_gateway/api/handler.py b/services/llm-gateway/src/llm_gateway/api/handler.py
index 6ff10be5de84..8e7121cd9e1c 100644
--- a/services/llm-gateway/src/llm_gateway/api/handler.py
+++ b/services/llm-gateway/src/llm_gateway/api/handler.py
@@ -297,7 +297,7 @@ async def _handle_streaming_request(
},
) from e
- async def stream_generator() -> AsyncGenerator[bytes, None]:
+ async def stream_generator() -> AsyncGenerator[bytes]:
ACTIVE_STREAMS.labels(provider=provider_config.name, model=model, product=product).inc()
status_code = "200"
provider_start = time.monotonic()
diff --git a/services/llm-gateway/src/llm_gateway/main.py b/services/llm-gateway/src/llm_gateway/main.py
index 42dec77a8ad5..e461c54d4e0c 100644
--- a/services/llm-gateway/src/llm_gateway/main.py
+++ b/services/llm-gateway/src/llm_gateway/main.py
@@ -135,7 +135,7 @@ def export_provider_credentials(settings: Settings) -> None:
@asynccontextmanager
-async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
+async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
settings = get_settings()
export_provider_credentials(settings)
diff --git a/services/llm-gateway/src/llm_gateway/streaming/sse.py b/services/llm-gateway/src/llm_gateway/streaming/sse.py
index d986fecfbf66..653299e65b6a 100644
--- a/services/llm-gateway/src/llm_gateway/streaming/sse.py
+++ b/services/llm-gateway/src/llm_gateway/streaming/sse.py
@@ -17,7 +17,7 @@ def _serialize_chunk(obj: Any) -> Any:
return obj
-async def format_sse_stream(llm_stream: AsyncGenerator[Any, None]) -> AsyncGenerator[bytes, None]:
+async def format_sse_stream(llm_stream: AsyncGenerator[Any]) -> AsyncGenerator[bytes]:
is_raw_passthrough = None
try:
diff --git a/services/llm-gateway/tests/cli/test_reset_posthog_code_usage.py b/services/llm-gateway/tests/cli/test_reset_posthog_code_usage.py
index ee176d883cac..9f291a08b3be 100644
--- a/services/llm-gateway/tests/cli/test_reset_posthog_code_usage.py
+++ b/services/llm-gateway/tests/cli/test_reset_posthog_code_usage.py
@@ -8,7 +8,7 @@ from llm_gateway.cli.reset_posthog_code_usage import _non_empty_user_id, reset_u
@pytest.fixture
-async def redis() -> AsyncGenerator[fakeredis.FakeRedis, None]:
+async def redis() -> AsyncGenerator[fakeredis.FakeRedis]:
yield fakeredis.FakeRedis()
diff --git a/services/llm-gateway/tests/conftest.py b/services/llm-gateway/tests/conftest.py
index 200c7b7282ba..6456b87e1c70 100644
--- a/services/llm-gateway/tests/conftest.py
+++ b/services/llm-gateway/tests/conftest.py
@@ -43,7 +43,7 @@ def create_test_app(
]
@asynccontextmanager
- async def test_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
+ async def test_lifespan(app: FastAPI) -> AsyncGenerator[None]:
app.state.db_pool = mock_db_pool
app.state.redis = None
app.state.throttle_runner = ThrottleRunner(throttles=throttles if throttles is not None else default_throttles)
@@ -85,25 +85,25 @@ def authenticated_user() -> AuthenticatedUser:
@pytest.fixture
-def app(mock_db_pool: MagicMock) -> Generator[FastAPI, None, None]:
+def app(mock_db_pool: MagicMock) -> Generator[FastAPI]:
application = create_test_app(mock_db_pool)
yield application
@pytest.fixture
-def client(app: FastAPI) -> Generator[TestClient, None, None]:
+def client(app: FastAPI) -> Generator[TestClient]:
with TestClient(app) as c:
yield c
@pytest.fixture
-async def async_client(app: FastAPI) -> AsyncGenerator[AsyncClient, None]:
+async def async_client(app: FastAPI) -> AsyncGenerator[AsyncClient]:
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
yield ac
@pytest.fixture
-def authenticated_client(mock_db_pool: MagicMock) -> Generator[TestClient, None, None]:
+def authenticated_client(mock_db_pool: MagicMock) -> Generator[TestClient]:
app = create_test_app(mock_db_pool)
conn = AsyncMock()
diff --git a/services/llm-gateway/tests/test_auth.py b/services/llm-gateway/tests/test_auth.py
index f9fdca092348..ddae514c5594 100644
--- a/services/llm-gateway/tests/test_auth.py
+++ b/services/llm-gateway/tests/test_auth.py
@@ -14,7 +14,7 @@ from llm_gateway.auth.service import AuthService, extract_token
@pytest.fixture(autouse=True)
-def reset_cache() -> Generator[None, None, None]:
+def reset_cache() -> Generator[None]:
reset_auth_cache()
yield
reset_auth_cache()
diff --git a/services/llm-gateway/tests/test_auth_cache.py b/services/llm-gateway/tests/test_auth_cache.py
index 2a286ff8dc56..c8139acdefd7 100644
--- a/services/llm-gateway/tests/test_auth_cache.py
+++ b/services/llm-gateway/tests/test_auth_cache.py
@@ -12,7 +12,7 @@ from llm_gateway.auth.service import AuthService
@pytest.fixture(autouse=True)
-def reset_cache() -> Generator[None, None, None]:
+def reset_cache() -> Generator[None]:
reset_auth_cache()
yield
reset_auth_cache()
diff --git a/services/llm-gateway/tests/test_streaming.py b/services/llm-gateway/tests/test_streaming.py
index 735b03100200..d72b3de7b447 100644
--- a/services/llm-gateway/tests/test_streaming.py
+++ b/services/llm-gateway/tests/test_streaming.py
@@ -8,7 +8,7 @@ import pytest
from llm_gateway.streaming.sse import format_sse_stream
-async def create_mock_stream(chunks: list[dict[str, Any]]) -> AsyncGenerator[Any, None]:
+async def create_mock_stream(chunks: list[dict[str, Any]]) -> AsyncGenerator[Any]:
for chunk in chunks:
mock_chunk = MagicMock()
mock_chunk.model_dump = MagicMock(return_value=chunk)
@@ -23,7 +23,7 @@ class ProviderError(Exception):
self.status_code = status_code
-async def create_error_stream(chunks_before_error: int = 1) -> AsyncGenerator[Any, None]:
+async def create_error_stream(chunks_before_error: int = 1) -> AsyncGenerator[Any]:
for i in range(chunks_before_error):
mock_chunk = MagicMock()
mock_chunk.model_dump = MagicMock(return_value={"chunk": i})
@@ -36,7 +36,7 @@ async def create_provider_error_stream(
message: str = "Service overloaded",
error_type: str = "overloaded_error",
status_code: int = 529,
-) -> AsyncGenerator[Any, None]:
+) -> AsyncGenerator[Any]:
for i in range(chunks_before_error):
mock_chunk = MagicMock()
mock_chunk.model_dump = MagicMock(return_value={"chunk": i})
@@ -44,7 +44,7 @@ async def create_provider_error_stream(
raise ProviderError(message, error_type, status_code)
-async def collect_stream(stream: AsyncGenerator[bytes, None]) -> list[bytes]:
+async def collect_stream(stream: AsyncGenerator[bytes]) -> list[bytes]:
chunks: list[bytes] = []
try:
async for chunk in stream:
diff --git a/services/llm-gateway/tests/test_streaming_errors.py b/services/llm-gateway/tests/test_streaming_errors.py
index 8d75ead9f371..f4022e916949 100644
--- a/services/llm-gateway/tests/test_streaming_errors.py
+++ b/services/llm-gateway/tests/test_streaming_errors.py
@@ -332,11 +332,11 @@ class TestRequestCountMetrics:
async def test_streaming_mid_stream_error_records_request_count(self, mock_user: AuthenticatedUser) -> None:
before = _get_request_count("500")
- async def error_stream() -> AsyncGenerator[dict[str, Any], None]:
+ async def error_stream() -> AsyncGenerator[dict[str, Any]]:
yield {"type": "content_block_delta", "delta": {"text": "Hello"}}
raise ValueError("mid-stream failure")
- async def mock_llm_call(**kwargs: Any) -> AsyncGenerator[dict[str, Any], None]:
+ async def mock_llm_call(**kwargs: Any) -> AsyncGenerator[dict[str, Any]]:
return error_stream()
response = await handle_llm_request(
@@ -363,11 +363,11 @@ class TestRequestCountMetrics:
provider="anthropic", error_type="ValueError", product="llm_gateway"
)._value.get()
- async def error_stream() -> AsyncGenerator[dict[str, Any], None]:
+ async def error_stream() -> AsyncGenerator[dict[str, Any]]:
yield {"type": "content_block_delta", "delta": {"text": "Hello"}}
raise ValueError("mid-stream failure")
- async def mock_llm_call(**kwargs: Any) -> AsyncGenerator[dict[str, Any], None]:
+ async def mock_llm_call(**kwargs: Any) -> AsyncGenerator[dict[str, Any]]:
return error_stream()
response = await handle_llm_request(