From 5378ece8efd17c9ca626346b8c1f7136dc1eb8cb Mon Sep 17 00:00:00 2001 From: Ishkirat Singh <68938737+Ishkirat-Singh@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:18:22 +0530 Subject: [PATCH 01/33] fix: keep frozenset and deque values when cleaning event properties (#1230) clean() turned set, list and tuple values into lists but sent frozenset and deque values as None, so those properties were silently lost. --- .sampo/changesets/frozen-deque-clean.md | 5 +++++ posthog/test/test_utils.py | 11 +++++++++++ posthog/utils.py | 4 ++-- 3 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 .sampo/changesets/frozen-deque-clean.md diff --git a/.sampo/changesets/frozen-deque-clean.md b/.sampo/changesets/frozen-deque-clean.md new file mode 100644 index 000000000..086791a13 --- /dev/null +++ b/.sampo/changesets/frozen-deque-clean.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +Keep `frozenset` and `deque` property values when cleaning events instead of replacing them with `None`. diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py index e655c8cd5..c8d5e5a1b 100644 --- a/posthog/test/test_utils.py +++ b/posthog/test/test_utils.py @@ -3,6 +3,7 @@ import sys import time import unittest +from collections import deque from contextlib import ExitStack from unittest import mock from dataclasses import dataclass @@ -315,6 +316,16 @@ def test_clean_containers_and_invalid_dict_values(self): "12345678-1234-5678-1234-567812345678", ] + assert utils.clean( + { + "frozenset": frozenset([Decimal("1.5")]), + "deque": deque([UUID("12345678123456781234567812345678")]), + } + ) == { + "frozenset": [1.5], + "deque": ["12345678-1234-5678-1234-567812345678"], + } + bad_value = object() def clean_or_raise(value): diff --git a/posthog/utils.py b/posthog/utils.py index 24e48a781..1f36416a8 100644 --- a/posthog/utils.py +++ b/posthog/utils.py @@ -4,7 +4,7 @@ import re import threading import time -from collections import defaultdict +from collections import defaultdict, deque from dataclasses import asdict, is_dataclass from datetime import date, datetime, timezone, timedelta from decimal import Decimal @@ -89,7 +89,7 @@ def clean(item): return str(item) if isinstance(item, (str, bool, numbers.Number, datetime, date, type(None))): return item - if isinstance(item, (set, list, tuple)): + if isinstance(item, (set, frozenset, list, tuple, deque)): return _clean_list(item) item = _clean_pydantic_model(item) From c0b023073cb226e0491117a703fdff799bb404c0 Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:02:42 +0000 Subject: [PATCH 02/33] chore: Release v7.87.2 [skip ci] --- .sampo/changesets/frozen-deque-clean.md | 5 ----- openfeature-provider/CHANGELOG.md | 6 ++++++ openfeature-provider/pyproject.toml | 2 +- posthog/CHANGELOG.md | 6 ++++++ posthog/version.py | 2 +- pyproject.toml | 2 +- uv.lock | 4 ++-- 7 files changed, 17 insertions(+), 10 deletions(-) delete mode 100644 .sampo/changesets/frozen-deque-clean.md diff --git a/.sampo/changesets/frozen-deque-clean.md b/.sampo/changesets/frozen-deque-clean.md deleted file mode 100644 index 086791a13..000000000 --- a/.sampo/changesets/frozen-deque-clean.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: patch ---- - -Keep `frozenset` and `deque` property values when cleaning events instead of replacing them with `None`. diff --git a/openfeature-provider/CHANGELOG.md b/openfeature-provider/CHANGELOG.md index 9bb007b32..fc8c3a829 100644 --- a/openfeature-provider/CHANGELOG.md +++ b/openfeature-provider/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to `openfeature-provider-posthog` are documented here. This file is maintained by [Sampo](https://github.com/bruits/sampo) from changesets in `.sampo/changesets/` that target `pypi/openfeature-provider-posthog`. +## 0.1.159 — 2026-11-12 + +### Patch changes + +- Updated dependencies: posthog@7.87.2 + ## 0.1.158 — 2026-11-11 ### Patch changes diff --git a/openfeature-provider/pyproject.toml b/openfeature-provider/pyproject.toml index 120233a50..1aed020bd 100644 --- a/openfeature-provider/pyproject.toml +++ b/openfeature-provider/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "openfeature-provider-posthog" -version = "0.1.158" +version = "0.1.159" description = "Official PostHog provider for the OpenFeature Python SDK." readme = "README.md" authors = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/posthog/CHANGELOG.md b/posthog/CHANGELOG.md index c554996eb..830d3dea3 100644 --- a/posthog/CHANGELOG.md +++ b/posthog/CHANGELOG.md @@ -1,5 +1,11 @@ # posthog +## 7.87.2 — 2026-11-12 + +### Patch changes + +- [5378ece8](https://github.com/posthog/posthog-python/commit/5378ece8efd17c9ca626346b8c1f7136dc1eb8cb) Keep `frozenset` and `deque` property values when cleaning events instead of replacing them with `None`. — Thanks @Ishkirat-Singh for your first contribution 🎉! + ## 7.87.1 — 2026-11-11 ### Patch changes diff --git a/posthog/version.py b/posthog/version.py index b650937f8..493c8b8e9 100644 --- a/posthog/version.py +++ b/posthog/version.py @@ -1 +1 @@ -VERSION = "7.87.1" +VERSION = "7.87.2" diff --git a/pyproject.toml b/pyproject.toml index 7889a1ad1..0829a5833 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "posthog" -version = "7.87.1" +version = "7.87.2" description = "Integrate PostHog into any python application." authors = [{ name = "PostHog", email = "engineering@posthog.com" }] maintainers = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/uv.lock b/uv.lock index f06f09591..3af3de736 100644 --- a/uv.lock +++ b/uv.lock @@ -2723,7 +2723,7 @@ wheels = [ [[package]] name = "openfeature-provider-posthog" -version = "0.1.158" +version = "0.1.159" source = { editable = "openfeature-provider" } dependencies = [ { name = "openfeature-sdk" }, @@ -3280,7 +3280,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.87.1" +version = "7.87.2" source = { editable = "." } dependencies = [ { name = "backoff" }, From 7eabca81234311dfd86e516c4354c5322f73bfc5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:08:46 +0200 Subject: [PATCH 03/33] chore(deps): bump langgraph from 1.2.12 to 1.2.14 in /examples/example-ai-crewai in the uv group across 1 directory (#1241) chore(deps): bump langgraph Bumps the uv group with 1 update in the /examples/example-ai-langgraph directory: [langgraph](https://github.com/langchain-ai/langgraph). Updates `langgraph` from 1.2.12 to 1.2.14 - [Release notes](https://github.com/langchain-ai/langgraph/releases) - [Commits](https://github.com/langchain-ai/langgraph/compare/1.2.12...1.2.14) --- updated-dependencies: - dependency-name: langgraph dependency-version: 1.2.14 dependency-type: direct:production dependency-group: uv ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- examples/example-ai-crewai/uv.lock | 18 +++++++++--------- examples/example-ai-langgraph/pyproject.toml | 2 +- examples/example-ai-langgraph/uv.lock | 13 ++++++++----- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/examples/example-ai-crewai/uv.lock b/examples/example-ai-crewai/uv.lock index 2078e56c2..6ec99c2ae 100644 --- a/examples/example-ai-crewai/uv.lock +++ b/examples/example-ai-crewai/uv.lock @@ -2372,14 +2372,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -2476,29 +2476,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] diff --git a/examples/example-ai-langgraph/pyproject.toml b/examples/example-ai-langgraph/pyproject.toml index 20ec5ef04..b43e11d96 100644 --- a/examples/example-ai-langgraph/pyproject.toml +++ b/examples/example-ai-langgraph/pyproject.toml @@ -3,7 +3,7 @@ name = "example-ai-langgraph" version = "0.1.0" requires-python = ">=3.10" dependencies = [ - "langgraph>=0.2.0", + "langgraph>=1.2.14", "langchain-openai>=1.1.14", "opentelemetry-instrumentation-langchain>=0.24.0", "opentelemetry-sdk>=1.30.0", diff --git a/examples/example-ai-langgraph/uv.lock b/examples/example-ai-langgraph/uv.lock index 11180b80f..a717e0111 100644 --- a/examples/example-ai-langgraph/uv.lock +++ b/examples/example-ai-langgraph/uv.lock @@ -192,7 +192,7 @@ dependencies = [ [package.metadata] requires-dist = [ { name = "langchain-openai", specifier = ">=1.1.14" }, - { name = "langgraph", specifier = ">=0.2.0" }, + { name = "langgraph", specifier = ">=1.2.14" }, { name = "opentelemetry-instrumentation-langchain", specifier = ">=0.24.0" }, { name = "opentelemetry-sdk", specifier = ">=1.30.0" }, { name = "posthog", extras = ["otel"], directory = "../../" }, @@ -434,7 +434,7 @@ wheels = [ [[package]] name = "langgraph" -version = "1.2.12" +version = "1.2.14" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "langchain-core" }, @@ -444,9 +444,9 @@ dependencies = [ { name = "pydantic" }, { name = "xxhash" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/99/7e/c9e4431adb5eb78d15f0035aae162a113c80d037ceb433ddd78835217848/langgraph-1.2.12.tar.gz", hash = "sha256:5fae9fa4ce771e90f10ff19ce0d5aaef4b41d7632c713d769e89cbce1241a4b9", size = 734541, upload-time = "2026-09-21T14:43:29.684Z" } +sdist = { url = "https://files.pythonhosted.org/packages/49/3f/6e60789eab2c5ceaf34ba2c626ac345df93b026bbe7385018aa4b9c30397/langgraph-1.2.14.tar.gz", hash = "sha256:5b1a72b7a7f994ac6947b7751fbbe00e949f8bb44d9ab78881604b703247ae55", size = 752793, upload-time = "2026-10-06T14:41:19.789Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/52/27/5a02054c535ed6fcfb2ab1e5c33c51c810cf1e773194ad28c928f0473509/langgraph-1.2.12-py3-none-any.whl", hash = "sha256:95403af7b510de8d79164742f71daaf866c69ca804a8cb72bef2cc1fa1ab9813", size = 250206, upload-time = "2026-09-21T14:43:28.196Z" }, + { url = "https://files.pythonhosted.org/packages/ec/4a/f976df0d3cf7fb7986dc39f656c6b7b5655834430e9bdfaef1e1e4fffaba/langgraph-1.2.14-py3-none-any.whl", hash = "sha256:e3f5f8ff4259f9281b73ff50fc9ef5cc3b025b8936b8283ecdca7cc0c4128690", size = 255980, upload-time = "2026-10-06T14:41:18.129Z" }, ] [[package]] @@ -834,7 +834,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.86.6" +version = "7.87.2" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -867,6 +867,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, From 9636fa20e4ea4315e8b6b6fd43c0ee63ec9bf054 Mon Sep 17 00:00:00 2001 From: Radu Raicea Date: Thu, 12 Nov 2026 10:58:45 -0500 Subject: [PATCH 04/33] feat(llma): support composite offline scorers (#1235) --- .github/scripts/check_strict_types.sh | 17 + .../changesets/composite-offline-scorers.md | 5 + .../example-offline-evaluations/README.md | 75 +++++ examples/example-offline-evaluations/main.py | 32 +- posthog/ai/evaluations/__init__.py | 8 + posthog/ai/evaluations/_client.py | 93 ++++-- posthog/ai/evaluations/_scorer_types.py | 44 +++ posthog/ai/evaluations/_scorers.py | 245 +++++++++++++- posthog/ai/evaluations/_types.py | 85 ++++- posthog/test/ai/test_evaluations.py | 300 +++++++++++++++++- posthog/test/ai/test_evaluations_scorers.py | 292 +++++++++++++++++ references/public_api_snapshot.txt | 49 ++- 12 files changed, 1183 insertions(+), 62 deletions(-) create mode 100644 .sampo/changesets/composite-offline-scorers.md diff --git a/.github/scripts/check_strict_types.sh b/.github/scripts/check_strict_types.sh index 4e41c9e8f..f27e39519 100755 --- a/.github/scripts/check_strict_types.sh +++ b/.github/scripts/check_strict_types.sh @@ -20,9 +20,11 @@ from posthog.ai.evaluations import ( AsyncOfflineEvaluations, BooleanScorerConfig, EvaluationItem, + EvaluationResult, NumericPassingRule, NumericScorerConfig, OfflineEvaluations, + ScorerComposition, ) client = Posthog("phc_test") @@ -73,6 +75,21 @@ async def offline_evaluation_types( async_experiment = await async_client.create_experiment(name="async run") await async_experiment.upload_result(item=item, scorer_version_id=boolean.current_version_id, value=False) _ = config + composition: ScorerComposition = { + "expression": "relevance", + "inputs": [{"alias": "relevance", "scorer_version_id": numeric.current_version_id}], + } + overall = sync_client.scorers.create( + name="Overall", kind="numeric", config=NumericScorerConfig(min=0, max=1), + calculation="composite", composition=composition, + ) + valid: bool = await async_client.scorers.validate_composition(kind="numeric", composition=composition) + sync_client.scorers.list(calculation="composite", input_definition_id=numeric.id) + experiment.upload_results([ + EvaluationResult(item=item, scorer_version_id=numeric.current_version_id, value=0.9), + EvaluationResult(item=item, scorer_version_id=overall.current_version_id, calculate=True), + ]) + _ = valid PY cat > "$tmp/invalid_types.py" <<'PY' diff --git a/.sampo/changesets/composite-offline-scorers.md b/.sampo/changesets/composite-offline-scorers.md new file mode 100644 index 000000000..07c1cb9ac --- /dev/null +++ b/.sampo/changesets/composite-offline-scorers.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: minor +--- + +Support versioned composite scorers for offline evaluations, including formula validation, dependency metadata, explicit server calculations, stored outcome receipts, and composite-safe bulk uploads. diff --git a/examples/example-offline-evaluations/README.md b/examples/example-offline-evaluations/README.md index 00dfec78e..188b2e22e 100644 --- a/examples/example-offline-evaluations/README.md +++ b/examples/example-offline-evaluations/README.md @@ -10,6 +10,8 @@ Offline evaluations must be enabled for your PostHog project. Use the project's | --- | --- | | Create experiments, upload results, complete/fail | Personal API key or project secret key with `offline_evaluation_ingestion:write` | | Fetch scorers and versions | Personal API key with `llm_analytics:read` | +| Validate a composite formula without saving | Personal API key with `llm_analytics:read` | +| Calculate composites using previously stored inputs | Personal API key with ingestion access, `evaluation:read`, and `llm_analytics:read` | | Create/update scorers and create versions | Personal API key with `llm_analytics:write` | | Fetch datasets, items, and history | Personal API key with `dataset:read` | | Create/update/archive/restore datasets and items | Personal API key with `dataset:write` | @@ -92,6 +94,79 @@ EvaluationItem(input=None) # Payload contains a null input. The client context manager releases connections. Call `complete()` explicitly after uploads succeed, or `fail()` when you deliberately want to close the experiment as failed. Neither exceptions nor async cancellation automatically close an experiment. Expected counts include every outcome status; the server checks them on completion. +## Composite item scores + +Composite scorers calculate one score per item on the PostHog server from exact reported scorer versions. They can return numeric, boolean, or categorical values. This requires a backend with composite scorer support; ordinary uploads remain compatible with older backends. + +Provision a composite once, using a personal key with scorer write access. This example assumes `correctness_version_id` identifies a reported boolean scorer and `relevance_version_id` a reported numeric scorer: + +```python +from posthog.ai.evaluations import ScorerComposition + +composition: ScorerComposition = { + "expression": "(number(correct) + relevance) / 2", + "inputs": [ + {"alias": "correct", "scorer_version_id": correctness_version_id}, + {"alias": "relevance", "scorer_version_id": relevance_version_id}, + ], +} +# Optional; read scope is sufficient and no scorer/version is created. +evaluations.scorers.validate_composition( + kind="numeric", composition=composition, config={"min": 0, "max": 1}, +) +overall = evaluations.scorers.create( + name="Overall", + kind="numeric", + calculation="composite", + config={"min": 0, "max": 1, "passing_rule": {"operator": "gte", "threshold": 0.8}}, + composition=composition, +) +overall_version_id = overall.current_version_id +``` + +Save that version UUID for your runs. Creating scorers/versions is not idempotent, so a lost response requires inspecting server state before repeating creation. Update a formula, output configuration, or pinned input through `create_version(scorer_id, config=..., composition=..., base_version=...)`. Supply the complete composition each time. New source versions never update a composite automatically. + +Upload the reported inputs and explicitly request the calculation: + +```python +experiment = evaluations.create_experiment( + name="Composite example", expected_item_count=1, expected_result_count=3, +) +item = EvaluationItem(input="Capital of France?", output="Paris") +receipt = experiment.upload_results([ + EvaluationResult(item=item, scorer_version_id=correctness_version_id, value=True), + EvaluationResult(item=item, scorer_version_id=relevance_version_id, value=0.8), + EvaluationResult(item=item, scorer_version_id=overall_version_id, calculate=True), +]) +for chunk in receipt.chunks: + for outcome in chunk.results: + print(outcome.scorer_version_id, outcome.status, outcome.error_code) +experiment.complete() +``` + +Calculation declarations contain only the item reference, scorer version, and `calculate=True`. Do not supply a value, reasoning, metadata, evaluator trace, or evaluation time. An item may also be referenced by its already accepted UUID. + +Project secret keys and ingestion-only personal keys must supply **every pinned input result in the same HTTP request**, including on retries. Previously uploaded inputs may be resubmitted with their original values and metadata. Reusing stored inputs without resubmitting them requires both `evaluation:read` and `llm_analytics:read`, in addition to ingestion access. Composite requests and retries also require current access to the composite and its inputs. + +The SDK keeps all supplied results for a composite-bearing item together without fetching scorer definitions. It preserves order, so interleaved composite items can form a larger indivisible group. Group each item's results together for large batches. If a group exceeds 1,000 items/results or 5 MiB, the entire call fails locally before any upload. The SDK cannot check that your supplied inputs match the pinned formula without read access; the server validates this. Missing inputs reject the whole HTTP request. Inputs can appear before or after their composite in that request. + +HTTP success acknowledges persistence, not successful calculation. Input errors become `composite_input_error`; formula errors or invalid output values become `composite_formula_error`. Input statuses propagate in the order `error`, `skipped`, `not_applicable`. Check each receipt's `status` and `error_code`; no result-read permission is needed. For ordinary results on an older backend, `status=None` means the backend omitted the outcome. Composite acknowledgments require an outcome. + +All accepted composite outcomes count toward `expected_result_count`, including errors and skips. Derived results add no uploaded-result billing usage. Omitting a composite leaves it unrequested. Exact retries return the stored outcome, including after completion; formulas are not recalculated on retry or read. Persist declarations with `to_dict` and restore them with `from_dict` for exact recovery. + +Formulas support 1–16 reported inputs and at most 1,024 characters; aliases start with a lowercase letter and contain lowercase letters, digits, or underscores, up to 32 characters. Nested composites are unsupported. Use `number(flag)` for explicit boolean conversion and `"good" in categories` for categorical membership. Boolean inputs retain their raw meaning regardless of passing rules. Numeric composites support bounds and passing thresholds, but no non-null `step`. Formula syntax, input access, and output types are validated by the server; runtime values and bounds are checked during ingestion. + +Read `scorer.calculation`, `scorer.composition`, and `scorer.input_scorers` to inspect saved inputs and their pinned/latest versions. `dependent_composite_count` counts accessible active dependents; `scorers.list(calculation="composite", input_definition_id=source_id)` retrieves them. Historical versions retain their saved composition. All operations also exist on `AsyncOfflineEvaluations`. + +The runnable capital-city example can include a composite consuming only its configured boolean scorer version. Provision one with expression `number(correct)`, pin that boolean version as `correct`, and pass its composite version UUID when creating a new state file: + +```bash +uv run python examples/example-offline-evaluations/main.py \ + --state composite-run.json --composite-version-id 'your-composite-version-uuid' +``` + +The state file includes both reported and calculation declarations and the combined expected count. Reusing the file replays that saved run regardless of newly supplied scorer flags. + ## Datasets and reproducible evaluations Use `evaluations.datasets` to manage PostHog-hosted datasets with the same client configuration as scorers and experiments. Dataset names are unique within a project; keep the returned UUID for subsequent operations. diff --git a/examples/example-offline-evaluations/main.py b/examples/example-offline-evaluations/main.py index 6c2e7826f..de0832cba 100644 --- a/examples/example-offline-evaluations/main.py +++ b/examples/example-offline-evaluations/main.py @@ -29,8 +29,8 @@ def resolve_version(evaluations: OfflineEvaluations) -> str: "Set POSTHOG_SCORER_ID or POSTHOG_SCORER_VERSION_ID, or run --create-scorer once." ) scorer = evaluations.scorers.get(scorer_id) - if scorer.kind != "boolean": - raise ValueError("This example requires a boolean scorer.") + if scorer.kind != "boolean" or scorer.calculation != "reported": + raise ValueError("This example requires a reported boolean scorer.") return scorer.current_version_id @@ -67,6 +67,7 @@ def prepare_state( *, dataset_id: str | None = None, dataset_revision: int | None = None, + composite_version_id: str | None = None, ) -> dict[str, Any]: version_id = resolve_version(evaluations) cases = [ @@ -100,7 +101,17 @@ def prepare_state( ) for case in cases ] - results = [exact_match_result(item, version_id) for item in items] + results = [] + for item in items: + results.append(exact_match_result(item, version_id)) + if composite_version_id is not None: + results.append( + EvaluationResult( + item=item, + scorer_version_id=composite_version_id, + calculate=True, + ) + ) return { "project_id": project_id, "host": host, @@ -153,6 +164,10 @@ def main() -> None: type=int, help="Pin this numeric revision; defaults to latest once.", ) + parser.add_argument( + "--composite-version-id", + help="Also calculate this composite version, which must pin the configured boolean scorer version.", + ) args = parser.parse_args() if args.dataset_revision is not None and args.dataset_id is None: parser.error("--dataset-revision requires --dataset-id") @@ -186,6 +201,7 @@ def main() -> None: host, dataset_id=args.dataset_id, dataset_revision=args.dataset_revision, + composite_version_id=args.composite_version_id, ) save_state(args.state, state) @@ -215,6 +231,16 @@ def main() -> None: print( f"Acknowledged {sum(len(chunk.results) for chunk in receipt.chunks)} results across {len(receipt.chunks)} chunks." ) + errors = [ + result + for chunk in receipt.chunks + for result in chunk.results + if result.status == "error" + ] + if errors: + print( + f"Accepted {len(errors)} error outcomes: {[result.error_code for result in errors]}" + ) print( f"Keep {args.state} for exact replay; choose a different --state path for a new experiment." ) diff --git a/posthog/ai/evaluations/__init__.py b/posthog/ai/evaluations/__init__.py index 2dbd0cc35..aa8c3e227 100644 --- a/posthog/ai/evaluations/__init__.py +++ b/posthog/ai/evaluations/__init__.py @@ -36,7 +36,11 @@ NumericPassingRule, NumericScorerConfig, Scorer, + ScorerCalculation, + ScorerComposition, + ScorerCompositionInput, ScorerConfig, + ScorerInput, ScorerKind, ScorerOrder, ScorerPage, @@ -99,7 +103,11 @@ "RunSource", "ScoreValue", "Scorer", + "ScorerCalculation", + "ScorerComposition", + "ScorerCompositionInput", "ScorerConfig", + "ScorerInput", "ScorerKind", "ScorerOrder", "ScorerPage", diff --git a/posthog/ai/evaluations/_client.py b/posthog/ai/evaluations/_client.py index db0a5d695..475a856a3 100644 --- a/posthog/ai/evaluations/_client.py +++ b/posthog/ai/evaluations/_client.py @@ -95,6 +95,30 @@ def _upload_body(items: list[bytes], results: list[bytes]) -> bytes: ) +def _group_ends(results: tuple[EvaluationResult, ...]) -> list[int]: + # A calculation only names a version, so ingestion-only clients cannot + # discover its dependencies. Keep every supplied result for that item in + # one request. Merge overlapping spans to retain the original order. + first: dict[str, int] = {} + last: dict[str, int] = {} + composite_items: set[str] = set() + for index, result in enumerate(results): + first.setdefault(result.item_id, index) + last[result.item_id] = index + 1 + if result.calculate: + composite_items.add(result.item_id) + spans = {first[item_id]: last[item_id] for item_id in composite_items} + ends: list[int] = [] + index = 0 + while index < len(results): + end = index + 1 + while index < end: + end = max(end, spans.get(index, index + 1)) + index += 1 + ends.append(end) + return ends + + def _chunks(results: tuple[EvaluationResult, ...]) -> list[_Chunk]: # Validate the finite submission before sending any chunk. Receipts and # prepared bodies use memory proportional to this caller-sized sequence. @@ -120,38 +144,50 @@ def _chunks(results: tuple[EvaluationResult, ...]) -> list[_Chunk]: encoded_results: list[bytes] = [] start = 0 size = len(_upload_body([], [])) - for index, result in enumerate(results): - # Include declarations wherever their results occur. This makes every - # chunk independently replayable even after a lost acknowledgment. - item = ( - declarations.get(result.item_id) if result.item_id not in item_ids else None - ) - extra = len(result._json) + bool(encoded_results) - if item is not None: - extra += len(item) + bool(items) - if encoded_results and ( - len(encoded_results) >= _MAX_RESULTS - or len(items) + (item is not None) > _MAX_ITEMS - or size + extra > _MAX_REQUEST_BYTES - ): + group_start = 0 + for end in _group_ends(results): + group = results[group_start:end] + group_results = [result._json for result in group] + group_items = { + result.item_id: declarations[result.item_id] + for result in group + if result.item_id in declarations + } + while True: + new_items = [body for id, body in group_items.items() if id not in item_ids] + extra = ( + sum(map(len, group_results)) + + len(group_results) + - (not encoded_results) + ) + if new_items: + extra += sum(map(len, new_items)) + len(new_items) - (not items) + fits = ( + len(encoded_results) + len(group) <= _MAX_RESULTS + and len(items) + len(new_items) <= _MAX_ITEMS + and size + extra <= _MAX_REQUEST_BYTES + ) + if fits: + break + if not encoded_results: + raise ValueError( + "One result or composite item group exceeds the upload request limit." + ) chunks.append( _Chunk( - start, results[start:index], _upload_body(items, encoded_results) + start, + results[start:group_start], + _upload_body(items, encoded_results), ) ) - start, size = index, len(_upload_body([], [])) + start, size = group_start, len(_upload_body([], [])) item_ids, items, encoded_results = set(), [], [] - item = declarations.get(result.item_id) - extra = len(result._json) + (len(item) if item is not None else 0) - if size + extra > _MAX_REQUEST_BYTES: - raise ValueError( - "One result and its item exceed the upload request byte limit." - ) - if item is not None: - item_ids.add(result.item_id) - items.append(item) - encoded_results.append(result._json) + # Repeat available declarations in every request for exact recovery. + item_ids.update(group_items) + items.extend(new_items) + encoded_results.extend(group_results) size += extra + group_start = end if encoded_results: chunks.append( _Chunk(start, results[start:], _upload_body(items, encoded_results)) @@ -245,6 +281,11 @@ def upload_results(self, results: Sequence[EvaluationResult]) -> BulkUploadRecei Returns per-chunk receipts; an empty sequence makes no requests. Memory scales with the caller's sequence. For large datasets, call in batches. BulkUploadError exposes committed chunks and pending_results to retry. + Items with calculations keep all their supplied results in one request. + Interleaved items may form a larger indivisible group; an oversized + group fails before any I/O. Group each item's results together when + preparing large batches. Stored inputs require evaluation:read and + llm_analytics:read; ingestion-only keys must supply every pinned input. """ prepared = tuple(results) chunks = _chunks(prepared) diff --git a/posthog/ai/evaluations/_scorer_types.py b/posthog/ai/evaluations/_scorer_types.py index e7aedd95b..7651047a6 100644 --- a/posthog/ai/evaluations/_scorer_types.py +++ b/posthog/ai/evaluations/_scorer_types.py @@ -10,6 +10,7 @@ ScorerKind = Literal["boolean", "numeric", "categorical"] +ScorerCalculation = Literal["reported", "composite"] ScorerOrder = Literal[ "name", "-name", @@ -89,6 +90,43 @@ class CategoricalScorerConfig(TypedDict, total=False): _ConfigT = TypeVar("_ConfigT", bound=ScorerConfig, covariant=True) +class ScorerCompositionInput(TypedDict): + """A formula alias and an exact reported scorer-version UUID.""" + + alias: str + scorer_version_id: str + + +class ScorerComposition(TypedDict): + """Server-evaluated formula and its pinned inputs for the same item. + + Formulas accept 1–16 reported inputs; nested composites are unsupported. + Boolean inputs retain their raw polarity and categorical inputs are key + lists. Use ``number(flag)`` and ``"key" in categories`` explicitly. + """ + + expression: str + inputs: list[ScorerCompositionInput] + + +@dataclass(frozen=True) +class ScorerInput: + """Pinned input metadata alongside the source's latest version. + + A new source version never changes the composite's pinned configuration. + """ + + alias: str + scorer_version_id: str + definition_id: str + name: str + kind: ScorerKind + version: int + config: ScorerConfig + latest_version_id: str | None + latest_version: int | None + + @dataclass(frozen=True) class Scorer(Generic[_ConfigT]): """Scorer metadata and the configuration of its current immutable version. @@ -112,6 +150,10 @@ class Scorer(Generic[_ConfigT]): created_by: dict[str, Any] | None team: int tags: tuple[str, ...] = () + calculation: ScorerCalculation = "reported" + composition: ScorerComposition | None = None + input_scorers: tuple[ScorerInput, ...] = () + dependent_composite_count: int = 0 @dataclass(frozen=True) @@ -125,6 +167,8 @@ class ScorerVersion(Generic[_ConfigT]): config: _ConfigT created_at: datetime created_by: dict[str, Any] | None + calculation: ScorerCalculation = "reported" + composition: ScorerComposition | None = None @dataclass(frozen=True) diff --git a/posthog/ai/evaluations/_scorers.py b/posthog/ai/evaluations/_scorers.py index a99bd7ddf..72ae60b9e 100644 --- a/posthog/ai/evaluations/_scorers.py +++ b/posthog/ai/evaluations/_scorers.py @@ -4,6 +4,7 @@ import copy import json +import re from datetime import datetime from typing import Any, Callable, Literal, Sequence, TypeVar, cast, overload from uuid import UUID @@ -13,7 +14,10 @@ CategoricalScorerConfig, NumericScorerConfig, Scorer, + ScorerCalculation, + ScorerComposition, ScorerConfig, + ScorerInput, ScorerKind, ScorerOrder, ScorerPage, @@ -56,6 +60,89 @@ def _kind(value: Any) -> ScorerKind: return cast(ScorerKind, value) +def _calculation(value: Any) -> ScorerCalculation: + if value not in ("reported", "composite"): + raise ValueError("Unsupported scorer calculation.") + return cast(ScorerCalculation, value) + + +def _alias(value: Any) -> str: + value = _text(value) + if not re.fullmatch(r"[a-z][a-z0-9_]{0,31}", value) or value in { + "number", + "min", + "max", + "abs", + "and", + "or", + "not", + "if", + "else", + "in", + "is", + "lambda", + "for", + "await", + }: + raise ValueError("Invalid composite input alias.") + return value + + +def _composition(value: Any) -> ScorerComposition: + data = _mapping(value) + expression = _text(data.get("expression")) + if not expression.strip() or len(expression) > 1024: + raise ValueError("A formula must contain 1–1024 characters.") + inputs = data.get("inputs") + if not isinstance(inputs, list) or not 1 <= len(inputs) <= 16: + raise ValueError("A composite requires 1–16 reported inputs.") + prepared = [ + { + "alias": _alias(_mapping(row).get("alias")), + "scorer_version_id": _uuid(row.get("scorer_version_id")), + } + for row in inputs + ] + if len({row["alias"] for row in prepared}) != len(prepared): + raise ValueError("Composite input aliases must be unique.") + return cast(ScorerComposition, {"expression": expression, "inputs": prepared}) + + +def _scoring( + data: dict[str, Any], +) -> tuple[ScorerCalculation, ScorerComposition | None]: + calculation = _calculation(data.get("calculation", "reported")) + composition = data.get("composition") + if calculation == "composite": + return calculation, _composition(composition) + if composition is not None: + raise ValueError("Reported scorers cannot contain a composition.") + return calculation, None + + +def _input_scorers(value: Any) -> tuple[ScorerInput, ...]: + if not isinstance(value, list): + raise ValueError("Expected input scorer metadata.") + return tuple( + ScorerInput( + alias=_alias(_mapping(row)["alias"]), + scorer_version_id=_uuid(row["scorer_version_id"]), + definition_id=_uuid(row["definition_id"]), + name=_text(row["name"]), + kind=_kind(row["kind"]), + version=_integer(row["version"], minimum=1), + config=cast(ScorerConfig, _mapping(row["config"])), + latest_version_id=None + if row["latest_version_id"] is None + else _uuid(row["latest_version_id"]), + latest_version=None + if row["latest_version"] is None + else _integer(row["latest_version"], minimum=1), + ) + for row in value + ) + + def _timestamp(value: Any) -> datetime: parsed = datetime.fromisoformat(_text(value).replace("Z", "+00:00")) if parsed.tzinfo is None or parsed.utcoffset() is None: @@ -70,6 +157,7 @@ def _mapping(value: Any) -> dict[str, Any]: def _scorer(data: dict[str, Any]) -> Scorer[ScorerConfig]: + calculation, composition = _scoring(data) archived = data["archived"] if not isinstance(archived, bool): raise ValueError("Expected boolean archived state.") @@ -89,10 +177,17 @@ def _scorer(data: dict[str, Any]) -> Scorer[ScorerConfig]: created_by=None if created_by is None else _mapping(created_by), team=_integer(data["team"], minimum=1), tags=_response_tags(data.get("tags", [])), + calculation=calculation, + composition=composition, + input_scorers=_input_scorers(data.get("input_scorers", [])), + dependent_composite_count=_integer( + data.get("dependent_composite_count", 0), minimum=0 + ), ) def _version(data: dict[str, Any]) -> ScorerVersion[ScorerConfig]: + calculation, composition = _scoring(data) created_by = data["created_by"] return ScorerVersion( id=_uuid(data["id"]), @@ -102,6 +197,8 @@ def _version(data: dict[str, Any]) -> ScorerVersion[ScorerConfig]: config=cast(ScorerConfig, _mapping(data["config"])), created_at=_timestamp(data["created_at"]), created_by=None if created_by is None else _mapping(created_by), + calculation=calculation, + composition=composition, ) @@ -154,12 +251,20 @@ def _create_body( config: ScorerConfig, description: str | None | _Omitted, tags: Sequence[str] | _Omitted, + calculation: ScorerCalculation, + composition: ScorerComposition | None, ) -> bytes: data: dict[str, Any] = { "name": name, "kind": _kind(kind), "config": _mapping(config), } + if _calculation(calculation) == "composite": + data["calculation"] = calculation + data["composition"] = _composition(composition) + _composite_config(kind, config) + elif composition is not None: + raise ValueError("Only composite scorers accept a composition.") if not isinstance(description, _Omitted): data["description"] = description if not isinstance(tags, _Omitted): @@ -192,9 +297,14 @@ def _version_body( base_version: int | None, name: str | _Omitted, description: str | None | _Omitted, + composition: ScorerComposition | None, ) -> bytes: data = _metadata(name, description) data["config"] = _mapping(config) + if composition is not None: + data["composition"] = _composition(composition) + if config.get("step") is not None: + raise ValueError("Numeric composite scorers do not accept a step.") if base_version is not None: data["base_version"] = _integer(base_version, minimum=1) return _encode(data) @@ -209,6 +319,8 @@ def _list_params( order_by: ScorerOrder | None, tags: Sequence[str] | None, tag_match: Literal["any", "all"], + calculation: ScorerCalculation | None, + input_definition_id: str | UUID | None, ) -> dict[str, str | int]: tag_params = _tag_params(tags, tag_match) params: dict[str, str | int] = { @@ -219,6 +331,10 @@ def _list_params( params["search"] = search if kind is not None: params["kind"] = _kind(kind) + if calculation is not None: + params["calculation"] = _calculation(calculation) + if input_definition_id is not None: + params["input_definition_id"] = _uuid(input_definition_id) if archived is not None: if not isinstance(archived, bool): raise ValueError("archived must be a boolean.") @@ -229,6 +345,30 @@ def _list_params( return params +def _composite_config(kind: ScorerKind, config: ScorerConfig) -> None: + if kind == "numeric" and config.get("step") is not None: + raise ValueError("Numeric composite scorers do not accept a step.") + + +def _validation_body( + kind: ScorerKind, composition: ScorerComposition, config: ScorerConfig | None +) -> bytes: + data: dict[str, Any] = { + "kind": _kind(kind), + "composition": _composition(composition), + } + if config is not None: + data["config"] = _mapping(config) + _composite_config(kind, config) + return _encode(data) + + +def _validation(data: dict[str, Any]) -> bool: + if data.get("valid") is not True: + raise ValueError("Expected successful formula validation.") + return True + + def _version_params(limit: int, cursor: str | None) -> dict[str, str | int]: if _integer(limit, minimum=1) > 100: raise ValueError("Version page limit must be between 1 and 100.") @@ -262,6 +402,8 @@ def create( config: BooleanScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, + calculation: ScorerCalculation = "reported", + composition: ScorerComposition | None = None, ) -> Scorer[BooleanScorerConfig]: ... @overload @@ -273,6 +415,8 @@ def create( config: NumericScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, + calculation: ScorerCalculation = "reported", + composition: ScorerComposition | None = None, ) -> Scorer[NumericScorerConfig]: ... @overload @@ -284,6 +428,8 @@ def create( config: CategoricalScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, + calculation: ScorerCalculation = "reported", + composition: ScorerComposition | None = None, ) -> Scorer[CategoricalScorerConfig]: ... def create( @@ -294,17 +440,23 @@ def create( config: ScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, + calculation: ScorerCalculation = "reported", + composition: ScorerComposition | None = None, ) -> Scorer[ScorerConfig]: """Create a scorer and its first version, optionally assigning tags. Tag names are trimmed, lowercased, deduplicated, and sorted by the server. + Set calculation="composite" with a composition to calculate item scores + on the server. Calculation and output kind cannot change after creation. """ return _parse( _scorer, self._transport.request( "POST", self._base, - body=_create_body(name, kind, config, description, tags), + body=_create_body( + name, kind, config, description, tags, calculation, composition + ), retry_safe=False, ), ) @@ -324,6 +476,8 @@ def list( order_by: ScorerOrder | None = None, tags: Sequence[str] | None = None, tag_match: Literal["any", "all"] = "any", + calculation: ScorerCalculation | None = None, + input_definition_id: str | UUID | None = None, ) -> ScorerPage: """Fetch one page. Omit ``archived`` to list active scorers. @@ -331,6 +485,8 @@ def list( Search matches names and descriptions; scorer names are not unique. ``tags`` accepts up to 20 names. ``tag_match`` matches any (default) or all selected tags; an empty sequence disables tag filtering. + Use calculation to select reported/composite scorers, and + input_definition_id to find composites depending on a source scorer. """ return _parse( _scorer_page, @@ -338,7 +494,16 @@ def list( "GET", self._base, params=_list_params( - limit, offset, search, kind, archived, order_by, tags, tag_match + limit, + offset, + search, + kind, + archived, + order_by, + tags, + tag_match, + calculation, + input_definition_id, ), ), ) @@ -376,12 +541,15 @@ def create_version( base_version: int | None = None, name: str | _Omitted = _OMITTED, description: str | None | _Omitted = _OMITTED, + composition: ScorerComposition | None = None, ) -> Scorer[_ConfigT]: """Create an immutable version and return the updated scorer. Pass the observed ``current_version`` as ``base_version`` to detect concurrent writes. Conflicts are surfaced without automatic refresh. Identical configuration is allowed, for example after a prompt change. + Composite versions require composition, including every pinned input, + even when only changing the output configuration. """ return cast( Scorer[_ConfigT], @@ -390,7 +558,9 @@ def create_version( self._transport.request( "POST", self._path(scorer_id) + "new_version/", - body=_version_body(config, base_version, name, description), + body=_version_body( + config, base_version, name, description, composition + ), retry_safe=False, ), ), @@ -407,6 +577,28 @@ def get_version( ), ) + def validate_composition( + self, + *, + kind: ScorerKind, + composition: ScorerComposition, + config: ScorerConfig | None = None, + ) -> bool: + """Validate a formula without saving, using llm_analytics:read access. + + Returns True on validation success; invalid formulas raise + EvaluationAPIError. Omit config to check syntax and types only. + Runtime values and output bounds are checked during calculation. + """ + return _parse( + _validation, + self._transport.request( + "POST", + self._base + "validate_composition/", + body=_validation_body(kind, composition, config), + ), + ) + def list_versions( self, scorer_id: str | UUID, *, limit: int = 50, cursor: str | None = None ) -> ScorerVersionPage: @@ -440,6 +632,8 @@ async def create( config: BooleanScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, + calculation: ScorerCalculation = "reported", + composition: ScorerComposition | None = None, ) -> Scorer[BooleanScorerConfig]: ... @overload @@ -451,6 +645,8 @@ async def create( config: NumericScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, + calculation: ScorerCalculation = "reported", + composition: ScorerComposition | None = None, ) -> Scorer[NumericScorerConfig]: ... @overload @@ -462,6 +658,8 @@ async def create( config: CategoricalScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, + calculation: ScorerCalculation = "reported", + composition: ScorerComposition | None = None, ) -> Scorer[CategoricalScorerConfig]: ... async def create( @@ -472,6 +670,8 @@ async def create( config: ScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, + calculation: ScorerCalculation = "reported", + composition: ScorerComposition | None = None, ) -> Scorer[ScorerConfig]: """Create a scorer with optional tags. See Scorers.create.""" return _parse( @@ -479,7 +679,9 @@ async def create( await self._transport.request( "POST", self._base, - body=_create_body(name, kind, config, description, tags), + body=_create_body( + name, kind, config, description, tags, calculation, composition + ), retry_safe=False, ), ) @@ -501,6 +703,8 @@ async def list( order_by: ScorerOrder | None = None, tags: Sequence[str] | None = None, tag_match: Literal["any", "all"] = "any", + calculation: ScorerCalculation | None = None, + input_definition_id: str | UUID | None = None, ) -> ScorerPage: """Fetch one page with optional tag filters. See Scorers.list.""" return _parse( @@ -509,7 +713,16 @@ async def list( "GET", self._base, params=_list_params( - limit, offset, search, kind, archived, order_by, tags, tag_match + limit, + offset, + search, + kind, + archived, + order_by, + tags, + tag_match, + calculation, + input_definition_id, ), ), ) @@ -542,6 +755,7 @@ async def create_version( base_version: int | None = None, name: str | _Omitted = _OMITTED, description: str | None | _Omitted = _OMITTED, + composition: ScorerComposition | None = None, ) -> Scorer[_ConfigT]: """Create a version; ``base_version`` detects concurrent configuration edits. @@ -554,7 +768,9 @@ async def create_version( await self._transport.request( "POST", self._path(scorer_id) + "new_version/", - body=_version_body(config, base_version, name, description), + body=_version_body( + config, base_version, name, description, composition + ), retry_safe=False, ), ), @@ -571,6 +787,23 @@ async def get_version( ), ) + async def validate_composition( + self, + *, + kind: ScorerKind, + composition: ScorerComposition, + config: ScorerConfig | None = None, + ) -> bool: + """Validate without saving. See Scorers.validate_composition.""" + return _parse( + _validation, + await self._transport.request( + "POST", + self._base + "validate_composition/", + body=_validation_body(kind, composition, config), + ), + ) + async def list_versions( self, scorer_id: str | UUID, *, limit: int = 50, cursor: str | None = None ) -> ScorerVersionPage: diff --git a/posthog/ai/evaluations/_types.py b/posthog/ai/evaluations/_types.py index 595f06920..7365ffb8a 100644 --- a/posthog/ai/evaluations/_types.py +++ b/posthog/ai/evaluations/_types.py @@ -3,7 +3,7 @@ import json from dataclasses import dataclass, field from datetime import datetime -from typing import Any, Literal, Mapping +from typing import Any, Literal, Mapping, cast from uuid import UUID, uuid4 from typing_extensions import TypedDict @@ -59,11 +59,13 @@ class ExperimentOptions(TypedDict, total=False): class ResultOptions(TypedDict, total=False): """Score outcome, trace references, and optional result payload fields. - ``value`` is required for ``ok`` (the default). ``error_code`` and + ``calculate=True`` requests a composite with no value or result metadata. + Otherwise ``value`` is required for ``ok`` (the default). ``error_code`` and ``error_message`` are permitted only for ``error``. Use either ``payload`` or individual payload fields; omitted values differ from explicit None. """ + calculate: bool value: ScoreValue | None status: ResultStatus error_code: str | None @@ -199,10 +201,14 @@ class EvaluationResult: determines whether the value passes. Other statuses contain no score. Pass an item object to declare it, or an item UUID already accepted by the experiment. Payloads and values are snapshotted during construction. + Set ``calculate=True`` to request a composite with no value or metadata. + Include its pinned reported inputs in the same upload unless the caller + has result-read access to reuse stored inputs. """ item: EvaluationItem | str scorer_version_id: str + calculate: bool _json: bytes = field(repr=False) def __init__( @@ -210,6 +216,7 @@ def __init__( *, item: EvaluationItem | str | UUID, scorer_version_id: str | UUID, + calculate: bool = False, value: ScoreValue | None = None, status: ResultStatus = "ok", error_code: str | None = None, @@ -222,6 +229,22 @@ def __init__( ) -> None: item_id = item.id if isinstance(item, EvaluationItem) else _uuid(item) version_id = _uuid(scorer_version_id) + if not isinstance(calculate, bool): + raise ValueError("calculate must be a boolean.") + if calculate and ( + value is not None + or status != "ok" + or error_code is not None + or evaluator_trace_id is not None + or evaluated_at is not None + or any( + not isinstance(field, _Unset) + for field in (reasoning, error_message, metadata, payload) + ) + ): + raise ValueError( + "A calculation accepts only item, scorer_version_id, and calculate=True." + ) if status not in ("ok", "error", "skipped", "not_applicable"): raise ValueError("Unsupported result status.") if status != "ok" and value is not None: @@ -231,9 +254,12 @@ def __init__( data: dict[str, Any] = { "item_id": item_id, "scorer_version_id": version_id, - "status": status, } - if status == "ok": + if calculate: + data["calculate"] = True + else: + data["status"] = status + if status == "ok" and not calculate: data["value"] = _score(value) if error_code is not None: data["error_code"] = _identifier(error_code, "error_code", 128) @@ -260,6 +286,7 @@ def __init__( self, "item", item if isinstance(item, EvaluationItem) else item_id ) object.__setattr__(self, "scorer_version_id", version_id) + object.__setattr__(self, "calculate", calculate) object.__setattr__(self, "_json", _encode(data)) @property @@ -310,10 +337,16 @@ class ItemReceipt: @dataclass(frozen=True) class ResultReceipt(ItemReceipt): - """Persisted result UUID and the item/scorer-version pair it acknowledges.""" + """Persisted result identity and stored outcome, including formula errors. + + ``status=None`` means an older backend omitted the outcome of a reported + result. Composite acknowledgments always require a server outcome. + """ item_id: str scorer_version_id: str + status: ResultStatus | None = None + error_code: str | None = None @dataclass(frozen=True) @@ -401,6 +434,30 @@ def _experiment_receipt(data: dict[str, Any], identity: str) -> ExperimentReceip ) from None +def _result_receipt(data: dict[str, Any]) -> ResultReceipt: + status = data.get("status") + error_code = data.get("error_code") + if "status" in data or "error_code" in data: + if ( + status not in ("ok", "error", "skipped", "not_applicable") + or "error_code" not in data + ): + raise ValueError("Invalid stored result outcome.") + if error_code is not None: + if status != "error": + raise ValueError("Only an error outcome may contain an error code.") + error_code = _identifier(error_code, "error_code", 128) + return ResultReceipt( + id=_uuid(data["id"]), + created=_boolean(data["created"]), + accepted_at=_date(data["accepted_at"]), + item_id=_uuid(data["item_id"]), + scorer_version_id=_uuid(data["scorer_version_id"]), + status=cast(ResultStatus | None, status), + error_code=error_code, + ) + + def _upload_receipt( data: dict[str, Any], results: tuple[EvaluationResult, ...] ) -> UploadReceipt: @@ -415,16 +472,7 @@ def _upload_receipt( ) for row in data["items"] ) - outcomes = tuple( - ResultReceipt( - id=_uuid(_object(row)["id"]), - created=_boolean(row["created"]), - accepted_at=_date(row["accepted_at"]), - item_id=_uuid(row["item_id"]), - scorer_version_id=_uuid(row["scorer_version_id"]), - ) - for row in data["results"] - ) + outcomes = tuple(_result_receipt(_object(row)) for row in data["results"]) if len(items) != len({item.id for item in items}) or { item.id for item in items } != {result.item_id for result in results}: @@ -435,6 +483,13 @@ def _upload_receipt( raise ValueError("Incomplete result acknowledgments.") if len({result.id for result in outcomes}) != len(outcomes): raise ValueError("Duplicate result identities in acknowledgment.") + if any( + result.calculate and outcome.status is None + for result, outcome in zip(results, outcomes) + ): + raise ValueError( + "A composite acknowledgment must include its stored outcome." + ) return UploadReceipt(items=items, results=outcomes) except (KeyError, TypeError, ValueError): raise EvaluationAPIError( diff --git a/posthog/test/ai/test_evaluations.py b/posthog/test/ai/test_evaluations.py index 99bcd962c..a132fa370 100644 --- a/posthog/test/ai/test_evaluations.py +++ b/posthog/test/ai/test_evaluations.py @@ -114,6 +114,283 @@ def result(item=None, **kwargs): ) +def composite(item): + return EvaluationResult( + item=item, scorer_version_id=OTHER_VERSION_ID, calculate=True + ) + + +def composite_response(method, path, *, body): + response = upload_response(body) + for row, declaration in zip(response["results"], json.loads(body)["results"]): + row.update( + status=declaration.get("status", "ok"), + error_code=declaration.get("error_code"), + ) + return response + + +def test_calculation_declarations_round_trip_without_metadata(): + item = EvaluationItem(input="question", model_version="test-model") + declaration = composite(item) + expected = { + "item_id": item.id, + "scorer_version_id": OTHER_VERSION_ID, + "calculate": True, + } + assert declaration.to_dict() == expected + restored = EvaluationResult.from_dict(expected, item=item) + expected["calculate"] = False + assert restored == declaration + assert restored.calculate is True + assert ( + EvaluationResult.from_dict(declaration.to_dict()).to_dict() + == declaration.to_dict() + ) + assert "calculate" not in result(item, calculate=False).to_dict() + + +@pytest.mark.parametrize( + "options", + [ + {"calculate": 1}, + {"calculate": "true"}, + {"calculate": None}, + {"value": False}, + {"value": 0}, + {"status": "error"}, + {"status": "skipped"}, + {"error_code": "bad"}, + {"reasoning": None}, + {"metadata": {}}, + {"error_message": None}, + {"payload": {}}, + {"evaluator_trace_id": "trace"}, + {"evaluated_at": ACCEPTED_AT}, + ], +) +def test_invalid_calculation_fields_fail_before_upload(client, options): + evaluations, transport = client + with pytest.raises(ValueError): + invoke( + evaluations.resume_experiment(EXPERIMENT_ID).upload_result, + **( + { + "item": EvaluationItem(), + "scorer_version_id": OTHER_VERSION_ID, + "calculate": True, + } + | options + ), + ) + transport.request.assert_not_called() + + +@pytest.mark.parametrize( + "status,error_code", + [ + ("ok", None), + ("error", "composite_input_error"), + ("error", "composite_formula_error"), + ("skipped", None), + ("not_applicable", None), + ], +) +def test_calculated_outcome_is_visible_on_initial_upload_and_replay( + client, status, error_code +): + evaluations, transport = client + experiment = evaluations.resume_experiment(EXPERIMENT_ID) + item = EvaluationItem() + + def acknowledge(method, path, *, body): + response = composite_response(method, path, body=body) + response["results"][0].update( + status=status, + error_code=error_code, + created=transport.request.call_count == 1, + ) + return response + + transport.request.side_effect = acknowledge + for created in [True, False]: + receipt = invoke( + experiment.upload_result, + item=item, + scorer_version_id=OTHER_VERSION_ID, + calculate=True, + ) + assert (receipt.results[0].status, receipt.results[0].error_code) == ( + status, + error_code, + ) + assert receipt.results[0].created is created + assert json.loads(transport.request.call_args.kwargs["body"])["results"] == [ + composite(item).to_dict() + ] + assert transport.request.call_args_list[0] == transport.request.call_args_list[1] + + +@pytest.mark.parametrize( + "outcome", + [ + {}, + {"status": "ok"}, + {"status": "unknown", "error_code": None}, + {"status": None, "error_code": None}, + {"status": "ok", "error_code": "unexpected"}, + {"status": "error", "error_code": 42}, + ], +) +def test_invalid_composite_acknowledgments_preserve_uncertain_pending_work( + client, outcome +): + evaluations, transport = client + declarations = [composite(EvaluationItem())] + + def acknowledge(method, path, *, body): + response = upload_response(body) + response["results"][0].update(outcome) + return response + + transport.request.side_effect = acknowledge + with pytest.raises(BulkUploadError) as caught: + invoke( + evaluations.resume_experiment(EXPERIMENT_ID).upload_results, declarations + ) + assert caught.value.code == "invalid_response" + assert caught.value.persistence == "unknown" + assert caught.value.pending_results == tuple(declarations) + + +def test_reported_receipts_accept_legacy_and_new_outcomes(client): + evaluations, transport = client + experiment = evaluations.resume_experiment(EXPERIMENT_ID) + kwargs = dict( + item=EvaluationItem(), + scorer_version_id=VERSION_ID, + status="error", + error_code="judge_failed", + ) + assert invoke(experiment.upload_result, **kwargs).results[0].status is None + transport.request.side_effect = composite_response + receipt = invoke(experiment.upload_result, **kwargs).results[0] + assert (receipt.status, receipt.error_code) == ("error", "judge_failed") + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_real_count_boundary_keeps_inputs_with_calculation_in_original_order( + client, reverse +): + evaluations, transport = client + transport.request.side_effect = composite_response + item = EvaluationItem() + group = [result(item), composite(item)] + if reverse: + group.reverse() + declarations = [result() for _ in range(999)] + group + receipt = invoke( + evaluations.resume_experiment(EXPERIMENT_ID).upload_results, declarations + ) + assert [len(chunk.results) for chunk in receipt.chunks] == [999, 2] + sent = [ + json.loads(call.kwargs["body"]) for call in transport.request.call_args_list + ] + assert sent[1] == { + "items": [item.to_dict()], + "results": [row.to_dict() for row in group], + } + assert [ + (row.item_id, row.scorer_version_id) + for chunk in receipt.chunks + for row in chunk.results + ] == [(row.item_id, row.scorer_version_id) for row in declarations] + + +def test_overlapping_composite_spans_preserve_order_and_item_declarations( + client, monkeypatch +): + evaluations, transport = client + transport.request.side_effect = composite_response + monkeypatch.setattr(_client, "_MAX_RESULTS", 4) + a, b = EvaluationItem(), EvaluationItem() + declarations = [result(), result(a), composite(b.id), composite(a.id), result(b)] + receipt = invoke( + evaluations.resume_experiment(EXPERIMENT_ID).upload_results, declarations + ) + assert [len(chunk.results) for chunk in receipt.chunks] == [1, 4] + body = json.loads(transport.request.call_args.kwargs["body"]) + assert body["results"] == [row.to_dict() for row in declarations[1:]] + assert body["items"] == [a.to_dict(), b.to_dict()] + + +def test_utf8_limit_accounts_for_whole_composite_group(client, monkeypatch): + evaluations, transport = client + transport.request.side_effect = composite_response + experiment = evaluations.resume_experiment(EXPERIMENT_ID) + item = EvaluationItem(input="🙂" * 100) + group = [result(item), composite(item)] + invoke(experiment.upload_results, group) + exact_limit = len(transport.request.call_args.kwargs["body"]) + monkeypatch.setattr(_client, "_MAX_REQUEST_BYTES", exact_limit) + transport.request.reset_mock() + receipt = invoke(experiment.upload_results, [result()] + group) + assert [len(chunk.results) for chunk in receipt.chunks] == [1, 2] + assert len(transport.request.call_args.kwargs["body"]) == exact_limit + monkeypatch.setattr(_client, "_MAX_REQUEST_BYTES", exact_limit - 1) + transport.request.reset_mock() + with pytest.raises(ValueError, match="limit"): + invoke(experiment.upload_results, [result()] + group) + transport.request.assert_not_called() + + +@pytest.mark.parametrize("limit,value", [("_MAX_RESULTS", 3), ("_MAX_ITEMS", 1)]) +def test_unsendable_interleaved_group_rejects_entire_bulk_before_io( + client, monkeypatch, limit, value +): + evaluations, transport = client + a, b = EvaluationItem(), EvaluationItem() + declarations = [result(), result(a), result(b), composite(a), composite(b)] + monkeypatch.setattr(_client, limit, value) + with pytest.raises(ValueError, match="limit"): + invoke( + evaluations.resume_experiment(EXPERIMENT_ID).upload_results, declarations + ) + transport.request.assert_not_called() + + +@pytest.mark.parametrize("persistence", ["unknown", "rejected"]) +def test_composite_partial_failure_replays_exact_group_and_original_index( + client, monkeypatch, persistence +): + evaluations, transport = client + monkeypatch.setattr(_client, "_MAX_RESULTS", 2) + item = EvaluationItem(input="question", model_version="model-b") + declarations = [result(), result(), composite(item), result(item), result()] + + def fail_second(method, path, *, body): + if transport.request.call_count == 2: + raise EvaluationAPIError(status=503, persistence=persistence) + return composite_response(method, path, body=body) + + transport.request.side_effect = fail_second + experiment = evaluations.resume_experiment(EXPERIMENT_ID) + with pytest.raises(BulkUploadError) as caught: + invoke(experiment.upload_results, declarations) + error = caught.value + assert error.failed_index == 2 + assert error.pending_results == tuple(declarations[2:]) + assert len(error.completed.chunks) == 1 + failed_body = transport.request.call_args.kwargs["body"] + assert error.failed_chunk["results"] == [row.to_dict() for row in declarations[2:4]] + transport.request.side_effect = composite_response + invoke(experiment.upload_results, error.pending_results) + assert transport.request.call_args_list[2].kwargs["body"] == failed_body + assert all( + call.args[1].endswith("/upload/") for call in transport.request.call_args_list + ) + + def test_experiment_tags_are_separate_from_creation_and_lifecycle_receipts(client): evaluations, transport = client experiment = invoke(evaluations.create_experiment, name="Tagged run") @@ -854,7 +1131,10 @@ async def run(): asyncio.run(run()) -def test_example_persists_before_writes_and_replays_the_same_run(monkeypatch, tmp_path): +@pytest.mark.parametrize("with_composite", [False, True]) +def test_example_persists_before_writes_and_replays_the_same_run( + monkeypatch, tmp_path, with_composite +): example = Path(__file__).parents[3] / "examples/example-offline-evaluations/main.py" spec = importlib.util.spec_from_file_location("offline_evaluation_example", example) module = importlib.util.module_from_spec(spec) @@ -864,18 +1144,34 @@ def test_example_persists_before_writes_and_replays_the_same_run(monkeypatch, tm monkeypatch.setenv("POSTHOG_SECRET_KEY", "never-persist-this-secret") monkeypatch.setenv("POSTHOG_HOST", "https://us.posthog.com") monkeypatch.setenv("POSTHOG_SCORER_VERSION_ID", VERSION_ID) - monkeypatch.setattr("sys.argv", [str(example), "--state", str(state_path)]) + monkeypatch.setattr( + "sys.argv", + [str(example), "--state", str(state_path)] + + (["--composite-version-id", OTHER_VERSION_ID] if with_composite else []), + ) transport = Mock(spec=SyncTransport) def check_state_before_write(method, path, **kwargs): assert state_path.exists() assert "never-persist-this-secret" not in state_path.read_text() + if with_composite and path.endswith("/upload/"): + body = json.loads(kwargs["body"]) + assert [row.get("calculate", False) for row in body["results"]] == [ + False, + True, + False, + True, + ] + return composite_response(method, path, **kwargs) return respond(method, path, **kwargs) transport.request.side_effect = check_state_before_write monkeypatch.setattr(_client, "SyncTransport", lambda *args: transport) module.main() prepared_state = state_path.read_bytes() + assert json.loads(prepared_state)["experiment"]["expected_result_count"] == ( + 4 if with_composite else 2 + ) module.main() assert state_path.read_bytes() == prepared_state requests = transport.request.call_args_list diff --git a/posthog/test/ai/test_evaluations_scorers.py b/posthog/test/ai/test_evaluations_scorers.py index 54cf97bac..21a37d4bb 100644 --- a/posthog/test/ai/test_evaluations_scorers.py +++ b/posthog/test/ai/test_evaluations_scorers.py @@ -26,6 +26,298 @@ BASE = "/api/projects/123/llm_analytics/score_definitions/" +def composition(): + return { + "expression": "number(correct)", + "inputs": [{"alias": "correct", "scorer_version_id": VERSION_ID}], + } + + +def input_scorer(): + return { + "alias": "correct", + "scorer_version_id": VERSION_ID, + "definition_id": SCORER_ID, + "name": "Correct", + "kind": "boolean", + "version": 1, + "config": {"true_is_failure": True}, + "latest_version_id": "f72481ec-1310-41de-b5bb-d20e1c59f122", + "latest_version": 2, + } + + +@pytest.mark.parametrize( + "kind,config,expression", + [ + ("numeric", {"min": 0, "max": 1}, "number(correct)"), + ("boolean", {"true_is_failure": False}, "correct"), + ( + "categorical", + {"options": [{"key": "good", "label": "Good"}]}, + '"good" if correct else "good"', + ), + ], +) +def test_composite_creation_and_detached_pinned_metadata( + scorers, kind, config, expression +): + namespace, transport = scorers + formula = composition() + formula["expression"] = expression + response = scorer_response( + kind=kind, + config=config, + calculation="composite", + composition=formula, + input_scorers=[input_scorer()], + dependent_composite_count=2, + ) + transport.request.return_value = response + scorer = invoke( + namespace.create, + name="Overall", + kind=kind, + config=config, + calculation="composite", + composition=formula, + ) + sent = json.loads(transport.request.call_args.kwargs["body"]) + assert sent == { + "name": "Overall", + "kind": kind, + "config": config, + "calculation": "composite", + "composition": formula, + } + assert transport.request.call_args.kwargs["retry_safe"] is False + assert scorer.calculation == "composite" + assert scorer.composition == formula + assert scorer.dependent_composite_count == 2 + pinned = scorer.input_scorers[0] + assert (pinned.version, pinned.latest_version) == (1, 2) + assert pinned.scorer_version_id == VERSION_ID + assert pinned.config == {"true_is_failure": True} + formula["inputs"][0]["alias"] = "changed" + response["input_scorers"][0]["config"]["true_is_failure"] = False + assert scorer.composition["inputs"][0]["alias"] == "correct" + assert pinned.config["true_is_failure"] is True + assert json.loads(transport.request.call_args.kwargs["body"]) == sent + + +def test_composite_versioning_history_and_dependency_filters(scorers): + namespace, transport = scorers + formula = composition() + transport.request.return_value = scorer_response( + calculation="composite", composition=formula + ) + invoke( + namespace.create_version, + SCORER_ID, + config={}, + composition=formula, + base_version=1, + ) + assert json.loads(transport.request.call_args.kwargs["body"]) == { + "config": {}, + "composition": formula, + "base_version": 1, + } + assert transport.request.call_args.kwargs["retry_safe"] is False + transport.request.return_value = version_response( + calculation="composite", composition=formula + ) + version = invoke(namespace.get_version, SCORER_ID, VERSION_ID) + assert version.composition == formula + assert version.calculation == "composite" + transport.request.return_value = { + "count": 1, + "results": [version_response(calculation="composite", composition=formula)], + "next_cursor": None, + } + assert invoke(namespace.list_versions, SCORER_ID).results == (version,) + transport.request.return_value = { + "count": 0, + "results": [], + "next": None, + "previous": None, + } + invoke( + namespace.list, + calculation="composite", + input_definition_id=UUID(SCORER_ID), + kind="numeric", + tags=["quality"], + offset=100, + ) + params = transport.request.call_args.kwargs["params"] + assert params["calculation"] == "composite" + assert params["input_definition_id"] == SCORER_ID + assert params["kind"] == "numeric" and params["offset"] == 100 + + +def test_legacy_scorers_and_versions_default_to_reported(scorers): + namespace, transport = scorers + scorer = invoke( + namespace.create, + name="Reported", + kind="numeric", + config={}, + calculation="reported", + ) + assert json.loads(transport.request.call_args.kwargs["body"]) == { + "name": "Reported", + "kind": "numeric", + "config": {}, + } + assert ( + scorer.calculation, + scorer.composition, + scorer.input_scorers, + scorer.dependent_composite_count, + ) == ( + "reported", + None, + (), + 0, + ) + transport.request.return_value = version_response() + version = invoke(namespace.get_version, SCORER_ID, VERSION_ID) + assert (version.calculation, version.composition) == ("reported", None) + + +@pytest.mark.parametrize("config", [None, {}, {"min": 0, "max": 1}]) +def test_validate_composition_is_read_only_and_preserves_optional_config( + scorers, config +): + namespace, transport = scorers + transport.request.return_value = {"valid": True} + assert ( + invoke( + namespace.validate_composition, + kind="numeric", + composition=composition(), + config=config, + ) + is True + ) + assert transport.request.call_args.args == ("POST", BASE + "validate_composition/") + body = json.loads(transport.request.call_args.kwargs["body"]) + assert body == { + "kind": "numeric", + "composition": composition(), + **({"config": config} if config is not None else {}), + } + transport.request.assert_called_once() + + +@pytest.mark.parametrize( + "response", [{}, {"valid": False}, {"valid": 1}, {"valid": "true"}] +) +def test_malformed_formula_validation_is_not_success(scorers, response): + namespace, transport = scorers + transport.request.return_value = response + with pytest.raises(EvaluationAPIError) as caught: + invoke( + namespace.validate_composition, kind="numeric", composition=composition() + ) + assert caught.value.code == "invalid_response" + + +def test_formula_validation_surfaces_server_access_and_formula_errors(scorers): + namespace, transport = scorers + for status, code in [(403, "permission_denied"), (400, "invalid_input")]: + error = EvaluationAPIError(status=status, code=code, persistence="rejected") + transport.request.side_effect = error + with pytest.raises(EvaluationAPIError) as caught: + invoke( + namespace.validate_composition, + kind="numeric", + composition=composition(), + ) + assert caught.value is error + + +@pytest.mark.parametrize( + "formula", + [ + {}, + {"expression": "", "inputs": []}, + {"expression": "x" * 1025, "inputs": composition()["inputs"]}, + {"expression": "correct", "inputs": []}, + {"expression": "correct", "inputs": composition()["inputs"] * 17}, + {"expression": "correct", "inputs": composition()["inputs"] * 2}, + { + "expression": "correct", + "inputs": [{"alias": "number", "scorer_version_id": VERSION_ID}], + }, + { + "expression": "correct", + "inputs": [{"alias": "bad-name", "scorer_version_id": VERSION_ID}], + }, + { + "expression": "correct", + "inputs": [{"alias": "correct", "scorer_version_id": "not-a-uuid"}], + }, + ], +) +def test_invalid_compositions_fail_before_io(scorers, formula): + namespace, transport = scorers + with pytest.raises(ValueError): + invoke( + namespace.create, + name="Overall", + kind="numeric", + config={}, + calculation="composite", + composition=formula, + ) + transport.request.assert_not_called() + + +@pytest.mark.parametrize( + "options", + [ + {"calculation": "unknown"}, + {"calculation": "reported", "composition": composition()}, + {"calculation": "composite"}, + { + "calculation": "composite", + "composition": composition(), + "config": {"step": 0.1}, + }, + ], +) +def test_invalid_calculation_configuration_fails_before_io(scorers, options): + namespace, transport = scorers + with pytest.raises(ValueError): + invoke( + namespace.create, + **({"name": "Overall", "kind": "numeric", "config": {}} | options), + ) + transport.request.assert_not_called() + + +@pytest.mark.parametrize( + "overrides", + [ + {"calculation": "unknown"}, + {"calculation": "composite"}, + {"composition": composition()}, + {"dependent_composite_count": -1}, + {"input_scorers": None}, + {"input_scorers": [input_scorer() | {"scorer_version_id": "invalid"}]}, + {"input_scorers": [input_scorer() | {"version": True}]}, + ], +) +def test_malformed_composite_metadata_is_not_acknowledged(scorers, overrides): + namespace, transport = scorers + transport.request.return_value = scorer_response(**overrides) + with pytest.raises(EvaluationAPIError) as caught: + invoke(namespace.get, SCORER_ID) + assert caught.value.code == "invalid_response" + + def scorer_response(**overrides): return { "id": SCORER_ID, diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index bfffd5d64..7b5f841fc 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -488,6 +488,7 @@ attribute posthog.ai.evaluations.EvaluationAPIError.retry_after = retry_after attribute posthog.ai.evaluations.EvaluationAPIError.status = status attribute posthog.ai.evaluations.EvaluationAPIError.submission = deepcopy(submission) attribute posthog.ai.evaluations.EvaluationItem.id: str +attribute posthog.ai.evaluations.EvaluationResult.calculate: bool attribute posthog.ai.evaluations.EvaluationResult.item: EvaluationItem | str attribute posthog.ai.evaluations.EvaluationResult.item_id: str attribute posthog.ai.evaluations.EvaluationResult.scorer_version_id: str @@ -529,6 +530,7 @@ attribute posthog.ai.evaluations.NumericScorerConfig.passing_rule: NumericPassin attribute posthog.ai.evaluations.NumericScorerConfig.step: float | None attribute posthog.ai.evaluations.OfflineEvaluations.datasets = Datasets(self._transport, project_id) attribute posthog.ai.evaluations.OfflineEvaluations.scorers = Scorers(self._transport, project_id) +attribute posthog.ai.evaluations.ResultOptions.calculate: bool attribute posthog.ai.evaluations.ResultOptions.error_code: str | None attribute posthog.ai.evaluations.ResultOptions.error_message: str | None attribute posthog.ai.evaluations.ResultOptions.evaluated_at: datetime | str | None @@ -538,25 +540,45 @@ attribute posthog.ai.evaluations.ResultOptions.payload: dict[str, JSONValue] attribute posthog.ai.evaluations.ResultOptions.reasoning: str | None attribute posthog.ai.evaluations.ResultOptions.status: ResultStatus attribute posthog.ai.evaluations.ResultOptions.value: ScoreValue | None +attribute posthog.ai.evaluations.ResultReceipt.error_code: str | None = None attribute posthog.ai.evaluations.ResultReceipt.item_id: str attribute posthog.ai.evaluations.ResultReceipt.scorer_version_id: str +attribute posthog.ai.evaluations.ResultReceipt.status: ResultStatus | None = None attribute posthog.ai.evaluations.ResultStatus = Literal['ok', 'error', 'skipped', 'not_applicable'] attribute posthog.ai.evaluations.RunSource = Literal['ci', 'local', 'scheduled'] attribute posthog.ai.evaluations.ScoreValue = bool | int | float | list[str] attribute posthog.ai.evaluations.Scorer.archived: bool +attribute posthog.ai.evaluations.Scorer.calculation: ScorerCalculation = 'reported' +attribute posthog.ai.evaluations.Scorer.composition: ScorerComposition | None = None attribute posthog.ai.evaluations.Scorer.config: _ConfigT attribute posthog.ai.evaluations.Scorer.created_at: datetime attribute posthog.ai.evaluations.Scorer.created_by: dict[str, Any] | None attribute posthog.ai.evaluations.Scorer.current_version: int attribute posthog.ai.evaluations.Scorer.current_version_id: str +attribute posthog.ai.evaluations.Scorer.dependent_composite_count: int = 0 attribute posthog.ai.evaluations.Scorer.description: str attribute posthog.ai.evaluations.Scorer.id: str +attribute posthog.ai.evaluations.Scorer.input_scorers: tuple[ScorerInput, ...] = () attribute posthog.ai.evaluations.Scorer.kind: ScorerKind attribute posthog.ai.evaluations.Scorer.name: str attribute posthog.ai.evaluations.Scorer.tags: tuple[str, ...] = () attribute posthog.ai.evaluations.Scorer.team: int attribute posthog.ai.evaluations.Scorer.updated_at: datetime +attribute posthog.ai.evaluations.ScorerCalculation = Literal['reported', 'composite'] +attribute posthog.ai.evaluations.ScorerComposition.expression: str +attribute posthog.ai.evaluations.ScorerComposition.inputs: list[ScorerCompositionInput] +attribute posthog.ai.evaluations.ScorerCompositionInput.alias: str +attribute posthog.ai.evaluations.ScorerCompositionInput.scorer_version_id: str attribute posthog.ai.evaluations.ScorerConfig = BooleanScorerConfig | NumericScorerConfig | CategoricalScorerConfig +attribute posthog.ai.evaluations.ScorerInput.alias: str +attribute posthog.ai.evaluations.ScorerInput.config: ScorerConfig +attribute posthog.ai.evaluations.ScorerInput.definition_id: str +attribute posthog.ai.evaluations.ScorerInput.kind: ScorerKind +attribute posthog.ai.evaluations.ScorerInput.latest_version: int | None +attribute posthog.ai.evaluations.ScorerInput.latest_version_id: str | None +attribute posthog.ai.evaluations.ScorerInput.name: str +attribute posthog.ai.evaluations.ScorerInput.scorer_version_id: str +attribute posthog.ai.evaluations.ScorerInput.version: int attribute posthog.ai.evaluations.ScorerKind = Literal['boolean', 'numeric', 'categorical'] attribute posthog.ai.evaluations.ScorerOrder = Literal['name', '-name', 'kind', '-kind', 'created_at', '-created_at', 'updated_at', '-updated_at', 'current_version', '-current_version'] attribute posthog.ai.evaluations.ScorerPage.count: int @@ -564,6 +586,8 @@ attribute posthog.ai.evaluations.ScorerPage.next: str | None attribute posthog.ai.evaluations.ScorerPage.next_offset: int | None attribute posthog.ai.evaluations.ScorerPage.previous: str | None attribute posthog.ai.evaluations.ScorerPage.results: tuple[Scorer[ScorerConfig], ...] +attribute posthog.ai.evaluations.ScorerVersion.calculation: ScorerCalculation = 'reported' +attribute posthog.ai.evaluations.ScorerVersion.composition: ScorerComposition | None = None attribute posthog.ai.evaluations.ScorerVersion.config: _ConfigT attribute posthog.ai.evaluations.ScorerVersion.created_at: datetime attribute posthog.ai.evaluations.ScorerVersion.created_by: dict[str, Any] | None @@ -1269,7 +1293,7 @@ class posthog.ai.evaluations.DatasetSnapshot(dataset: Dataset, revision: int, re class posthog.ai.evaluations.Datasets(transport: SyncTransport, project_id: int) class posthog.ai.evaluations.EvaluationAPIError(*, status: int | None = None, code: str | None = None, detail: Any = None, attr: str | None = None, errors: Any = None, response: dict[str, Any] | None = None, retry_after: float | None = None, persistence: Literal['rejected', 'unknown', 'not_sent'] = 'unknown', submission: dict[str, Any] | None = None) class posthog.ai.evaluations.EvaluationItem(*, id: str | UUID | None = None, input: JSONValue | _Unset = _UNSET, output: JSONValue | _Unset = _UNSET, expected_output: JSONValue | _Unset = _UNSET, metadata: dict[str, JSONValue] | None | _Unset = _UNSET, case_key: str | None = None, trial: str | None = None, dataset_item_identifier: str | None = None, dataset_item_version_identifier: str | None = None, dataset_item_version_id: str | UUID | None = None, application_trace_id: str | None = None, model_version: str | None = None, payload: dict[str, JSONValue] | _Unset = _UNSET) -class posthog.ai.evaluations.EvaluationResult(*, item: EvaluationItem | str | UUID, scorer_version_id: str | UUID, value: ScoreValue | None = None, status: ResultStatus = 'ok', error_code: str | None = None, reasoning: str | None | _Unset = _UNSET, error_message: str | None | _Unset = _UNSET, metadata: dict[str, JSONValue] | None | _Unset = _UNSET, evaluator_trace_id: str | None = None, evaluated_at: datetime | str | None = None, payload: dict[str, JSONValue] | _Unset = _UNSET) +class posthog.ai.evaluations.EvaluationResult(*, item: EvaluationItem | str | UUID, scorer_version_id: str | UUID, calculate: bool = False, value: ScoreValue | None = None, status: ResultStatus = 'ok', error_code: str | None = None, reasoning: str | None | _Unset = _UNSET, error_message: str | None | _Unset = _UNSET, metadata: dict[str, JSONValue] | None | _Unset = _UNSET, evaluator_trace_id: str | None = None, evaluated_at: datetime | str | None = None, payload: dict[str, JSONValue] | _Unset = _UNSET) class posthog.ai.evaluations.Experiment(transport: SyncTransport, project_id: int, id: str, *, receipt: ExperimentReceipt | None = None, submission: bytes | None = None) class posthog.ai.evaluations.ExperimentOptions class posthog.ai.evaluations.ExperimentReceipt(id: str, status: Literal['uploading', 'completed', 'failed'], created: bool, started_at: datetime, created_at: datetime, finished_at: datetime | None, expected_item_count: int | None, expected_result_count: int | None, accepted_item_count: int, accepted_result_count: int) @@ -1278,10 +1302,13 @@ class posthog.ai.evaluations.NumericPassingRule class posthog.ai.evaluations.NumericScorerConfig class posthog.ai.evaluations.OfflineEvaluations(*, project_id: int, secret_key: str, host: str | None = None, timeout: float = 15, max_retries: int = 3) class posthog.ai.evaluations.ResultOptions -class posthog.ai.evaluations.ResultReceipt(id: str, created: bool, accepted_at: datetime, item_id: str, scorer_version_id: str) -class posthog.ai.evaluations.Scorer(id: str, name: str, description: str, kind: ScorerKind, archived: bool, current_version: int, current_version_id: str, config: _ConfigT, created_at: datetime, updated_at: datetime, created_by: dict[str, Any] | None, team: int, tags: tuple[str, ...] = ()) +class posthog.ai.evaluations.ResultReceipt(id: str, created: bool, accepted_at: datetime, item_id: str, scorer_version_id: str, status: ResultStatus | None = None, error_code: str | None = None) +class posthog.ai.evaluations.Scorer(id: str, name: str, description: str, kind: ScorerKind, archived: bool, current_version: int, current_version_id: str, config: _ConfigT, created_at: datetime, updated_at: datetime, created_by: dict[str, Any] | None, team: int, tags: tuple[str, ...] = (), calculation: ScorerCalculation = 'reported', composition: ScorerComposition | None = None, input_scorers: tuple[ScorerInput, ...] = (), dependent_composite_count: int = 0) +class posthog.ai.evaluations.ScorerComposition +class posthog.ai.evaluations.ScorerCompositionInput +class posthog.ai.evaluations.ScorerInput(alias: str, scorer_version_id: str, definition_id: str, name: str, kind: ScorerKind, version: int, config: ScorerConfig, latest_version_id: str | None, latest_version: int | None) class posthog.ai.evaluations.ScorerPage(count: int, results: tuple[Scorer[ScorerConfig], ...], next: str | None, previous: str | None, next_offset: int | None) -class posthog.ai.evaluations.ScorerVersion(id: str, definition_id: str, version: int, kind: ScorerKind, config: _ConfigT, created_at: datetime, created_by: dict[str, Any] | None) +class posthog.ai.evaluations.ScorerVersion(id: str, definition_id: str, version: int, kind: ScorerKind, config: _ConfigT, created_at: datetime, created_by: dict[str, Any] | None, calculation: ScorerCalculation = 'reported', composition: ScorerComposition | None = None) class posthog.ai.evaluations.ScorerVersionPage(count: int, results: tuple[ScorerVersion[ScorerConfig], ...], next_cursor: str | None) class posthog.ai.evaluations.Scorers(transport: SyncTransport, project_id: int) class posthog.ai.evaluations.UploadReceipt(items: tuple[ItemReceipt, ...], results: tuple[ResultReceipt, ...]) @@ -1669,13 +1696,14 @@ method posthog.ai.evaluations.AsyncExperiment.upload_results(results: Sequence[E method posthog.ai.evaluations.AsyncOfflineEvaluations.aclose() method posthog.ai.evaluations.AsyncOfflineEvaluations.create_experiment(*, name: str, **options: Unpack[ExperimentOptions]) method posthog.ai.evaluations.AsyncOfflineEvaluations.resume_experiment(id: str | UUID) -method posthog.ai.evaluations.AsyncScorers.create(*, name: str, kind: ScorerKind, config: ScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED) -method posthog.ai.evaluations.AsyncScorers.create_version(scorer_id: str | UUID, *, config: _ConfigT, base_version: int | None = None, name: str | _Omitted = _OMITTED, description: str | None | _Omitted = _OMITTED) +method posthog.ai.evaluations.AsyncScorers.create(*, name: str, kind: ScorerKind, config: ScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, calculation: ScorerCalculation = 'reported', composition: ScorerComposition | None = None) +method posthog.ai.evaluations.AsyncScorers.create_version(scorer_id: str | UUID, *, config: _ConfigT, base_version: int | None = None, name: str | _Omitted = _OMITTED, description: str | None | _Omitted = _OMITTED, composition: ScorerComposition | None = None) method posthog.ai.evaluations.AsyncScorers.get(scorer_id: str | UUID) method posthog.ai.evaluations.AsyncScorers.get_version(scorer_id: str | UUID, version_id: str | UUID) -method posthog.ai.evaluations.AsyncScorers.list(*, limit: int = 100, offset: int = 0, search: str | None = None, kind: ScorerKind | None = None, archived: bool | None = None, order_by: ScorerOrder | None = None, tags: Sequence[str] | None = None, tag_match: Literal['any', 'all'] = 'any') +method posthog.ai.evaluations.AsyncScorers.list(*, limit: int = 100, offset: int = 0, search: str | None = None, kind: ScorerKind | None = None, archived: bool | None = None, order_by: ScorerOrder | None = None, tags: Sequence[str] | None = None, tag_match: Literal['any', 'all'] = 'any', calculation: ScorerCalculation | None = None, input_definition_id: str | UUID | None = None) method posthog.ai.evaluations.AsyncScorers.list_versions(scorer_id: str | UUID, *, limit: int = 50, cursor: str | None = None) method posthog.ai.evaluations.AsyncScorers.update(scorer_id: str | UUID, *, name: str | _Omitted = _OMITTED, description: str | None | _Omitted = _OMITTED, archived: bool | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED) +method posthog.ai.evaluations.AsyncScorers.validate_composition(*, kind: ScorerKind, composition: ScorerComposition, config: ScorerConfig | None = None) method posthog.ai.evaluations.DatasetSnapshot.iter_items(*, page_size: int = 25) method posthog.ai.evaluations.Datasets.archive(dataset_id: str | UUID) method posthog.ai.evaluations.Datasets.archive_item(item_id: str | UUID, *, base_version: int) @@ -1706,13 +1734,14 @@ method posthog.ai.evaluations.Experiment.upload_results(results: Sequence[Evalua method posthog.ai.evaluations.OfflineEvaluations.close() method posthog.ai.evaluations.OfflineEvaluations.create_experiment(*, name: str, **options: Unpack[ExperimentOptions]) method posthog.ai.evaluations.OfflineEvaluations.resume_experiment(id: str | UUID) -method posthog.ai.evaluations.Scorers.create(*, name: str, kind: ScorerKind, config: ScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED) -method posthog.ai.evaluations.Scorers.create_version(scorer_id: str | UUID, *, config: _ConfigT, base_version: int | None = None, name: str | _Omitted = _OMITTED, description: str | None | _Omitted = _OMITTED) +method posthog.ai.evaluations.Scorers.create(*, name: str, kind: ScorerKind, config: ScorerConfig, description: str | None | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED, calculation: ScorerCalculation = 'reported', composition: ScorerComposition | None = None) +method posthog.ai.evaluations.Scorers.create_version(scorer_id: str | UUID, *, config: _ConfigT, base_version: int | None = None, name: str | _Omitted = _OMITTED, description: str | None | _Omitted = _OMITTED, composition: ScorerComposition | None = None) method posthog.ai.evaluations.Scorers.get(scorer_id: str | UUID) method posthog.ai.evaluations.Scorers.get_version(scorer_id: str | UUID, version_id: str | UUID) -method posthog.ai.evaluations.Scorers.list(*, limit: int = 100, offset: int = 0, search: str | None = None, kind: ScorerKind | None = None, archived: bool | None = None, order_by: ScorerOrder | None = None, tags: Sequence[str] | None = None, tag_match: Literal['any', 'all'] = 'any') +method posthog.ai.evaluations.Scorers.list(*, limit: int = 100, offset: int = 0, search: str | None = None, kind: ScorerKind | None = None, archived: bool | None = None, order_by: ScorerOrder | None = None, tags: Sequence[str] | None = None, tag_match: Literal['any', 'all'] = 'any', calculation: ScorerCalculation | None = None, input_definition_id: str | UUID | None = None) method posthog.ai.evaluations.Scorers.list_versions(scorer_id: str | UUID, *, limit: int = 50, cursor: str | None = None) method posthog.ai.evaluations.Scorers.update(scorer_id: str | UUID, *, name: str | _Omitted = _OMITTED, description: str | None | _Omitted = _OMITTED, archived: bool | _Omitted = _OMITTED, tags: Sequence[str] | _Omitted = _OMITTED) +method posthog.ai.evaluations.Scorers.validate_composition(*, kind: ScorerKind, composition: ScorerComposition, config: ScorerConfig | None = None) method posthog.ai.gemini.gemini.Models.embed_content(model: str, contents, posthog_distinct_id: Optional[str] = None, posthog_trace_id: Optional[str] = None, posthog_properties: Optional[Dict[str, Any]] = None, posthog_privacy_mode: Optional[bool] = None, posthog_groups: Optional[Dict[str, Any]] = None, **kwargs: Any) method posthog.ai.gemini.gemini.Models.generate_content(model: str, contents, posthog_distinct_id: Optional[str] = None, posthog_trace_id: Optional[str] = None, posthog_properties: Optional[Dict[str, Any]] = None, posthog_privacy_mode: Optional[bool] = None, posthog_groups: Optional[Dict[str, Any]] = None, **kwargs: Any) method posthog.ai.gemini.gemini.Models.generate_content_stream(model: str, contents, posthog_distinct_id: Optional[str] = None, posthog_trace_id: Optional[str] = None, posthog_properties: Optional[Dict[str, Any]] = None, posthog_privacy_mode: Optional[bool] = None, posthog_groups: Optional[Dict[str, Any]] = None, **kwargs: Any) From aaeedb0799801667459400eace242c393345e3be Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:02:31 +0000 Subject: [PATCH 05/33] chore: Release v7.88.0 [skip ci] --- .sampo/changesets/composite-offline-scorers.md | 5 ----- openfeature-provider/CHANGELOG.md | 6 ++++++ openfeature-provider/pyproject.toml | 2 +- posthog/CHANGELOG.md | 6 ++++++ posthog/version.py | 2 +- pyproject.toml | 2 +- uv.lock | 4 ++-- 7 files changed, 17 insertions(+), 10 deletions(-) delete mode 100644 .sampo/changesets/composite-offline-scorers.md diff --git a/.sampo/changesets/composite-offline-scorers.md b/.sampo/changesets/composite-offline-scorers.md deleted file mode 100644 index 07c1cb9ac..000000000 --- a/.sampo/changesets/composite-offline-scorers.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: minor ---- - -Support versioned composite scorers for offline evaluations, including formula validation, dependency metadata, explicit server calculations, stored outcome receipts, and composite-safe bulk uploads. diff --git a/openfeature-provider/CHANGELOG.md b/openfeature-provider/CHANGELOG.md index fc8c3a829..78adac941 100644 --- a/openfeature-provider/CHANGELOG.md +++ b/openfeature-provider/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to `openfeature-provider-posthog` are documented here. This file is maintained by [Sampo](https://github.com/bruits/sampo) from changesets in `.sampo/changesets/` that target `pypi/openfeature-provider-posthog`. +## 0.1.160 — 2026-11-12 + +### Patch changes + +- Updated dependencies: posthog@7.88.0 + ## 0.1.159 — 2026-11-12 ### Patch changes diff --git a/openfeature-provider/pyproject.toml b/openfeature-provider/pyproject.toml index 1aed020bd..b3fed3b7c 100644 --- a/openfeature-provider/pyproject.toml +++ b/openfeature-provider/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "openfeature-provider-posthog" -version = "0.1.159" +version = "0.1.160" description = "Official PostHog provider for the OpenFeature Python SDK." readme = "README.md" authors = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/posthog/CHANGELOG.md b/posthog/CHANGELOG.md index 830d3dea3..17b418d6a 100644 --- a/posthog/CHANGELOG.md +++ b/posthog/CHANGELOG.md @@ -1,5 +1,11 @@ # posthog +## 7.88.0 — 2026-11-12 + +### Minor changes + +- [9636fa20](https://github.com/posthog/posthog-python/commit/9636fa20e4ea4315e8b6b6fd43c0ee63ec9bf054) Support versioned composite scorers for offline evaluations, including formula validation, dependency metadata, explicit server calculations, stored outcome receipts, and composite-safe bulk uploads. — Thanks @Radu-Raicea! + ## 7.87.2 — 2026-11-12 ### Patch changes diff --git a/posthog/version.py b/posthog/version.py index 493c8b8e9..db9ba7491 100644 --- a/posthog/version.py +++ b/posthog/version.py @@ -1 +1 @@ -VERSION = "7.87.2" +VERSION = "7.88.0" diff --git a/pyproject.toml b/pyproject.toml index 0829a5833..825fd5dc8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "posthog" -version = "7.87.2" +version = "7.88.0" description = "Integrate PostHog into any python application." authors = [{ name = "PostHog", email = "engineering@posthog.com" }] maintainers = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/uv.lock b/uv.lock index 3af3de736..6098a8d3b 100644 --- a/uv.lock +++ b/uv.lock @@ -2723,7 +2723,7 @@ wheels = [ [[package]] name = "openfeature-provider-posthog" -version = "0.1.159" +version = "0.1.160" source = { editable = "openfeature-provider" } dependencies = [ { name = "openfeature-sdk" }, @@ -3280,7 +3280,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.87.2" +version = "7.88.0" source = { editable = "." } dependencies = [ { name = "backoff" }, From ac25b4bf287794288dc25b0c10a5cc04c39c7a16 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:34:55 +0100 Subject: [PATCH 06/33] feat(emails): let a code send set its tracking and sensitivity (#1216) * feat(emails): let a code send turn off open and click tracking Adds track_opens_and_clicks to the code form of emails.send. False sends the email without PostHog's open pixel and rewritten links. The field goes into the request body only when the caller sets it, so a default send keeps today's body. The template form refuses it, like capture_engagement. Co-Authored-By: Claude Opus 5.5 * docs(emails): say track_opens_and_clicks only removes the open pixel PostHog never rewrites the links of an email sent from code, so it counts no clicks either way. False removes the open pixel only. Co-Authored-By: Claude Opus 5.5 * feat(emails): let a code send choose its tracking Replace track_opens_and_clicks with tracking: True, False, or an EmailTracking dict of opens, clicks and engagement. Leave tracking and capture_engagement out of the body unless the caller sets them, so the API can refuse a send that sets both. Deprecate capture_engagement. Co-Authored-By: Claude Opus 5.5 * test(emails): prove the tracking choice over real HTTP Send each tracking form through the public send API to a local HTTP server and assert the body it receives, instead of a stubbed transport. Co-Authored-By: Claude Opus 5.5 * feat(emails): let a code send mark its email sensitive A code send now takes an optional `sensitive`, sent only when set. Without it, PostHog keeps today's behavior: a send whose template_key matches a saved template follows that template, and any other send is sensitive. Click tracking follows it unless `tracking` sets clicks. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .github/scripts/check_strict_types.sh | 8 +- .sampo/changesets/emails-tracking.md | 23 ++++++ posthog/emails.py | 78 ++++++++++++++++--- posthog/test/test_emails.py | 105 +++++++++++++++++++++++++- references/public_api_snapshot.txt | 6 ++ 5 files changed, 208 insertions(+), 12 deletions(-) create mode 100644 .sampo/changesets/emails-tracking.md diff --git a/.github/scripts/check_strict_types.sh b/.github/scripts/check_strict_types.sh index f27e39519..4855a9ec9 100755 --- a/.github/scripts/check_strict_types.sh +++ b/.github/scripts/check_strict_types.sh @@ -46,7 +46,10 @@ _ = (flag_value, all_flags, enabled, payload, evaluations, active) emails = Emails("phs_example") template_send: SendEmailResult = emails.send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", template_data={"name": "Ada"}) rendered_send: SendEmailResult = emails.send(to="user@example.com", template_key="password-reset", subject="Reset", html="

Reset

", from_="Acme ", reply_to=["help@example.com"], capture_engagement=False, max_retries=0) -_ = (template_send, rendered_send) +tracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="

Hi

", tracking={"clicks": True, "engagement": False}) +untracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="

Hi

", tracking=False) +not_sensitive_send: SendEmailResult = emails.send(to="user@example.com", template_key="newsletter", subject="News", html="

News

", sensitive=False) +_ = (template_send, rendered_send, tracked_send, untracked_send) async def async_email_types() -> None: @@ -106,6 +109,9 @@ Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3 Emails("phs_example").send(to="user@example.com", template_key="welcome", html="

Hi

") # expected-type-error Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", cc="team@example.com") # expected-type-error Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", capture_engagement=False) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", tracking=False) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", sensitive=False) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", tracking={"open": False}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", template_data={"name": "Ada"}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", cc="team@example.com") # expected-type-error diff --git a/.sampo/changesets/emails-tracking.md b/.sampo/changesets/emails-tracking.md new file mode 100644 index 000000000..e1053e63d --- /dev/null +++ b/.sampo/changesets/emails-tracking.md @@ -0,0 +1,23 @@ +--- +pypi/posthog: minor +--- + +A send with `template_key` now takes `tracking` and `sensitive`. The template form doesn't take either one. + +`tracking` chooses what PostHog tracks for the email. `tracking=True` turns on opens, clicks and engagement events. `tracking=False` turns them all off. A dict such as `{"clicks": True}` or `{"engagement": False}` turns each kind on or off, and a key you leave out keeps its default. Without it, PostHog counts opens, captures engagement events, and counts clicks only when the email isn't sensitive. + +`sensitive` marks an email that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `template_key` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. A send that sets neither option works exactly as before. + +```python +posthog.emails.send( + to="user@example.com", + template_key="newsletter", + subject="What's new at Acme", + html=rendered_html, + sensitive=False, +) +``` + +`capture_engagement` is deprecated in favor of `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both. + +`tracking` and `sensitive` need PostHog's API support, which is rolling out. Until it reaches your PostHog instance, PostHog refuses a send that sets either one. diff --git a/posthog/emails.py b/posthog/emails.py index 42e70b971..2839a2dd6 100644 --- a/posthog/emails.py +++ b/posthog/emails.py @@ -131,6 +131,7 @@ "CodeEmailArgs", "EmailError", "EmailStatus", + "EmailTracking", "EmailWarning", "Emails", "SendEmailResult", @@ -241,6 +242,28 @@ class TemplateEmailArgs(_RecipientArgs): template_data: NotRequired[Optional[Mapping[str, Any]]] +class EmailTracking(TypedDict, total=False): + """Which kinds of tracking a send with ``template_key`` turns on. + + A key you leave out keeps its default. + + Args: + opens: Counts opens with PostHog's open pixel. Defaults to ``True``. + clicks: Counts clicks by sending the email's links through PostHog's + click tracking. Defaults to ``False`` for a sensitive email and + ``True`` for any other. Needs ``opens``: PostHog refuses a send + with ``opens=False`` and ``clicks=True``. + engagement: Captures the email's engagement events (sent, + delivered, opened, clicked, bounced) as events of the recipient. + Defaults to ``True``. A project whose admin turned engagement + capture off captures nothing, whatever the send asks. + """ + + opens: bool + clicks: bool + engagement: bool + + class CodeEmailArgs(_RecipientArgs): """A send of email content that your code rendered for one recipient, named by a key. @@ -260,11 +283,31 @@ class CodeEmailArgs(_RecipientArgs): without a plain-text part. from_: A verified sender, such as ``"Acme "``. reply_to: One address or a list of addresses. An empty list sends no reply-to. - capture_engagement: Capture the email's opens and clicks as events of - the recipient. Defaults to ``True``. A project whose admin turned - engagement capture off captures nothing, whatever the send asks. A - template made in PostHog follows the project's setting, so the - template form doesn't take it. + capture_engagement: Deprecated, use ``tracking={"engagement": False}``. + It keeps working, but PostHog refuses a send that sets both + ``capture_engagement`` and ``tracking``. Captures the email's + engagement events as events of the recipient. Defaults to + ``True``. A project whose admin turned engagement capture off + captures nothing, whatever the send asks. A template made in + PostHog follows the project's setting, so the template form + doesn't take it. + sensitive: Marks the email as sensitive, such as one that carries + login links, reset tokens or codes. A sensitive email keeps its + links as they are unless ``tracking`` turns clicks on, leaves its + subject off engagement events, and keeps its content out of + PostHog's logs. Without it, a send whose ``template_key`` matches + a template saved in PostHog follows that template's setting, and + any other send is sensitive. The template form doesn't take it. + tracking: What PostHog tracks for this email. Without it, PostHog + counts opens with its open pixel, captures engagement events, and + counts clicks only when the email isn't sensitive. ``True`` turns + on opens, clicks and engagement events. ``False`` turns off all + tracking, including kinds PostHog adds later: PostHog can't count + the email's opens or clicks, and captures no engagement events. + An :class:`EmailTracking` dict turns each kind on or off, and a + key you leave out keeps its default. Turn clicks on for a + sensitive email only when its links are safe to send through + PostHog's click tracking. The template form doesn't take it. distinct_id: The recipient's distinct ID in your product. idempotency_key: 1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for @@ -282,6 +325,8 @@ class CodeEmailArgs(_RecipientArgs): from_: NotRequired[Optional[str]] reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] capture_engagement: NotRequired[Optional[bool]] + sensitive: NotRequired[Optional[bool]] + tracking: NotRequired[Optional[Union[bool, EmailTracking]]] _OPTIONAL_CODE_FIELDS = frozenset( @@ -291,6 +336,8 @@ class CodeEmailArgs(_RecipientArgs): "from_", "reply_to", "capture_engagement", + "sensitive", + "tracking", } ) @@ -406,13 +453,26 @@ def _sender(args: Mapping[str, Any]) -> dict[str, Any]: reply_to = _addresses("reply_to", args["reply_to"]) if "reply_to" in args else [] if reply_to: sender["reply_to"] = reply_to - capture_engagement = args.get("capture_engagement", True) - if not isinstance(capture_engagement, bool): - raise TypeError("capture_engagement must be True or False.") - sender["capture_engagement"] = capture_engagement + for flag in ("capture_engagement", "sensitive"): + if flag in args: + if not isinstance(args[flag], bool): + raise TypeError(f"{flag} must be True or False.") + sender[flag] = args[flag] + if "tracking" in args: + sender["tracking"] = _tracking(args["tracking"]) return sender +def _tracking(value: Any) -> Union[bool, dict[str, Any]]: + if isinstance(value, bool): + return value + if isinstance(value, Mapping): + return dict(value) + raise TypeError( + "tracking must be True, False or a dict of opens, clicks and engagement." + ) + + def _addresses(field: str, value: Any) -> list[str]: addresses = [value] if isinstance(value, str) else value if not isinstance(addresses, Sequence) or not all( diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py index eaf1c0949..b13b8a0c6 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -3,9 +3,11 @@ import asyncio import json import logging +import threading from datetime import datetime, timezone from decimal import Decimal -from typing import Any, Optional, Union +from http.server import BaseHTTPRequestHandler, HTTPServer +from typing import Any, Iterator, Optional, Union from unittest import mock import httpx @@ -693,11 +695,88 @@ def test_rendered_content_is_posted_as_is(_name, overrides, extra_body): "to": "user@example.com", "template_key": "password-reset", "subject": "Reset your password", - "capture_engagement": True, **extra_body, } +class _CaptureServer(HTTPServer): + received: list[Any] + + +class _CaptureHandler(BaseHTTPRequestHandler): + server: _CaptureServer + + def do_POST(self) -> None: + body = self.rfile.read(int(self.headers["Content-Length"])) + self.server.received.append(json.loads(body)) + reply = json.dumps({"message_id": "msg_1", "replayed": False}).encode() + self.send_response(202) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(reply))) + self.end_headers() + self.wfile.write(reply) + + def log_message(self, *args: Any) -> None: + pass + + +@pytest.fixture +def capture_server() -> Iterator[_CaptureServer]: + server = _CaptureServer(("127.0.0.1", 0), _CaptureHandler) + server.received = [] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield server + server.shutdown() + server.server_close() + + +@pytest.mark.parametrize( + "overrides, extra_body", + [ + pytest.param({}, {}, id="no_tracking_or_sensitive_choice"), + pytest.param( + {"tracking": None, "capture_engagement": None, "sensitive": None}, + {}, + id="none_as_left_out", + ), + pytest.param({"sensitive": True}, {"sensitive": True}, id="marked_sensitive"), + pytest.param( + {"sensitive": False}, {"sensitive": False}, id="marked_not_sensitive" + ), + pytest.param({"tracking": False}, {"tracking": False}, id="all_tracking_off"), + pytest.param({"tracking": True}, {"tracking": True}, id="all_tracking_on"), + pytest.param( + {"tracking": {"opens": True, "clicks": True, "engagement": False}}, + {"tracking": {"opens": True, "clicks": True, "engagement": False}}, + id="each_kind_of_tracking_chosen", + ), + pytest.param( + {"capture_engagement": False}, + {"capture_engagement": False}, + id="deprecated_capture_engagement", + ), + ], +) +def test_a_code_send_delivers_its_tracking_and_sensitive_choice( + capture_server, overrides, extra_body +): + host = f"http://127.0.0.1:{capture_server.server_port}" + with Emails(SECRET_KEY, host=host) as emails: + result = send_code(emails, html=HTML, **overrides) + + assert result.id == "msg_1" + assert capture_server.received == [ + { + "to": "user@example.com", + "template_key": "password-reset", + "subject": "Reset your password", + "html": HTML, + **extra_body, + } + ] + + @pytest.mark.asyncio async def test_async_client_posts_rendered_content_and_names_the_provider(): seen: list[httpx.Request] = [] @@ -782,6 +861,28 @@ def handler(request: httpx.Request) -> httpx.Response: }, TypeError, ), + ( + "tracking_on_template_form", + { + "template_id": TEMPLATE_ID, + "template_key": None, + "subject": None, + "tracking": False, + }, + TypeError, + ), + ( + "sensitive_on_template_form", + { + "template_id": TEMPLATE_ID, + "template_key": None, + "subject": None, + "sensitive": False, + }, + TypeError, + ), + ("tracking_not_bool_or_dict", {"html": HTML, "tracking": "off"}, TypeError), + ("sensitive_not_bool", {"html": HTML, "sensitive": "yes"}, TypeError), ] ) def test_rejects_a_code_send_that_mixes_or_misses_fields(_name, overrides, error): diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index 7b5f841fc..8eec881b9 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -916,9 +916,11 @@ attribute posthog.emails.CodeEmailArgs.capture_engagement: NotRequired[Optional[ attribute posthog.emails.CodeEmailArgs.from_: NotRequired[Optional[str]] attribute posthog.emails.CodeEmailArgs.html: NotRequired[Optional[str]] attribute posthog.emails.CodeEmailArgs.reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] +attribute posthog.emails.CodeEmailArgs.sensitive: NotRequired[Optional[bool]] attribute posthog.emails.CodeEmailArgs.subject: str attribute posthog.emails.CodeEmailArgs.template_key: str attribute posthog.emails.CodeEmailArgs.text: NotRequired[Optional[str]] +attribute posthog.emails.CodeEmailArgs.tracking: NotRequired[Optional[Union[bool, EmailTracking]]] attribute posthog.emails.EmailError.code = code attribute posthog.emails.EmailError.docs_url = docs_url attribute posthog.emails.EmailError.field = field @@ -933,6 +935,9 @@ attribute posthog.emails.EmailStatus.id: str attribute posthog.emails.EmailStatus.reason: Optional[str] = None attribute posthog.emails.EmailStatus.status: str attribute posthog.emails.EmailStatus.status_at: datetime +attribute posthog.emails.EmailTracking.clicks: bool +attribute posthog.emails.EmailTracking.engagement: bool +attribute posthog.emails.EmailTracking.opens: bool attribute posthog.emails.EmailWarning.code: str attribute posthog.emails.EmailWarning.fix: Optional[str] = None attribute posthog.emails.EmailWarning.message: str @@ -1373,6 +1378,7 @@ class posthog.emails.AsyncEmails(secret_key: Optional[str], *, host: Optional[st class posthog.emails.CodeEmailArgs class posthog.emails.EmailError(*, name: str, code: str, message: str, status_code: Optional[int] = None, why: Optional[str] = None, fix: Optional[str] = None, docs_url: Optional[str] = None, field: Optional[str] = None, retry_after: Optional[float] = None) class posthog.emails.EmailStatus(id: str, status: str, created_at: datetime, status_at: datetime, reason: Optional[str] = None) +class posthog.emails.EmailTracking class posthog.emails.EmailWarning(code: str, message: str, fix: Optional[str] = None) class posthog.emails.Emails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, session: Optional[requests.Session] = None, migrated_from: Optional[str] = None) class posthog.emails.SendEmailResult(id: str, replayed: bool = False, warnings: tuple[EmailWarning, ...] = ()) From 71124f1ab621ab4f64d4d4605a9d417b940d70a1 Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:38:25 +0000 Subject: [PATCH 07/33] chore: Release v7.89.0 [skip ci] --- .sampo/changesets/emails-tracking.md | 23 ----------------------- openfeature-provider/CHANGELOG.md | 6 ++++++ openfeature-provider/pyproject.toml | 2 +- posthog/CHANGELOG.md | 24 ++++++++++++++++++++++++ posthog/version.py | 2 +- pyproject.toml | 2 +- uv.lock | 4 ++-- 7 files changed, 35 insertions(+), 28 deletions(-) delete mode 100644 .sampo/changesets/emails-tracking.md diff --git a/.sampo/changesets/emails-tracking.md b/.sampo/changesets/emails-tracking.md deleted file mode 100644 index e1053e63d..000000000 --- a/.sampo/changesets/emails-tracking.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -pypi/posthog: minor ---- - -A send with `template_key` now takes `tracking` and `sensitive`. The template form doesn't take either one. - -`tracking` chooses what PostHog tracks for the email. `tracking=True` turns on opens, clicks and engagement events. `tracking=False` turns them all off. A dict such as `{"clicks": True}` or `{"engagement": False}` turns each kind on or off, and a key you leave out keeps its default. Without it, PostHog counts opens, captures engagement events, and counts clicks only when the email isn't sensitive. - -`sensitive` marks an email that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `template_key` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. A send that sets neither option works exactly as before. - -```python -posthog.emails.send( - to="user@example.com", - template_key="newsletter", - subject="What's new at Acme", - html=rendered_html, - sensitive=False, -) -``` - -`capture_engagement` is deprecated in favor of `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both. - -`tracking` and `sensitive` need PostHog's API support, which is rolling out. Until it reaches your PostHog instance, PostHog refuses a send that sets either one. diff --git a/openfeature-provider/CHANGELOG.md b/openfeature-provider/CHANGELOG.md index 78adac941..86c1202eb 100644 --- a/openfeature-provider/CHANGELOG.md +++ b/openfeature-provider/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to `openfeature-provider-posthog` are documented here. This file is maintained by [Sampo](https://github.com/bruits/sampo) from changesets in `.sampo/changesets/` that target `pypi/openfeature-provider-posthog`. +## 0.1.161 — 2026-11-12 + +### Patch changes + +- Updated dependencies: posthog@7.89.0 + ## 0.1.160 — 2026-11-12 ### Patch changes diff --git a/openfeature-provider/pyproject.toml b/openfeature-provider/pyproject.toml index b3fed3b7c..a29fe41b8 100644 --- a/openfeature-provider/pyproject.toml +++ b/openfeature-provider/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "openfeature-provider-posthog" -version = "0.1.160" +version = "0.1.161" description = "Official PostHog provider for the OpenFeature Python SDK." readme = "README.md" authors = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/posthog/CHANGELOG.md b/posthog/CHANGELOG.md index 17b418d6a..720f182b1 100644 --- a/posthog/CHANGELOG.md +++ b/posthog/CHANGELOG.md @@ -1,5 +1,29 @@ # posthog +## 7.89.0 — 2026-11-12 + +### Minor changes + +- [ac25b4bf](https://github.com/posthog/posthog-python/commit/ac25b4bf287794288dc25b0c10a5cc04c39c7a16) A send with `template_key` now takes `tracking` and `sensitive`. The template form doesn't take either one. + + `tracking` chooses what PostHog tracks for the email. `tracking=True` turns on opens, clicks and engagement events. `tracking=False` turns them all off. A dict such as `{"clicks": True}` or `{"engagement": False}` turns each kind on or off, and a key you leave out keeps its default. Without it, PostHog counts opens, captures engagement events, and counts clicks only when the email isn't sensitive. + + `sensitive` marks an email that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `template_key` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. A send that sets neither option works exactly as before. + + ```python + posthog.emails.send( + to="user@example.com", + template_key="newsletter", + subject="What's new at Acme", + html=rendered_html, + sensitive=False, + ) + ``` + + `capture_engagement` is deprecated in favor of `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both. + + `tracking` and `sensitive` need PostHog's API support, which is rolling out. Until it reaches your PostHog instance, PostHog refuses a send that sets either one. — Thanks @Silthus! + ## 7.88.0 — 2026-11-12 ### Minor changes diff --git a/posthog/version.py b/posthog/version.py index db9ba7491..ea63ebc5f 100644 --- a/posthog/version.py +++ b/posthog/version.py @@ -1 +1 @@ -VERSION = "7.88.0" +VERSION = "7.89.0" diff --git a/pyproject.toml b/pyproject.toml index 825fd5dc8..61c79756e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "posthog" -version = "7.88.0" +version = "7.89.0" description = "Integrate PostHog into any python application." authors = [{ name = "PostHog", email = "engineering@posthog.com" }] maintainers = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/uv.lock b/uv.lock index 6098a8d3b..a9c2dd8b3 100644 --- a/uv.lock +++ b/uv.lock @@ -2723,7 +2723,7 @@ wheels = [ [[package]] name = "openfeature-provider-posthog" -version = "0.1.160" +version = "0.1.161" source = { editable = "openfeature-provider" } dependencies = [ { name = "openfeature-sdk" }, @@ -3280,7 +3280,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.88.0" +version = "7.89.0" source = { editable = "." } dependencies = [ { name = "backoff" }, From bf5f036fa82c6014b06eb002f8a16fd9c820a70e Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:38:35 +0000 Subject: [PATCH 08/33] Update generated references --- references/posthog-python-7.md | 18 +++++++++++++++++- references/posthog-python-reference.md | 18 +++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/references/posthog-python-7.md b/references/posthog-python-7.md index bfa813789..14dd3cfdc 100644 --- a/references/posthog-python-7.md +++ b/references/posthog-python-7.md @@ -4022,7 +4022,9 @@ Name | Type | Description | Default `text` | | The plain-text body. Without it, PostHog derives it from `html`. HTML with no text in it, such as a single image, goes out without a plain-text part. | `from_` | | A verified sender, such as `"Acme "`. | `reply_to` | | One address or a list of addresses. An empty list sends no reply-to. | -`capture_engagement` | | Capture the email's opens and clicks as events of the recipient. Defaults to `True`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. | +`capture_engagement` | | Deprecated, use `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both `capture_engagement` and `tracking`. Captures the email's engagement events as events of the recipient. Defaults to `True`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. | +`sensitive` | | Marks the email as sensitive, such as one that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `template_key` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. The template form doesn't take it. | +`tracking` | | What PostHog tracks for this email. Without it, PostHog counts opens with its open pixel, captures engagement events, and counts clicks only when the email isn't sensitive. `True` turns on opens, clicks and engagement events. `False` turns off all tracking, including kinds PostHog adds later: PostHog can't count the email's opens or clicks, and captures no engagement events. An `EmailTracking` dict turns each kind on or off, and a key you leave out keeps its default. Turn clicks on for a sensitive email only when its links are safe to send through PostHog's click tracking. The template form doesn't take it. | `distinct_id` | | The recipient's distinct ID in your product. | `idempotency_key` | | 1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for another email, or for a `template_id` send, raises `idempotency_key_reused`. A retry with the same key returns the first send's result, also when its workflow was paused since. | `max_retries` | | Overrides the client's maximum number of retries for this send. `0` turns retries off. | @@ -4038,10 +4040,12 @@ Name | Type | Description `idempotency_key` | `NotRequired[Optional[str]]` | `max_retries` | `NotRequired[Optional[int]]` | `reply_to` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | +`sensitive` | `NotRequired[Optional[bool]]` | `subject` | `str` | `template_key` | `str` | `text` | `NotRequired[Optional[str]]` | `to` | `str` | +`tracking` | `NotRequired[Optional[Union[bool, EmailTracking]]]` | #### `posthog.emails.CodeEmailArgs.capture_engagement` @@ -4085,6 +4089,12 @@ max_retries: NotRequired[Optional[int]] reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] ``` +#### `posthog.emails.CodeEmailArgs.sensitive` + +```python +sensitive: NotRequired[Optional[bool]] +``` + #### `posthog.emails.CodeEmailArgs.subject` ```python @@ -4108,3 +4118,9 @@ text: NotRequired[Optional[str]] ```python to: str ``` + +#### `posthog.emails.CodeEmailArgs.tracking` + +```python +tracking: NotRequired[Optional[Union[bool, EmailTracking]]] +``` diff --git a/references/posthog-python-reference.md b/references/posthog-python-reference.md index fa798a96c..fd92c182b 100644 --- a/references/posthog-python-reference.md +++ b/references/posthog-python-reference.md @@ -4022,7 +4022,9 @@ Name | Type | Description | Default `text` | | The plain-text body. Without it, PostHog derives it from `html`. HTML with no text in it, such as a single image, goes out without a plain-text part. | `from_` | | A verified sender, such as `"Acme "`. | `reply_to` | | One address or a list of addresses. An empty list sends no reply-to. | -`capture_engagement` | | Capture the email's opens and clicks as events of the recipient. Defaults to `True`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. | +`capture_engagement` | | Deprecated, use `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both `capture_engagement` and `tracking`. Captures the email's engagement events as events of the recipient. Defaults to `True`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. | +`sensitive` | | Marks the email as sensitive, such as one that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `template_key` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. The template form doesn't take it. | +`tracking` | | What PostHog tracks for this email. Without it, PostHog counts opens with its open pixel, captures engagement events, and counts clicks only when the email isn't sensitive. `True` turns on opens, clicks and engagement events. `False` turns off all tracking, including kinds PostHog adds later: PostHog can't count the email's opens or clicks, and captures no engagement events. An `EmailTracking` dict turns each kind on or off, and a key you leave out keeps its default. Turn clicks on for a sensitive email only when its links are safe to send through PostHog's click tracking. The template form doesn't take it. | `distinct_id` | | The recipient's distinct ID in your product. | `idempotency_key` | | 1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for another email, or for a `template_id` send, raises `idempotency_key_reused`. A retry with the same key returns the first send's result, also when its workflow was paused since. | `max_retries` | | Overrides the client's maximum number of retries for this send. `0` turns retries off. | @@ -4038,10 +4040,12 @@ Name | Type | Description `idempotency_key` | `NotRequired[Optional[str]]` | `max_retries` | `NotRequired[Optional[int]]` | `reply_to` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | +`sensitive` | `NotRequired[Optional[bool]]` | `subject` | `str` | `template_key` | `str` | `text` | `NotRequired[Optional[str]]` | `to` | `str` | +`tracking` | `NotRequired[Optional[Union[bool, EmailTracking]]]` | #### `posthog.emails.CodeEmailArgs.capture_engagement` @@ -4085,6 +4089,12 @@ max_retries: NotRequired[Optional[int]] reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] ``` +#### `posthog.emails.CodeEmailArgs.sensitive` + +```python +sensitive: NotRequired[Optional[bool]] +``` + #### `posthog.emails.CodeEmailArgs.subject` ```python @@ -4108,3 +4118,9 @@ text: NotRequired[Optional[str]] ```python to: str ``` + +#### `posthog.emails.CodeEmailArgs.tracking` + +```python +tracking: NotRequired[Optional[Union[bool, EmailTracking]]] +``` From e2fb8da670206007004508cd2f963960e1020ade Mon Sep 17 00:00:00 2001 From: Manoel Aranda Neto <5731772+marandaneto@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:24:55 +0700 Subject: [PATCH 09/33] chore: remove mutation testing setup (#1239) --- .github/workflows/ci.yml | 37 +++++-------------------------------- .gitignore | 1 - posthog/utils.py | 16 +++++++--------- pyproject.toml | 7 ------- 4 files changed, 12 insertions(+), 49 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef0ff8a61..d93383859 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -205,8 +205,8 @@ jobs: run: | pytest posthog/test/mcp --verbose --timeout=30 - mutation-tests: - name: Targeted mutation tests + utils-quality: + name: Utils quality runs-on: ubuntu-latest steps: @@ -214,7 +214,7 @@ jobs: with: fetch-depth: 0 - - name: Check targeted mutation inputs changed + - name: Check utils quality inputs changed id: changes shell: bash run: | @@ -235,11 +235,11 @@ jobs: if [[ -n "$changed_files" ]]; then echo "changed=true" >> "$GITHUB_OUTPUT" - echo "Targeted mutation inputs changed:" + echo "Utils quality inputs changed:" echo "$changed_files" else echo "changed=false" >> "$GITHUB_OUTPUT" - echo "Skipping targeted mutation tests: inputs unchanged." + echo "Skipping utils quality check: inputs unchanged." fi - name: Set up Python 3.11 @@ -263,33 +263,6 @@ jobs: UV_PROJECT_ENVIRONMENT=$pythonLocation uv run --extra test --with pytest-crap --with pytest-cov pytest posthog/test/test_utils.py posthog/test/test_size_limited_dict.py --timeout=30 --cov=posthog.utils --crap --crap-threshold=10 --crap-top-n=40 -q UV_PROJECT_ENVIRONMENT=$pythonLocation uv run --extra test --with pytest-crap --with pytest-cov python .github/scripts/check_crap_threshold.py posthog/utils.py --max-crap 10 - - name: Restore mutmut cache - id: mutmut-cache - if: steps.changes.outputs.changed == 'true' - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: mutants - key: mutmut-${{ runner.os }}-py311-${{ hashFiles('posthog/utils.py', 'posthog/test/test_utils.py', 'posthog/test/test_size_limited_dict.py') }} - restore-keys: | - mutmut-${{ runner.os }}-py311- - - - name: Skip mutation tests on exact cache hit - if: steps.changes.outputs.changed == 'true' && steps.mutmut-cache.outputs.cache-hit == 'true' - run: | - echo "Skipping targeted mutation tests: exact mutmut cache hit." - - - name: Run targeted mutation tests - if: steps.changes.outputs.changed == 'true' && steps.mutmut-cache.outputs.cache-hit != 'true' - shell: bash - run: | - set -euo pipefail - UV_PROJECT_ENVIRONMENT=$pythonLocation uv run --extra test --with mutmut mutmut run --max-children 1 - results="$(UV_PROJECT_ENVIRONMENT=$pythonLocation uv run --extra test --with mutmut mutmut results)" - if [[ -n "$results" ]]; then - echo "$results" - exit 1 - fi - import-check: name: Python ${{ matrix.python-version }} import check runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index b8e7cb9ac..4e3d70dcb 100644 --- a/.gitignore +++ b/.gitignore @@ -22,4 +22,3 @@ pyrightconfig.json .DS_Store posthog-python-references.json .claude/settings.local.json -mutants/ diff --git a/posthog/utils.py b/posthog/utils.py index 1f36416a8..cfa508565 100644 --- a/posthog/utils.py +++ b/posthog/utils.py @@ -21,7 +21,7 @@ def is_naive(dt: datetime) -> bool: """Determines if a given datetime.datetime is naive.""" - return dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None # pragma: no mutate + return dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None def total_seconds(delta: timedelta) -> float: @@ -36,14 +36,12 @@ def guess_timezone(dt: datetime) -> datetime: # attempts to guess the datetime.datetime.now() local timezone # case, and then defaults to utc delta = total_seconds(datetime.now() - dt) - if 0 <= delta < 5: # pragma: no mutate + if 0 <= delta < 5: # this was created using datetime.datetime.now(), # so use the current system local timezone # Equivalent to converting the naive value directly because this path # only handles values created in the current local timezone. - dt = dt.replace( - tzinfo=datetime.now().astimezone().tzinfo - ) # pragma: no mutate + dt = dt.replace(tzinfo=datetime.now().astimezone().tzinfo) else: # at this point, the best we can do is guess UTC dt = dt.replace(tzinfo=timezone.utc) @@ -62,7 +60,7 @@ def _normalize_timestamp(timestamp: Union[datetime, str]) -> str: try: # Python 3.10 needs the replacements; on 3.11+ fromisoformat accepts Z # and compact UTC offsets such as +0530. - normalized_timestamp = timestamp.replace("Z", "+00:00") # pragma: no mutate + normalized_timestamp = timestamp.replace("Z", "+00:00") normalized_timestamp = re.sub( r"([+-]\d{2})(\d{2})$", r"\1:\2", normalized_timestamp ) @@ -162,7 +160,7 @@ def _coerce_unicode(cmplx: Any) -> Optional[str]: item = None try: if isinstance(cmplx, bytes): - item = cmplx.decode("utf-8", "strict") # pragma: no mutate + item = cmplx.decode("utf-8", "strict") elif isinstance(cmplx, str): item = cmplx except Exception as exception: @@ -569,7 +567,7 @@ def invalidate_version(self, old_version): self._delete_keys_with_version(keys, old_version) if cursor == 0: - break # pragma: no mutate + break except Exception: # Redis error - silently fail @@ -641,7 +639,7 @@ def clear(self): if keys: self.redis.delete(*keys) if cursor == 0: - break # pragma: no mutate + break except Exception: # Redis error - silently fail pass diff --git a/pyproject.toml b/pyproject.toml index 61c79756e..692afae43 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -173,13 +173,6 @@ asyncio_default_fixture_loop_scope = "function" testpaths = ["posthog/test"] norecursedirs = ["integration_tests"] -[tool.mutmut] -paths_to_mutate = ["posthog/utils.py"] -do_not_mutate = ["posthog/test/*"] -tests_dir = ["posthog/test/test_utils.py", "posthog/test/test_size_limited_dict.py"] -also_copy = ["posthog"] -pytest_add_cli_args = ["--timeout=30"] - [dependency-groups] dev = [ "claude-agent-sdk>=0.1.50", From 013986168a131efed4a86d75a222e554f2f542d8 Mon Sep 17 00:00:00 2001 From: Lucas Faria <12522524+lucasheriques@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:23:56 -0300 Subject: [PATCH 10/33] fix(mcp): report the exception behind a FastMCP isError tool result (#1226) * test(mcp): failing repro for FastMCP tool failures losing the raised exception Standalone FastMCP converts a raised tool exception into an isError result before our wrapped handler returns, so the failure is reported as a generic "Error" with no frames (posthog-python#1223). Fails on fastmcp 3/mcp 1 and fastmcp 4/mcp 2. * fix(mcp): report the exception behind a FastMCP isError tool result Standalone FastMCP converts a raised tool exception into CallToolResult(isError=True) inside the tools/call handler we wrap, so every failure was captured from the result text: $mcp_error_type "Error", one generic $exception_list entry, no frames (posthog-python#1223). instrument() now wraps the server's public call_tool, which still raises (ToolError chained from the tool's exception). The wrapper hands the outermost call's outcome to the enclosing handler through a context variable, and the handler records it next to the result. fastmcp's "Error calling tool" ToolError joins the dispatch wrappers the scalars step past, so $mcp_error_type names the tool's own exception. Tested: - test_fastmcp_tool_errors.py fails before, passes after, on fastmcp 3.2 + mcp 1.30 and fastmcp 4.1.8 + mcp 2.3 - pytest posthog/test/mcp: 694 passed (mcp 1.x), 575 passed (mcp 2.x) - issue repro: $mcp_error_type RuntimeError, chain ToolError -> RuntimeError -> ConnectionError with frames - ruff format/check, mypy clean Not included: $mcp_error_status. The taxonomy defines it as the upstream status of PostHog's own server calls and no SDK sets it today; setting it from the SDK is a cross-SDK contract change. * fix(mcp): keep another server's handled tool failure off this call Pre-PR gate findings on the previous commit: - The error slot was shared across servers. A tool that called another instrumented FastMCP's call_tool and handled its failure got that exception on its own successful event, whenever its own server's call_tool was not wrapped (a raw low-level server, or a FastMCP instrumented only through _mcp_server). The slot now names the server whose handler opened it, and only that server's call_tool writes to it. - The "Error calling tool" wrapper match also unwrapped a tool's own ToolError worded that way. It now requires fastmcp's quoted tool name. Tested: both repros added to test_fastmcp_tool_errors.py; pytest posthog/test/mcp 697 passed (mcp 1.30 + fastmcp 3.2), 578 passed (mcp 2.3 + fastmcp 4.1.8); ruff and mypy clean. * fix(mcp): keep FastMCP 2.x instrumented, and freeze the slot on exit Review on 81b3170 (PostHog Review, confirmed by ioannisj): - FastMCP 2.x has no public call_tool, so wrapping it raised AttributeError and instrument() fell back to no-op analytics: no MCP events at all on a supported stack. 2.x dispatches tools/call through _call_tool_middleware, so that is the seam wrapped there. 2.x now also reports the raised exception. - A background task holding the slot could settle it after the handler's dispatch returned. The slot now closes when the handler leaves it. - CI gains a v1-fastmcp2 leg (mcp 1.x + fastmcp 2.x), which would have caught the first point. Tested: pytest posthog/test/mcp passes on fastmcp 2.14.7 + mcp 1.30, fastmcp 3.2 + mcp 1.30, fastmcp 4.1.8 + mcp 2.3 (at 81b3170, 63 tests failed on fastmcp 2.14.7; at ae8f0bd all passed). The background race did not reproduce in a 0-40 tick sweep on 3.2 or 4.1.8, so it has no test; the close-on-exit makes it impossible by construction. * fix(mcp): redact secrets in captured exception frame source lines The MCP sanitizer scrubbed each exception's value but not its frames' pre_context, context_line and post_context. A token written in the source around a raise reached $exception verbatim. This was already true on the official SDK path; #1223's fix made it reachable on standalone FastMCP too, where frames were never sent before. Those three keys now pass through the same sanitize_captured_value as the value. Tested: test_secrets_in_frame_source_lines_are_redacted fails without the sanitizer change and passes with it; full MCP suites pass on fastmcp 2.14.7, 3.2 and 4.1.8. * fix(mcp): don't let a lingering background task keep a tool's traceback alive PostHog Review on 34fbaeb: a background task started by a failing tool copies the request's context, and with it the slot holding the raised exception. Closing the slot left the exception attached, so its traceback and every frame's locals lived as long as the task. The slot the context can reach is now emptied on exit; the handler reads the outcome from a separate object only it holds. Tested: test_a_background_task_does_not_keep_the_failure_alive holds a weakref to a tool local while the tool's background task is still pending. It fails before and passes after on fastmcp 2.14.7, 3.2 and 4.1.8. The test turns logging off, because pytest's log capture keeps fastmcp's error records and their exc_info would retain the traceback by itself. Full MCP suites: 690 / 699 / 580 passed. * fix(mcp): redact sensitive JSON members inside captured strings Review on 52fc421 (PostHog Review, dustinbyrne): a failed FastMCP tool whose source has `credentials = {"password": "hunter2"}` sent the password in its frame's source context. The cause is wider than frames: the MCP Payload privacy spec requires redacting, inside any captured string, the value of a JSON member whose key is on the credential list, and posthog-python never implemented it. posthog-go and posthog-rs do. This ports their pattern into _redact_credentials, so it covers response text, error messages and frame source alike. Tested: posthog-go's TestSanitizeStringRedactsSensitiveJSONMembers table ported as a parameterized test, plus a source-line case; 13 redaction cases failed before, all 17 pass after. The frame test now also carries a JSON credential next to a benign member that must survive. Full MCP suites pass: 716 (fastmcp 3.2 + mcp 1.30), 597 (fastmcp 4.1.8 + mcp 2.3), 707 (fastmcp 2.14.7 + mcp 1.30). Ruff and mypy clean. * fix(mcp): keep JSON-member redaction linear on malformed arrays Review on d8a7a55 (PostHog Review, veria-ai): the array part of the JSON-member pattern made every comma optional. Go and Rust run that pattern on linear-time engines; Python's re backtracks, so a caller's `{"note":[` + 40 digits + `!` split the digits into array items in exponentially many ways and blocked the event loop. Every item after the first now needs its comma, with an optional trailing one so an array cut off mid-list still matches, which leaves each input one parse. Tested: test_json_member_redaction_runs_in_linear_time_on_malformed_arrays timed out at 5 s on two of three inputs before and passes after. Ten adversarial 100k-character shapes (open arrays, lone quotes, unclosed strings, escapes, number characters) each finish under 10 ms. All JSON-member cases still pass. Full MCP suites: 719 / 600 / 710 passed on fastmcp 3.2 / 4.1.8 / 2.14.7. * fix(mcp): scan JSON members once instead of retrying the regex at every quote Review on 9c1cb4f (PostHog Review, veria-ai): with no member to match, the JSON-member regex restarted at every quote and rescanned the rest of the text, so 16,000 escaped quote pairs took about 3 s and 64,000 took 49 s on the server's event loop. This is the second performance finding in that regex: Go and Rust run it on linear-time engines, and Python's re does not. It is replaced by a scanner that tries the same key starts but caches where a string body ends and what follows each closing quote, so overlapping candidates share their work. Tested: the linear-time test gains escaped-quote and JSON-encoded-quote inputs at 32,000 pairs, which timed out at 5 s before and pass after; ten adversarial 100k-200k-character shapes each finish under 60 ms. A differential test keeps the reference pattern as an oracle and checks the scanner against it on 30,000 random texts (a one-off run of 200,000 longer ones found no mismatch). Full MCP suites: 722 / 603 / 713 passed on fastmcp 3.2 / 4.1.8 / 2.14.7; ruff and mypy clean. --- .github/workflows/ci.yml | 10 +- .../fastmcp-tool-error-exception.md | 5 + posthog/mcp/__init__.py | 7 +- posthog/mcp/_instrument_lowlevel.py | 5 +- posthog/mcp/_instrument_v2.py | 9 +- posthog/mcp/_instrumentation.py | 17 +- posthog/mcp/_posthog_events.py | 1 + posthog/mcp/_raised_tool_error.py | 83 +++++++ posthog/mcp/_sanitization.py | 182 ++++++++++++++- posthog/test/mcp/test_fastmcp_tool_errors.py | 209 ++++++++++++++++++ posthog/test/mcp/test_pipeline.py | 136 ++++++++++++ 11 files changed, 647 insertions(+), 17 deletions(-) create mode 100644 .sampo/changesets/fastmcp-tool-error-exception.md create mode 100644 posthog/mcp/_raised_tool_error.py create mode 100644 posthog/test/mcp/test_fastmcp_tool_errors.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d93383859..d8b16e245 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -156,7 +156,9 @@ jobs: # the lockfile's mcp 1.x (also exercised incidentally by the `tests` # matrix — this leg exists as an explicit, named signal); the v2 leg # (spec 2026-07-28) swaps in mcp>=2 and standalone FastMCP 4, which uses - # the v2 registry. The v2-bare leg runs mcp>=2 without FastMCP: importing + # the v2 registry. The v1-fastmcp2 leg keeps mcp 1.x and swaps in + # standalone FastMCP 2, which dispatches tools without a public + # call_tool. The v2-bare leg runs mcp>=2 without FastMCP: importing # FastMCP 4 patches camelCase properties onto mcp_types models for the # whole process, which hides reads that plain mcp 2.x rejects. # posthog/test/mcp/conftest.py splits collection by major. @@ -166,8 +168,10 @@ jobs: strategy: matrix: python-version: ['3.10', '3.14'] - mcp-major: ['v1', 'v2', 'v2-bare'] + mcp-major: ['v1', 'v1-fastmcp2', 'v2', 'v2-bare'] include: + - mcp-major: 'v1-fastmcp2' + mcp-packages: "'mcp>=1.28.1,<2' 'fastmcp>=2,<3'" - mcp-major: 'v2' mcp-packages: "'mcp>=2,<3' 'fastmcp>=4,<5'" - mcp-major: 'v2-bare' @@ -194,7 +198,7 @@ jobs: run: | UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --extra test - - name: Swap in MCP SDK v2 + - name: Swap in MCP packages if: matrix.mcp-major != 'v1' shell: bash run: | diff --git a/.sampo/changesets/fastmcp-tool-error-exception.md b/.sampo/changesets/fastmcp-tool-error-exception.md new file mode 100644 index 000000000..ab1520bd5 --- /dev/null +++ b/.sampo/changesets/fastmcp-tool-error-exception.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +`posthog.mcp`: a failed tool call on a standalone FastMCP server now reports the exception the tool raised, with its cause chain and stack frames, and `$mcp_error_type` names its class. Before, FastMCP converted the exception into an error result first, so the failure was a generic `Error` with no frames. diff --git a/posthog/mcp/__init__.py b/posthog/mcp/__init__.py index 98a73bede..9f9db0211 100644 --- a/posthog/mcp/__init__.py +++ b/posthog/mcp/__init__.py @@ -290,6 +290,7 @@ def instrument( from ._instrument_fastmcp import instrument_fastmcp from ._instrument_lowlevel import instrument_fastmcp_v2, instrument_low_level from ._instrument_v2 import instrument_lowlevel_v2, instrument_mcpserver_v2 + from ._raised_tool_error import wrap_tool_dispatch client = _resolve_client(posthog_client) if client is None: @@ -306,8 +307,10 @@ def instrument( server_build=server_build, ) - if is_fastmcp_v2(server) and uses_v2_handler_registry(key): - data.standalone_fastmcp = weakref.ref(server) + if is_fastmcp_v2(server): + wrap_tool_dispatch(server) + if uses_v2_handler_registry(key): + data.standalone_fastmcp = weakref.ref(server) # A standalone FastMCP wrapper and its low-level server share one tracking # key, so instrumenting the second of the pair must still attach what only diff --git a/posthog/mcp/_instrument_lowlevel.py b/posthog/mcp/_instrument_lowlevel.py index a8ab58671..8d6cf4393 100644 --- a/posthog/mcp/_instrument_lowlevel.py +++ b/posthog/mcp/_instrument_lowlevel.py @@ -54,6 +54,7 @@ from ._model_parameters import request_meta_from_context from ._model_parameters import can_inject_model_parameter, is_capture_model_enabled from ._output_instructions import mirror_instructions_into_structured_content +from ._raised_tool_error import raised_tool_error from .logger import log, warn from .tools import get_more_tools_result_text @@ -282,7 +283,8 @@ async def handler(req: Any) -> Any: start = time.monotonic() try: - result = await original(req) + with raised_tool_error(high_level) as raised: + result = await original(req) except Exception as error: if await lifecycle.record_if_unknown_tool( await registered_tool_exists(high_level, name) @@ -349,6 +351,7 @@ async def handler(req: Any) -> Any: call_result, duration_ms, conversation_id_delivered=delivered, + error=raised.error, ) return result diff --git a/posthog/mcp/_instrument_v2.py b/posthog/mcp/_instrument_v2.py index b7d597789..da85d2c06 100644 --- a/posthog/mcp/_instrument_v2.py +++ b/posthog/mcp/_instrument_v2.py @@ -75,6 +75,7 @@ request_meta_from_context, ) from ._output_instructions import mirror_instructions_into_structured_content +from ._raised_tool_error import raised_tool_error from ._tool_input import get_registered_tool_input_schema from .asgi import get_mcp_session from .logger import log @@ -673,7 +674,8 @@ async def handler(ctx: Any, params: Any) -> Any: start = time.monotonic() try: - result = await original(ctx, params) + with raised_tool_error(standalone) as raised: + result = await original(ctx, params) except Exception as error: if await lifecycle.record_if_unknown_tool( await registered_tool_exists(standalone, name) @@ -702,7 +704,10 @@ async def handler(ctx: Any, params: Any) -> Any: return result await lifecycle.record_result( - result, duration_ms, conversation_id_delivered=delivered + result, + duration_ms, + conversation_id_delivered=delivered, + error=raised.error, ) return result diff --git a/posthog/mcp/_instrumentation.py b/posthog/mcp/_instrumentation.py index 9b1db44c7..023497620 100644 --- a/posthog/mcp/_instrumentation.py +++ b/posthog/mcp/_instrumentation.py @@ -665,7 +665,12 @@ async def record_error(self, error: Any, duration_ms: float) -> None: ) async def record_result( - self, result: Any, duration_ms: float, *, conversation_id_delivered: bool + self, + result: Any, + duration_ms: float, + *, + conversation_id_delivered: bool, + error: Optional[BaseException] = None, ) -> None: conversation_id = self._anchored_conversation_id(conversation_id_delivered) session_id = await self.prepare_session(conversation_id) @@ -678,6 +683,7 @@ async def record_result( allow_self_reported_model=self.allow_self_reported_model, analytics_owned_parameters=self.analytics_owned_parameters, result=result, + error=error, duration_ms=duration_ms, client_name=self.client_name, client_version=self.client_version, @@ -813,14 +819,13 @@ async def record_tool_call( event["llm_model"] = model event["llm_model_source"] = source + if result is not None: + event["response"] = _wrap_response(result) + if error is None and is_tool_result_error(result): + error = result if error is not None: event["is_error"] = True event["error"] = capture_exception(error) - elif result is not None: - event["response"] = _wrap_response(result) - if is_tool_result_error(result): - event["is_error"] = True - event["error"] = capture_exception(result) props = await resolve_event_properties(data, request, extra) input_aliases = None diff --git a/posthog/mcp/_posthog_events.py b/posthog/mcp/_posthog_events.py index f7b58f0e7..e20971aed 100644 --- a/posthog/mcp/_posthog_events.py +++ b/posthog/mcp/_posthog_events.py @@ -178,6 +178,7 @@ def _add_common_properties(event: Event, properties: Dict[str, Any]) -> None: # its text, so reporting it loses nothing. _DISPATCH_WRAPPERS = ( (("ToolError", "UnexpectedToolError"), "Error executing tool"), + (("ToolError",), "Error calling tool '"), (("MCPError", "UnexpectedResourceError"), "Error reading resource"), ) diff --git a/posthog/mcp/_raised_tool_error.py b/posthog/mcp/_raised_tool_error.py new file mode 100644 index 000000000..e694cf6fe --- /dev/null +++ b/posthog/mcp/_raised_tool_error.py @@ -0,0 +1,83 @@ +"""Recover the exception behind a standalone FastMCP ``isError`` tool result. + +FastMCP's ``tools/call`` handler, the one we wrap, turns whatever its tool +dispatch raised into ``CallToolResult(isError=True)``, keeping only the +message text. Wrapping that dispatch on the server instance sees the exception +first, and hands it to the enclosing handler through a context variable. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from typing import Any, Iterator, Optional + +_WRAPPED_FLAG = "__posthog_mcp_wrapped__" + +# fastmcp 3+ dispatches tools/call through the public `call_tool`; 2.x has no +# `call_tool` and dispatches through `_call_tool_middleware`. +_DISPATCH_METHODS = ("call_tool", "_call_tool_middleware") + + +@dataclass +class RaisedToolError: + error: Optional[BaseException] = None + + +@dataclass +class _Slot: + server: Any + error: Optional[BaseException] = None + open: bool = True + + +_current: ContextVar[Optional[_Slot]] = ContextVar( + "posthog_mcp_raised_tool_error", default=None +) + + +def wrap_tool_dispatch(server: Any) -> None: + method = next((m for m in _DISPATCH_METHODS if hasattr(server, m)), None) + if method is None: + return + original = getattr(server, method) + if getattr(original, _WRAPPED_FLAG, False): + return + + async def dispatch(*args: Any, **kwargs: Any) -> Any: + # A tool calling another tool nests these calls. The outermost call + # settles last, so the slot ends holding the outcome the client sees. + try: + result = await original(*args, **kwargs) + except Exception as error: + _settle(server, error) + raise + _settle(server, None) + return result + + setattr(dispatch, _WRAPPED_FLAG, True) + setattr(server, method, dispatch) + + +def _settle(server: Any, error: Optional[BaseException]) -> None: + # Another server's dispatch, reached from inside a tool, must not write + # its outcome onto this call, nor may a background task that outlives it. + slot = _current.get() + if slot is not None and slot.open and slot.server is server: + slot.error = error + + +@contextmanager +def raised_tool_error(server: Any) -> Iterator[RaisedToolError]: + slot = _Slot(server) + raised = RaisedToolError() + token = _current.set(slot) + try: + yield raised + finally: + _current.reset(token) + # A background task started by the tool keeps a copy of this context, + # so the slot outlives the call; it must not keep the traceback alive. + raised.error, slot.error = slot.error, None + slot.open = False diff --git a/posthog/mcp/_sanitization.py b/posthog/mcp/_sanitization.py index 426d2d29f..12b442245 100644 --- a/posthog/mcp/_sanitization.py +++ b/posthog/mcp/_sanitization.py @@ -10,6 +10,7 @@ from __future__ import annotations +import json import re from typing import Any, Dict, List, Optional, Set, Tuple from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit, urlunsplit @@ -32,6 +33,10 @@ re.IGNORECASE, ) +_JSON_STRING_STOP = re.compile(r'["\\\n]') +_JSON_NUMBER = re.compile(r"-?\d[\d.eE+-]*") +_NON_SPACE = re.compile(r"\S") + # No leading `\b`: a word boundary needs a non-word character before the scheme, # so `resource_https://user:pw@host` (an `_` before the scheme) would match # nothing and stay unredacted. Without it the leftmost match wins — `foo.https://x` @@ -442,9 +447,155 @@ def _redact_credentials(value: str) -> str: entropy detector scans. Running the URL pass last loses nothing — it only redacts or percent-encodes, so it never exposes a credential the detectors could have matched.""" + value = _redact_json_members(value) return _redact_secret_tokens(_POSTHOG_TOKEN_PATTERN.sub(_REDACTED_VALUE, value)) +def _redact_json_members(value: str) -> str: + if '"' not in value: + return value + return _JsonMemberScan(value).redacted() + + +class _JsonMemberScan: + """Redacts the members posthog-go's jsonMemberPattern and posthog-rs's + JSON_MEMBER match: `"key": value`, where the value is a string, number, + boolean, or flat array of those (with every item after the first needing its + comma). A tool that returns structuredContent also returns it as JSON text, + where a credential is a member inside a string rather than a dict key. + + Like those patterns, any quote may open a key, and the scan resumes after + each member. They run on linear-time engines; Python's `re` backtracks and + would rescan the rest of the text from every quote, so this caches where a + string body ends and what follows each closing quote. + + A JSON string never holds a raw newline, so one cut off by truncation ends + at the line or the text instead of swallowing prose up to the next quote. + Values that nest objects, and JSON inside a JSON string, are out of scope. + """ + + def __init__(self, text: str) -> None: + self.text = text + self.body_ends: Dict[int, int] = {} + self.members: Dict[int, Optional[Tuple[int, int]]] = {} + + def redacted(self) -> str: + text = self.text + parts: List[str] = [] + last = 0 + quote = text.find('"') + while quote != -1: + key_end = self.body_end(quote + 1) + member = ( + self.member_after(key_end + 1) + if key_end < len(text) and text[key_end] == '"' + else None + ) + if member is None: + quote = text.find('"', quote + 1) + continue + value_start, value_end = member + if _should_redact_key(_decoded_json_key(text[quote + 1 : key_end])): + parts.append(text[last:value_start]) + parts.append(f'"{_REDACTED_VALUE}"') + last = value_end + quote = text.find('"', value_end) + parts.append(text[last:]) + return "".join(parts) + + def body_end(self, start: int) -> int: + """Where a string body starting at `start` stops: its closing quote, a + newline, a backslash with nothing left to escape, or the end.""" + text = self.text + escapes = [] + pos = start + while True: + stop = _JSON_STRING_STOP.search(text, pos) + end = stop.start() if stop else len(text) + if end in self.body_ends: + end = self.body_ends[end] + break + if text[end : end + 1] != "\\" or text[end + 1 : end + 2] in ("", "\n"): + break + escapes.append(end) + pos = end + 2 + for escape in escapes: + self.body_ends[escape] = end + return end + + def member_after(self, pos: int) -> Optional[Tuple[int, int]]: + """Where the value after a key that closed just before `pos` starts and + ends, or None when no `: value` follows. Every quote inside a run of + escaped quotes closes on the same key, so this is computed once.""" + if pos not in self.members: + colon = self.skip_space(pos) + member = None + if self.text[colon : colon + 1] == ":": + value_start = self.skip_space(colon + 1) + value_end = self.value_end(value_start) + if value_end is not None: + member = (value_start, value_end) + self.members[pos] = member + return self.members[pos] + + def value_end(self, pos: int) -> Optional[int]: + if self.text[pos : pos + 1] == "[": + return self.array_end(pos + 1) + return self.scalar_end(pos) + + def scalar_end(self, pos: int) -> Optional[int]: + text = self.text + if text[pos : pos + 1] == '"': + end = self.body_end(pos + 1) + return end + 1 if text[end : end + 1] in ('"', "\\") else end + number = _JSON_NUMBER.match(text, pos) + if number: + return number.end() + for literal in ("true", "false"): + if text.startswith(literal, pos): + return pos + len(literal) + return None + + def item_end(self, pos: int) -> Optional[int]: + end = self.scalar_end(pos) + if end is None and self.text.startswith("null", pos): + end = pos + 4 + return None if end is None else self.skip_space(end) + + def array_end(self, pos: int) -> Optional[int]: + text = self.text + pos = self.skip_space(pos) + item = self.item_end(pos) + if item is not None: + pos = item + while text[pos : pos + 1] == ",": + after_comma = self.skip_space(pos + 1) + item = self.item_end(after_comma) + if item is None: + pos = after_comma + break + pos = item + if text[pos : pos + 1] == "]": + return pos + 1 + if pos == len(text) or (pos == len(text) - 1 and text[pos] == "\n"): + return pos + return None + + def skip_space(self, pos: int) -> int: + non_space = _NON_SPACE.search(self.text, pos) + return non_space.start() if non_space else len(self.text) + + +def _decoded_json_key(raw: str) -> str: + if "\\" not in raw: + return raw + try: + decoded = json.loads(f'"{raw}"') + except ValueError: + return raw + return decoded if isinstance(decoded, str) else raw + + def sanitize_free_text(value: Any) -> Any: """Sanitize agent-narrated free text (the intent, the send_feedback fields): the binary gate, the credential passes, structured PII, then URLs. @@ -680,14 +831,39 @@ def _sanitize_exception_values(error: Any) -> Any: return { **error, "$exception_list": [ - {**exception, "value": sanitize_captured_value(exception.get("value"))} - if isinstance(exception, dict) - else exception + _sanitize_exception(exception) if isinstance(exception, dict) else exception for exception in exception_list ], } +_FRAME_SOURCE_KEYS = ("pre_context", "context_line", "post_context") + + +def _sanitize_exception(exception: Dict[str, Any]) -> Dict[str, Any]: + sanitized = {**exception, "value": sanitize_captured_value(exception.get("value"))} + stacktrace = exception.get("stacktrace") + if isinstance(stacktrace, dict) and isinstance(stacktrace.get("frames"), list): + sanitized["stacktrace"] = { + **stacktrace, + "frames": [_sanitize_frame(frame) for frame in stacktrace["frames"]], + } + return sanitized + + +def _sanitize_frame(frame: Any) -> Any: + if not isinstance(frame, dict): + return frame + return { + **frame, + **{ + key: sanitize_captured_value(frame[key]) + for key in _FRAME_SOURCE_KEYS + if key in frame + }, + } + + def _sanitize_response(response: Any) -> Any: if response is None or not isinstance(response, (dict, list, str)): return sanitize_captured_value(response) diff --git a/posthog/test/mcp/test_fastmcp_tool_errors.py b/posthog/test/mcp/test_fastmcp_tool_errors.py new file mode 100644 index 000000000..c1f1100cd --- /dev/null +++ b/posthog/test/mcp/test_fastmcp_tool_errors.py @@ -0,0 +1,209 @@ +"""Standalone FastMCP turns a raised tool exception into an ``isError`` result +before the handler we wrap returns. The failure must still carry what was raised +(posthog-python#1223).""" + +import asyncio +import gc +import logging +import weakref + +import pytest + +pytest.importorskip("fastmcp") + +from fastmcp import Client, FastMCP # noqa: E402 +from fastmcp.exceptions import ToolError # noqa: E402 + +from posthog.mcp import MCPAnalyticsOptions, instrument # noqa: E402 +from posthog.test.mcp._helpers import FakeClient, events_named, flush_background # noqa: E402 + + +def _upstream(): + raise ConnectionError("upstream down") + + +def _chained(): + try: + _upstream() + except ConnectionError as exc: + raise RuntimeError("lookup failed") from exc + + +def _tool_error(): + raise ToolError("bad input") + + +def _tool_error_worded_like_fastmcp(): + try: + _upstream() + except ConnectionError as exc: + raise ToolError("Error calling tool: lookup failed") from exc + + +@pytest.mark.parametrize( + "raise_in_tool, mask_error_details, error_type, message, chain", + [ + ( + _chained, + False, + "RuntimeError", + "lookup failed", + ["RuntimeError", "ConnectionError"], + ), + ( + _chained, + True, + "RuntimeError", + "lookup failed", + ["RuntimeError", "ConnectionError"], + ), + (_tool_error, False, "ToolError", "bad input", ["ToolError"]), + ( + _tool_error_worded_like_fastmcp, + False, + "ToolError", + "Error calling tool: lookup failed", + ["ToolError", "ConnectionError"], + ), + ], +) +async def test_failed_call_carries_the_raised_exception( + raise_in_tool, mask_error_details, error_type, message, chain +): + server = FastMCP("example-server", mask_error_details=mask_error_details) + + @server.tool + def fail() -> str: + raise_in_tool() + return "unreachable" + + sink = FakeClient() + instrument(server, sink, MCPAnalyticsOptions()) + + async with Client(server) as client: + result = await client.call_tool("fail", {}, raise_on_error=False) + await flush_background() + + assert result.is_error + [call] = events_named(sink, "$mcp_tool_call") + assert call["properties"]["$mcp_is_error"] is True + assert call["properties"]["$mcp_error_type"] == error_type + assert call["properties"]["$mcp_error_message"] == message + [exception] = events_named(sink, "$exception") + exception_list = exception["properties"]["$exception_list"] + raised = [e for e in exception_list if e["type"] in chain] + assert [e["type"] for e in raised] == chain + assert all(e["stacktrace"]["frames"] for e in raised) + + +@pytest.mark.parametrize( + "failing_server, instrumented", + [ + ("same", "wrapper"), + ("other", "wrapper"), + ("other", "low_level_only"), + ], +) +async def test_exception_caught_by_the_tool_is_not_reported( + failing_server, instrumented +): + if not hasattr(FastMCP, "call_tool"): + pytest.skip("fastmcp 2 has no public call_tool for a tool to call") + server = FastMCP("example-server") + other = FastMCP("other-server") + instrument(other, FakeClient(), MCPAnalyticsOptions()) + backend = server if failing_server == "same" else other + + @backend.tool + def inner() -> str: + raise RuntimeError("inner failure") + + @server.tool + async def outer() -> str: + try: + await backend.call_tool("inner", {}) + except ToolError: + pass + return "recovered" + + sink = FakeClient() + target = server if instrumented == "wrapper" else server._mcp_server + instrument(target, sink, MCPAnalyticsOptions()) + + async with Client(server) as client: + result = await client.call_tool("outer", {}, raise_on_error=False) + await flush_background() + + assert not result.is_error + [call] = events_named(sink, "$mcp_tool_call") + assert call["properties"]["$mcp_is_error"] is False + assert events_named(sink, "$exception") == [] + + +async def test_secrets_in_frame_source_lines_are_redacted(): + server = FastMCP("example-server") + + @server.tool + def fail() -> str: + dsn = "postgres://admin:hunter2@db.example.com/app" + credentials = {"password": "swordfish", "account": "reader"} + raise RuntimeError(f"connect failed for {credentials['account']}@{dsn[-6:]}") + + sink = FakeClient() + instrument(server, sink, MCPAnalyticsOptions()) + + async with Client(server) as client: + await client.call_tool("fail", {}, raise_on_error=False) + await flush_background() + + [exception] = events_named(sink, "$exception") + frames = [ + frame + for entry in exception["properties"]["$exception_list"] + for frame in entry["stacktrace"]["frames"] + ] + assert "db.example.com/app" in repr(frames) + assert '"account": "reader"' in repr(frames) + assert "hunter2" not in repr(frames) + assert "swordfish" not in repr(frames) + + +@pytest.fixture +def logging_off(): + # pytest's log capture keeps fastmcp's "Error calling tool" records, and + # their exc_info would keep the traceback alive on its own. + logging.disable(logging.CRITICAL) + yield + logging.disable(logging.NOTSET) + + +async def test_a_background_task_does_not_keep_the_failure_alive(logging_off): + server = FastMCP("example-server") + release = asyncio.Event() + lingering = [] + payload_refs = [] + + class Payload: + pass + + @server.tool + async def fail() -> str: + payload = Payload() + payload_refs.append(weakref.ref(payload)) + lingering.append(asyncio.get_running_loop().create_task(release.wait())) + raise RuntimeError("failed") + + sink = FakeClient() + instrument(server, sink, MCPAnalyticsOptions()) + + async with Client(server) as client: + await client.call_tool("fail", {}, raise_on_error=False) + await flush_background() + gc.collect() + + try: + assert not lingering[0].done() + assert payload_refs[0]() is None + finally: + release.set() + await lingering[0] diff --git a/posthog/test/mcp/test_pipeline.py b/posthog/test/mcp/test_pipeline.py index ea7457023..1e8728920 100644 --- a/posthog/test/mcp/test_pipeline.py +++ b/posthog/test/mcp/test_pipeline.py @@ -1,5 +1,8 @@ """Unit tests for the MCP analytics core pipeline (Milestone 1, no server).""" +import json +import re +import random from datetime import datetime, timezone import pytest @@ -9,6 +12,7 @@ PostHogMCPAnalyticsEvent, PostHogMCPAnalyticsProperty, ) +import posthog.mcp._sanitization as sanitization from posthog.mcp._event_types import MCPAnalyticsEventType from posthog.mcp._exceptions import capture_exception from posthog.mcp._ids import deterministic_prefixed_id, new_prefixed_id @@ -73,6 +77,138 @@ def test_sanitize_redacts_sensitive_keys(): assert out["safe"] == "keep" +@pytest.mark.parametrize( + "value, expected", + [ + pytest.param( + '{"user":"ada","password":"hunter2"}', + '{"user":"ada","password":"[redacted]"}', + id="string", + ), + pytest.param( + '{\n "Password" : "hun\\"ter2",\n "n": 1\n}', + '{\n "Password" : "[redacted]",\n "n": 1\n}', + id="escaped quote and spacing", + ), + pytest.param('{"api_key":12345}', '{"api_key":"[redacted]"}', id="number"), + pytest.param( + '{"access-token":true}', '{"access-token":"[redacted]"}', id="boolean" + ), + pytest.param( + '{"refresh_token":"abcdefgh', + '{"refresh_token":"[redacted]"', + id="cut off at the end of the text", + ), + pytest.param( + '{"private_key":"abc\\', + '{"private_key":"[redacted]"', + id="cut off after an escape", + ), + pytest.param( + '{"Authorization":["Bearer x"]}', + '{"Authorization":"[redacted]"}', + id="array", + ), + pytest.param( + '{"cookie": [\n "a=1",\n "b=2"\n]}', + '{"cookie": "[redacted]"}', + id="indented array", + ), + pytest.param( + '{"set-cookie":["a=1","b=2', + '{"set-cookie":"[redacted]"', + id="array cut off", + ), + pytest.param( + 'retry failed: "token": "abc"', + 'retry failed: "token": "[redacted]"', + id="inside prose", + ), + pytest.param( + '"token": "abc\nnext "line"', + '"token": "[redacted]"\nnext "line"', + id="unclosed in prose stops at the line", + ), + pytest.param( + '{"pass\\u0077ord":"hunter2"}', + '{"pass\\u0077ord":"[redacted]"}', + id="escaped key", + ), + pytest.param( + ' credentials = {"password": "hunter2", "account": "reader"}', + ' credentials = {"password": "[redacted]", "account": "reader"}', + id="source line", + ), + pytest.param( + '{"password_hint":"pet"}', + '{"password_hint":"pet"}', + id="key only contains a sensitive word", + ), + pytest.param('{"token":null}', '{"token":null}', id="null"), + pytest.param( + '{"secret":{"v":"x"}}', + '{"secret":{"v":"x"}}', + id="out of scope: nested object", + ), + pytest.param( + '{"body":"{\\"password\\":\\"x\\"}"}', + '{"body":"{\\"password\\":\\"x\\"}"}', + id="out of scope: JSON inside a JSON string", + ), + ], +) +def test_sanitize_redacts_sensitive_json_members_inside_strings(value, expected): + assert sanitize_captured_value(value) == expected + + +@pytest.mark.timeout(5) +@pytest.mark.parametrize( + "value", + [ + pytest.param('{"note":[' + "1" * 40 + "!", id="digits"), + pytest.param('{"note":[' + "1 " * 40 + "!", id="spaced digits"), + pytest.param('{"note":[' + "1," * 20_000 + "!", id="long array"), + pytest.param('\\"' * 32_000, id="escaped quotes"), + pytest.param(json.dumps('"' * 32_000), id="JSON-encoded quotes"), + ], +) +def test_json_member_redaction_runs_in_linear_time_on_adversarial_text(value): + assert sanitize_captured_value(value) == value + + +# The pattern posthog-go and posthog-rs match JSON members with (with every +# array item after the first needing its comma), run on Python's re. The SDK's +# scanner must find exactly its members, only without its quadratic retries. +_JSON_STRING_ORACLE = r'"(?:[^"\\\n]|\\.)*(?:"|\\?(?m:$))' +_JSON_SCALAR_ORACLE = _JSON_STRING_ORACLE + r"|-?\d[\d.eE+-]*|true|false" +_JSON_ITEM_ORACLE = r"(?:" + _JSON_SCALAR_ORACLE + r"|null)\s*" +_JSON_MEMBER_ORACLE = re.compile( + r'("((?:[^"\\\n]|\\.)*)"\s*:\s*)(?:' + + _JSON_SCALAR_ORACLE + + r"|\[\s*(?:" + + _JSON_ITEM_ORACLE + + r"(?:,\s*" + + _JSON_ITEM_ORACLE + + r")*(?:,\s*)?)?(?:\]|$))" +) + + +def test_json_member_scan_finds_what_the_reference_pattern_finds(monkeypatch): + monkeypatch.setattr(sanitization, "_should_redact_key", lambda key: True) + rng = random.Random(1223) + alphabet = ['"', '"', "\\", ":", ",", "[", "]", " ", "\n", "1", "-", "e", "x"] + words = ["true", "false", "null", '"k"', '"k": ', "[1, 2]", '\\"'] + texts = [ + "".join(rng.choice(alphabet + words) for _ in range(rng.randrange(16))) + for _ in range(30_000) + ] + for text in texts: + expected = _JSON_MEMBER_ORACLE.sub( + lambda member: member.group(1) + '"[redacted]"', text + ) + assert sanitization._redact_json_members(text) == expected, repr(text) + + def test_sanitize_redacts_large_base64(): blob = "A" * 11000 assert sanitize_captured_value(blob).startswith("[binary data redacted") From dd7577bccbe22cf4b2da970b1373d6f16bafeb20 Mon Sep 17 00:00:00 2001 From: Lucas Faria <12522524+lucasheriques@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:23:56 -0300 Subject: [PATCH 11/33] feat(mcp): set $mcp_error_status from the raised exception's cause chain (#1229) * feat(mcp): set $mcp_error_status from the raised exception's cause chain MCP Analytics groups failed calls by $mcp_error_status, but only PostHog's own server set it, so every posthog.mcp failure landed in "unknown". Rootly asked for it in #1223. Walk the cause chain inward (__cause__, else __context__ unless suppressed) and take the first int 100-599 from status_code, statusCode or status on the exception or its response, per the sdk-specs Failure capture rule. A caller's properties still win. Tested: pytest posthog/test/mcp (720 passed, 11 skipped); new parameterized test_error_status.py covers chain shapes and rejected values; FastMCP end-to-end row raises httpx.HTTPStatusError(503) under mask_error_details=True. * fix(mcp): follow __cause__ whenever set, and cap the status walk at 50 links Pre-PR adversarial review found two gaps against the sdk-specs rule: a __cause__ left with __suppress_context__ False was skipped for __context__, and a chain whose links are built on read never ended. Walk the chain a traceback prints, capped at 50 links like $exception_list. Tested: pytest posthog/test/mcp (724 passed, 11 skipped); mypy baseline clean. * fix(mcp): type the status walk's seen set, and record ERROR_STATUS in the API snapshot CI on 68b8974 failed Mypy (var-annotated on `seen` in _exceptions.py) and the Public API snapshot check (the new PostHogMCPAnalyticsProperty.ERROR_STATUS constant), which PostHog Review also flagged. Tested: mypy | mypy-baseline filter clean; check_public_api.py up to date; pytest posthog/test/mcp 725 / 606 / 716 passed on fastmcp 3.2 + mcp 1.30, 4.1.8 + mcp 2.3, 2.14.7 + mcp 1.30. --- .sampo/changesets/mcp-error-status.md | 5 + posthog/mcp/_capture.py | 1 + posthog/mcp/_exceptions.py | 49 ++++++- posthog/mcp/_instrumentation.py | 3 +- posthog/mcp/_posthog_events.py | 2 + posthog/mcp/constants.py | 1 + posthog/mcp/posthog_mcp.py | 3 +- posthog/mcp/types.py | 2 +- posthog/test/mcp/test_error_status.py | 145 +++++++++++++++++++ posthog/test/mcp/test_fastmcp_tool_errors.py | 27 +++- references/public_api_snapshot.txt | 1 + 11 files changed, 232 insertions(+), 7 deletions(-) create mode 100644 .sampo/changesets/mcp-error-status.md create mode 100644 posthog/test/mcp/test_error_status.py diff --git a/.sampo/changesets/mcp-error-status.md b/.sampo/changesets/mcp-error-status.md new file mode 100644 index 000000000..9ad073dfc --- /dev/null +++ b/.sampo/changesets/mcp-error-status.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: minor +--- + +`posthog.mcp`: a failed tool call now sets `$mcp_error_status` to the HTTP status behind it, read from the raised exception or its cause chain (`status_code`, `statusCode` or `status`, on the exception or its `response`, as `httpx.HTTPStatusError` and `requests.HTTPError` carry it). Failures from an upstream API now group by status in MCP Analytics instead of landing in "unknown". diff --git a/posthog/mcp/_capture.py b/posthog/mcp/_capture.py index ef48ef4a4..857dd2be6 100644 --- a/posthog/mcp/_capture.py +++ b/posthog/mcp/_capture.py @@ -69,6 +69,7 @@ def capture_event( "is_error": event_input.get("is_error"), "error": event_input.get("error"), "error_type": event_input.get("error_type"), + "error_status": event_input.get("error_status"), "conversation_id": event_input.get("conversation_id"), "properties": event_input.get("properties"), } diff --git a/posthog/mcp/_exceptions.py b/posthog/mcp/_exceptions.py index f34f30c7b..f74e1a167 100644 --- a/posthog/mcp/_exceptions.py +++ b/posthog/mcp/_exceptions.py @@ -10,7 +10,7 @@ from __future__ import annotations -from typing import Any, List +from typing import Any, Iterator, List, Optional, Set from posthog.exception_utils import exceptions_from_error_tuple @@ -38,6 +38,53 @@ def capture_exception(error: Any) -> ErrorProperties: return _from_message(_safe_str(error)) +_STATUS_ATTRIBUTES = ("status_code", "statusCode", "status") +_MAX_CHAIN_LINKS = 50 + + +def http_status(error: Any) -> Optional[int]: + """The HTTP status behind a failure, for ``$mcp_error_status``: the first + one found walking the raised exception's cause chain inward, so a status the + tool raised itself beats the one on the error it wrapped (httpx and requests + keep theirs on ``response.status_code``).""" + for link in _cause_chain(error): + for holder in (link, _attribute(link, "response")): + for name in _STATUS_ATTRIBUTES: + status = _attribute(holder, name) + if ( + isinstance(status, int) + and not isinstance(status, bool) + and 100 <= status <= 599 + ): + return int(status) + return None + + +def _cause_chain(error: Any) -> Iterator[BaseException]: + """The chain a traceback prints, capped like ``$exception_list``.""" + seen: Set[int] = set() + link = error + while ( + isinstance(link, BaseException) + and id(link) not in seen + and len(seen) < _MAX_CHAIN_LINKS + ): + seen.add(id(link)) + yield link + if link.__cause__ is not None: + link = link.__cause__ + else: + link = None if link.__suppress_context__ else link.__context__ + + +def _attribute(value: Any, name: str) -> Any: + # A third-party property can raise anything; a failed probe must not drop the event. + try: + return getattr(value, name, None) + except Exception: + return None + + def _from_message(message: str) -> ErrorProperties: return { "$exception_list": [ diff --git a/posthog/mcp/_instrumentation.py b/posthog/mcp/_instrumentation.py index 023497620..dd5d51e7e 100644 --- a/posthog/mcp/_instrumentation.py +++ b/posthog/mcp/_instrumentation.py @@ -30,7 +30,7 @@ resolve_conversation_id, ) from ._event_types import MCPAnalyticsEventType -from ._exceptions import capture_exception +from ._exceptions import capture_exception, http_status from .feedback import ( build_feedback_event_properties, build_feedback_intent, @@ -826,6 +826,7 @@ async def record_tool_call( if error is not None: event["is_error"] = True event["error"] = capture_exception(error) + event["error_status"] = http_status(error) props = await resolve_event_properties(data, request, extra) input_aliases = None diff --git a/posthog/mcp/_posthog_events.py b/posthog/mcp/_posthog_events.py index e20971aed..aeda2f86b 100644 --- a/posthog/mcp/_posthog_events.py +++ b/posthog/mcp/_posthog_events.py @@ -252,6 +252,8 @@ def _add_error_details(event: Event, properties: Dict[str, Any]) -> None: message = first.get("value") if message: properties[_P.ERROR_MESSAGE] = message + if event.get("error_status") is not None: + properties[_P.ERROR_STATUS] = event["error_status"] def _add_custom_properties(event: Event, properties: Dict[str, Any]) -> None: diff --git a/posthog/mcp/constants.py b/posthog/mcp/constants.py index 5fc725b35..0ad282e36 100644 --- a/posthog/mcp/constants.py +++ b/posthog/mcp/constants.py @@ -68,6 +68,7 @@ class PostHogMCPAnalyticsProperty: CONVERSATION_ID = "$mcp_conversation_id" DURATION_MS = "$mcp_duration_ms" ERROR_MESSAGE = "$mcp_error_message" + ERROR_STATUS = "$mcp_error_status" ERROR_TYPE = "$mcp_error_type" FEEDBACK_DETAILS = "$mcp_feedback_details" FEEDBACK_FRICTION_POINTS = "$mcp_feedback_friction_points" diff --git a/posthog/mcp/posthog_mcp.py b/posthog/mcp/posthog_mcp.py index 2e1c4d3e5..0f039620c 100644 --- a/posthog/mcp/posthog_mcp.py +++ b/posthog/mcp/posthog_mcp.py @@ -33,7 +33,7 @@ resolve_conversation_id, ) from ._event_types import MCPAnalyticsEventType -from ._exceptions import capture_exception +from ._exceptions import capture_exception, http_status from ._instrumentation import ( VIRTUAL_TOOL_FEEDBACK, VIRTUAL_TOOL_MISSING_CAPABILITY, @@ -242,6 +242,7 @@ def capture_tool_call( event["error"] = capture_exception( error if error is not None else f"Tool {tool_name} returned an error" ) + event["error_status"] = http_status(error) self._emit(event) def capture_initialize( diff --git a/posthog/mcp/types.py b/posthog/mcp/types.py index 04d1256c8..a44f23ab2 100644 --- a/posthog/mcp/types.py +++ b/posthog/mcp/types.py @@ -63,7 +63,7 @@ # plain dict (constructed and read with ``.get()`` throughout) to mirror the TS # plain-object pipeline. Snake_case keys map to the ``$mcp_*`` wire keys in # ``posthog_events``. Known keys: client_name, client_version, conversation_id, -# duration, error, error_type, event_name, event_type, groups, id, identify_actor_data, +# duration, error, error_status, error_type, event_name, event_type, groups, id, identify_actor_data, # identify_actor_given_id, is_error, listed_tool_names, parameters, properties, # resource_name, response, server_name, server_version, session_id, timestamp, # tool_category, tool_description, user_intent, user_intent_source, llm_model, diff --git a/posthog/test/mcp/test_error_status.py b/posthog/test/mcp/test_error_status.py new file mode 100644 index 000000000..98d0f44af --- /dev/null +++ b/posthog/test/mcp/test_error_status.py @@ -0,0 +1,145 @@ +"""``$mcp_error_status``: the HTTP status behind a failed call, read off the +raised exception's cause chain (posthog-python#1223, sdk-specs mcp-analytics +"Failure capture").""" + +from http import HTTPStatus +from types import SimpleNamespace + +import httpx +import pytest + +from posthog.mcp import PostHogMCP +from posthog.mcp.constants import PostHogMCPAnalyticsProperty as P +from posthog.test.mcp._helpers import events_named, flush_background + + +class Failure(Exception): + def __init__(self, message="failed", **attributes): + super().__init__(message) + for name, value in attributes.items(): + setattr(self, name, value) + + +def _http_status_error(status): + request = httpx.Request("GET", "https://api.example.com/invoices/1") + response = httpx.Response(status, request=request) + return httpx.HTTPStatusError( + f"{status} from upstream", request=request, response=response + ) + + +def _raised_from(outer, inner): + try: + try: + raise inner + except Exception as error: + raise outer from error + except Exception as error: + return error + + +def _raised_during(outer, inner): + try: + try: + raise inner + except Exception: + raise outer + except Exception as error: + return error + + +def _raised_from_none(outer, inner): + try: + try: + raise inner + except Exception: + raise outer from None + except Exception as error: + return error + + +def _cause_without_suppressed_context(): + error = _raised_during(RuntimeError("lookup failed"), Failure(status=500)) + error.__cause__ = Failure(status=404) + error.__suppress_context__ = False + return error + + +def _chain_of(length, status): + error = Failure("innermost", status=status) + for _ in range(length - 1): + error = _raised_from(Failure("wrapper"), error) + return error + + +class UnreadableResponse(Exception): + @property + def response(self): + raise RuntimeError("response not loaded") + + +def _cycle(): + first, second = Failure("first"), Failure("second") + first.__cause__, second.__cause__ = second, first + return first + + +@pytest.mark.parametrize( + "error, status", + [ + (_http_status_error(503), 503), + (_raised_from(RuntimeError("lookup failed"), _http_status_error(503)), 503), + (_raised_during(RuntimeError("lookup failed"), _http_status_error(429)), 429), + ( + _raised_from_none(RuntimeError("lookup failed"), _http_status_error(503)), + None, + ), + (_raised_from(Failure(status_code=404), _http_status_error(503)), 404), + (Failure(status_code=502), 502), + (Failure(statusCode=502), 502), + (Failure(status=502), 502), + (Failure(status_code=None, status=502), 502), + (Failure(response=SimpleNamespace(status=502)), 502), + (Failure(status="failed", response=SimpleNamespace(status_code=401)), 401), + (Failure(status=HTTPStatus.BAD_GATEWAY), 502), + (Failure(status_code=42), None), + (Failure(status_code=600), None), + (Failure(status_code=True), None), + (Failure(status_code="503"), None), + (Failure(status_code=503.0), None), + (Failure("no status here"), None), + (_cause_without_suppressed_context(), 404), + (_chain_of(50, 503), 503), + (_chain_of(51, 503), None), + (_cycle(), None), + (UnreadableResponse("failed"), None), + ("upstream returned 503", None), + ], +) +async def test_failed_call_carries_the_status_from_the_cause_chain(error, status): + client = PostHogMCP("phc_test") + captured = [] + client.capture = lambda event, **kw: captured.append({"event": event, **kw}) + + client.capture_tool_call("fetch_invoice", is_error=True, error=error) + await flush_background() + + [call] = events_named(captured, "$mcp_tool_call") + assert call["properties"].get(P.ERROR_STATUS) == status + + +async def test_explicit_status_wins_over_the_derived_one(): + client = PostHogMCP("phc_test") + captured = [] + client.capture = lambda event, **kw: captured.append({"event": event, **kw}) + + client.capture_tool_call( + "fetch_invoice", + is_error=True, + error=_http_status_error(503), + properties={P.ERROR_STATUS: 418}, + ) + await flush_background() + + [call] = events_named(captured, "$mcp_tool_call") + assert call["properties"][P.ERROR_STATUS] == 418 diff --git a/posthog/test/mcp/test_fastmcp_tool_errors.py b/posthog/test/mcp/test_fastmcp_tool_errors.py index c1f1100cd..23bb5ed74 100644 --- a/posthog/test/mcp/test_fastmcp_tool_errors.py +++ b/posthog/test/mcp/test_fastmcp_tool_errors.py @@ -7,6 +7,7 @@ import logging import weakref +import httpx import pytest pytest.importorskip("fastmcp") @@ -33,6 +34,14 @@ def _tool_error(): raise ToolError("bad input") +def _upstream_status(): + request = httpx.Request("GET", "https://api.example.com/invoices/1") + try: + httpx.Response(503, request=request).raise_for_status() + except httpx.HTTPStatusError as exc: + raise RuntimeError("invoice lookup failed") from exc + + def _tool_error_worded_like_fastmcp(): try: _upstream() @@ -41,7 +50,7 @@ def _tool_error_worded_like_fastmcp(): @pytest.mark.parametrize( - "raise_in_tool, mask_error_details, error_type, message, chain", + "raise_in_tool, mask_error_details, error_type, message, chain, status", [ ( _chained, @@ -49,6 +58,7 @@ def _tool_error_worded_like_fastmcp(): "RuntimeError", "lookup failed", ["RuntimeError", "ConnectionError"], + None, ), ( _chained, @@ -56,19 +66,29 @@ def _tool_error_worded_like_fastmcp(): "RuntimeError", "lookup failed", ["RuntimeError", "ConnectionError"], + None, ), - (_tool_error, False, "ToolError", "bad input", ["ToolError"]), + (_tool_error, False, "ToolError", "bad input", ["ToolError"], None), ( _tool_error_worded_like_fastmcp, False, "ToolError", "Error calling tool: lookup failed", ["ToolError", "ConnectionError"], + None, + ), + ( + _upstream_status, + True, + "RuntimeError", + "invoice lookup failed", + ["RuntimeError", "HTTPStatusError"], + 503, ), ], ) async def test_failed_call_carries_the_raised_exception( - raise_in_tool, mask_error_details, error_type, message, chain + raise_in_tool, mask_error_details, error_type, message, chain, status ): server = FastMCP("example-server", mask_error_details=mask_error_details) @@ -89,6 +109,7 @@ def fail() -> str: assert call["properties"]["$mcp_is_error"] is True assert call["properties"]["$mcp_error_type"] == error_type assert call["properties"]["$mcp_error_message"] == message + assert call["properties"].get("$mcp_error_status") == status [exception] = events_named(sink, "$exception") exception_list = exception["properties"]["$exception_list"] raised = [e for e in exception_list if e["type"] in chain] diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index 8eec881b9..0dc7fadbb 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -1058,6 +1058,7 @@ attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.CLIENT_VERSION = '$m attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.CONVERSATION_ID = '$mcp_conversation_id' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.DURATION_MS = '$mcp_duration_ms' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.ERROR_MESSAGE = '$mcp_error_message' +attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.ERROR_STATUS = '$mcp_error_status' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.ERROR_TYPE = '$mcp_error_type' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.FEEDBACK_DETAILS = '$mcp_feedback_details' attribute posthog.mcp.constants.PostHogMCPAnalyticsProperty.FEEDBACK_FRICTION_POINTS = '$mcp_feedback_friction_points' From 9e4935f7036f03905f6e0475d7d3ab3b4cc9dbff Mon Sep 17 00:00:00 2001 From: Lucas Faria <12522524+lucasheriques@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:30:58 -0300 Subject: [PATCH 12/33] fix(mcp): report the raised exception on mcp 1.x low-level isError results (#1231) * fix(mcp): report the raised exception on mcp 1.x low-level isError results On mcp 1.x the low-level @server.call_tool() decorator catches a tool's raise and returns CallToolResult(isError=True) before our handler sees it, so $mcp_tool_call had $mcp_error_type "Error", no frames and no $mcp_error_status (#1223). The decorator builds that result through server._make_error_result inside its except block, so an instance wrapper reads the live exception there and settles it into the same raised_tool_error slot standalone FastMCP uses. Validation failures also pass through that method inside an except block; only a message equal to str(exception) is the tool's own raise. mcp 2.x low-level needs no change: raw handlers raise through to our wrapper, and a scratch check showed RuntimeError, both frames and status 503. Tested: parameterized test in test_lowlevel.py (plain and wrapped 503, plain ValueError, input-validation guard). Red before on the three raising rows. Removing the message guard turns the validation row into ValidationError. pytest posthog/test/mcp: mcp 1.30 727 passed / 11 skipped; mcp 2.3 bare 551 passed / 55 skipped. CI-exact mypy: only the base branch's _exceptions.py:65. * chore(mcp): scope the low-level raise recovery note and changeset to what it covers Pre-PR review: the message guard admits any exception the decorator's catch-all sees (tool body, list_tools cache refresh, result construction), not only the tool's own raise, and _make_error_result first ships in mcp 1.10. Comment and changeset now say so. Tested: pytest posthog/test/mcp on mcp 1.30, 727 passed. * fix(mcp): tell validation results apart before rendering the exception Review on #1231 (PostHog Review, dustinbyrne): the message guard called str(error) on jsonschema ValidationErrors, which renders the whole instance and schema. On a deeply nested payload that raised RecursionError and replaced the SDK's validation response; on a large one it blocked the loop. A validation result is now matched by the prefix plus the error's own short .message first, and any failure while inspecting the exception leaves the original result untouched. A tool's own raise worded like a validation error is still recovered. Tested: parameterized test gains a 400-deep payload row (red before: response text 'maximum recursion depth exceeded') and a prefix-worded ValueError row. pytest posthog/test/mcp: mcp 1.30 730 passed / 11 skipped; mcp 2.3 bare 551 passed / 55 skipped. CI-exact mypy clean. --- .../changesets/mcp-lowlevel-raised-error.md | 5 + posthog/mcp/_instrument_lowlevel.py | 7 +- posthog/mcp/_raised_tool_error.py | 48 ++++++++- posthog/test/mcp/test_lowlevel.py | 102 +++++++++++++++--- 4 files changed, 140 insertions(+), 22 deletions(-) create mode 100644 .sampo/changesets/mcp-lowlevel-raised-error.md diff --git a/.sampo/changesets/mcp-lowlevel-raised-error.md b/.sampo/changesets/mcp-lowlevel-raised-error.md new file mode 100644 index 000000000..312638b87 --- /dev/null +++ b/.sampo/changesets/mcp-lowlevel-raised-error.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +`posthog.mcp`: on mcp 1.x (1.10 and later), a tool registered with the low-level `Server`'s `@server.call_tool()` decorator that raises now reports the exception it raised, with its cause chain, stack frames and `$mcp_error_status`, and `$mcp_error_type` names its class. Before, the decorator converted the exception into an error result first, so the failure was a generic `Error` with no frames and no status. diff --git a/posthog/mcp/_instrument_lowlevel.py b/posthog/mcp/_instrument_lowlevel.py index 8d6cf4393..ace769fd3 100644 --- a/posthog/mcp/_instrument_lowlevel.py +++ b/posthog/mcp/_instrument_lowlevel.py @@ -54,7 +54,7 @@ from ._model_parameters import request_meta_from_context from ._model_parameters import can_inject_model_parameter, is_capture_model_enabled from ._output_instructions import mirror_instructions_into_structured_content -from ._raised_tool_error import raised_tool_error +from ._raised_tool_error import raised_tool_error, wrap_error_result from .logger import log, warn from .tools import get_more_tools_result_text @@ -69,6 +69,7 @@ def instrument_low_level(server: Any, data: MCPAnalyticsData) -> None: """ data.server_name = getattr(server, "name", None) data.server_version = getattr(server, "version", None) + wrap_error_result(server) _wrap_call_tool(server, data, strip_injected=False) _wrap_list_tools(server, data, context_required=False) _wrap_resource_requests(server, data) @@ -283,7 +284,9 @@ async def handler(req: Any) -> Any: start = time.monotonic() try: - with raised_tool_error(high_level) as raised: + with raised_tool_error( + server if high_level is None else high_level + ) as raised: result = await original(req) except Exception as error: if await lifecycle.record_if_unknown_tool( diff --git a/posthog/mcp/_raised_tool_error.py b/posthog/mcp/_raised_tool_error.py index e694cf6fe..6cb375f54 100644 --- a/posthog/mcp/_raised_tool_error.py +++ b/posthog/mcp/_raised_tool_error.py @@ -1,13 +1,15 @@ -"""Recover the exception behind a standalone FastMCP ``isError`` tool result. +"""Recover the exception behind an ``isError`` tool result. -FastMCP's ``tools/call`` handler, the one we wrap, turns whatever its tool -dispatch raised into ``CallToolResult(isError=True)``, keeping only the -message text. Wrapping that dispatch on the server instance sees the exception -first, and hands it to the enclosing handler through a context variable. +Standalone FastMCP's ``tools/call`` handler, and the mcp 1.x low-level +``@server.call_tool()`` decorator, turn whatever the tool raised into +``CallToolResult(isError=True)``, keeping only the message text. A wrapper on +the server instance sees the exception first, and hands it to the enclosing +handler through a context variable. """ from __future__ import annotations +import sys from contextlib import contextmanager from contextvars import ContextVar from dataclasses import dataclass @@ -19,6 +21,10 @@ # `call_tool` and dispatches through `_call_tool_middleware`. _DISPATCH_METHODS = ("call_tool", "_call_tool_middleware") +# The prefixes the mcp 1.x `@server.call_tool()` decorator puts on jsonschema +# validation failures. +_VALIDATION_PREFIXES = ("Input validation error: ", "Output validation error: ") + @dataclass class RaisedToolError: @@ -60,6 +66,38 @@ async def dispatch(*args: Any, **kwargs: Any) -> Any: setattr(server, method, dispatch) +def wrap_error_result(server: Any) -> None: + original = getattr(server, "_make_error_result", None) + if original is None or getattr(original, _WRAPPED_FLAG, False): + return + + def make_error_result(error_message: str) -> Any: + error = sys.exc_info()[1] + if isinstance(error, Exception) and _carries_bare_text(error, error_message): + _settle(server, error) + return original(error_message) + + setattr(make_error_result, _WRAPPED_FLAG, True) + setattr(server, "_make_error_result", make_error_result) + + +def _carries_bare_text(error: Exception, error_message: str) -> bool: + # Input and output validation failures also land here from inside an + # except block, with the validator's short message behind a prefix. Only + # the catch-all around the tool call passes an exception's bare text. + # Rendering a validation error walks the whole instance and schema, so + # those results are told apart before `str(error)` runs. + try: + detail = getattr(error, "message", None) + if isinstance(detail, str) and any( + error_message == prefix + detail for prefix in _VALIDATION_PREFIXES + ): + return False + return error_message == str(error) + except Exception: + return False + + def _settle(server: Any, error: Optional[BaseException]) -> None: # Another server's dispatch, reached from inside a tool, must not write # its outcome onto this call, nor may a background task that outlives it. diff --git a/posthog/test/mcp/test_lowlevel.py b/posthog/test/mcp/test_lowlevel.py index 62dbd1ed0..8cbff6413 100644 --- a/posthog/test/mcp/test_lowlevel.py +++ b/posthog/test/mcp/test_lowlevel.py @@ -2,6 +2,7 @@ import json +import httpx import pytest import mcp.types as mcp_types @@ -17,7 +18,25 @@ ) -def make_server(*, resource_error: bool = False, listing: str = "resources") -> Server: +def _boom(): + raise ValueError("boom") + + +def _upstream_503(): + request = httpx.Request("GET", "https://api.example.com/invoices/1") + httpx.Response(503, request=request).raise_for_status() + + +def _wrapped_upstream_503(): + try: + _upstream_503() + except httpx.HTTPStatusError as exc: + raise RuntimeError("invoice lookup failed") from exc + + +def make_server( + *, resource_error: bool = False, listing: str = "resources", fail=_boom +) -> Server: server = Server("test-lowlevel") @server.list_tools() @@ -38,7 +57,7 @@ async def list_tools(): async def call_tool(name, arguments): if name == "echo": return [mcp_types.TextContent(type="text", text=str(arguments.get("msg")))] - raise ValueError("boom") + fail() async def list_resources(_request): if listing == "error": @@ -344,26 +363,79 @@ async def test_tool_call_success_captures_intent(): assert "context" not in props["$mcp_parameters"]["request"]["params"]["arguments"] -async def test_tool_call_error_captured_from_is_error_result(): - server = make_server() +def _worded_like_validation(): + raise ValueError("Input validation error: quota exceeded") + + +def _nested(depth): + value = 0 + for _ in range(depth): + value = [value] + return value + + +@pytest.mark.parametrize( + "fail, name, payload, error_type, chain, status, response", + [ + (_boom, "fail", None, "ValueError", ["ValueError"], None, "boom"), + ( + _upstream_503, + "fail", + None, + "HTTPStatusError", + ["HTTPStatusError"], + 503, + "Server error '503 Service Unavailable'", + ), + ( + _wrapped_upstream_503, + "fail", + None, + "RuntimeError", + ["RuntimeError", "HTTPStatusError"], + 503, + "invoice lookup failed", + ), + ( + _worded_like_validation, + "fail", + None, + "ValueError", + ["ValueError"], + None, + "Input validation error: quota exceeded", + ), + # Missing "msg" fails the SDK's input validation before the tool runs. + (_boom, "echo", None, "Error", [], None, "Input validation error"), + (_boom, "echo", _nested(400), "Error", [], None, "Input validation error"), + ], +) +async def test_raise_converted_to_is_error_result_carries_the_raised_exception( + fail, name, payload, error_type, chain, status, response +): + server = make_server(fail=fail) client = FakeClient() instrument(server, client) + await server.request_handlers[mcp_types.ListToolsRequest](None) - handler = server.request_handlers[mcp_types.CallToolRequest] - # "fail" is unlisted -> no validation -> handler raises -> isError result - result = await handler( - _call_request("fail", {"context": "trying a tool that errors"}) + result = await server.request_handlers[mcp_types.CallToolRequest]( + _call_request( + name, {"context": "trying a tool that errors", "payload": payload} + ) ) await _flush() assert result.root.isError is True - calls = _events(client, "$mcp_tool_call") - assert calls and calls[0]["properties"]["$mcp_is_error"] is True - exceptions = _events(client, "$exception") - assert ( - exceptions - and "boom" in exceptions[0]["properties"]["$exception_list"][0]["value"] - ) + assert result.root.content[0].text.startswith(response) + [call] = _events(client, "$mcp_tool_call") + assert call["properties"]["$mcp_is_error"] is True + assert call["properties"]["$mcp_error_type"] == error_type + assert call["properties"].get("$mcp_error_status") == status + [exception] = _events(client, "$exception") + exception_list = exception["properties"]["$exception_list"] + raised = [e for e in exception_list if e["type"] in chain] + assert [e["type"] for e in raised] == chain + assert all(e["stacktrace"]["frames"] for e in raised) async def test_initialize_emitted_once(): From 390f3dd932a4fe3b0a1ce016e1692a0b5a7f8fba Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:39:50 +0000 Subject: [PATCH 13/33] chore: Release v7.90.0 [skip ci] --- .sampo/changesets/fastmcp-tool-error-exception.md | 5 ----- .sampo/changesets/mcp-error-status.md | 5 ----- .sampo/changesets/mcp-lowlevel-raised-error.md | 5 ----- openfeature-provider/CHANGELOG.md | 6 ++++++ openfeature-provider/pyproject.toml | 2 +- posthog/CHANGELOG.md | 11 +++++++++++ posthog/version.py | 2 +- pyproject.toml | 2 +- uv.lock | 4 ++-- 9 files changed, 22 insertions(+), 20 deletions(-) delete mode 100644 .sampo/changesets/fastmcp-tool-error-exception.md delete mode 100644 .sampo/changesets/mcp-error-status.md delete mode 100644 .sampo/changesets/mcp-lowlevel-raised-error.md diff --git a/.sampo/changesets/fastmcp-tool-error-exception.md b/.sampo/changesets/fastmcp-tool-error-exception.md deleted file mode 100644 index ab1520bd5..000000000 --- a/.sampo/changesets/fastmcp-tool-error-exception.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: patch ---- - -`posthog.mcp`: a failed tool call on a standalone FastMCP server now reports the exception the tool raised, with its cause chain and stack frames, and `$mcp_error_type` names its class. Before, FastMCP converted the exception into an error result first, so the failure was a generic `Error` with no frames. diff --git a/.sampo/changesets/mcp-error-status.md b/.sampo/changesets/mcp-error-status.md deleted file mode 100644 index 9ad073dfc..000000000 --- a/.sampo/changesets/mcp-error-status.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: minor ---- - -`posthog.mcp`: a failed tool call now sets `$mcp_error_status` to the HTTP status behind it, read from the raised exception or its cause chain (`status_code`, `statusCode` or `status`, on the exception or its `response`, as `httpx.HTTPStatusError` and `requests.HTTPError` carry it). Failures from an upstream API now group by status in MCP Analytics instead of landing in "unknown". diff --git a/.sampo/changesets/mcp-lowlevel-raised-error.md b/.sampo/changesets/mcp-lowlevel-raised-error.md deleted file mode 100644 index 312638b87..000000000 --- a/.sampo/changesets/mcp-lowlevel-raised-error.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: patch ---- - -`posthog.mcp`: on mcp 1.x (1.10 and later), a tool registered with the low-level `Server`'s `@server.call_tool()` decorator that raises now reports the exception it raised, with its cause chain, stack frames and `$mcp_error_status`, and `$mcp_error_type` names its class. Before, the decorator converted the exception into an error result first, so the failure was a generic `Error` with no frames and no status. diff --git a/openfeature-provider/CHANGELOG.md b/openfeature-provider/CHANGELOG.md index 86c1202eb..2e02e2d1e 100644 --- a/openfeature-provider/CHANGELOG.md +++ b/openfeature-provider/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to `openfeature-provider-posthog` are documented here. This file is maintained by [Sampo](https://github.com/bruits/sampo) from changesets in `.sampo/changesets/` that target `pypi/openfeature-provider-posthog`. +## 0.1.162 — 2026-11-13 + +### Patch changes + +- Updated dependencies: posthog@7.90.0 + ## 0.1.161 — 2026-11-12 ### Patch changes diff --git a/openfeature-provider/pyproject.toml b/openfeature-provider/pyproject.toml index a29fe41b8..9ac9ea6c9 100644 --- a/openfeature-provider/pyproject.toml +++ b/openfeature-provider/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "openfeature-provider-posthog" -version = "0.1.161" +version = "0.1.162" description = "Official PostHog provider for the OpenFeature Python SDK." readme = "README.md" authors = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/posthog/CHANGELOG.md b/posthog/CHANGELOG.md index 720f182b1..34066322d 100644 --- a/posthog/CHANGELOG.md +++ b/posthog/CHANGELOG.md @@ -1,5 +1,16 @@ # posthog +## 7.90.0 — 2026-11-13 + +### Minor changes + +- [dd7577bc](https://github.com/posthog/posthog-python/commit/dd7577bccbe22cf4b2da970b1373d6f16bafeb20) `posthog.mcp`: a failed tool call now sets `$mcp_error_status` to the HTTP status behind it, read from the raised exception or its cause chain (`status_code`, `statusCode` or `status`, on the exception or its `response`, as `httpx.HTTPStatusError` and `requests.HTTPError` carry it). Failures from an upstream API now group by status in MCP Analytics instead of landing in "unknown". — Thanks @lucasheriques! + +### Patch changes + +- [9e4935f7](https://github.com/posthog/posthog-python/commit/9e4935f7036f03905f6e0475d7d3ab3b4cc9dbff) `posthog.mcp`: on mcp 1.x (1.10 and later), a tool registered with the low-level `Server`'s `@server.call_tool()` decorator that raises now reports the exception it raised, with its cause chain, stack frames and `$mcp_error_status`, and `$mcp_error_type` names its class. Before, the decorator converted the exception into an error result first, so the failure was a generic `Error` with no frames and no status. — Thanks @lucasheriques! +- [01398616](https://github.com/posthog/posthog-python/commit/013986168a131efed4a86d75a222e554f2f542d8) `posthog.mcp`: a failed tool call on a standalone FastMCP server now reports the exception the tool raised, with its cause chain and stack frames, and `$mcp_error_type` names its class. Before, FastMCP converted the exception into an error result first, so the failure was a generic `Error` with no frames. — Thanks @lucasheriques! + ## 7.89.0 — 2026-11-12 ### Minor changes diff --git a/posthog/version.py b/posthog/version.py index ea63ebc5f..1598a9920 100644 --- a/posthog/version.py +++ b/posthog/version.py @@ -1 +1 @@ -VERSION = "7.89.0" +VERSION = "7.90.0" diff --git a/pyproject.toml b/pyproject.toml index 692afae43..502f85d9e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "posthog" -version = "7.89.0" +version = "7.90.0" description = "Integrate PostHog into any python application." authors = [{ name = "PostHog", email = "engineering@posthog.com" }] maintainers = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/uv.lock b/uv.lock index a9c2dd8b3..d0aea5795 100644 --- a/uv.lock +++ b/uv.lock @@ -2723,7 +2723,7 @@ wheels = [ [[package]] name = "openfeature-provider-posthog" -version = "0.1.161" +version = "0.1.162" source = { editable = "openfeature-provider" } dependencies = [ { name = "openfeature-sdk" }, @@ -3280,7 +3280,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.89.0" +version = "7.90.0" source = { editable = "." } dependencies = [ { name = "backoff" }, From cd821fbe07f4ee8db9509ecb2bd54f128cdf31c6 Mon Sep 17 00:00:00 2001 From: Michael Reichenbach <755327+Silthus@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:04:19 +0100 Subject: [PATCH 14/33] feat: send cc, bcc and attachments with emails.send (#1172) * feat: send email content from code with posthog.emails.send Squash of Silthus/posthog-python#2 at e5fdedf, re-signed for required signatures. Co-Authored-By: Claude Opus 5.5 * feat: cut emails.send to the template and rendered code forms Parks the local-template form (template_data on a code send, the content hash, the upload by key and its retry) and the cc, bcc, headers, tags and attachments fields, to match posthog-node. A code send now takes rendered html and/or text only. Co-Authored-By: Claude Opus 5.5 * test(emails): cover the async code-form send and migrated_from Co-Authored-By: Claude Opus 5.5 * feat: send cc, bcc and attachments with emails.send A code send takes cc and bcc as one address or a list, and attachments as files with bytes or Base64 content. The client encodes bytes once, before any retry. A file it can't send raises EmailError with the code invalid_attachment and a field such as attachments__0__content, and the error never repeats the file's content. A template_id send refuses all three fields before any request. Co-Authored-By: Claude Opus 5.5 * fix: refuse every unknown attachment key, a None key included next(..., None) used None as its no-match value, so a None key hid the unknown keys after it. Co-Authored-By: Claude Opus 5.5 * test: cover a None attachment key before an unknown one Co-Authored-By: Claude Opus 5.5 * docs: describe an older server's refusal without its error code Co-Authored-By: Claude Opus 5.5 * fix(emails): leave reply_to out when the list is empty Co-Authored-By: Claude Opus 5.5 * fix(emails): refuse an attachment string that is not base64 A text file passed as a str was sent unchecked as if it were Base64. The client now raises invalid_attachment before any request and hints to pass the file's bytes instead. Co-Authored-By: Claude Opus 5.5 * chore(emails): name the refused-send test after what it guards Co-Authored-By: Claude Opus 5.5 * chore(emails): drop a comment the name and test already state Co-Authored-By: Claude Opus 5.5 * chore(emails): give cc, bcc and attachments their own changeset The base PR owns emails-code-form.md, so this PR no longer edits it. Co-Authored-By: Claude Opus 5.5 * fix(emails): refuse an attachment with an empty filename Co-Authored-By: Claude Opus 5.5 * feat(emails): upload attachments by hash, then send their references A code send hashes each file, asks PostHog which files it lacks, PUTs those straight to PostHog's file storage with the returned headers and without the secret key, then sends the email naming each file by its SHA-256. The client checks 10 files and the 40 MB message estimate before any request. A failed upload sends no email and surfaces the storage's answer. Part of PostHog/michaelr-context#81. Co-Authored-By: Claude Opus 5.5 * fix(emails): send the storage upload exactly as signed An injected client's defaults leaked into the presigned PUT: httpx params replaced the URL's signature query, a requests session appended its params, and default headers rode along. The upload is now a standalone request with only the returned URL and headers, sent through the same transport and retries. Part of PostHog/michaelr-context#81. Co-Authored-By: Claude Opus 5.5 * fix(emails): keep the environment's TLS settings and the signed URL private on uploads The standalone storage PUT skipped requests' environment merge, so a custom CA bundle or proxy applied to sends but not to uploads. It now merges the environment's transport settings, without session headers or auth. A storage network error is re-raised without its cause, so the presigned URL never reaches a traceback. Part of PostHog/michaelr-context#81. Co-Authored-By: Claude Opus 5.5 * fix(emails): upload shared bytes once and retry a storage's passing faults - The client counts attachments before it reads any file. - Bytes that two attachments share go in the upload request once. - The upload parser returns only the uploads still to make, each with its attachment index. - A storage 500, 502 or 504 is retried like 503. - A refused upload no longer takes the names of PostHog's API statuses. - An unreachable storage raises network_error naming the attachment. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): retry a storage's 429 and name what the comments said The previous commit stopped retrying a storage 429, which the general rate-limit branch had retried. Storage 429 is retried again and named rate_limit_exceeded. Names replace the comments that commit added. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): name attachments when PostHog has no upload route A PostHog version without the upload route answered 404, and the send raised a bare not_found with no field. The docs promise that an older PostHog's refusal names the field. It now raises not_found with field attachments, a reason and a fix, and sends nothing. Tests now cover the names a storage fault gets once its retries run out. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): size attachments before copying them The client copied and hashed every file before it checked the message size. Ten views of one large buffer could exhaust memory before message_too_large. Each file is now sized from its buffer or its Base64 length, the estimate is checked, and only then are files read and hashed. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): size Base64 content by its data, not its padding Extra trailing padding decodes, so it must not shrink the estimate. Ticket: PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): pin each body's count in the size estimate The server counts html and text each like a file: UTF-8 bytes, Base64 with line breaks. Pin both bodies, their UTF-8 length and per-body rounding. Ticket: PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): report PostHog's own answer to an upload-route 404 A 404 can mean a PostHog without the upload route or sending from code off for the project, so keep the server's reason on attachments instead of naming one cause. Ticket: PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): say which Base64 the SDK takes and where a refused upload goes wrong A wrapped, unpadded or URL-safe string now learns it needs one padded line from base64.b64encode. A storage refusal points at a fresh send or a proxy, not at bytes the caller can't change. Ticket: PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): count the subject in the message estimate like the server The server now adds 75 bytes per 42 UTF-8 bytes of subject, so a long subject beside a near-limit file must be refused before the upload. Ticket: PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): check uploads against their signed checksum like real storage The fake storage now refuses a PUT whose bytes don't match the signed checksum and length, and each upload slot is signed for its own file. A new test asserts every file PostHog lacks lands in storage under its own hash. Refs PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): size padded Base64 without a copy and never follow a storage redirect Sizing a Base64 string no longer strips its padding into a new string, so refusing an oversized file allocates nothing the size of the file. The async upload passes follow_redirects=False, so an injected client that follows redirects can't turn a storage 302 into a GET that looks like a stored file. The subject's share of the size limit is now pinned through send instead of through a private helper. Refs PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): prove the async upload refuses a storage redirect over real sockets The redirect test now runs against a local HTTP server that answers the upload route, redirects the PUT and serves a login page, instead of a scripted transport. It asserts upload_failed and that the login page and the send route were never reached. Refs PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): test attachments against fakes that behave like PostHog and S3 The attachment tests now run against one in-memory PostHog with its file storage. The upload and send routes need the secret key and refuse fields outside their schema. Storage refuses a presigned PUT the way S3 does: an added query parameter, an Authorization header, an expired URL or bytes that don't match the signed checksum. A send delivers an email with the stored bytes and replays a repeated idempotency key. Tests assert the delivered email, the bucket and the EmailError, not request shapes. The CA test runs a real TLS handshake against a local storage server with a certificate made in the test. Refs PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): count the text PostHog derives and upload only over https Without text, PostHog derives the plain text from the HTML and counts it in the message size, so an HTML-only email near the limit uploaded its files and was then refused. The client now counts the HTML twice, since the derived text is never longer. A plain HTTP upload URL from misconfigured storage would carry the file and its signed URL unencrypted. The client now stops before any upload with api_error naming the attachment, unless the client's host is plain HTTP too, as in local development. The fake PostHog now checks each route's method and records the content type storage keeps. Tests assert stored files, not storage keys, and the tests that only exercised the fake are gone. Refs PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): name the caller's attachment in upload refusals and read storage answers whole An upload-route refusal named the wire field (files, files__1__size), which the caller never passed. It now names attachments, or the first attachment holding that file. A session with stream=True left a storage answer unread until after the upload, so a cut-off answer lost its attachment; the storage request now always reads the answer at once. The cc and bcc tests now assert the recipients of the delivered email, and the template-content tests are back to main's shape. Refs PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): serve the test's TLS storage at TLS 1.2 or later CodeQL flags the local HTTPS storage server's SSLContext for allowing TLS 1.0 and 1.1. Pin the minimum version. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): assert outcomes, not request traces, in the real-socket upload tests The redirect and cut-short storage tests compared the server's request list, which held the storage object path. They now assert the caller's error, that no email was sent, and that the redirect was never followed. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): run the field refusal and size tests against the PostHog fake The cc refusal test now sends to a PostHog that doesn't take cc and asserts the caller's error and that nothing was delivered, instead of counting requests on a canned transport. The two oversized-email tests assert that nothing was stored or delivered. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): prove an upload never follows storage to another server A client that follows a 307 or 308 on the PUT sends the file again to the new URL, even over plain HTTP, and reports success. Both upload paths already refuse redirects. New sync and async tests have the storage answer 307 to a plain-HTTP server and assert upload_failed on the attachment without either URL, that the other server received nothing, and that no email was sent. Without the fix, requests and an httpx client with follow_redirects deliver the file there. The docs and changeset say the client never follows a redirect. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): name the lost-reply retry test for what it proves The test shows a send retried after a lost reply replays with its idempotency key. It can't observe whether uploads are asked for again, so the name no longer promises that. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * fix(emails): refuse extra Base64 padding before copying the string The size check walked back over any number of trailing "=", so a short Base64 string followed by tens of millions of "=" passed as a few bytes, and b64decode then copied and scanned all of it, blocking the async client's event loop. Standard Base64 has at most two "=", so a third now raises invalid_attachment with the Base64 advice during that walk, before any copy. The extra-padding size case is refused this way now. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * feat(emails): name a failed attachment upload attachment_upload_failed Go, JS, Ruby and PHP raise attachment_upload_failed for a refused or redirected upload, and the docs list one code for every SDK. The code was upload_failed only in this unreleased change, so it takes the shared name in the error, the tests, the docstrings and the changeset. PostHog/michaelr-context#81 Co-Authored-By: Claude Opus 5.5 * test(emails): follow a storage 307 to another server over real sockets The two cross-server redirect tests now run against a local PostHog whose storage answers the upload with a 307 to a second local server. They assert the second server receives nothing and no email is sent, instead of injecting the redirect through mocked transports. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .github/scripts/check_strict_types.sh | 7 +- .sampo/changesets/emails-code-attachments.md | 5 + posthog/emails.py | 658 ++++++- posthog/test/test_emails.py | 1789 +++++++++++++++++- references/public_api_snapshot.txt | 8 + typings/requests/__init__.pyi | 28 + 6 files changed, 2429 insertions(+), 66 deletions(-) create mode 100644 .sampo/changesets/emails-code-attachments.md diff --git a/.github/scripts/check_strict_types.sh b/.github/scripts/check_strict_types.sh index 4855a9ec9..d1647516b 100755 --- a/.github/scripts/check_strict_types.sh +++ b/.github/scripts/check_strict_types.sh @@ -46,10 +46,11 @@ _ = (flag_value, all_flags, enabled, payload, evaluations, active) emails = Emails("phs_example") template_send: SendEmailResult = emails.send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", template_data={"name": "Ada"}) rendered_send: SendEmailResult = emails.send(to="user@example.com", template_key="password-reset", subject="Reset", html="

Reset

", from_="Acme ", reply_to=["help@example.com"], capture_engagement=False, max_retries=0) +invite_send: SendEmailResult = emails.send(to="user@example.com", template_key="invite", subject="Invite", html="

Invite

", cc="team@example.com", bcc=["audit@example.com"], attachments=[{"filename": "invite.ics", "content": b"BEGIN:VCALENDAR", "content_type": "text/calendar"}, {"filename": "logo.png", "content": "iVBORw0KGgo=", "content_id": "logo"}]) tracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="

Hi

", tracking={"clicks": True, "engagement": False}) untracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="

Hi

", tracking=False) not_sensitive_send: SendEmailResult = emails.send(to="user@example.com", template_key="newsletter", subject="News", html="

News

", sensitive=False) -_ = (template_send, rendered_send, tracked_send, untracked_send) +_ = (template_send, rendered_send, invite_send, tracked_send, untracked_send, not_sensitive_send) async def async_email_types() -> None: @@ -113,7 +114,9 @@ Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3 Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", sensitive=False) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", tracking={"open": False}) # expected-type-error Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", template_data={"name": "Ada"}) # expected-type-error -Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", cc="team@example.com") # expected-type-error +Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", attachments=[{"filename": "a.txt", "content": [104, 105]}]) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="

Hi

", attachments=[{"filename": "a.txt", "content": b"hi", "path": "/tmp/a.txt"}]) # expected-type-error +Emails("phs_example").send(to="user@example.com", template_id="0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b", attachments=[{"filename": "a.txt", "content": b"hi"}]) # expected-type-error async def invalid_async_email() -> None: diff --git a/.sampo/changesets/emails-code-attachments.md b/.sampo/changesets/emails-code-attachments.md new file mode 100644 index 000000000..48bc79ed0 --- /dev/null +++ b/.sampo/changesets/emails-code-attachments.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: minor +--- + +A code send with `posthog.emails.send` takes `cc`, `bcc` and `attachments`: at most 10 files and 40 MB per message after Base64 encoding, about 29 MB of files, with the HTML counted twice when there is no `text`, since PostHog derives the text from it. An attachment is a `filename` and its `content`, as bytes or a Base64 string, with an optional `content_type` and `content_id`. The client checks the limits before any request, uploads each file PostHog doesn't hold yet straight to PostHog's file storage over https, never following a redirect, then sends the email with each file's SHA-256. A refused or redirected upload raises `EmailError` with the code `attachment_upload_failed`, and an unreachable storage `network_error` with `field` naming the attachment. Either way no email is sent. diff --git a/posthog/emails.py b/posthog/emails.py index 2839a2dd6..141255b17 100644 --- a/posthog/emails.py +++ b/posthog/emails.py @@ -59,6 +59,19 @@ ``"resend"``, on the client or on :class:`Emails`, so PostHog knows where your sends came from. +Attachments: a code send takes ``attachments``, at most 10 files and 40 MB per +message after Base64 encoding, about 29 MB of files. Without ``text``, the +HTML counts twice, since PostHog derives the text from it. The client checks +both before any request. It then asks PostHog which files it lacks, uploads +each of those to the https URL PostHog answers, without the secret key, and +sends the email naming each file by its SHA-256. A file the project already +sent uploads nothing, and the same bytes in two attachments upload once. An +upload retries like a send when the storage is unreachable or answers a +passing fault. A failed upload sends no email. A plain HTTP upload URL is +refused before any upload unless the client's host is plain HTTP too, as in +local development. The upload URL's host is not the app host, so a network +that limits outbound requests must allow it. + Errors: a send that is not queued raises :class:`EmailError`. Branch on ``code``. The ones a setup usually hits: @@ -71,6 +84,27 @@ - ``client_disabled``: the client is disabled, so it sends nothing. - ``client_closed``: the client is shut down. +A send with attachments can also raise: + +- ``too_many_attachments`` or ``message_too_large``: the email is over the + limits above. The client raises these before any request. +- ``invalid_attachment``: the client can't send a file, such as one without + content. +- ``attachment_upload_failed``: PostHog's file storage refused an upload or + answered with a redirect, which the client never follows. ``message`` and + ``why`` carry its answer, and ``field`` names the attachment. +- ``network_error`` with ``field`` naming an attachment: the file storage + didn't answer, such as when a firewall blocks its host. +- ``api_error`` with ``field`` naming an attachment: PostHog named an upload + URL that isn't https. Fix the file storage's URL. Nothing was uploaded. +- ``upload_quota_exceeded`` (429): the project uploaded its daily limit of + file bytes. Files it already sent don't count. +- ``field_not_accepted`` with ``field`` ``attachments``: the project can't send + files yet. +- ``not_found`` (404) with ``field`` ``attachments``: this PostHog version + doesn't take files yet, or sending email from code is off for the project. + ``message`` carries PostHog's answer, and no email was sent. + Status: ``emails.get(message_id)`` reads what happened to a sent email, for 30 days after the send, as an :class:`EmailStatus`. A key with only ``transactional_email:read`` can read statuses but not send. ``get`` raises @@ -89,6 +123,9 @@ from __future__ import annotations import asyncio +import base64 +import binascii +import hashlib import importlib import json import logging @@ -102,6 +139,7 @@ from types import TracebackType from typing import ( Any, + Awaitable, Callable, Mapping, Optional, @@ -129,6 +167,7 @@ __all__ = [ "AsyncEmails", "CodeEmailArgs", + "EmailAttachment", "EmailError", "EmailStatus", "EmailTracking", @@ -141,6 +180,7 @@ log = logging.getLogger("posthog") _SEND_PATH = "/api/projects/@current/messaging/send/email/" +_UPLOADS_PATH = "/api/projects/@current/messaging/attachments/uploads/" _STATUS_PATH = "/api/projects/@current/messaging/emails/{message_id}/" _TEMPLATE_KEY = re.compile(r"[a-zA-Z0-9_-]{1,400}") _MAX_RETRY_DELAY = 30.0 @@ -148,6 +188,15 @@ _HEADER_TOKEN = re.compile(r"[\x21-\x7e]+") _IN_FLIGHT_CODES = frozenset({"idempotency_key_in_flight"}) _QUOTA_CODES = frozenset({"quota_limited"}) +_DAILY_QUOTA_CODES = frozenset({"upload_quota_exceeded"}) +_MAX_ATTACHMENTS = 10 +_STORAGE_RETRY_STATUSES = frozenset({429, 500, 502, 503, 504}) +_MAX_MESSAGE_BYTES = 40_000_000 +_HEADERS_AND_MIME_BOUNDARIES_BYTES = 64 * 1024 +_SUBJECT_BYTES_PER_ENCODED_WORD = 42 +_ENCODED_WORD_BYTES = 75 +_MESSAGE_LIMIT = "40 MB after Base64 encoding, about 29 MB of files" +_STORAGE_ERROR = re.compile(r"<(Code|Message)>([^<]{1,500})") class EmailError(Exception): @@ -217,6 +266,26 @@ class SendEmailResult: warnings: tuple[EmailWarning, ...] = () +class EmailAttachment(TypedDict): + """A file sent with the email. + + Args: + filename: The file name the recipient sees, such as ``invite.ics``. + content: The file as ``bytes``, ``bytearray`` or ``memoryview``, or + Base64 encoded as a string on one line with its padding, as + ``base64.b64encode`` gives. PostHog can't fetch a file from a path + or URL. + content_type: The MIME type. Without it, the type follows the file name. + content_id: Shows the file inline: reference it in ``html`` as + ```` with ``content_id`` ``logo``. + """ + + filename: str + content: Union[bytes, bytearray, memoryview, str] + content_type: NotRequired[str] + content_id: NotRequired[str] + + class _RecipientArgs(TypedDict): to: str distinct_id: NotRequired[Optional[str]] @@ -272,6 +341,10 @@ class CodeEmailArgs(_RecipientArgs): An optional field passed as ``None`` counts as left out. + A PostHog version that doesn't take a field yet, such as ``cc``, refuses + the send with an error that names the field in ``EmailError.field``. It + never drops the field and sends the rest. + Args: to: One recipient email address. template_key: Names the email, so its metrics, logs and status group @@ -283,6 +356,16 @@ class CodeEmailArgs(_RecipientArgs): without a plain-text part. from_: A verified sender, such as ``"Acme "``. reply_to: One address or a list of addresses. An empty list sends no reply-to. + cc: One address or a list of addresses that get a visible copy, at + most 10. + bcc: One address or a list of addresses that get a hidden copy, at + most 10. + attachments: Files sent with the email: at most 10 files and 40 MB + per message after Base64 encoding, about 29 MB of files. The + client checks both before any request. It uploads each file that + PostHog doesn't hold yet, then sends the email. A file the client + can't send raises :class:`EmailError` with ``code`` + ``invalid_attachment``. capture_engagement: Deprecated, use ``tracking={"engagement": False}``. It keeps working, but PostHog refuses a send that sets both ``capture_engagement`` and ``tracking``. Captures the email's @@ -324,17 +407,24 @@ class CodeEmailArgs(_RecipientArgs): text: NotRequired[Optional[str]] from_: NotRequired[Optional[str]] reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] + cc: NotRequired[Optional[Union[str, Sequence[str]]]] + bcc: NotRequired[Optional[Union[str, Sequence[str]]]] + attachments: NotRequired[Optional[Sequence[EmailAttachment]]] capture_engagement: NotRequired[Optional[bool]] sensitive: NotRequired[Optional[bool]] tracking: NotRequired[Optional[Union[bool, EmailTracking]]] +_ATTACHMENT_FIELDS = frozenset(EmailAttachment.__annotations__) _OPTIONAL_CODE_FIELDS = frozenset( { "html", "text", "from_", "reply_to", + "cc", + "bcc", + "attachments", "capture_engagement", "sensitive", "tracking", @@ -375,12 +465,32 @@ class EmailStatus: reason: Optional[str] = None +@dataclass(frozen=True) +class _File: + sha256: str + content: bytes + first_attachment_index: int + + @property + def size(self) -> int: + return len(self.content) + + +@dataclass(frozen=True) +class _Upload: + file: _File + url: str + method: str + headers: dict[str, str] + + @dataclass(frozen=True) class _PreparedSend: path: str body: bytes idempotency_key: str max_retries: Optional[int] = None + files: tuple[_File, ...] = () def _prepare(args: Mapping[str, Any]) -> _PreparedSend: @@ -434,15 +544,20 @@ def _prepare_code_send(args: Mapping[str, Any]) -> _PreparedSend: if not (content.get("html") or content.get("text")): raise ValueError("html or text must be a nonempty string.") + references, files = _attachments(args.get("attachments", []), content) + payload: dict[str, Any] = {"to": to, "template_key": template_key, **content} if distinct_id is not None: payload["distinct_id"] = distinct_id payload.update(_sender(args)) + if references: + payload["attachments"] = references return _PreparedSend( path=_SEND_PATH, body=_encode(payload), idempotency_key=idempotency_key, max_retries=max_retries, + files=_each_file_once(files), ) @@ -450,9 +565,10 @@ def _sender(args: Mapping[str, Any]) -> dict[str, Any]: sender: dict[str, Any] = {} if "from_" in args: sender["from"] = _nonempty_text(args, "from_") - reply_to = _addresses("reply_to", args["reply_to"]) if "reply_to" in args else [] - if reply_to: - sender["reply_to"] = reply_to + for field in ("reply_to", "cc", "bcc"): + addresses = _addresses(field, args[field]) if field in args else [] + if addresses: + sender[field] = addresses for flag in ("capture_engagement", "sensitive"): if flag in args: if not isinstance(args[flag], bool): @@ -484,6 +600,189 @@ def _addresses(field: str, value: Any) -> list[str]: return list(addresses) +def _each_file_once(files: Sequence[_File]) -> tuple[_File, ...]: + by_hash: dict[str, _File] = {} + for file in files: + by_hash.setdefault(file.sha256, file) + return tuple(by_hash.values()) + + +def _invalid_attachment(message: str, field: str) -> EmailError: + return EmailError( + name="validation_error", + code="invalid_attachment", + message=message, + field=field, + ) + + +def _attachments( + attachments: Any, content: Mapping[str, str] +) -> tuple[list[dict[str, str]], tuple[_File, ...]]: + if isinstance( + attachments, (str, bytes, bytearray, memoryview, Mapping) + ) or not isinstance(attachments, Sequence): + raise _invalid_attachment("attachments must be a list of files.", "attachments") + if len(attachments) > _MAX_ATTACHMENTS: + raise _over_the_limit( + "too_many_attachments", + f"An email carries at most {_MAX_ATTACHMENTS} files, so no email was sent.", + fix=f"Send at most {_MAX_ATTACHMENTS} files, and link to any others " + "from the email body.", + ) + checked = [ + _checked_attachment(index, file) for index, file in enumerate(attachments) + ] + _check_message_size( + [ + _content_size(f"attachments__{index}", file.get("content")) + for index, file in enumerate(checked) + ], + content, + ) + prepared = [_attachment(index, file) for index, file in enumerate(checked)] + return [reference for reference, _ in prepared], tuple(file for _, file in prepared) + + +def _checked_attachment(index: int, file: Any) -> Mapping[str, Any]: + field = f"attachments__{index}" + if not isinstance(file, Mapping): + raise _invalid_attachment( + "An attachment is a mapping with filename and content. " + "Pass the file's bytes as its content.", + field, + ) + if "path" in file: + raise _invalid_attachment( + "PostHog can't fetch an attachment from a path or URL. " + "Read the file and pass its bytes as content instead.", + f"{field}__path", + ) + unknown = [name for name in file if name not in _ATTACHMENT_FIELDS] + if unknown: + raise _invalid_attachment( + "An attachment takes filename, content, content_type and content_id, " + f"not {unknown[0]}.", + f"{field}__{unknown[0]}", + ) + if not isinstance(file.get("filename"), str) or not file["filename"]: + raise _invalid_attachment( + "An attachment needs a filename, such as 'invoice.pdf'.", + f"{field}__filename", + ) + for name in ("content_type", "content_id"): + if name in file and not isinstance(file[name], str): + raise _invalid_attachment( + f"An attachment's {name} must be a string.", f"{field}__{name}" + ) + return file + + +def _content_size(field: str, content: Any) -> int: + if isinstance(content, (bytes, bytearray, memoryview)): + size = memoryview(content).nbytes + elif isinstance(content, str): + data_end = len(content) + while data_end and content[data_end - 1] == "=": + data_end -= 1 + if len(content) - data_end > 2: + raise _not_standard_base64(field) + size = data_end * 3 // 4 + else: + raise _invalid_attachment( + "An attachment needs content: bytes or a Base64 string. " + "Convert a list of byte values with bytes(content).", + f"{field}__content", + ) + if not size: + raise _invalid_attachment( + "An attachment's content is empty, and an empty file gives the " + "recipient nothing to open. Leave the file out.", + f"{field}__content", + ) + return size + + +def _attachment(index: int, file: Mapping[str, Any]) -> tuple[dict[str, str], _File]: + content = _file_bytes(f"attachments__{index}", file["content"]) + sha256 = hashlib.sha256(content).hexdigest() + reference = {"sha256": sha256, "filename": file["filename"]} + for name in ("content_type", "content_id"): + if name in file: + reference[name] = file[name] + return reference, _File( + sha256=sha256, content=content, first_attachment_index=index + ) + + +def _file_bytes(field: str, content: Union[bytes, bytearray, memoryview, str]) -> bytes: + if not isinstance(content, str): + return bytes(content) + try: + return base64.b64decode(content, validate=True) + except (binascii.Error, ValueError): + raise _not_standard_base64(field) from None + + +def _not_standard_base64(field: str) -> EmailError: + return _invalid_attachment( + "An attachment's content string must be standard Base64 on one line " + "with its padding, as base64.b64encode gives. Pass the file's bytes " + "instead, such as text.encode() for text.", + f"{field}__content", + ) + + +def _check_message_size(file_sizes: Sequence[int], content: Mapping[str, str]) -> None: + if ( + file_sizes + and _estimated_message_bytes(file_sizes, content) > _MAX_MESSAGE_BYTES + ): + raise _over_the_limit( + "message_too_large", + f"These files make the email larger than {_MESSAGE_LIMIT}, so no email was sent.", + fix="Send fewer or smaller files, or link to large files from the email body.", + ) + + +def _over_the_limit(code: str, message: str, *, fix: str) -> EmailError: + return EmailError( + name="validation_error", + code=code, + message=message, + why=f"An email carries at most {_MAX_ATTACHMENTS} files and {_MESSAGE_LIMIT}.", + fix=fix, + field="attachments", + ) + + +def _estimated_message_bytes( + file_sizes: Sequence[int], content: Mapping[str, str] +) -> int: + html, text = content.get("html") or "", content.get("text") or "" + body_sizes = [len(body.encode("utf-8")) for body in (html, text or html) if body] + return ( + _HEADERS_AND_MIME_BOUNDARIES_BYTES + + sum(_base64_transfer_bytes(size) for size in [*file_sizes, *body_sizes]) + + _encoded_subject_bytes(content["subject"]) + ) + + +def _encoded_subject_bytes(subject: str) -> int: + return ( + _ceil_div(len(subject.encode("utf-8")), _SUBJECT_BYTES_PER_ENCODED_WORD) + * _ENCODED_WORD_BYTES + ) + + +def _base64_transfer_bytes(size: int) -> int: + return _ceil_div(_ceil_div(size, 3) * 4 * 78, 76) + + +def _ceil_div(dividend: int, divisor: int) -> int: + return -(-dividend // divisor) + + def _string(args: Mapping[str, Any], name: str) -> str: value = args[name] if not isinstance(value, str): @@ -633,6 +932,8 @@ def _error_name(status: Optional[int], code: str) -> str: else "validation_error" ) if status == 429: + if code in _DAILY_QUOTA_CODES: + return "daily_quota_exceeded" return ( "monthly_quota_exceeded" if code in _QUOTA_CODES else "rate_limit_exceeded" ) @@ -654,10 +955,18 @@ def _retry_after(header: Optional[str]) -> Optional[float]: return max(0.0, seconds) +def _json_object(body: bytes) -> dict[str, Any]: + try: + payload = json.loads(body) + except ValueError: + return {} + return payload if isinstance(payload, dict) else {} + + def _parse_response( - status: int, payload: Any, retry_after_header: Optional[str] + status: int, body: bytes, retry_after_header: Optional[str] ) -> SendEmailResult: - fields = payload if isinstance(payload, dict) else {} + fields = _json_object(body) if 200 <= status < 300: message_id = _text(fields.get("message_id")) if message_id is None: @@ -697,9 +1006,9 @@ def _timestamp(value: Any) -> Optional[datetime]: def _parse_status_response( - status: int, payload: Any, retry_after_header: Optional[str] + status: int, body: bytes, retry_after_header: Optional[str] ) -> EmailStatus: - fields = payload if isinstance(payload, dict) else {} + fields = _json_object(body) if not 200 <= status < 300: raise _response_error(fields, status, retry_after_header) message_id = _text(fields.get("id")) @@ -724,6 +1033,135 @@ def _parse_status_response( ) +def _pending_uploads_parser( + files: Sequence[_File], plain_http_allowed: bool +) -> _Parse[list[_Upload]]: + def parse( + status: int, body: bytes, retry_after_header: Optional[str] + ) -> list[_Upload]: + fields = _json_object(body) + if status == 404: + raise _upload_route_not_found(fields, retry_after_header) + if not 200 <= status < 300: + attr = _attachments_field(fields.get("attr"), files) + raise _response_error({**fields, "attr": attr}, status, retry_after_header) + slots = fields.get("files") + if not isinstance(slots, list) or len(slots) != len(files): + raise _no_upload_slots(status) + pending = ( + _pending_upload(slot, file, status) for slot, file in zip(slots, files) + ) + uploads = [upload for upload in pending if upload is not None] + for upload in uploads: + if not plain_http_allowed and not upload.url.lower().startswith("https://"): + raise _upload_url_not_https(upload.file.first_attachment_index, status) + return uploads + + return parse + + +def _attachments_field(attr: Any, files: Sequence[_File]) -> Any: + if not isinstance(attr, str) or not attr.startswith("files"): + return attr + index = attr.split("__")[1] if attr.startswith("files__") else "" + if index.isdigit() and int(index) < len(files): + return f"attachments__{files[int(index)].first_attachment_index}" + return "attachments" + + +def _pending_upload(slot: Any, file: _File, status: int) -> Optional[_Upload]: + if not isinstance(slot, dict) or slot.get("sha256") != file.sha256: + raise _no_upload_slots(status) + if slot.get("status") == "present": + return None + url, method, headers = ( + _text(slot.get("url")), + _text(slot.get("method", "PUT")), + slot.get("headers"), + ) + if ( + slot.get("status") != "upload" + or url is None + or method is None + or not isinstance(headers, dict) + or not all(isinstance(value, str) for value in headers.values()) + ): + raise _no_upload_slots(status) + return _Upload(file=file, url=url, method=method, headers=headers) + + +def _upload_route_not_found( + fields: Mapping[str, Any], retry_after_header: Optional[str] +) -> EmailError: + unanswered = { + "code": "not_found", + "why": "This PostHog version doesn't take attachments yet, or sending " + "email from code is off for the project.", + "fix": "Send the email without attachments, or check that the project " + "can send email from code.", + } + answered = {key: value for key, value in fields.items() if value is not None} + return _response_error( + {**unanswered, **answered, "attr": "attachments"}, 404, retry_after_header + ) + + +def _upload_url_not_https(index: int, status: int) -> EmailError: + return EmailError( + name=_error_name(status, "api_error"), + code="api_error", + message=f"PostHog named an upload URL that isn't https, so attachments[{index}] " + "would travel unencrypted. No email was sent.", + status_code=status, + why="PostHog's file storage is set up with a plain HTTP URL.", + fix="Fix the file storage's URL so it uses https. For local development " + "over plain HTTP, give the client a host that starts with http://.", + field=f"attachments__{index}", + ) + + +def _no_upload_slots(status: int) -> EmailError: + return _sdk_error( + "api_error", "PostHog answered without an upload slot for each file.", status + ) + + +def _upload_parser(index: int) -> _Parse[None]: + def parse(status: int, body: bytes, retry_after_header: Optional[str]) -> None: + if not 200 <= status < 300: + raise _upload_error(index, status, body, retry_after_header) + + return parse + + +def _upload_error( + index: int, status: int, body: bytes, retry_after_header: Optional[str] +) -> EmailError: + answer = dict(_STORAGE_ERROR.findall(body.decode("utf-8", "replace"))) + storage_answer = " ".join(filter(None, (f"HTTP {status}", answer.get("Code")))) + return EmailError( + name=_storage_error_name(status), + code="attachment_upload_failed", + message=f"PostHog's file storage refused the upload of attachments[{index}] " + f"with {storage_answer}, so no email was sent.", + status_code=status, + why=answer.get("Message"), + fix="Send the email again, which asks for a fresh upload URL. If the " + "upload keeps failing, check whether a proxy between your app and " + "PostHog's file storage changes or holds up uploads.", + field=f"attachments__{index}", + retry_after=_retry_after(retry_after_header), + ) + + +def _storage_error_name(status: int) -> str: + if status == 429: + return "rate_limit_exceeded" + if status in _STORAGE_RETRY_STATUSES: + return "service_unavailable" + return "application_error" + + def _response_error( fields: Mapping[str, Any], status: int, retry_after_header: Optional[str] ) -> EmailError: @@ -745,10 +1183,12 @@ def _is_retryable(error: EmailError) -> bool: # A send carries an idempotency key, so a retry can't queue a second email. A status read changes nothing. if error.status_code is None: return error.code == "network_error" + if error.code == "attachment_upload_failed": + return error.status_code in _STORAGE_RETRY_STATUSES if error.status_code == 409: return error.code in _IN_FLIGHT_CODES if error.status_code == 429: - return error.code not in _QUOTA_CODES + return error.code not in _QUOTA_CODES | _DAILY_QUOTA_CODES return error.status_code == 503 @@ -800,7 +1240,7 @@ def _headers( "transactional_email:read or transactional_email:write scope." ) _ResultT = TypeVar("_ResultT") -_Parse = Callable[[int, Any, Optional[str]], _ResultT] +_Parse = Callable[[int, bytes, Optional[str]], _ResultT] class _BearerAuth(requests.auth.AuthBase): @@ -813,6 +1253,24 @@ def __call__(self, request: requests.PreparedRequest) -> requests.PreparedReques return request +def _storage_unreachable(index: int, exc: Exception) -> EmailError: + return EmailError( + name="service_unavailable", + code="network_error", + message=f"PostHog's file storage didn't answer the upload of attachments[{index}] " + f"({type(exc).__name__}), so no email was sent.", + fix="Send the email again. If it keeps failing, check that your network " + "lets the app reach PostHog's file storage.", + field=f"attachments__{index}", + ) + + +def _files_body(files: Sequence[_File]) -> bytes: + return _encode( + {"files": [{"sha256": file.sha256, "size": file.size} for file in files]} + ) + + class _EmailsBase: def __init__( self, @@ -935,6 +1393,11 @@ def send(self, **kwargs: Any) -> SendEmailResult: Raises: EmailError: PostHog did not queue the email, or the client could not tell whether it did. + With attachments, ``code`` is ``too_many_attachments``, + ``message_too_large`` or ``invalid_attachment`` before any + request, ``attachment_upload_failed`` when the storage + refused an upload, and ``network_error`` with ``field`` + naming the attachment when the storage didn't answer. TypeError, ValueError: An argument has the wrong type or format. Examples: @@ -965,6 +1428,8 @@ def send(self, **kwargs: Any) -> SendEmailResult: return result def _deliver(self, prepared: _PreparedSend, secret_key: str) -> SendEmailResult: + if prepared.files: + self._upload(prepared, secret_key) headers = _headers( secret_key, self.migrated_from, @@ -972,14 +1437,29 @@ def _deliver(self, prepared: _PreparedSend, secret_key: str) -> SendEmailResult: idempotency_key=prepared.idempotency_key, ) return self._call( - "POST", - prepared.path, - prepared.body, - headers, + self._posthog_request("POST", prepared.path, prepared.body, headers), _parse_response, prepared.max_retries, ) + def _upload(self, prepared: _PreparedSend, secret_key: str) -> None: + headers = _headers(secret_key, self.migrated_from, has_body=True) + uploads = self._call( + self._posthog_request( + "POST", _UPLOADS_PATH, _files_body(prepared.files), headers + ), + _pending_uploads_parser( + prepared.files, self.host.lower().startswith("http://") + ), + prepared.max_retries, + ) + for upload in uploads: + self._call( + self._storage_request(upload), + _upload_parser(upload.file.first_attachment_index), + prepared.max_retries, + ) + def get(self, message_id: Union[str, UUID]) -> EmailStatus: """Read what happened to an email that :meth:`send` queued. @@ -1008,41 +1488,61 @@ def get(self, message_id: Union[str, UUID]) -> EmailStatus: finish = self._start(_GET_NOT_DONE) try: headers = _headers(self._secret_key(_GET_KEY_NEEDED), self.migrated_from) - return self._call("GET", path, None, headers, _parse_status_response) + return self._call( + self._posthog_request("GET", path, None, headers), + _parse_status_response, + ) finally: finish() + def _posthog_request( + self, method: str, path: str, body: Optional[bytes], headers: dict[str, str] + ) -> Callable[[], requests.Response]: + session, auth = self._get_session(), _BearerAuth(headers) + return lambda: session.request( + method, + self.host + path, + data=body, + auth=auth, + timeout=self.timeout, + allow_redirects=False, + ) + + def _storage_request(self, upload: _Upload) -> Callable[[], requests.Response]: + session = self._get_session() + request = requests.Request( + upload.method, upload.url, data=upload.file.content, headers=upload.headers + ).prepare() + transport = session.merge_environment_settings( + upload.url, {}, False, None, None + ) + + def send() -> requests.Response: + try: + return session.send( + request, timeout=self.timeout, allow_redirects=False, **transport + ) + except requests.exceptions.RequestException as exc: + raise _storage_unreachable( + upload.file.first_attachment_index, exc + ) from None + + return send + def _call( self, - method: str, - path: str, - body: Optional[bytes], - headers: dict[str, str], + send: Callable[[], requests.Response], parse: _Parse[_ResultT], max_retries: Optional[int] = None, ) -> _ResultT: - auth = _BearerAuth(headers) - session = self._get_session() - url = self.host + path retries = self.max_retries if max_retries is None else max_retries for attempt in range(retries + 1): try: - response = session.request( - method, - url, - data=body, - auth=auth, - timeout=self.timeout, - allow_redirects=False, - ) + response = send() try: - try: - payload = response.json() - except ValueError: - payload = None return parse( response.status_code, - payload, + response.content, response.headers.get("Retry-After"), ) finally: @@ -1149,6 +1649,8 @@ async def send(self, **kwargs: Any) -> SendEmailResult: async def _deliver( self, prepared: _PreparedSend, secret_key: str ) -> SendEmailResult: + if prepared.files: + await self._upload(prepared, secret_key) headers = _headers( secret_key, self.migrated_from, @@ -1156,14 +1658,29 @@ async def _deliver( idempotency_key=prepared.idempotency_key, ) return await self._call( - "POST", - prepared.path, - prepared.body, - headers, + self._posthog_request("POST", prepared.path, prepared.body, headers), _parse_response, prepared.max_retries, ) + async def _upload(self, prepared: _PreparedSend, secret_key: str) -> None: + headers = _headers(secret_key, self.migrated_from, has_body=True) + uploads = await self._call( + self._posthog_request( + "POST", _UPLOADS_PATH, _files_body(prepared.files), headers + ), + _pending_uploads_parser( + prepared.files, self.host.lower().startswith("http://") + ), + prepared.max_retries, + ) + for upload in uploads: + await self._call( + self._storage_request(upload), + _upload_parser(upload.file.first_attachment_index), + prepared.max_retries, + ) + async def get(self, message_id: Union[str, UUID]) -> EmailStatus: """Read what happened to an email that :meth:`send` queued. @@ -1174,42 +1691,63 @@ async def get(self, message_id: Union[str, UUID]) -> EmailStatus: finish = self._start(_GET_NOT_DONE) try: headers = _headers(self._secret_key(_GET_KEY_NEEDED), self.migrated_from) - return await self._call("GET", path, None, headers, _parse_status_response) + return await self._call( + self._posthog_request("GET", path, None, headers), + _parse_status_response, + ) finally: finish() + def _posthog_request( + self, method: str, path: str, body: Optional[bytes], headers: dict[str, str] + ) -> Callable[[], Awaitable[Any]]: + _, client = self._get_client() + # An injected client may carry its own auth and timeout, so set both per request: auth=None keeps + # the secret key's Bearer header, and the request timeout applies whatever the client's default. + return lambda: client.request( + method, + self.host + path, + content=body, + headers=headers, + auth=None, + timeout=self.timeout, + ) + + def _storage_request(self, upload: _Upload) -> Callable[[], Awaitable[Any]]: + httpx, client = self._get_client() + request = httpx.Request( + upload.method, + upload.url, + content=upload.file.content, + headers=upload.headers, + extensions={"timeout": httpx.Timeout(self.timeout).as_dict()}, + ) + + async def send() -> Any: + try: + return await client.send(request, auth=None, follow_redirects=False) + except httpx.RequestError as exc: + raise _storage_unreachable( + upload.file.first_attachment_index, exc + ) from None + + return send + async def _call( self, - method: str, - path: str, - body: Optional[bytes], - headers: dict[str, str], + send: Callable[[], Awaitable[Any]], parse: _Parse[_ResultT], max_retries: Optional[int] = None, ) -> _ResultT: - httpx, client = self._get_client() - url = self.host + path + httpx, _ = self._get_client() retries = self.max_retries if max_retries is None else max_retries for attempt in range(retries + 1): try: - # An injected client may carry its own auth and timeout, so set both per request: auth=None keeps - # the secret key's Bearer header, and the request timeout applies whatever the client's default. - response = await client.request( - method, - url, - content=body, - headers=headers, - auth=None, - timeout=self.timeout, - ) + response = await send() try: - try: - payload = response.json() - except ValueError: - payload = None return parse( response.status_code, - payload, + response.content, response.headers.get("Retry-After"), ) finally: diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py index b13b8a0c6..82b8a8dce 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -1,14 +1,28 @@ from __future__ import annotations import asyncio +import base64 +import hashlib +import hmac import json import logging +import re +import ssl import threading -from datetime import datetime, timezone +import time +import traceback +import tracemalloc +from contextlib import contextmanager +from dataclasses import dataclass, field, replace +from datetime import datetime, timedelta, timezone from decimal import Decimal -from http.server import BaseHTTPRequestHandler, HTTPServer -from typing import Any, Iterator, Optional, Union +from http.server import BaseHTTPRequestHandler, HTTPServer, ThreadingHTTPServer +from ipaddress import ip_address +from pathlib import Path +from typing import Any, Callable, Iterator, Mapping, Optional, Union from unittest import mock +from urllib.parse import parse_qsl, urlencode, urlsplit +from uuid import uuid4 import httpx import pytest @@ -622,6 +636,8 @@ def handler(request: httpx.Request) -> httpx.Response: HTML = "

Reset it here.

" +INVITE = b"BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n" +INVITE_BASE64 = "QkVHSU46VkNBTEVOREFSDQpFTkQ6VkNBTEVOREFSDQo=" def send_code(emails: Emails, **overrides: Any): @@ -845,12 +861,13 @@ def handler(request: httpx.Request) -> httpx.Response: ("empty_html_and_text", {"html": "", "text": ""}, ValueError), ("blank_reply_to", {"html": HTML, "reply_to": " "}, ValueError), ("reply_to_not_text", {"html": HTML, "reply_to": 123}, TypeError), + ("blank_cc", {"html": HTML, "cc": " "}, ValueError), + ("bcc_not_text", {"html": HTML, "bcc": [123]}, TypeError), ( "template_data_on_code_form", {"html": HTML, "template_data": {"first_name": "Jane"}}, TypeError, ), - ("cc_on_code_form", {"html": HTML, "cc": "a@example.com"}, TypeError), ( "capture_engagement_on_template_form", { @@ -861,6 +878,36 @@ def handler(request: httpx.Request) -> httpx.Response: }, TypeError, ), + ( + "cc_on_template_form", + { + "template_id": TEMPLATE_ID, + "template_key": None, + "subject": None, + "cc": "a@example.com", + }, + TypeError, + ), + ( + "bcc_on_template_form", + { + "template_id": TEMPLATE_ID, + "template_key": None, + "subject": None, + "bcc": ["a@example.com"], + }, + TypeError, + ), + ( + "attachments_on_template_form", + { + "template_id": TEMPLATE_ID, + "template_key": None, + "subject": None, + "attachments": [{"filename": "a.txt", "content": b"hi"}], + }, + TypeError, + ), ( "tracking_on_template_form", { @@ -900,3 +947,1737 @@ def test_rejects_a_code_send_that_mixes_or_misses_fields(_name, overrides, error ) assert adapter.requests == [] + + +def test_a_refused_send_names_the_field_from_attr(): + posthog = FakePostHog() + posthog.send_fields = SEND_FIELDS - {"cc"} + + with pytest.raises(EmailError) as raised: + send_code(emails_on(posthog), html=HTML, cc="manager@example.com") + + assert (raised.value.code, raised.value.field) == ("invalid_input", "cc") + assert posthog.delivered == [] + + +POSTHOG_HOST = "https://us.posthog.com" +UPLOADS_PATH = "/api/projects/@current/messaging/attachments/uploads/" +SEND_PATH = "/api/projects/@current/messaging/send/email/" +STORAGE_URL = "https://files.example.com/team/1" +STORAGE_SIGNING_KEY = b"fake-storage-signing-key" +URL_LIFETIME_SECONDS = 900 +SEND_FIELDS = frozenset( + { + "to", + "template_key", + "subject", + "html", + "text", + "from", + "reply_to", + "cc", + "bcc", + "capture_engagement", + "sensitive", + "tracking", + "distinct_id", + "attachments", + } +) +REFERENCE_FIELDS = frozenset({"sha256", "filename", "content_type", "content_id"}) +SHA256_HEX = re.compile(r"[0-9a-f]{64}") + + +@dataclass(frozen=True) +class Answer: + status: int + body: bytes = b"" + headers: dict[str, str] = field(default_factory=dict) + + @classmethod + def of_json(cls, status: int, payload: dict[str, Any]) -> Answer: + return cls( + status, json.dumps(payload).encode(), {"Content-Type": "application/json"} + ) + + +def api_error( + status: int, code: str, detail: str, kind: str = "validation_error", **extra: Any +) -> Answer: + return Answer.of_json( + status, {"type": kind, "code": code, "detail": detail, **extra} + ) + + +def storage_error(status: int, code: str, message: str) -> Answer: + return Answer( + status, + f'{code}' + f"{message}".encode(), + {"Content-Type": "application/xml"}, + ) + + +UNAUTHORIZED = api_error( + 401, + "authentication_failed", + "Incorrect authentication credentials.", + kind="authentication_error", +) + + +@dataclass(frozen=True) +class Incoming: + method: str + url: str + headers: Mapping[str, str] + body: bytes + + @property + def path(self) -> str: + return urlsplit(self.url).path + + @property + def is_authorized(self) -> bool: + return self.headers.get("authorization") == f"Bearer {SECRET_KEY}" + + +class Unreachable(Exception): + pass + + +Handler = Callable[[Incoming], Answer] +Fault = Callable[[Incoming, Handler], Answer] + + +def answers(answer: Answer) -> Fault: + return lambda _incoming, _handle: answer + + +def loses_the_reply(answer: Answer) -> Fault: + def fault(incoming: Incoming, handle: Handler) -> Answer: + handle(incoming) + return answer + + return fault + + +def unreachable(incoming: Incoming, _handle: Handler) -> Answer: + raise Unreachable(f"Max retries exceeded with url: {incoming.url}") + + +def alters_the_bytes(incoming: Incoming, handle: Handler) -> Answer: + return handle(replace(incoming, body=incoming.body[::-1])) + + +@dataclass(frozen=True) +class DeliveredFile: + filename: str + content: bytes + content_type: Optional[str] = None + content_id: Optional[str] = None + + +@dataclass(frozen=True) +class DeliveredEmail: + message_id: str + to: str + cc: tuple[str, ...] + bcc: tuple[str, ...] + subject: str + html: Optional[str] + text: Optional[str] + attachments: tuple[DeliveredFile, ...] + + +def checksum(content: bytes) -> str: + return base64.b64encode(hashlib.sha256(content).digest()).decode() + + +def storage_signature( + method: str, path: str, query: Mapping[str, str], headers: Mapping[str, str] +) -> str: + canonical = "\n".join( + [ + method, + path, + urlencode(sorted(query.items())), + headers.get("content-length", ""), + headers.get("x-amz-checksum-sha256", ""), + ] + ) + return hmac.new(STORAGE_SIGNING_KEY, canonical.encode(), hashlib.sha256).hexdigest() + + +def json_or_none(body: bytes) -> Any: + try: + return json.loads(body) + except ValueError: + return None + + +def files_asked_for(body: bytes) -> Optional[list[tuple[str, int]]]: + payload = json_or_none(body) + if not isinstance(payload, dict) or set(payload) != {"files"}: + return None + files = payload["files"] + if not isinstance(files, list) or not files: + return None + if not all( + isinstance(file, dict) + and set(file) == {"sha256", "size"} + and isinstance(file["sha256"], str) + and SHA256_HEX.fullmatch(file["sha256"]) + and type(file["size"]) is int + and file["size"] > 0 + for file in files + ): + return None + return [(file["sha256"], file["size"]) for file in files] + + +class FakePostHog: + def __init__( + self, storage_url: str = STORAGE_URL, posthog_host: str = POSTHOG_HOST + ) -> None: + self.storage_url = storage_url + self.posthog_host = posthog_host + self._bucket: dict[str, bytes] = {} + self._content_types: dict[str, Optional[str]] = {} + self.writes = 0 + self.delivered: list[DeliveredEmail] = [] + self.project_can_send_files = True + self.send_fields = SEND_FIELDS + self._sent_by_idempotency_key: dict[str, str] = {} + self._faults: dict[str, list[Fault]] = { + "uploads": [], + "send": [], + "storage": [], + } + self._signing_delay = 0.0 + + @property + def stored_files(self) -> list[bytes]: + return sorted(self._bucket.values()) + + @property + def stored_content_types(self) -> list[Optional[str]]: + return list(self._content_types.values()) + + def already_has(self, content: bytes) -> None: + self._bucket[hashlib.sha256(content).hexdigest()] = content + + def inject(self, route: str, *faults: Fault) -> None: + self._faults[route].extend(faults) + + def sign_urls_in_the_past(self, minutes: int) -> None: + self._signing_delay = minutes * 60.0 + + def handle(self, incoming: Incoming) -> Answer: + route, handler = self._route(incoming) + faults = self._faults.get(route) + if faults: + return faults.pop(0)(incoming, handler) + return handler(incoming) + + def _route(self, incoming: Incoming) -> tuple[str, Handler]: + if incoming.url.startswith(self.storage_url + "/"): + if incoming.method != "PUT": + return "storage", lambda _incoming: storage_error( + 405, + "MethodNotAllowed", + "The specified method is not allowed against this resource.", + ) + return "storage", self._store + if incoming.url.startswith(self.posthog_host + "/") and incoming.path in ( + UPLOADS_PATH, + SEND_PATH, + ): + route = "uploads" if incoming.path == UPLOADS_PATH else "send" + if incoming.method != "POST": + return route, lambda _incoming: api_error( + 405, + "method_not_allowed", + f'Method "{incoming.method}" not allowed.', + kind="invalid_request", + ) + return route, (self._answer_uploads if route == "uploads" else self._send) + return "unknown", lambda _incoming: api_error( + 404, "not_found", "Not found.", kind="invalid_request" + ) + + def _answer_uploads(self, incoming: Incoming) -> Answer: + if not incoming.is_authorized: + return UNAUTHORIZED + if not self.project_can_send_files: + return api_error( + 400, + "field_not_accepted", + "This project can't send files yet, so PostHog didn't prepare the uploads.", + kind="invalid_request", + attr="files", + why="Sending files isn't available to this project yet.", + fix="Send the email without files.", + ) + files = files_asked_for(incoming.body) + if files is None: + return api_error( + 400, "invalid_input", "Name each file by sha256 and size.", attr="files" + ) + return Answer.of_json( + 200, {"files": [self._slot(sha256, size) for sha256, size in files]} + ) + + def _slot(self, sha256: str, size: int) -> dict[str, Any]: + if sha256 in self._bucket: + return { + "sha256": sha256, + "status": "present", + "expires_at": "2026-12-16T00:00:00Z", + } + url = f"{self.storage_url}/{sha256}" + headers = { + "content-length": str(size), + "x-amz-checksum-sha256": base64.b64encode(bytes.fromhex(sha256)).decode(), + } + query = { + "X-Amz-Date": str(int(time.time() - self._signing_delay)), + "X-Amz-Expires": str(URL_LIFETIME_SECONDS), + "X-Amz-SignedHeaders": "content-length;x-amz-checksum-sha256", + } + signature = storage_signature("PUT", urlsplit(url).path, query, headers) + return { + "sha256": sha256, + "status": "upload", + "url": f"{url}?{urlencode({**query, 'X-Amz-Signature': signature})}", + "method": "PUT", + "headers": headers, + "url_expires_at": "2026-11-09T12:15:00Z", + } + + def _store(self, incoming: Incoming) -> Answer: + if "authorization" in incoming.headers: + return storage_error( + 400, + "InvalidArgument", + "Only one auth mechanism allowed; only the X-Amz-Algorithm query " + "parameter, Signature query string parameter or the Authorization " + "header should be specified", + ) + query = dict(parse_qsl(urlsplit(incoming.url).query, keep_blank_values=True)) + signature = query.pop("X-Amz-Signature", "") + expected = storage_signature( + incoming.method, incoming.path, query, incoming.headers + ) + if not hmac.compare_digest(signature, expected): + return storage_error( + 403, + "SignatureDoesNotMatch", + "The request signature we calculated does not match the signature you provided.", + ) + if time.time() > int(query["X-Amz-Date"]) + int(query["X-Amz-Expires"]): + return storage_error(403, "AccessDenied", "Request has expired") + if incoming.headers["content-length"] != str( + len(incoming.body) + ) or incoming.headers["x-amz-checksum-sha256"] != checksum(incoming.body): + return storage_error( + 400, + "BadDigest", + "The SHA256 you specified did not match the calculated checksum.", + ) + key = incoming.path.rsplit("/", 1)[1] + self._bucket[key] = incoming.body + self._content_types[key] = incoming.headers.get("content-type") + self.writes += 1 + return Answer(200) + + def _send(self, incoming: Incoming) -> Answer: + if not incoming.is_authorized: + return UNAUTHORIZED + idempotency_key = incoming.headers.get("idempotency-key", "") + if idempotency_key in self._sent_by_idempotency_key: + return Answer.of_json( + 200, + { + "message_id": self._sent_by_idempotency_key[idempotency_key], + "replayed": True, + }, + ) + payload = json_or_none(incoming.body) + if not isinstance(payload, dict): + return api_error(400, "invalid_input", "Send a JSON object.") + unknown = sorted(set(payload) - self.send_fields) + if unknown: + return api_error( + 400, + "invalid_input", + f"PostHog doesn't take {unknown[0]}.", + attr=unknown[0], + ) + references = payload.get("attachments", []) + for index, reference in enumerate(references): + refused = self._refused_reference(index, reference) + if refused is not None: + return refused + message_id = str(uuid4()) + self.delivered.append(self._email(message_id, payload, references)) + if idempotency_key: + self._sent_by_idempotency_key[idempotency_key] = message_id + return Answer.of_json(202, {"message_id": message_id}) + + def _refused_reference(self, index: int, reference: Any) -> Optional[Answer]: + if ( + not isinstance(reference, dict) + or not {"sha256", "filename"} <= set(reference) <= REFERENCE_FIELDS + ): + return api_error( + 400, + "invalid_input", + "An attachment names sha256 and filename.", + attr=f"attachments__{index}", + ) + if reference["sha256"] not in self._bucket: + return api_error( + 400, + "attachment_not_uploaded", + "PostHog doesn't hold this file. Upload it first.", + attr=f"attachments__{index}", + ) + return None + + def _email( + self, message_id: str, payload: dict[str, Any], references: list[Any] + ) -> DeliveredEmail: + return DeliveredEmail( + message_id=message_id, + to=payload["to"], + cc=tuple(payload.get("cc", ())), + bcc=tuple(payload.get("bcc", ())), + subject=payload["subject"], + html=payload.get("html"), + text=payload.get("text"), + attachments=tuple( + DeliveredFile( + filename=reference["filename"], + content=self._bucket[reference["sha256"]], + content_type=reference.get("content_type"), + content_id=reference.get("content_id"), + ) + for reference in references + ), + ) + + +def lowercase(headers: Any) -> dict[str, str]: + return {name.lower(): value for name, value in headers.items()} + + +class FakePostHogAdapter(requests.adapters.BaseAdapter): + def __init__(self, posthog: FakePostHog) -> None: + super().__init__() + self.posthog = posthog + + def send( + self, request: requests.PreparedRequest, **kwargs: Any + ) -> requests.Response: + incoming = Incoming( + request.method or "", + request.url or "", + lowercase(request.headers), + request.body if isinstance(request.body, bytes) else b"", + ) + try: + answer = self.posthog.handle(incoming) + except Unreachable as exc: + raise requests.exceptions.ConnectionError(str(exc)) + response = requests.Response() + response.status_code = answer.status + response._content = answer.body + response.headers.update(answer.headers) + response.request = request + response.url = incoming.url + return response + + def close(self) -> None: + pass + + +def httpx_transport(posthog: FakePostHog) -> httpx.MockTransport: + def handle(request: httpx.Request) -> httpx.Response: + incoming = Incoming( + request.method, str(request.url), lowercase(request.headers), request.read() + ) + try: + answer = posthog.handle(incoming) + except Unreachable as exc: + raise httpx.ConnectError(str(exc), request=request) + return httpx.Response( + answer.status, content=answer.body, headers=answer.headers + ) + + return httpx.MockTransport(handle) + + +def session_on(posthog: FakePostHog, prefix: str = "https://") -> requests.Session: + session = requests.Session() + session.mount(prefix, FakePostHogAdapter(posthog)) + return session + + +def emails_on(posthog: FakePostHog, **options: Any) -> Emails: + return Emails(SECRET_KEY, session=session_on(posthog), **options) + + +def async_emails_on( + posthog: FakePostHog, max_retries: int = 2, **client_options: Any +) -> AsyncEmails: + return AsyncEmails( + SECRET_KEY, + max_retries=max_retries, + http_client=httpx.AsyncClient( + transport=httpx_transport(posthog), **client_options + ), + ) + + +INVITE_SHA256 = "215efae54e34ac5657da47b49c8d1bd8ea12649ee1efa838c9a47d7233f18afb" +LOGO = b"\x89PNG\r\n\x1a\n" +INVITE_FILE = {"filename": "invite.ics", "content": INVITE} +INVITE_AND_LOGO = [ + { + "filename": "invite.ics", + "content": INVITE, + "content_type": "text/calendar; method=REQUEST", + }, + {"filename": "logo.png", "content": "iVBORw0KGgo=", "content_id": "logo"}, +] +DELIVERED_INVITE_AND_LOGO = ( + DeliveredFile("invite.ics", INVITE, content_type="text/calendar; method=REQUEST"), + DeliveredFile("logo.png", LOGO, content_id="logo"), +) + + +def test_delivers_each_file_with_its_name_type_and_content_id(): + posthog = FakePostHog() + + result = send_code(emails_on(posthog), html=HTML, attachments=INVITE_AND_LOGO) + + [email] = posthog.delivered + assert result.id == email.message_id + assert email.attachments == DELIVERED_INVITE_AND_LOGO + + +def test_delivers_cc_and_bcc_beside_the_files(): + posthog = FakePostHog() + + send_code( + emails_on(posthog), + html=HTML, + cc="manager@example.com", + bcc=["audit@example.com", "archive@example.com"], + attachments=[INVITE_FILE], + ) + + [email] = posthog.delivered + assert (email.cc, email.bcc) == ( + ("manager@example.com",), + ("audit@example.com", "archive@example.com"), + ) + assert email.attachments == (DeliveredFile("invite.ics", INVITE),) + + +@parameterized.expand( + [ + ( + "one_address_each", + {"cc": "manager@example.com", "bcc": "audit@example.com"}, + ("manager@example.com",), + ("audit@example.com",), + ), + ( + "lists", + { + "cc": ["manager@example.com", "finance@example.com"], + "bcc": ["audit@example.com"], + }, + ("manager@example.com", "finance@example.com"), + ("audit@example.com",), + ), + ("empty_lists", {"cc": [], "bcc": [], "attachments": []}, (), ()), + ("none", {"cc": None, "bcc": None, "attachments": None}, (), ()), + ] +) +def test_delivers_cc_and_bcc_as_given(_name, overrides, cc, bcc): + posthog = FakePostHog() + + send_code(emails_on(posthog), html=HTML, **overrides) + + [email] = posthog.delivered + assert (email.to, email.cc, email.bcc, email.attachments) == ( + "user@example.com", + cc, + bcc, + (), + ) + + +@pytest.mark.asyncio +async def test_async_delivers_cc_and_bcc(): + posthog = FakePostHog() + + await send_code( + async_emails_on(posthog), + html=HTML, + cc="manager@example.com", + bcc=["audit@example.com", "archive@example.com"], + ) + + [email] = posthog.delivered + assert (email.cc, email.bcc) == ( + ("manager@example.com",), + ("audit@example.com", "archive@example.com"), + ) + + +def test_stores_only_the_files_posthog_lacks_under_their_own_hash(): + posthog = FakePostHog() + posthog.already_has(LOGO) + + send_code(emails_on(posthog), html=HTML, attachments=INVITE_AND_LOGO) + + assert posthog.stored_files == sorted([INVITE, LOGO]) + assert posthog.writes == 1 + [email] = posthog.delivered + assert email.attachments == DELIVERED_INVITE_AND_LOGO + + +def test_sends_without_uploading_when_posthog_has_every_file(): + posthog = FakePostHog() + posthog.already_has(INVITE) + + send_code(emails_on(posthog), html=HTML, attachments=[INVITE_FILE]) + + assert posthog.writes == 0 + [email] = posthog.delivered + assert email.attachments == (DeliveredFile("invite.ics", INVITE),) + + +def test_the_upload_carries_only_the_signed_url_and_headers_whatever_the_session_holds(): + posthog = FakePostHog() + session = session_on(posthog) + session.params = {"api_key": "session-default"} + session.headers.update( + {"Authorization": "Bearer session-default", "Content-Type": "text/plain"} + ) + + send_code(Emails(SECRET_KEY, session=session), html=HTML, attachments=[INVITE_FILE]) + + assert (posthog.stored_files, posthog.stored_content_types) == ([INVITE], [None]) + [email] = posthog.delivered + assert email.attachments == (DeliveredFile("invite.ics", INVITE),) + + +@parameterized.expand( + [ + ("bytearray", bytearray(INVITE)), + ("memoryview", memoryview(INVITE)), + ( + "strided_memoryview", + memoryview(bytes(b for byte in INVITE for b in (byte, 0)))[::2], + ), + ("base64_string", INVITE_BASE64), + ] +) +def test_file_content_from_bytes_or_base64_uploads_the_same_bytes(_name, content): + posthog = FakePostHog() + + send_code( + emails_on(posthog), + html=HTML, + attachments=[{"filename": "invite.ics", "content": content}], + ) + + assert posthog.stored_files == [INVITE] + [email] = posthog.delivered + assert email.attachments == (DeliveredFile("invite.ics", INVITE),) + + +def bytes_altered_on_the_way(posthog: FakePostHog) -> None: + posthog.inject("storage", alters_the_bytes) + + +def url_signed_16_minutes_ago(posthog: FakePostHog) -> None: + posthog.sign_urls_in_the_past(16) + + +@parameterized.expand( + [ + ( + "bytes_altered_on_the_way", + bytes_altered_on_the_way, + 400, + "BadDigest", + "The SHA256 you specified did not match the calculated checksum.", + ), + ( + "expired_url", + url_signed_16_minutes_ago, + 403, + "AccessDenied", + "Request has expired", + ), + ] +) +def test_a_refused_upload_sends_no_email_and_surfaces_the_storage_answer( + _name, arrange, status, storage_code, storage_message +): + posthog = FakePostHog() + arrange(posthog) + + with pytest.raises(EmailError) as raised: + send_code(emails_on(posthog), html=HTML, attachments=[INVITE_FILE]) + + error = raised.value + assert (error.name, error.code, error.status_code, error.field, error.why) == ( + "application_error", + "attachment_upload_failed", + status, + "attachments__0", + storage_message, + ) + assert storage_code in error.message + assert "proxy" in error.fix + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +@parameterized.expand( + [ + ("line_wrapped", base64.encodebytes(bytes(100)).decode()), + ("unpadded", "QUI"), + ("url_safe", base64.urlsafe_b64encode(b"\xfb\xff").decode()), + ] +) +def test_refuses_base64_not_in_one_padded_line_and_says_how_to_encode(_name, content): + posthog = FakePostHog() + + with pytest.raises(EmailError) as raised: + send_code( + emails_on(posthog), + html=HTML, + attachments=[{"filename": "a.bin", "content": content}], + ) + + error = raised.value + assert (error.code, error.field) == ( + "invalid_attachment", + "attachments__0__content", + ) + assert "base64.b64encode" in error.message + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +def self_signed_certificate(directory: Path) -> tuple[Path, Path]: + pytest.importorskip("cryptography") + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID + + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "127.0.0.1")]) + now = datetime.now(timezone.utc) + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=5)) + .not_valid_after(now + timedelta(days=1)) + .add_extension( + x509.SubjectAlternativeName([x509.IPAddress(ip_address("127.0.0.1"))]), + critical=False, + ) + .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) + .add_extension( + x509.KeyUsage( + digital_signature=True, + content_commitment=False, + key_encipherment=False, + data_encipherment=False, + key_agreement=False, + key_cert_sign=True, + crl_sign=False, + encipher_only=False, + decipher_only=False, + ), + critical=True, + ) + .add_extension( + x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False + ) + .add_extension( + x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False + ) + .add_extension( + x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()), + critical=False, + ) + .sign(key, hashes.SHA256()) + ) + certificate_path, key_path = directory / "storage.pem", directory / "storage.key" + certificate_path.write_bytes(certificate.public_bytes(serialization.Encoding.PEM)) + key_path.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + return certificate_path, key_path + + +def storage_handler(posthog: FakePostHog) -> type[BaseHTTPRequestHandler]: + class Storage(BaseHTTPRequestHandler): + def do_PUT(self) -> None: + body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + origin = f"https://127.0.0.1:{self.server.server_address[1]}" + answer = posthog.handle( + Incoming("PUT", origin + self.path, lowercase(self.headers), body) + ) + self.send_response(answer.status) + for name, value in answer.headers.items(): + self.send_header(name, value) + self.send_header("Content-Length", str(len(answer.body))) + self.end_headers() + self.wfile.write(answer.body) + + def log_message(self, *args: Any) -> None: + pass + + return Storage + + +@pytest.fixture +def posthog_with_tls_storage(tmp_path): + certificate, key = self_signed_certificate(tmp_path) + posthog = FakePostHog() + server = ThreadingHTTPServer(("127.0.0.1", 0), storage_handler(posthog)) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.load_cert_chain(certificate, key) + server.socket = context.wrap_socket(server.socket, server_side=True) + posthog.storage_url = f"https://127.0.0.1:{server.server_address[1]}/bucket" + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + yield posthog, certificate + finally: + server.shutdown() + server.server_close() + + +def test_the_upload_trusts_the_certificates_the_environment_names( + posthog_with_tls_storage, monkeypatch +): + posthog, certificate = posthog_with_tls_storage + monkeypatch.setenv("REQUESTS_CA_BUNDLE", str(certificate)) + emails = Emails(SECRET_KEY, session=session_on(posthog, POSTHOG_HOST)) + + send_code(emails, html=HTML, attachments=[INVITE_FILE]) + + assert posthog.stored_files == [INVITE] + [email] = posthog.delivered + assert email.attachments == (DeliveredFile("invite.ics", INVITE),) + + +def test_the_upload_refuses_a_storage_whose_certificate_nothing_trusts( + posthog_with_tls_storage, monkeypatch +): + posthog, _certificate = posthog_with_tls_storage + monkeypatch.delenv("REQUESTS_CA_BUNDLE", raising=False) + monkeypatch.delenv("CURL_CA_BUNDLE", raising=False) + emails = Emails(SECRET_KEY, session=session_on(posthog, POSTHOG_HOST)) + + with pytest.raises(EmailError) as raised: + send_code(emails, html=HTML, attachments=[INVITE_FILE]) + + assert (raised.value.code, raised.value.field) == ( + "network_error", + "attachments__0", + ) + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +def test_an_unreachable_storage_never_shows_the_signed_url_in_the_traceback(): + posthog = FakePostHog() + posthog.inject("storage", unreachable, unreachable, unreachable) + + with pytest.raises(EmailError) as raised: + send_code(emails_on(posthog), html=HTML, attachments=[INVITE_FILE]) + + error = raised.value + assert (error.code, error.field) == ("network_error", "attachments__0") + assert "file storage" in error.message + assert "X-Amz-Signature" not in "".join(traceback.format_exception(error)) + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +@pytest.mark.asyncio +async def test_async_unreachable_storage_never_shows_the_signed_url_in_the_traceback(): + posthog = FakePostHog() + posthog.inject("storage", unreachable) + + with pytest.raises(EmailError) as raised: + await send_code( + async_emails_on(posthog, max_retries=0), + html=HTML, + attachments=[INVITE_FILE], + ) + + error = raised.value + assert (error.code, error.field) == ("network_error", "attachments__0") + assert "file storage" in error.message + assert "X-Amz-Signature" not in "".join(traceback.format_exception(error)) + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +@parameterized.expand( + [ + ( + "slow_down", + answers(storage_error(503, "SlowDown", "Please reduce your request rate.")), + ), + ( + "internal_error", + answers(storage_error(500, "InternalError", "Please try again.")), + ), + ( + "too_many_requests", + answers(storage_error(429, "SlowDown", "Please reduce your request rate.")), + ), + ("connection_dropped", unreachable), + ] +) +def test_a_storage_that_asks_for_a_retry_is_retried_before_the_send(_name, fault): + posthog = FakePostHog() + posthog.inject("storage", fault) + + send_code(emails_on(posthog), html=HTML, attachments=[INVITE_FILE]) + + assert posthog.stored_files == [INVITE] + [email] = posthog.delivered + assert email.attachments == (DeliveredFile("invite.ics", INVITE),) + + +def test_a_project_that_cannot_send_files_uploads_and_sends_nothing(): + posthog = FakePostHog() + posthog.project_can_send_files = False + + with pytest.raises(EmailError) as raised: + send_code(emails_on(posthog), html=HTML, attachments=[INVITE_FILE]) + + error = raised.value + assert (error.code, error.field, error.why) == ( + "field_not_accepted", + "attachments", + "Sending files isn't available to this project yet.", + ) + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +def test_an_upload_refusal_naming_a_file_names_the_first_attachment_with_those_bytes(): + posthog = FakePostHog() + posthog.inject( + "uploads", + answers( + api_error( + 400, + "message_too_large", + "This file is too large to send.", + attr="files__1__size", + ) + ), + ) + + with pytest.raises(EmailError) as raised: + send_code( + emails_on(posthog), + html=HTML, + attachments=[ + INVITE_FILE, + {"filename": "invite-copy.ics", "content": INVITE}, + {"filename": "logo.png", "content": LOGO}, + ], + ) + + assert (raised.value.code, raised.value.field) == ( + "message_too_large", + "attachments__2", + ) + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +@parameterized.expand( + [ + ("throttled", 429, "SlowDown", "rate_limit_exceeded"), + ("unavailable", 503, "ServiceUnavailable", "service_unavailable"), + ] +) +def test_a_storage_out_of_retries_names_its_passing_fault( + _name, status, storage_code, name +): + posthog = FakePostHog() + posthog.inject( + "storage", answers(storage_error(status, storage_code, "Try again.")) + ) + + with pytest.raises(EmailError) as raised: + send_code( + emails_on(posthog, max_retries=0), html=HTML, attachments=[INVITE_FILE] + ) + + assert (raised.value.name, raised.value.code) == (name, "attachment_upload_failed") + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +@parameterized.expand( + [ + ("posthog_without_the_upload_route", "Endpoint not found."), + ("sending_from_code_off_for_the_project", "Not found."), + ] +) +def test_an_upload_route_404_reports_posthogs_answer_on_attachments_and_sends_nothing( + _name, detail +): + posthog = FakePostHog() + posthog.inject( + "uploads", + answers(api_error(404, "not_found", detail, kind="invalid_request", attr=None)), + ) + + with pytest.raises(EmailError) as raised: + send_code(emails_on(posthog), html=HTML, attachments=[INVITE_FILE]) + + error = raised.value + assert (error.name, error.code, error.status_code, error.field, error.message) == ( + "not_found", + "not_found", + 404, + "attachments", + detail, + ) + assert error.why and error.fix + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +def test_an_upload_route_404_without_an_answer_still_names_attachments(): + posthog = FakePostHog() + posthog.inject("uploads", answers(Answer(404, b"

Not Found

"))) + + with pytest.raises(EmailError) as raised: + send_code(emails_on(posthog), html=HTML, attachments=[INVITE_FILE]) + + error = raised.value + assert (error.code, error.status_code, error.field) == ( + "not_found", + 404, + "attachments", + ) + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +def test_a_project_over_its_daily_upload_bytes_is_told_without_retrying(): + posthog = FakePostHog() + posthog.inject( + "uploads", + answers( + api_error( + 429, + "upload_quota_exceeded", + "The project uploaded its daily limit of file bytes.", + kind="throttled_error", + ) + ), + ) + + with pytest.raises(EmailError) as raised: + send_code(emails_on(posthog), html=HTML, attachments=[INVITE_FILE]) + + assert (raised.value.code, raised.value.name) == ( + "upload_quota_exceeded", + "daily_quota_exceeded", + ) + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +def test_a_send_retried_after_a_lost_reply_replays_with_its_idempotency_key(): + posthog = FakePostHog() + posthog.inject( + "send", + loses_the_reply( + api_error(503, "delivery_unavailable", "Try again.", kind="server_error") + ), + ) + + result = send_code( + emails_on(posthog), + html=HTML, + idempotency_key="invite:user_123", + attachments=[INVITE_FILE], + ) + + [email] = posthog.delivered + assert (result.id, result.replayed) == (email.message_id, True) + assert email.attachments == (DeliveredFile("invite.ics", INVITE),) + + +def test_the_same_bytes_in_two_attachments_upload_once(): + posthog = FakePostHog() + + send_code( + emails_on(posthog), + html=HTML, + attachments=[ + {"filename": "logo.png", "content": LOGO, "content_id": "logo"}, + {"filename": "logo-copy.png", "content": LOGO}, + ], + ) + + assert (posthog.stored_files, posthog.writes) == ([LOGO], 1) + [email] = posthog.delivered + assert email.attachments == ( + DeliveredFile("logo.png", LOGO, content_id="logo"), + DeliveredFile("logo-copy.png", LOGO), + ) + + +def test_a_failed_upload_names_the_first_attachment_with_those_bytes(): + posthog = FakePostHog() + posthog.already_has(INVITE) + posthog.sign_urls_in_the_past(16) + + with pytest.raises(EmailError) as raised: + send_code( + emails_on(posthog), + html=HTML, + attachments=[ + INVITE_FILE, + {"filename": "logo.png", "content": LOGO}, + {"filename": "logo-copy.png", "content": LOGO}, + ], + ) + + assert (raised.value.code, raised.value.field) == ( + "attachment_upload_failed", + "attachments__1", + ) + assert posthog.delivered == [] + + +def test_refuses_eleven_files_before_reading_any_of_them(): + posthog = FakePostHog() + attachments: list[Any] = [ + {"filename": f"{i}.txt", "content": b"hi"} for i in range(10) + ] + + with pytest.raises(EmailError) as raised: + send_code( + emails_on(posthog), + html=HTML, + attachments=attachments + [{"filename": "late.txt", "content": None}], + ) + + assert raised.value.code == "too_many_attachments" + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +@parameterized.expand( + [ + ( + "eleven_files", + [{"filename": f"{i}.txt", "content": b"hi"} for i in range(11)], + "too_many_attachments", + ), + ( + "one_file_too_large_beside_the_body", + [{"filename": "scan.pdf", "content": bytes(29_182_821)}], + "message_too_large", + ), + ( + "files_too_large_together", + [{"filename": f"{i}.pdf", "content": bytes(3_000_000)} for i in range(10)], + "message_too_large", + ), + ] +) +def test_refuses_an_email_over_the_limits_before_any_request(_name, attachments, code): + posthog = FakePostHog() + + with pytest.raises(EmailError) as raised: + send_code(emails_on(posthog), html="Hi!", attachments=attachments) + + error = raised.value + assert (error.name, error.code, error.field) == ( + "validation_error", + code, + "attachments", + ) + assert error.fix + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +def test_refuses_an_oversized_email_without_copying_its_files(): + posthog = FakePostHog() + emails = emails_on(posthog) + scan = memoryview(bytearray(8 * 1024 * 1024)) + + tracemalloc.start() + try: + with pytest.raises(EmailError) as raised: + send_code( + emails, + html=HTML, + attachments=[ + {"filename": f"scan-{i}.pdf", "content": scan} for i in range(10) + ], + ) + _current, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + + assert raised.value.code == "message_too_large" + assert peak < len(scan) + assert posthog.stored_files == [] + assert posthog.delivered == [] + + +def test_refuses_oversized_padded_base64_without_copying_it(): + posthog = FakePostHog() + emails = emails_on(posthog) + scan = "AAAA" * 10_000_000 + "AA==" + + tracemalloc.start() + try: + with pytest.raises(EmailError) as raised: + send_code( + emails, + html=HTML, + attachments=[{"filename": "scan.pdf", "content": scan}], + ) + _current, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + + assert raised.value.code == "message_too_large" + assert peak < len(scan) // 4 + assert posthog.stored_files == [] + assert posthog.delivered == [] + + +def test_refuses_extra_base64_padding_without_copying_it(): + posthog = FakePostHog() + emails = emails_on(posthog) + content = "YWJj" + "=" * 40_000_000 + + tracemalloc.start() + try: + with pytest.raises(EmailError) as raised: + send_code( + emails, + html=HTML, + attachments=[{"filename": "a.txt", "content": content}], + ) + _current, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + + assert (raised.value.code, raised.value.field) == ( + "invalid_attachment", + "attachments__0__content", + ) + assert "base64.b64encode" in raised.value.message + assert peak < len(content) // 4 + assert posthog.stored_files == [] + assert posthog.delivered == [] + + +LARGEST_SCAN = bytes(29_182_815) + + +def test_sends_the_largest_file_that_fits_beside_the_body(): + posthog = FakePostHog() + + send_code( + emails_on(posthog), + html="Hi!", + attachments=[{"filename": "scan.pdf", "content": LARGEST_SCAN}], + ) + + [email] = posthog.delivered + assert email.attachments == (DeliveredFile("scan.pdf", LARGEST_SCAN),) + + +SCAN_BESIDE_A_78_BYTE_BODY = bytes(29_182_761) + + +@parameterized.expand( + [ + ("html", "html", "text"), + ("text", "text", "html"), + ] +) +def test_counts_a_body_like_a_file_in_the_size_estimate( + _name, body_field, other_body_field +): + posthog = FakePostHog() + emails = emails_on(posthog) + attachments = [{"filename": "scan.pdf", "content": SCAN_BESIDE_A_78_BYTE_BODY}] + + send_code( + emails, attachments=attachments, **{body_field: "a" * 57, other_body_field: "b"} + ) + with pytest.raises(EmailError) as raised: + send_code( + emails, + attachments=attachments, + **{body_field: "é" * 57, other_body_field: "b"}, + ) + + assert raised.value.code == "message_too_large" + assert len(posthog.delivered) == 1 + + +def test_counts_the_html_twice_without_text_since_posthog_derives_the_text(): + posthog = FakePostHog() + emails = emails_on(posthog) + attachments = [{"filename": "scan.pdf", "content": SCAN_BESIDE_A_78_BYTE_BODY}] + + with pytest.raises(EmailError) as raised: + send_code(emails, html="a" * 57, attachments=attachments) + send_code(emails, html="a" * 57, text="b", attachments=attachments) + + assert raised.value.code == "message_too_large" + assert len(posthog.delivered) == 1 + + +def test_uploads_only_to_an_https_storage_url(): + posthog = FakePostHog(storage_url="http://files.example.com/team/1") + + with pytest.raises(EmailError) as raised: + send_code( + emails_on(posthog), + html=HTML, + attachments=[ + {"filename": "notes.txt", "content": b"notes"}, + {"filename": "invite.ics", "content": INVITE}, + ], + ) + + error = raised.value + assert (error.code, error.field) == ("api_error", "attachments__0") + assert "https" in error.message and "file storage" in (error.fix or "") + assert "files.example.com" not in str(error) + str(vars(error)) + assert (posthog.delivered, posthog.stored_files, posthog.writes) == ([], [], 0) + + +def test_a_plain_http_host_for_local_development_uploads_over_plain_http(): + posthog = FakePostHog( + storage_url="http://localhost:8333/team/1", + posthog_host="http://localhost:8000", + ) + emails = Emails( + SECRET_KEY, + host="http://localhost:8000", + session=session_on(posthog, "http://"), + ) + + send_code( + emails, html=HTML, attachments=[{"filename": "invite.ics", "content": INVITE}] + ) + + [email] = posthog.delivered + assert email.attachments == (DeliveredFile("invite.ics", INVITE),) + + +@parameterized.expand( + [ + ("42_ascii_bytes_take_75", "a" * 42, 29_182_815), + ("43_ascii_bytes_take_150", "a" * 43, 29_182_758), + ("21_two_byte_characters_take_75", "é" * 21, 29_182_815), + ("22_two_byte_characters_take_150", "é" * 22, 29_182_758), + ] +) +def test_a_subject_takes_75_bytes_of_the_limit_per_42_utf8_bytes( + _name, subject, largest_file_size +): + posthog = FakePostHog() + emails = emails_on(posthog) + + send_code( + emails, + html="Hi!", + subject=subject, + attachments=[{"filename": "scan.pdf", "content": bytes(largest_file_size)}], + ) + with pytest.raises(EmailError) as raised: + send_code( + emails, + html="Hi!", + subject=subject, + attachments=[ + {"filename": "scan.pdf", "content": bytes(largest_file_size + 1)} + ], + ) + + assert raised.value.code == "message_too_large" + assert len(posthog.delivered) == 1 + + +class PostHogWithARedirectingStorage(BaseHTTPRequestHandler): + emails_sent = 0 + redirect_followed = False + + def do_POST(self) -> None: + self.rfile.read(int(self.headers["Content-Length"])) + if self.path.endswith("/attachments/uploads/"): + slot = { + "sha256": INVITE_SHA256, + "status": "upload", + "url": f"http://{self.headers['Host']}/bucket/{INVITE_SHA256}", + "method": "PUT", + "headers": {"content-length": str(len(INVITE))}, + "url_expires_at": "2026-11-09T12:15:00Z", + } + self.answer(200, json.dumps({"files": [slot]}).encode()) + else: + type(self).emails_sent += 1 + self.answer(202, json.dumps({"message_id": "msg_1"}).encode()) + + def do_PUT(self) -> None: + self.rfile.read(int(self.headers["Content-Length"])) + self.send_response(302) + self.send_header("Location", "/login") + self.send_header("Content-Length", "0") + self.end_headers() + + def do_GET(self) -> None: + type(self).redirect_followed = True + self.answer(200, b"Sign in") + + def answer(self, status: int, body: bytes) -> None: + self.send_response(status) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args: Any) -> None: + pass + + +class PostHogWithAStorageThatHangsUp(PostHogWithARedirectingStorage): + def do_PUT(self) -> None: + self.rfile.read(int(self.headers["Content-Length"])) + self.send_response(500) + self.send_header("Content-Length", "100") + self.end_headers() + self.wfile.write(b"") + self.close_connection = True + + +def test_a_storage_answer_cut_short_names_the_attachment_even_on_a_streaming_session(): + server = ThreadingHTTPServer(("127.0.0.1", 0), PostHogWithAStorageThatHangsUp) + PostHogWithAStorageThatHangsUp.emails_sent = 0 + threading.Thread(target=server.serve_forever, daemon=True).start() + session = requests.Session() + session.stream = True + session.trust_env = False + emails = Emails( + SECRET_KEY, + host=f"http://127.0.0.1:{server.server_address[1]}", + max_retries=0, + session=session, + ) + + try: + with pytest.raises(EmailError) as raised: + send_code(emails, html=HTML, attachments=[INVITE_FILE]) + finally: + server.shutdown() + server.server_close() + + assert (raised.value.code, raised.value.field) == ( + "network_error", + "attachments__0", + ) + assert PostHogWithAStorageThatHangsUp.emails_sent == 0 + + +@pytest.mark.asyncio +async def test_async_upload_never_follows_a_storage_redirect_even_when_the_client_does(): + server = ThreadingHTTPServer(("127.0.0.1", 0), PostHogWithARedirectingStorage) + PostHogWithARedirectingStorage.emails_sent = 0 + PostHogWithARedirectingStorage.redirect_followed = False + threading.Thread(target=server.serve_forever, daemon=True).start() + emails = AsyncEmails( + SECRET_KEY, + host=f"http://127.0.0.1:{server.server_address[1]}", + max_retries=0, + http_client=httpx.AsyncClient(follow_redirects=True, trust_env=False), + ) + + try: + with pytest.raises(EmailError) as raised: + await emails.send( + to="user@example.com", + template_key="password-reset", + subject="Reset your password", + html=HTML, + attachments=[{"filename": "invite.ics", "content": INVITE}], + ) + finally: + server.shutdown() + server.server_close() + + assert (raised.value.code, raised.value.field) == ( + "attachment_upload_failed", + "attachments__0", + ) + assert PostHogWithARedirectingStorage.emails_sent == 0 + assert not PostHogWithARedirectingStorage.redirect_followed + + +class ServerElsewhere(BaseHTTPRequestHandler): + requests_received = 0 + + def do_PUT(self) -> None: + type(self).requests_received += 1 + self.rfile.read(int(self.headers.get("Content-Length", 0))) + self.send_response(200) + self.send_header("Content-Length", "0") + self.end_headers() + + do_GET = do_POST = do_PUT + + def log_message(self, *args: Any) -> None: + pass + + +class PostHogWithStorageRedirectingElsewhere(PostHogWithARedirectingStorage): + elsewhere = "" + + def do_PUT(self) -> None: + self.rfile.read(int(self.headers["Content-Length"])) + self.send_response(307) + self.send_header("Location", f"{self.elsewhere}/bucket/copy") + self.send_header("Content-Length", "0") + self.end_headers() + + +@contextmanager +def serving(handler: type[BaseHTTPRequestHandler]) -> Iterator[str]: + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}" + finally: + server.shutdown() + server.server_close() + + +@contextmanager +def posthog_redirecting_storage_elsewhere() -> Iterator[tuple[str, str]]: + ServerElsewhere.requests_received = 0 + PostHogWithStorageRedirectingElsewhere.emails_sent = 0 + with serving(ServerElsewhere) as elsewhere: + PostHogWithStorageRedirectingElsewhere.elsewhere = elsewhere + with serving(PostHogWithStorageRedirectingElsewhere) as posthog: + yield posthog, elsewhere + + +def error_text(error: EmailError) -> str: + return " ".join(str(part) for part in (error, error.message, error.why, error.fix)) + + +def test_an_upload_never_follows_storage_to_another_server(): + session = requests.Session() + session.trust_env = False + + with posthog_redirecting_storage_elsewhere() as (posthog, elsewhere): + with pytest.raises(EmailError) as raised: + send_code( + Emails(SECRET_KEY, host=posthog, max_retries=0, session=session), + html=HTML, + attachments=[INVITE_FILE], + ) + + assert (raised.value.code, raised.value.field) == ( + "attachment_upload_failed", + "attachments__0", + ) + assert elsewhere not in error_text(raised.value) + assert "/bucket/" not in error_text(raised.value) + assert ServerElsewhere.requests_received == 0 + assert PostHogWithStorageRedirectingElsewhere.emails_sent == 0 + + +@pytest.mark.asyncio +async def test_async_upload_never_follows_storage_to_another_server(): + with posthog_redirecting_storage_elsewhere() as (posthog, elsewhere): + emails = AsyncEmails( + SECRET_KEY, + host=posthog, + max_retries=0, + http_client=httpx.AsyncClient(follow_redirects=True, trust_env=False), + ) + with pytest.raises(EmailError) as raised: + await emails.send( + to="user@example.com", + template_key="password-reset", + subject="Reset your password", + html=HTML, + attachments=[INVITE_FILE], + ) + + assert (raised.value.code, raised.value.field) == ( + "attachment_upload_failed", + "attachments__0", + ) + assert elsewhere not in error_text(raised.value) + assert "/bucket/" not in error_text(raised.value) + assert ServerElsewhere.requests_received == 0 + assert PostHogWithStorageRedirectingElsewhere.emails_sent == 0 + + +@pytest.mark.asyncio +async def test_async_upload_carries_only_the_signed_url_and_headers_whatever_the_client_holds(): + posthog = FakePostHog() + emails = async_emails_on( + posthog, + params={"api_key": "client-default"}, + headers={ + "Authorization": "Bearer client-default", + "Content-Type": "text/plain", + }, + ) + + result = await send_code(emails, html=HTML, attachments=INVITE_AND_LOGO) + + assert (posthog.stored_files, posthog.stored_content_types) == ( + sorted([INVITE, LOGO]), + [None, None], + ) + [email] = posthog.delivered + assert result.id == email.message_id + assert email.attachments == DELIVERED_INVITE_AND_LOGO + + +@pytest.mark.asyncio +async def test_async_refused_upload_sends_no_email(): + posthog = FakePostHog() + posthog.sign_urls_in_the_past(16) + + with pytest.raises(EmailError) as raised: + await send_code(async_emails_on(posthog), html=HTML, attachments=[INVITE_FILE]) + + assert (raised.value.code, raised.value.field, raised.value.status_code) == ( + "attachment_upload_failed", + "attachments__0", + 403, + ) + assert (posthog.delivered, posthog.stored_files) == ([], []) + + +SECRET_CONTENT = b"secret-file-content" + + +@parameterized.expand( + [ + ( + "one_file_not_a_list", + {"filename": "a.txt", "content": SECRET_CONTENT}, + "attachments", + ), + ("bytes_not_a_list", SECRET_CONTENT, "attachments"), + ("file_not_a_mapping", [SECRET_CONTENT], "attachments__0"), + ( + "list_of_ints", + [{"filename": "a.txt", "content": list(SECRET_CONTENT)}], + "attachments__0__content", + ), + ("no_content", [{"filename": "a.txt"}], "attachments__0__content"), + ( + "empty_content", + [{"filename": "a.txt", "content": b""}], + "attachments__0__content", + ), + ( + "text_not_base64", + [{"filename": "a.txt", "content": "secret-file-content"}], + "attachments__0__content", + ), + ( + "non_ascii_text", + [{"filename": "a.txt", "content": "secret-file-content é"}], + "attachments__0__content", + ), + ("no_filename", [{"content": SECRET_CONTENT}], "attachments__0__filename"), + ( + "empty_filename", + [{"filename": "", "content": SECRET_CONTENT}], + "attachments__0__filename", + ), + ( + "path", + [{"filename": "a.txt", "content": SECRET_CONTENT, "path": "/tmp/a.txt"}], + "attachments__0__path", + ), + ( + "unknown_field", + [ + { + "filename": "a.txt", + "content": SECRET_CONTENT, + "contentType": "text/plain", + } + ], + "attachments__0__contentType", + ), + ( + "none_key_before_an_unknown_field", + [ + { + None: "ignored", + "filename": "a.txt", + "content": SECRET_CONTENT, + "contentType": "text/plain", + } + ], + "attachments__0__None", + ), + ( + "content_type_not_text", + [ + {"filename": "a.txt", "content": "aGk="}, + {"filename": "b.txt", "content": SECRET_CONTENT, "content_type": 1}, + ], + "attachments__1__content_type", + ), + ] +) +def test_rejects_an_attachment_it_cannot_send_without_repeating_its_content( + _name, attachments, field +): + posthog = FakePostHog() + + with pytest.raises(EmailError) as raised: + send_code(emails_on(posthog), html=HTML, attachments=attachments) + + error = raised.value + assert (error.name, error.code, error.field) == ( + "validation_error", + "invalid_attachment", + field, + ) + assert "secret-file-content" not in str(error) + assert "115, 101" not in str(error) + assert (posthog.delivered, posthog.stored_files) == ([], []) diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index 0dc7fadbb..b9d617def 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -912,7 +912,10 @@ attribute posthog.debug = False attribute posthog.default_client = None attribute posthog.disable_geoip = True attribute posthog.disabled = False +attribute posthog.emails.CodeEmailArgs.attachments: NotRequired[Optional[Sequence[EmailAttachment]]] +attribute posthog.emails.CodeEmailArgs.bcc: NotRequired[Optional[Union[str, Sequence[str]]]] attribute posthog.emails.CodeEmailArgs.capture_engagement: NotRequired[Optional[bool]] +attribute posthog.emails.CodeEmailArgs.cc: NotRequired[Optional[Union[str, Sequence[str]]]] attribute posthog.emails.CodeEmailArgs.from_: NotRequired[Optional[str]] attribute posthog.emails.CodeEmailArgs.html: NotRequired[Optional[str]] attribute posthog.emails.CodeEmailArgs.reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] @@ -921,6 +924,10 @@ attribute posthog.emails.CodeEmailArgs.subject: str attribute posthog.emails.CodeEmailArgs.template_key: str attribute posthog.emails.CodeEmailArgs.text: NotRequired[Optional[str]] attribute posthog.emails.CodeEmailArgs.tracking: NotRequired[Optional[Union[bool, EmailTracking]]] +attribute posthog.emails.EmailAttachment.content: Union[bytes, bytearray, memoryview, str] +attribute posthog.emails.EmailAttachment.content_id: NotRequired[str] +attribute posthog.emails.EmailAttachment.content_type: NotRequired[str] +attribute posthog.emails.EmailAttachment.filename: str attribute posthog.emails.EmailError.code = code attribute posthog.emails.EmailError.docs_url = docs_url attribute posthog.emails.EmailError.field = field @@ -1377,6 +1384,7 @@ class posthog.consumer.Consumer(queue, api_key, flush_at=100, host=None, on_erro class posthog.contexts.ContextScope(parent=None, fresh: bool = False, capture_exceptions: bool = True, client: Optional[Client] = None) class posthog.emails.AsyncEmails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, http_client: Any = None, migrated_from: Optional[str] = None) class posthog.emails.CodeEmailArgs +class posthog.emails.EmailAttachment class posthog.emails.EmailError(*, name: str, code: str, message: str, status_code: Optional[int] = None, why: Optional[str] = None, fix: Optional[str] = None, docs_url: Optional[str] = None, field: Optional[str] = None, retry_after: Optional[float] = None) class posthog.emails.EmailStatus(id: str, status: str, created_at: datetime, status_at: datetime, reason: Optional[str] = None) class posthog.emails.EmailTracking diff --git a/typings/requests/__init__.pyi b/typings/requests/__init__.pyi index 1c545b680..91e583b5e 100644 --- a/typings/requests/__init__.pyi +++ b/typings/requests/__init__.pyi @@ -6,10 +6,22 @@ from .auth import AuthBase as _AuthBase class PreparedRequest: headers: dict[str, str] +class Request: + def __init__( + self, + method: str, + url: str, + *, + data: bytes | None = ..., + headers: dict[str, str] | None = ..., + ) -> None: ... + def prepare(self) -> PreparedRequest: ... + class Response: status_code: int ok: bool text: str + content: bytes headers: dict[str, str] def json(self) -> Any: ... def close(self) -> None: ... @@ -19,6 +31,22 @@ class Session: headers: dict[str, str] def mount(self, prefix: str, adapter: adapters.HTTPAdapter) -> None: ... def close(self) -> None: ... + def merge_environment_settings( + self, + url: str, + proxies: dict[str, str], + stream: bool | None, + verify: bool | str | None, + cert: str | None, + ) -> dict[str, Any]: ... + def send( + self, + request: PreparedRequest, + *, + timeout: float | None = ..., + allow_redirects: bool = ..., + **kwargs: Any, + ) -> Response: ... def request( self, method: str, From 7f5a6b300e05e15cf389ea5f0ee424bfbfc57084 Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:11:13 +0000 Subject: [PATCH 15/33] chore: Release v7.91.0 [skip ci] --- .sampo/changesets/emails-code-attachments.md | 5 ----- openfeature-provider/CHANGELOG.md | 6 ++++++ openfeature-provider/pyproject.toml | 2 +- posthog/CHANGELOG.md | 6 ++++++ posthog/version.py | 2 +- pyproject.toml | 2 +- uv.lock | 4 ++-- 7 files changed, 17 insertions(+), 10 deletions(-) delete mode 100644 .sampo/changesets/emails-code-attachments.md diff --git a/.sampo/changesets/emails-code-attachments.md b/.sampo/changesets/emails-code-attachments.md deleted file mode 100644 index 48bc79ed0..000000000 --- a/.sampo/changesets/emails-code-attachments.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: minor ---- - -A code send with `posthog.emails.send` takes `cc`, `bcc` and `attachments`: at most 10 files and 40 MB per message after Base64 encoding, about 29 MB of files, with the HTML counted twice when there is no `text`, since PostHog derives the text from it. An attachment is a `filename` and its `content`, as bytes or a Base64 string, with an optional `content_type` and `content_id`. The client checks the limits before any request, uploads each file PostHog doesn't hold yet straight to PostHog's file storage over https, never following a redirect, then sends the email with each file's SHA-256. A refused or redirected upload raises `EmailError` with the code `attachment_upload_failed`, and an unreachable storage `network_error` with `field` naming the attachment. Either way no email is sent. diff --git a/openfeature-provider/CHANGELOG.md b/openfeature-provider/CHANGELOG.md index 2e02e2d1e..a8ca504df 100644 --- a/openfeature-provider/CHANGELOG.md +++ b/openfeature-provider/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to `openfeature-provider-posthog` are documented here. This file is maintained by [Sampo](https://github.com/bruits/sampo) from changesets in `.sampo/changesets/` that target `pypi/openfeature-provider-posthog`. +## 0.1.163 — 2026-11-13 + +### Patch changes + +- Updated dependencies: posthog@7.91.0 + ## 0.1.162 — 2026-11-13 ### Patch changes diff --git a/openfeature-provider/pyproject.toml b/openfeature-provider/pyproject.toml index 9ac9ea6c9..e04c875bd 100644 --- a/openfeature-provider/pyproject.toml +++ b/openfeature-provider/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "openfeature-provider-posthog" -version = "0.1.162" +version = "0.1.163" description = "Official PostHog provider for the OpenFeature Python SDK." readme = "README.md" authors = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/posthog/CHANGELOG.md b/posthog/CHANGELOG.md index 34066322d..836b10382 100644 --- a/posthog/CHANGELOG.md +++ b/posthog/CHANGELOG.md @@ -1,5 +1,11 @@ # posthog +## 7.91.0 — 2026-11-13 + +### Minor changes + +- [cd821fbe](https://github.com/posthog/posthog-python/commit/cd821fbe07f4ee8db9509ecb2bd54f128cdf31c6) A code send with `posthog.emails.send` takes `cc`, `bcc` and `attachments`: at most 10 files and 40 MB per message after Base64 encoding, about 29 MB of files, with the HTML counted twice when there is no `text`, since PostHog derives the text from it. An attachment is a `filename` and its `content`, as bytes or a Base64 string, with an optional `content_type` and `content_id`. The client checks the limits before any request, uploads each file PostHog doesn't hold yet straight to PostHog's file storage over https, never following a redirect, then sends the email with each file's SHA-256. A refused or redirected upload raises `EmailError` with the code `attachment_upload_failed`, and an unreachable storage `network_error` with `field` naming the attachment. Either way no email is sent. — Thanks @Silthus! + ## 7.90.0 — 2026-11-13 ### Minor changes diff --git a/posthog/version.py b/posthog/version.py index 1598a9920..f0d60c57d 100644 --- a/posthog/version.py +++ b/posthog/version.py @@ -1 +1 @@ -VERSION = "7.90.0" +VERSION = "7.91.0" diff --git a/pyproject.toml b/pyproject.toml index 502f85d9e..8e5d19720 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "posthog" -version = "7.90.0" +version = "7.91.0" description = "Integrate PostHog into any python application." authors = [{ name = "PostHog", email = "engineering@posthog.com" }] maintainers = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/uv.lock b/uv.lock index d0aea5795..051754280 100644 --- a/uv.lock +++ b/uv.lock @@ -2723,7 +2723,7 @@ wheels = [ [[package]] name = "openfeature-provider-posthog" -version = "0.1.162" +version = "0.1.163" source = { editable = "openfeature-provider" } dependencies = [ { name = "openfeature-sdk" }, @@ -3280,7 +3280,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.90.0" +version = "7.91.0" source = { editable = "." } dependencies = [ { name = "backoff" }, From f6f61834c8782e2b8c7ec6136af51c077d8bb22c Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:11:24 +0000 Subject: [PATCH 16/33] Update generated references --- references/posthog-python-7.md | 30 +++++++++++++++++++++++++- references/posthog-python-reference.md | 30 +++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/references/posthog-python-7.md b/references/posthog-python-7.md index 14dd3cfdc..4704eef67 100644 --- a/references/posthog-python-7.md +++ b/references/posthog-python-7.md @@ -3800,7 +3800,7 @@ Type | Description Type | Description ---- | ----------- -`EmailError` | PostHog did not queue the email, or the client could not tell whether it did. +`EmailError` | PostHog did not queue the email, or the client could not tell whether it did. With attachments, `code` is `too_many_attachments`, `message_too_large` or `invalid_attachment` before any request, `attachment_upload_failed` when the storage refused an upload, and `network_error` with `field` naming the attachment when the storage didn't answer. `(TypeError, ValueError)` | An argument has the wrong type or format. **Examples:** @@ -4011,6 +4011,10 @@ your app first. An optional field passed as `None` counts as left out. +A PostHog version that doesn't take a field yet, such as `cc`, refuses +the send with an error that names the field in `EmailError.field`. It +never drops the field and sends the rest. + **Parameters:** Name | Type | Description | Default @@ -4022,6 +4026,9 @@ Name | Type | Description | Default `text` | | The plain-text body. Without it, PostHog derives it from `html`. HTML with no text in it, such as a single image, goes out without a plain-text part. | `from_` | | A verified sender, such as `"Acme "`. | `reply_to` | | One address or a list of addresses. An empty list sends no reply-to. | +`cc` | | One address or a list of addresses that get a visible copy, at most 10. | +`bcc` | | One address or a list of addresses that get a hidden copy, at most 10. | +`attachments` | | Files sent with the email: at most 10 files and 40 MB per message after Base64 encoding, about 29 MB of files. The client checks both before any request. It uploads each file that PostHog doesn't hold yet, then sends the email. A file the client can't send raises `EmailError` with `code` `invalid_attachment`. | `capture_engagement` | | Deprecated, use `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both `capture_engagement` and `tracking`. Captures the email's engagement events as events of the recipient. Defaults to `True`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. | `sensitive` | | Marks the email as sensitive, such as one that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `template_key` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. The template form doesn't take it. | `tracking` | | What PostHog tracks for this email. Without it, PostHog counts opens with its open pixel, captures engagement events, and counts clicks only when the email isn't sensitive. `True` turns on opens, clicks and engagement events. `False` turns off all tracking, including kinds PostHog adds later: PostHog can't count the email's opens or clicks, and captures no engagement events. An `EmailTracking` dict turns each kind on or off, and a key you leave out keeps its default. Turn clicks on for a sensitive email only when its links are safe to send through PostHog's click tracking. The template form doesn't take it. | @@ -4033,7 +4040,10 @@ Name | Type | Description | Default Name | Type | Description ---- | ---- | ----------- +`attachments` | `NotRequired[Optional[Sequence[EmailAttachment]]]` | +`bcc` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | `capture_engagement` | `NotRequired[Optional[bool]]` | +`cc` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | `distinct_id` | `NotRequired[Optional[str]]` | `from_` | `NotRequired[Optional[str]]` | `html` | `NotRequired[Optional[str]]` | @@ -4047,12 +4057,30 @@ Name | Type | Description `to` | `str` | `tracking` | `NotRequired[Optional[Union[bool, EmailTracking]]]` | +#### `posthog.emails.CodeEmailArgs.attachments` + +```python +attachments: NotRequired[Optional[Sequence[EmailAttachment]]] +``` + +#### `posthog.emails.CodeEmailArgs.bcc` + +```python +bcc: NotRequired[Optional[Union[str, Sequence[str]]]] +``` + #### `posthog.emails.CodeEmailArgs.capture_engagement` ```python capture_engagement: NotRequired[Optional[bool]] ``` +#### `posthog.emails.CodeEmailArgs.cc` + +```python +cc: NotRequired[Optional[Union[str, Sequence[str]]]] +``` + #### `posthog.emails.CodeEmailArgs.distinct_id` ```python diff --git a/references/posthog-python-reference.md b/references/posthog-python-reference.md index fd92c182b..e40076965 100644 --- a/references/posthog-python-reference.md +++ b/references/posthog-python-reference.md @@ -3800,7 +3800,7 @@ Type | Description Type | Description ---- | ----------- -`EmailError` | PostHog did not queue the email, or the client could not tell whether it did. +`EmailError` | PostHog did not queue the email, or the client could not tell whether it did. With attachments, `code` is `too_many_attachments`, `message_too_large` or `invalid_attachment` before any request, `attachment_upload_failed` when the storage refused an upload, and `network_error` with `field` naming the attachment when the storage didn't answer. `(TypeError, ValueError)` | An argument has the wrong type or format. **Examples:** @@ -4011,6 +4011,10 @@ your app first. An optional field passed as `None` counts as left out. +A PostHog version that doesn't take a field yet, such as `cc`, refuses +the send with an error that names the field in `EmailError.field`. It +never drops the field and sends the rest. + **Parameters:** Name | Type | Description | Default @@ -4022,6 +4026,9 @@ Name | Type | Description | Default `text` | | The plain-text body. Without it, PostHog derives it from `html`. HTML with no text in it, such as a single image, goes out without a plain-text part. | `from_` | | A verified sender, such as `"Acme "`. | `reply_to` | | One address or a list of addresses. An empty list sends no reply-to. | +`cc` | | One address or a list of addresses that get a visible copy, at most 10. | +`bcc` | | One address or a list of addresses that get a hidden copy, at most 10. | +`attachments` | | Files sent with the email: at most 10 files and 40 MB per message after Base64 encoding, about 29 MB of files. The client checks both before any request. It uploads each file that PostHog doesn't hold yet, then sends the email. A file the client can't send raises `EmailError` with `code` `invalid_attachment`. | `capture_engagement` | | Deprecated, use `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both `capture_engagement` and `tracking`. Captures the email's engagement events as events of the recipient. Defaults to `True`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. | `sensitive` | | Marks the email as sensitive, such as one that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `template_key` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. The template form doesn't take it. | `tracking` | | What PostHog tracks for this email. Without it, PostHog counts opens with its open pixel, captures engagement events, and counts clicks only when the email isn't sensitive. `True` turns on opens, clicks and engagement events. `False` turns off all tracking, including kinds PostHog adds later: PostHog can't count the email's opens or clicks, and captures no engagement events. An `EmailTracking` dict turns each kind on or off, and a key you leave out keeps its default. Turn clicks on for a sensitive email only when its links are safe to send through PostHog's click tracking. The template form doesn't take it. | @@ -4033,7 +4040,10 @@ Name | Type | Description | Default Name | Type | Description ---- | ---- | ----------- +`attachments` | `NotRequired[Optional[Sequence[EmailAttachment]]]` | +`bcc` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | `capture_engagement` | `NotRequired[Optional[bool]]` | +`cc` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | `distinct_id` | `NotRequired[Optional[str]]` | `from_` | `NotRequired[Optional[str]]` | `html` | `NotRequired[Optional[str]]` | @@ -4047,12 +4057,30 @@ Name | Type | Description `to` | `str` | `tracking` | `NotRequired[Optional[Union[bool, EmailTracking]]]` | +#### `posthog.emails.CodeEmailArgs.attachments` + +```python +attachments: NotRequired[Optional[Sequence[EmailAttachment]]] +``` + +#### `posthog.emails.CodeEmailArgs.bcc` + +```python +bcc: NotRequired[Optional[Union[str, Sequence[str]]]] +``` + #### `posthog.emails.CodeEmailArgs.capture_engagement` ```python capture_engagement: NotRequired[Optional[bool]] ``` +#### `posthog.emails.CodeEmailArgs.cc` + +```python +cc: NotRequired[Optional[Union[str, Sequence[str]]]] +``` + #### `posthog.emails.CodeEmailArgs.distinct_id` ```python From 03174d0c29dc1d240001981c46f6f15a8ae4a6d1 Mon Sep 17 00:00:00 2001 From: Manoel Aranda Neto <5731772+marandaneto@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:41:59 +0700 Subject: [PATCH 17/33] refactor: reduce SDK complexity and improve CRAP analysis (#1242) * chore: remove mutation testing setup * refactor: reduce SDK complexity and correct CRAP scoring * test: isolate MCP cancellation from optional version helpers --- .github/scripts/check_crap_threshold.py | 74 +- .github/scripts/check_public_api.py | 3 + .../scripts/constructor_helper_attributes.py | 110 + .github/scripts/test_check_crap_threshold.py | 147 + .github/scripts/test_check_public_api.py | 193 +- .github/workflows/ci.yml | 12 +- posthog/__init__.py | 14 +- posthog/_async_consumer.py | 88 +- posthog/_async_request.py | 27 +- posthog/_async_utils.py | 103 +- posthog/_metrics_autocapture.py | 443 +-- posthog/ai/anthropic/_anthropic_stream.py | 66 +- posthog/ai/anthropic/anthropic_converter.py | 300 +- posthog/ai/claude_agent_sdk/client.py | 157 +- posthog/ai/claude_agent_sdk/formatting.py | 25 +- posthog/ai/claude_agent_sdk/processor.py | 357 ++- posthog/ai/evaluations/_async_datasets.py | 9 +- posthog/ai/evaluations/_client.py | 120 +- .../ai/evaluations/_dataset_serialization.py | 47 +- posthog/ai/evaluations/_datasets.py | 7 +- posthog/ai/evaluations/_serialization.py | 78 +- posthog/ai/evaluations/_transport.py | 22 +- posthog/ai/evaluations/_types.py | 149 +- posthog/ai/gemini/gemini_converter.py | 495 ++-- posthog/ai/langchain/callbacks.py | 427 +-- posthog/ai/langchain/middleware.py | 39 +- posthog/ai/media.py | 10 +- posthog/ai/openai/_streaming.py | 52 +- posthog/ai/openai/openai_converter.py | 1080 +++---- posthog/ai/openai_agents/processor.py | 391 ++- posthog/ai/otel/_privacy.py | 18 +- posthog/ai/otel/_request_context.py | 16 +- posthog/ai/prompts.py | 228 +- posthog/ai/utils.py | 897 +++--- posthog/async_client.py | 545 ++-- posthog/capture_compression.py | 4 + posthog/capture_v1.py | 230 +- posthog/client.py | 2536 ++++++++++------- posthog/consumer.py | 91 +- posthog/emails.py | 109 +- posthog/exception_utils.py | 419 ++- posthog/feature_flag_evaluations.py | 78 +- posthog/feature_flags.py | 1469 ++++++---- posthog/integrations/asgi.py | 52 +- posthog/integrations/celery.py | 29 +- posthog/integrations/django.py | 58 +- posthog/mcp/__init__.py | 136 +- posthog/mcp/_capture.py | 13 +- posthog/mcp/_context_parameters.py | 22 +- posthog/mcp/_conversation_id.py | 55 +- posthog/mcp/_instrument_lowlevel.py | 50 +- posthog/mcp/_instrument_v2.py | 43 +- posthog/mcp/_instrumentation.py | 92 +- posthog/mcp/_output_instructions.py | 44 +- posthog/mcp/_posthog_events.py | 119 +- posthog/mcp/_sanitization.py | 37 +- posthog/mcp/_tool_input.py | 138 +- posthog/mcp/_truncation.py | 98 +- posthog/mcp/asgi.py | 47 +- posthog/mcp/feedback.py | 88 +- posthog/mcp/posthog_mcp.py | 212 +- posthog/mcp/session_token.py | 53 +- posthog/metrics_capture.py | 376 +-- posthog/request.py | 42 +- .../ai/anthropic/test_anthropic_converter.py | 92 + .../test/ai/claude_agent_sdk/test_client.py | 372 +++ .../test/ai/gemini/test_gemini_converter.py | 61 + .../test/ai/openai/test_openai_converter.py | 126 + .../test/ai/openai_agents/test_processor.py | 67 + posthog/test/ai/test_sanitization.py | 29 + posthog/test/ai/test_utils.py | 166 ++ .../integrations/test_asgi_integration.py | 27 +- posthog/test/mcp/test_asgi.py | 28 + posthog/test/mcp/test_capture.py | 69 + .../mcp/test_instrument_lowlevel_ownership.py | 70 + posthog/test/mcp/test_instrument_v2.py | 36 + posthog/test/mcp/test_model_parameters.py | 24 + posthog/test/mcp/test_posthog_mcp.py | 66 + posthog/test/test_async_client.py | 247 ++ posthog/test/test_async_consumer.py | 113 +- posthog/test/test_client_crap_flags.py | 170 ++ posthog/test/test_code_variables.py | 71 + posthog/test/test_emails.py | 97 + posthog/test/test_evaluate_flags.py | 90 + posthog/test/test_exception_utils.py | 264 ++ posthog/test/test_feature_flags.py | 3 + posthog/test/test_metrics.py | 44 + posthog/test/test_metrics_autocapture.py | 54 + posthog/test/tracing/test_export.py | 49 + posthog/tracing/_config.py | 24 +- posthog/tracing/_context.py | 21 +- posthog/tracing/_export.py | 205 +- posthog/tracing/_limits.py | 46 +- posthog/tracing/_otlp.py | 89 +- posthog/tracing/_pipeline.py | 49 +- posthog/tracing/_sanitize.py | 24 +- posthog/tracing/_span.py | 9 +- posthog/tracing/_traceparent.py | 10 +- posthog/tracing/_transport.py | 19 +- posthog/types.py | 32 +- references/public_api_snapshot.txt | 1 + 101 files changed, 10745 insertions(+), 5708 deletions(-) create mode 100644 .github/scripts/constructor_helper_attributes.py create mode 100644 .github/scripts/test_check_crap_threshold.py create mode 100644 posthog/test/ai/claude_agent_sdk/test_client.py create mode 100644 posthog/test/ai/test_utils.py create mode 100644 posthog/test/mcp/test_asgi.py create mode 100644 posthog/test/mcp/test_capture.py create mode 100644 posthog/test/mcp/test_instrument_lowlevel_ownership.py create mode 100644 posthog/test/mcp/test_instrument_v2.py create mode 100644 posthog/test/test_client_crap_flags.py diff --git a/.github/scripts/check_crap_threshold.py b/.github/scripts/check_crap_threshold.py index 0fac2e794..fbc19de37 100644 --- a/.github/scripts/check_crap_threshold.py +++ b/.github/scripts/check_crap_threshold.py @@ -1,26 +1,48 @@ #!/usr/bin/env python3 -"""Fail when pytest-crap reports a CRAP score at or above a threshold.""" +"""Enforce CRAP scores using executable-statement coverage.""" from __future__ import annotations import argparse +from dataclasses import replace import sys from pathlib import Path -from coverage import CoverageData -from pytest_crap.calculator import calculate_crap +from coverage import Coverage +from pytest_crap.calculator import FunctionScore, calculate_crap -def covered_lines_for_file(coverage_file: Path, source_file: Path) -> set[int]: - data = CoverageData(basename=str(coverage_file)) - data.read() +def scores_for_file(coverage: Coverage, source_file: Path) -> list[FunctionScore]: + measured_files = { + Path(filename).resolve() for filename in coverage.get_data().measured_files() + } + if source_file.resolve() not in measured_files: + raise SystemExit(f"No coverage data found for {source_file.resolve()}") - source_file = source_file.resolve() - for measured_file in data.measured_files(): - if Path(measured_file).resolve() == source_file: - return set(data.lines(measured_file) or []) - - raise SystemExit(f"No coverage data found for {source_file}") + _, statements, excluded, missing, _ = coverage.analysis2(str(source_file)) + executable_lines = set(statements) - set(excluded) + missing_lines = set(missing) + scores = [] + for score in calculate_crap(str(source_file), executable_lines - missing_lines): + function_lines = { + line + for line in executable_lines + if score.start_line <= line <= score.end_line + } + fraction = ( + len(function_lines - missing_lines) / len(function_lines) + if function_lines + else 1.0 + ) + # pytest-crap's physical-line denominator penalizes comments and docstrings. + scores.append( + replace( + score, + coverage_percent=fraction * 100, + crap=score.cc**2 * (1 - fraction) ** 3 + score.cc, + ) + ) + return scores def main() -> int: @@ -30,9 +52,31 @@ def main() -> int: parser.add_argument("--max-crap", type=float, required=True) args = parser.parse_args() - covered_lines = covered_lines_for_file(args.coverage_file, args.source_file) - scores = calculate_crap(str(args.source_file), covered_lines) + if args.source_file.is_dir(): + source_files = sorted( + path + for path in args.source_file.rglob("*.py") + if not {"test", "tests"}.intersection( + path.relative_to(args.source_file).parts + ) + ) + else: + source_files = [args.source_file] + if not source_files: + raise SystemExit(f"No production Python files found in {args.source_file}") + + coverage = Coverage(data_file=str(args.coverage_file)) + coverage.load() + scores = [ + score + for source_file in source_files + for score in scores_for_file(coverage, source_file) + ] offenders = [score for score in scores if score.crap >= args.max_crap] + print( + f"Analyzed {len(scores)} functions in {len(source_files)} production files; " + f"{len(offenders)} functions scored at or above {args.max_crap:g}" + ) if not offenders: print(f"All CRAP scores are below {args.max_crap:g} for {args.source_file}") @@ -41,7 +85,7 @@ def main() -> int: print(f"CRAP scores must be below {args.max_crap:g} for {args.source_file}") for score in sorted(offenders, key=lambda item: item.crap, reverse=True): print( - f"{score.name}: CRAP={score.crap:.2f}, " + f"{score.file_path}:{score.start_line} {score.name}: CRAP={score.crap:.2f}, " f"CC={score.cc}, coverage={score.coverage_percent:.1f}%" ) return 1 diff --git a/.github/scripts/check_public_api.py b/.github/scripts/check_public_api.py index bc8a3a8d6..899ddbb8c 100644 --- a/.github/scripts/check_public_api.py +++ b/.github/scripts/check_public_api.py @@ -233,11 +233,14 @@ def _load_griffe(): def generate_snapshot() -> str: griffe = _load_griffe() + from constructor_helper_attributes import ConstructorHelperAttributes + package = griffe.load( "posthog", allow_inspection=False, search_paths=[ROOT], submodules=True, + extensions=griffe.load_extensions(ConstructorHelperAttributes()), ) records = sorted(_record(obj) for obj in _iter_module_members(package)) return HEADER + "\n".join(records) + "\n" diff --git a/.github/scripts/constructor_helper_attributes.py b/.github/scripts/constructor_helper_attributes.py new file mode 100644 index 000000000..c1ef96bfb --- /dev/null +++ b/.github/scripts/constructor_helper_attributes.py @@ -0,0 +1,110 @@ +"""Recover public instance attributes initialized by private constructor helpers.""" + +from __future__ import annotations + +import ast +from typing import Iterator + +from griffe import Class, Extension, Function, Visitor, ast_children + + +_DEFERRED_SCOPES = ( + ast.FunctionDef, + ast.AsyncFunctionDef, + ast.ClassDef, + ast.Lambda, + ast.GeneratorExp, +) + + +def _eager_nodes(node: ast.AST) -> Iterator[ast.AST]: + if isinstance(node, _DEFERRED_SCOPES): + return + yield node + for child in ast_children(node): + yield from _eager_nodes(child) + + +def _public_instance_target(node: ast.AST) -> ast.Attribute | None: + if isinstance(node, ast.Assign): + targets = node.targets + elif isinstance(node, ast.AnnAssign): + targets = [node.target] + else: + return None + if ( + len(targets) == 1 + and isinstance(target := targets[0], ast.Attribute) + and isinstance(target.value, ast.Name) + and target.value.id == "self" + and not target.attr.startswith("_") + ): + return target + return None + + +class ConstructorHelperAttributes(Extension): + """Add missing attributes from direct, same-class private helper calls. + + Griffe ignores method-body assignments outside ``__init__``. Replay only + simple public instance assignments from reachable synchronous, undecorated helpers, + keeping existing constructor and class records unchanged. + """ + + def on_class_members(self, *, node, cls: Class, agent, **kwargs) -> None: + if not isinstance(node, ast.ClassDef) or not isinstance(agent, Visitor): + return + methods = { + method.name: method + for method in node.body + if isinstance(method, ast.FunctionDef) + and not method.decorator_list + and method.args.args + and method.args.args[0].arg == "self" + } + constructor = cls.members.get("__init__") + if not isinstance(constructor, Function) or "__init__" not in methods: + return + existing_names = set(cls.members) + previous = agent.current + try: + # Griffe's constructor visitor also stores Function despite this annotation. + agent.current = constructor # type: ignore[assignment] + self._follow( + methods["__init__"], methods, agent, existing_names, set(), False + ) + finally: + agent.current = previous + + def _follow(self, method, methods, agent, existing_names, active, in_helper): + if method.name in active: + return + active.add(method.name) + try: + # ast_children supplies parent links required by Griffe's assignment visitor. + for statement in ast_children(method): + if statement not in method.body: + continue + for node in _eager_nodes(statement): + target = _public_instance_target(node) if in_helper else None + if target is not None and target.attr not in existing_names: + agent.visit(node) + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id == "self" + and node.func.attr.startswith("_") + and not node.func.attr.startswith("__") + and node.func.attr in methods + ): + self._follow( + methods[node.func.attr], + methods, + agent, + existing_names, + active, + True, + ) + finally: + active.remove(method.name) diff --git a/.github/scripts/test_check_crap_threshold.py b/.github/scripts/test_check_crap_threshold.py new file mode 100644 index 000000000..5d697750a --- /dev/null +++ b/.github/scripts/test_check_crap_threshold.py @@ -0,0 +1,147 @@ +"""Regression tests for executable-line CRAP scoring.""" + +from pathlib import Path +import subprocess +import sys + +from coverage import CoverageData +import pytest + + +SCRIPT_PATH = Path(__file__).with_name("check_crap_threshold.py") +FUNCTION = """def choose(value): + if value == 1: + return 'one' + if value == 2: + return 'two' + if value == 3: + return 'three' + if value == 4: + return 'four' + return 'other' + +for value in range(5): + choose(value) +""" + + +def collect_coverage(tmp_path, source): + source_file = (tmp_path / "example.py").resolve() + source_file.write_text(source) + data_file = tmp_path / ".coverage" + config_file = tmp_path / ".coveragerc" + config_file.write_text("[run]\n") + subprocess.run( + [ + sys.executable, + "-m", + "coverage", + "run", + f"--rcfile={config_file}", + f"--data-file={data_file}", + str(source_file), + ], + check=True, + capture_output=True, + text=True, + ) + return source_file, data_file + + +def check(source_file, data_file, threshold): + return subprocess.run( + [ + sys.executable, + str(SCRIPT_PATH), + str(source_file), + "--coverage-file", + str(data_file), + "--max-crap", + str(threshold), + ], + capture_output=True, + text=True, + ) + + +@pytest.mark.parametrize( + "source", + [ + FUNCTION, + FUNCTION.replace( + " if value == 1:", " # Explanation\n\n" * 30 + " if value == 1:" + ), + FUNCTION.replace( + " if value == 1:", + ' """Description.\n' + + " Details.\n" * 30 + + ' """\n if value == 1:', + ), + FUNCTION.replace("def choose(value):", "def choose(\n value,\n):"), + ], + ids=["plain", "comments-and-blanks", "docstring", "multiline-signature"], +) +def test_fully_covered_function_is_unaffected_by_non_executable_lines(tmp_path, source): + source_file, data_file = collect_coverage(tmp_path, source) + result = check(source_file, data_file, 10) + assert result.returncode == 0, result.stdout + result.stderr + at_complexity_floor = check(source_file, data_file, 5) + assert at_complexity_floor.returncode == 1 + assert "CRAP=5.00, CC=5, coverage=100.0%" in at_complexity_floor.stdout + + +def test_uncovered_executable_branch_still_increases_score(tmp_path): + source_file, data_file = collect_coverage( + tmp_path, + "def choose(value):\n if value:\n return 1\n return 0\n\nchoose(True)\n", + ) + result = check(source_file, data_file, 2.0625) + assert result.returncode == 1 + assert "CRAP=2.06, CC=2, coverage=75.0%" in result.stdout + assert check(source_file, data_file, 2.0626).returncode == 0 + + +def test_coverage_exclusions_are_not_missing_statements(tmp_path): + source_file, data_file = collect_coverage( + tmp_path, + "def choose(value):\n if value: # pragma: no cover\n return 1\n return 0\n\nchoose(False)\n", + ) + result = check(source_file, data_file, 2) + assert result.returncode == 1 + assert "CRAP=2.00, CC=2, coverage=100.0%" in result.stdout + + +def test_directory_includes_unexecuted_production_and_excludes_test_helpers(tmp_path): + package = tmp_path / "posthog" + source_file = package / "ai" / "converter.py" + source_file.parent.mkdir(parents=True) + source_file.write_text( + "def choose(value):\n if value:\n return 1\n return 0\n" + ) + for directory in ("test", "tests"): + helper = package / directory / "ai" / "utils.py" + helper.parent.mkdir(parents=True) + helper.write_text("not valid Python") + data_file = tmp_path / ".coverage" + data = CoverageData(basename=str(data_file)) + data.add_lines({str(source_file.resolve()): set()}) + data.write() + result = check(package, data_file, 6) + assert result.returncode == 1 + assert "1 functions in 1 production files" in result.stdout + assert "CRAP=6.00, CC=2, coverage=0.0%" in result.stdout + assert str(source_file) in result.stdout + + +def test_missing_coverage_does_not_pass(tmp_path): + source_file = tmp_path / "example.py" + source_file.write_text("def choose():\n return 1\n") + result = check(source_file, tmp_path / ".coverage", 10) + assert result.returncode != 0 + assert "No coverage data found" in result.stderr + + +def test_empty_source_directory_does_not_pass(tmp_path): + result = check(tmp_path, tmp_path / ".coverage", 10) + assert result.returncode != 0 + assert "No production Python files found" in result.stderr diff --git a/.github/scripts/test_check_public_api.py b/.github/scripts/test_check_public_api.py index 5aa6da473..923e2a371 100644 --- a/.github/scripts/test_check_public_api.py +++ b/.github/scripts/test_check_public_api.py @@ -7,6 +7,9 @@ from pathlib import Path from types import SimpleNamespace from tempfile import TemporaryDirectory +from textwrap import dedent + +import pytest SCRIPT_PATH = Path(__file__).with_name("check_public_api.py") @@ -75,11 +78,193 @@ def test_explicit_exports_from_private_modules_include_signatures() -> None: assert not any("Hidden" in record or "_internal" in record for record in records) +def _snapshot_for_source(tmp_path, source): + package = tmp_path / "posthog" + package.mkdir(exist_ok=True) + (package / "__init__.py").write_text(dedent(source)) + checker = load_check_public_api() + checker.ROOT = tmp_path + with pytest.MonkeyPatch.context() as patch: + patch.chdir(tmp_path) + return checker.generate_snapshot() + + +def test_constructor_helpers_preserve_public_attributes(tmp_path): + snapshot = _snapshot_for_source( + tmp_path, + """ + class Client: + def __init__(self, key, before_send): + self._configure(key) + self._set_before_send(before_send) + def _configure(self, key): + self.secret_key: str = key + self._configure_more() + def _configure_more(self): + self.options = dict(enabled=True) + def _set_before_send(self, before_send): + self.before_send = before_send + """, + ) + assert "attribute posthog.Client.secret_key: str = key\n" in snapshot + assert "attribute posthog.Client.options = dict(enabled=True)\n" in snapshot + assert "attribute posthog.Client.before_send = before_send\n" in snapshot + assert "_configure" not in snapshot + + +def test_constructor_helper_cycles_do_not_leak_class_context(tmp_path): + snapshot = _snapshot_for_source( + tmp_path, + """ + class First: + def __init__(self): self._one() + def _one(self): + self.one = 1 + self._two() + def _two(self): + self.two = 2 + self._one() + class Second: + def __init__(self): self.three = 3 + module_value = 4 + """, + ) + assert "attribute posthog.First.one = 1\n" in snapshot + assert "attribute posthog.First.two = 2\n" in snapshot + assert "attribute posthog.Second.three = 3\n" in snapshot + assert "attribute posthog.module_value = 4\n" in snapshot + assert "posthog.First.three" not in snapshot + + +def test_uncalled_and_deferred_helpers_do_not_add_attributes(tmp_path): + snapshot = _snapshot_for_source( + tmp_path, + """ + class Client: + def __init__(self): + self._configure() + saved = self._unrelated + later = lambda: self._lambda_only() + deferred = (self._generator_only() for _ in range(1)) + def nested(): self._nested_only() + class Inner: + def run(inner): self._inner_only() + self.public() + other._foreign() + self._static() + self._async() + def _configure(self): + self.visible = True + self._private = False + def _unrelated(self): self.unrelated = True + def _lambda_only(self): self.lambda_only = True + def _generator_only(self): self.generator_only = True + def _nested_only(self): self.nested_only = True + def _inner_only(self): self.inner_only = True + def public(self): self.public_only = True + def _foreign(self): self.foreign_only = True + @staticmethod + def _static(self): self.static_only = True + async def _async(self): self.async_only = True + """, + ) + attributes = { + record + for record in snapshot.splitlines() + if record.startswith("attribute posthog.Client.") + } + assert attributes == {"attribute posthog.Client.visible = True"} + + +def test_direct_constructor_records_and_griffe_branch_precedence_are_preserved( + tmp_path, +): + snapshot = _snapshot_for_source( + tmp_path, + """ + class Client: + def __init__(self): + self.direct: int = 10 + self._configure() + def _configure(self): + self.direct = 20 + if condition: + self.branch = "first" + else: + self.branch = "second" + self.root = None + if self.root is None: + try: + self.root = getcwd() + except Exception: + self.root = None + """, + ) + assert "attribute posthog.Client.direct: int = 10\n" in snapshot + assert "attribute posthog.Client.branch = 'first'\n" in snapshot + assert "attribute posthog.Client.root = getcwd()\n" in snapshot + + +def test_helper_attribute_changes_remain_visible_in_snapshot(tmp_path): + source = """ + class Client: + def __init__(self): self._configure() + def _configure(self): self.visible = True + """ + before = _snapshot_for_source(tmp_path, source) + removed = _snapshot_for_source( + tmp_path, source.replace("self.visible = True", "pass") + ) + changed = _snapshot_for_source( + tmp_path, source.replace("self.visible = True", "self.visible = False") + ) + assert "attribute posthog.Client.visible = True\n" in before + assert "attribute posthog.Client.visible" not in removed + assert "attribute posthog.Client.visible = False\n" in changed + + +def test_constructor_discovery_retains_builtin_dataclass_processing(tmp_path): + snapshot = _snapshot_for_source( + tmp_path, + """ + from dataclasses import dataclass + @dataclass + class Record: + value: str + """, + ) + assert "class posthog.Record(value: str)\n" in snapshot + + +def test_constructor_helper_discovery_restores_visitor_after_failure(monkeypatch): + import ast + import griffe + from constructor_helper_attributes import ConstructorHelperAttributes + + cls = griffe.Class("Client") + constructor = griffe.Function("__init__", parent=cls) + cls.set_member("__init__", constructor) + source = ( + "class Client:\n" + " def __init__(self): self._helper()\n" + " def _helper(self): self.value = 1\n" + ) + agent = griffe.Visitor("sample", Path("sample.py"), source, griffe.Extensions()) + agent.current = cls + + def fail_to_visit(node): + raise RuntimeError("sentinel") + + monkeypatch.setattr(agent, "visit", fail_to_visit) + with pytest.raises(RuntimeError, match="sentinel"): + ConstructorHelperAttributes().on_class_members( + node=ast.parse(source).body[0], cls=cls, agent=agent + ) + assert agent.current is cls + + def main() -> int: - test_attribute_details_uses_placeholder_values() - test_explicit_exports_from_private_modules_include_signatures() - print("check_public_api tests passed.") - return 0 + return pytest.main([str(Path(__file__)), "--timeout=30", "-q"]) if __name__ == "__main__": diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d8b16e245..55055eb4c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,7 +74,7 @@ jobs: - name: Check public API snapshot run: | - python .github/scripts/test_check_public_api.py + UV_PROJECT_ENVIRONMENT=$pythonLocation uv run --extra dev --with pytest --with pytest-timeout python .github/scripts/test_check_public_api.py make public_api_check strict-type-smoke: @@ -235,7 +235,12 @@ jobs: changed_files="$(git diff --name-only "$base" "$head" -- \ posthog/utils.py \ posthog/test/test_utils.py \ - posthog/test/test_size_limited_dict.py)" + posthog/test/test_size_limited_dict.py \ + .github/scripts/check_crap_threshold.py \ + .github/scripts/test_check_crap_threshold.py \ + .github/workflows/ci.yml \ + pyproject.toml \ + uv.lock)" if [[ -n "$changed_files" ]]; then echo "changed=true" >> "$GITHUB_OUTPUT" @@ -264,7 +269,8 @@ jobs: shell: bash run: | set -euo pipefail - UV_PROJECT_ENVIRONMENT=$pythonLocation uv run --extra test --with pytest-crap --with pytest-cov pytest posthog/test/test_utils.py posthog/test/test_size_limited_dict.py --timeout=30 --cov=posthog.utils --crap --crap-threshold=10 --crap-top-n=40 -q + UV_PROJECT_ENVIRONMENT=$pythonLocation uv run --extra test --with pytest-crap --with pytest-cov pytest .github/scripts/test_check_crap_threshold.py --timeout=30 -q + UV_PROJECT_ENVIRONMENT=$pythonLocation uv run --extra test --with pytest-crap --with pytest-cov pytest posthog/test/test_utils.py posthog/test/test_size_limited_dict.py --timeout=30 --cov=posthog.utils -q UV_PROJECT_ENVIRONMENT=$pythonLocation uv run --extra test --with pytest-crap --with pytest-cov python .github/scripts/check_crap_threshold.py posthog/utils.py --max-crap 10 import-check: diff --git a/posthog/__init__.py b/posthog/__init__.py index 705c4e5b7..3b5f1f876 100644 --- a/posthog/__init__.py +++ b/posthog/__init__.py @@ -1476,11 +1476,7 @@ def setup() -> Client: default_client.debug = debug default_client.privacy_mode = bool(privacy_mode) default_client._set_before_send(before_send) - default_client.enable_full_ai_capture = ( - bool(enable_full_ai_capture) - or bool(_use_ai_lane) - or bool(_enable_multimodal_capture) - ) + default_client.enable_full_ai_capture = _full_ai_capture_enabled() # Metrics config is consumed lazily on first `.metrics` access, so late # module-attr assignment (e.g. a Django ready() hook running after something # already forced setup()) still applies until the metrics API is first used. @@ -1496,6 +1492,14 @@ def setup() -> Client: return default_client +def _full_ai_capture_enabled() -> bool: + return ( + bool(enable_full_ai_capture) + or bool(_use_ai_lane) + or bool(_enable_multimodal_capture) + ) + + def _proxy(method, *args, **kwargs): """Create an analytics client if one doesn't exist and send to it.""" setup() diff --git a/posthog/_async_consumer.py b/posthog/_async_consumer.py index 5bdfd33f1..87f86f652 100644 --- a/posthog/_async_consumer.py +++ b/posthog/_async_consumer.py @@ -165,17 +165,58 @@ async def upload(self, batch: list[dict[str, Any]]) -> None: for _ in batch: self.queue.task_done() - async def next(self) -> tuple[list[dict[str, Any]], bool]: - items: list[dict[str, Any]] = [] - total_size = 0 - stop = False - started = asyncio.get_running_loop().time() + async def _prepare_queued_event( + self, queued: _QueuedEvent + ) -> Optional[tuple[dict[str, Any], int]]: + try: + process_task = queued.context.run( + asyncio.create_task, self._process_queued_event(queued.event) + ) + item = await process_task + except Exception as error: + self.log.error( + "unable to process queued event, dropping (%s)", + type(error).__name__, + ) + self.queue.task_done() + return None + if item is None: + self.queue.task_done() + return None + + try: + item_size = await _serialized_event_size(item) + except Exception: + self.log.error("unable to serialize queued event for sizing, dropping") + self.queue.task_done() + return None + + if item_size > MAX_MSG_SIZE: + self.log.error( + "Event %s (%d bytes) exceeds the %dKiB limit, dropping.", + item.get("event"), + item_size, + MAX_MSG_SIZE // 1024, + ) + self.queue.task_done() + return None + return item, item_size + + def _take_carryover(self, items: list[dict[str, Any]]) -> int: if self._carryover is not None: carried_item, carried_size = self._carryover self._carryover = None items.append(carried_item) - total_size = carried_size + return carried_size + return 0 + + async def next(self) -> tuple[list[dict[str, Any]], bool]: + items: list[dict[str, Any]] = [] + stop = False + started = asyncio.get_running_loop().time() + + total_size = self._take_carryover(items) while len(items) < self.flush_at: remaining = self.flush_interval - ( @@ -193,39 +234,10 @@ async def next(self) -> tuple[list[dict[str, Any]], bool]: stop = True break - try: - process_task = queued.context.run( - asyncio.create_task, self._process_queued_event(queued.event) - ) - item = await process_task - except Exception as error: - self.log.error( - "unable to process queued event, dropping (%s)", - type(error).__name__, - ) - self.queue.task_done() - continue - - if item is None: - self.queue.task_done() - continue - - try: - item_size = await _serialized_event_size(item) - except Exception: - self.log.error("unable to serialize queued event for sizing, dropping") - self.queue.task_done() - continue - - if item_size > MAX_MSG_SIZE: - self.log.error( - "Event %s (%d bytes) exceeds the %dKiB limit, dropping.", - item.get("event"), - item_size, - MAX_MSG_SIZE // 1024, - ) - self.queue.task_done() + prepared = await self._prepare_queued_event(queued) + if prepared is None: continue + item, item_size = prepared if items and total_size + item_size > BATCH_SIZE_LIMIT: self._carryover = (item, item_size) diff --git a/posthog/_async_request.py b/posthog/_async_request.py index 50dfe829c..ff407687f 100644 --- a/posthog/_async_request.py +++ b/posthog/_async_request.py @@ -236,18 +236,9 @@ async def async_batch_post( _process_response(response) return - location = response.headers.get("Location") or response.headers.get( - "location" + redirect_url = _capture_redirect_url( + base_url, request_url, response, redirect_count ) - redirect_url = ( - _same_origin_redirect_url(base_url, request_url, location) - if location - else None - ) - if redirect_url is None: - raise APIError(400, "Cross-origin or invalid redirect blocked") - if redirect_count >= 5: - raise APIError(400, "Too many capture redirects") request_url = redirect_url finally: if owns_client: @@ -275,3 +266,17 @@ async def async_send_v1_batch( max_retries=max_retries, historical_migration=historical_migration, ) + + +def _capture_redirect_url( + base_url: str, request_url: str, response: Any, redirect_count: int +) -> str: + location = response.headers.get("Location") or response.headers.get("location") + redirect_url = ( + _same_origin_redirect_url(base_url, request_url, location) if location else None + ) + if redirect_url is None: + raise APIError(400, "Cross-origin or invalid redirect blocked") + if redirect_count >= 5: + raise APIError(400, "Too many capture redirects") + return redirect_url diff --git a/posthog/_async_utils.py b/posthog/_async_utils.py index f81d6964b..b62cf19ba 100644 --- a/posthog/_async_utils.py +++ b/posthog/_async_utils.py @@ -139,13 +139,9 @@ async def _await_result(awaitable: Awaitable[Any]) -> Any: def _ensure_loop(self) -> asyncio.AbstractEventLoop: with self._lock: - if ( - self._loop is not None - and self._thread is not None - and self._thread.is_alive() - and not self._loop.is_closed() - ): - return self._loop + ready_loop = self._ready_loop() + if ready_loop is not None: + return ready_loop startup: _LoopStartup if self._thread is None or not self._thread.is_alive(): @@ -176,30 +172,10 @@ def _run_loop(self, startup: _LoopStartup) -> None: loop = None try: loop = asyncio.new_event_loop() - original_run_in_executor = loop.run_in_executor - - def run_in_executor(executor, func, *args): - call = _ContextExecutorCall(copy_context(), func, args) - return original_run_in_executor(executor, call) - - try: - setattr(loop, "run_in_executor", run_in_executor) - except (AttributeError, TypeError): - # A loop that cannot carry callback context is unsafe for - # lifecycle re-entry from executor threads. Use the equivalent - # context-aware platform loop rather than silently losing it. - loop.close() - loop = _ContextEventLoop() + loop = self._install_context_executor(loop) asyncio.set_event_loop(loop) except BaseException as error: - if loop is not None and not loop.is_closed(): - loop.close() - with self._lock: - if startup.error is None: - startup.error = error - if self._thread is threading.current_thread(): - self._thread = None - startup.done.set() + self._fail_startup(startup, loop, error) return with self._lock: @@ -216,17 +192,7 @@ def run_in_executor(executor, func, *args): try: loop.run_forever() finally: - pending = asyncio.all_tasks(loop) - for task in pending: - task.cancel() - if pending: - loop.run_until_complete( - asyncio.gather(*pending, return_exceptions=True) - ) - loop.run_until_complete(loop.shutdown_asyncgens()) - loop.run_until_complete(loop.shutdown_default_executor()) - asyncio.set_event_loop(None) - loop.close() + self._close_loop(loop) current = threading.current_thread() with self._lock: if self._thread is current: @@ -236,3 +202,60 @@ def run_in_executor(executor, func, *args): if self._startup is startup: self._startup = None self._closing_threads.discard(current) + + def _ready_loop(self) -> asyncio.AbstractEventLoop | None: + if ( + self._loop is not None + and self._thread is not None + and self._thread.is_alive() + and not self._loop.is_closed() + ): + return self._loop + return None + + @staticmethod + def _close_loop(loop: asyncio.AbstractEventLoop) -> None: + pending = asyncio.all_tasks(loop) + for task in pending: + task.cancel() + if pending: + loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True)) + loop.run_until_complete(loop.shutdown_asyncgens()) + loop.run_until_complete(loop.shutdown_default_executor()) + asyncio.set_event_loop(None) + loop.close() + + @staticmethod + def _install_context_executor( + loop: asyncio.AbstractEventLoop, + ) -> asyncio.AbstractEventLoop: + original_run_in_executor = loop.run_in_executor + + def run_in_executor(executor, func, *args): + call = _ContextExecutorCall(copy_context(), func, args) + return original_run_in_executor(executor, call) + + try: + setattr(loop, "run_in_executor", run_in_executor) + except (AttributeError, TypeError): + # A loop that cannot carry callback context is unsafe for + # lifecycle re-entry from executor threads. Use the equivalent + # context-aware platform loop rather than silently losing it. + loop.close() + loop = _ContextEventLoop() + return loop + + def _fail_startup( + self, + startup: _LoopStartup, + loop: asyncio.AbstractEventLoop | None, + error: BaseException, + ) -> None: + if loop is not None and not loop.is_closed(): + loop.close() + with self._lock: + if startup.error is None: + startup.error = error + if self._thread is threading.current_thread(): + self._thread = None + startup.done.set() diff --git a/posthog/_metrics_autocapture.py b/posthog/_metrics_autocapture.py index 4771f2d5a..73fde54bf 100644 --- a/posthog/_metrics_autocapture.py +++ b/posthog/_metrics_autocapture.py @@ -230,11 +230,7 @@ def _clean_attributes(attributes: Any) -> Any: return None cleaned: Dict[str, Any] = {} for key, value in items: - if ( - not isinstance(key, str) - or key in _UNSAFE_ATTRIBUTES - or key.startswith(_UNSAFE_ATTRIBUTE_PREFIXES) - ): + if not _safe_attribute_key(key): continue if isinstance(value, _ATTRIBUTE_VALUE_TYPES): cleaned[key] = value @@ -730,7 +726,7 @@ def on_end(self, span): ) def _record(self, span): - from opentelemetry.trace import SpanKind, StatusCode + from opentelemetry.trace import SpanKind scope = getattr(span, "instrumentation_scope", None) if ( @@ -742,42 +738,7 @@ def _record(self, span): system = _first_string(attributes, ("db.system.name", "db.system")) if not system or span.start_time is None or span.end_time is None: return - metric_attributes: Dict[str, Any] = {"db.system.name": system} - operation = _first_string(attributes, ("db.operation.name", "db.operation")) - if operation is None: - statement = _first_string(attributes, ("db.query.text", "db.statement")) - match = _STATEMENT_KEYWORD.match(statement or "") - operation = match.group(1).upper() if match else None - else: - # Only the leading keyword is bounded, as for a statement. - words = operation.split() - operation = words[0] if words else None - collection = _first_string( - attributes, - ( - "db.collection.name", - "db.mongodb.collection", - "db.sql.table", - "db.cassandra.table", - ), - ) - namespace = _first_string(attributes, ("db.namespace", "db.name")) - address = _first_string(attributes, ("server.address", "net.peer.name")) - port = attributes.get("server.port", attributes.get("net.peer.port")) - if operation: - metric_attributes["db.operation.name"] = operation - if collection: - metric_attributes["db.collection.name"] = collection - if namespace: - metric_attributes["db.namespace"] = namespace - if address: - metric_attributes["server.address"] = address - if isinstance(port, int) and not isinstance(port, bool): - metric_attributes["server.port"] = port - if span.status.status_code == StatusCode.ERROR: - metric_attributes["error.type"] = ( - _first_string(attributes, ("error.type",)) or "_OTHER" - ) + metric_attributes = _db_metric_attributes(span, attributes, system) self._histogram.record( (span.end_time - span.start_time) / 1e9, metric_attributes ) @@ -1103,73 +1064,23 @@ def start_metrics_autocapture( instrumentors: List[Any] = [] stopped = threading.Event() try: - if not _is_default_provider( - metrics_api.get_meter_provider() - ) or not _is_default_provider(trace_api.get_tracer_provider()): - log.warning( - "OpenTelemetry is already set up in this process, so metrics autocapture does not start. " - "Point your OTLP metrics exporter at PostHog instead: https://posthog.com/docs/metrics" - ) + if not _autocapture_providers_available(metrics_api, trace_api): return None - # The same resource as `client.metrics`: the OTEL_SERVICE_NAME and - # OTEL_RESOURCE_ATTRIBUTES of the app are not read. - resource = sdk_resources.Resource( - { - **resource_attributes, - "service.name": service_name or "unknown_service", - "telemetry.sdk.language": "python", - "telemetry.sdk.name": "opentelemetry", - "telemetry.sdk.version": _import_module( - "opentelemetry.sdk.version" - ).__version__, - "telemetry.distro.name": "posthog-python", - "telemetry.distro.version": VERSION, - } + resource = _autocapture_resource( + sdk_resources, service_name, resource_attributes ) reader = _metric_reader if reader is None: - exporter_base: Any = otlp.OTLPMetricExporter - delta = sdk_metrics_export.AggregationTemporality.DELTA - cumulative = sdk_metrics_export.AggregationTemporality.CUMULATIVE - - class _GatedExporter(exporter_base): - # The exporter still sends while the client is disabled unless it is gated here. - def export(self, metrics_data, timeout_millis=10_000, **kwargs): - if not is_enabled(): - return sdk_metrics_export.MetricExportResult.SUCCESS - return super().export( - metrics_data, timeout_millis=timeout_millis, **kwargs - ) - - exporter = _GatedExporter( - endpoint=f"{host}/i/v1/metrics", - headers={"Authorization": f"Bearer {api_key}"}, - timeout=_EXPORT_TIMEOUT_SECONDS, - compression=_import_module( - "opentelemetry.exporter.otlp.proto.http" - ).Compression.NoCompression, - session=_metrics_export_session(api_key), - # Delta, like the `posthog.metrics` wire shape; values that go - # up and down stay cumulative. - preferred_temporality={ - sdk_metrics.Counter: delta, - sdk_metrics.Histogram: delta, - sdk_metrics.ObservableCounter: delta, - sdk_metrics.UpDownCounter: cumulative, - sdk_metrics.ObservableUpDownCounter: cumulative, - sdk_metrics.ObservableGauge: cumulative, - }, - preferred_aggregation={ - sdk_metrics.Histogram: _import_module( - "opentelemetry.sdk.metrics.view" - ).ExplicitBucketHistogramAggregation(), - }, - ) - reader = sdk_metrics_export.PeriodicExportingMetricReader( - exporter, - export_interval_millis=(export_interval_seconds or 10.0) * 1000, + reader = _autocapture_metric_reader( + otlp, + sdk_metrics, + sdk_metrics_export, + host, + api_key, + is_enabled, + export_interval_seconds, ) # The client exports the last window at exit, within its exit budget. # The provider's own exit hook waits up to the export timeout, also @@ -1225,79 +1136,15 @@ def get_description(self): ) ) - posthog_url_pattern = _posthog_url_pattern(host) - wanted = set(_instrumentor_names(areas)) - with _stable_http_semconv(): - for entry_point in entry_points(group="opentelemetry_instrumentor"): - if entry_point.name not in wanted: - continue - if ( - entry_point.name == "django" - and not _django_settings_configured() - ): - # Without settings, the Django instrumentor configures empty - # ones, and the app's own settings.configure() then fails. - # In AppConfig.ready() the settings are configured. - log.debug( - "Metrics autocapture skipped django: its settings are not configured yet" - ) - continue - try: - kwargs: Dict[str, Any] = { - "tracer_provider": tracer_provider - if entry_point.name in _DB_INSTRUMENTORS - else no_op_tracer_provider, - "meter_provider": bounded_meter_provider, - } - environ: Dict[str, Optional[str]] = {} - if entry_point.name in _HTTP_CLIENT_INSTRUMENTORS: - # PostHog's own uploads, including this exporter's, are not app traffic. - variable, excluded = _excluded_urls( - entry_point.name, posthog_url_pattern - ) - kwargs["excluded_urls"] = excluded - environ[variable] = excluded - with _patched_environ(environ): - instrumentor_class = entry_point.load() - # Instrumentors are singletons, and creating one runs - # `__init__` again on the existing instance. That would - # reset the config of an instance that the app uses. - existing = getattr(instrumentor_class, "_instance", None) - if ( - existing is not None - and existing.is_instrumented_by_opentelemetry - ): - continue - instrumentor = ( - instrumentor_class(config=_RUNTIME_CONFIG) - if entry_point.name == "system_metrics" - else instrumentor_class() - ) - if instrumentor.is_instrumented_by_opentelemetry: - # The app instrumented this library itself. - continue - instrumentor.instrument(**kwargs) - if instrumentor.is_instrumented_by_opentelemetry: - instrumentors.append(instrumentor) - _disable_propagation(instrumentor_class) - if entry_point.name == "aiohttp-client": - _gate_aiohttp_trace_configs( - bounded_meter_provider, stopped, posthog_url_pattern - ) - if entry_point.name == "flask": - _track_flask_apps( - instrumentor_class, - { - "tracer_provider": no_op_tracer_provider, - "meter_provider": bounded_meter_provider, - }, - ) - except Exception: - log.debug( - "Metrics autocapture skipped %s", - entry_point.name, - exc_info=True, - ) + _instrument_metrics_libraries( + instrumentors, + areas, + host, + tracer_provider, + no_op_tracer_provider, + bounded_meter_provider, + stopped, + ) _active = MetricsAutocapture( meter_provider, tracer_provider, instrumentors, reader, stopped @@ -1310,3 +1157,247 @@ def get_description(self): _uninstrument(instrumentors) _shut_down(tracer_provider, meter_provider or reader) return None + + +def _safe_attribute_key(key: Any) -> bool: + return ( + isinstance(key, str) + and key not in _UNSAFE_ATTRIBUTES + and not key.startswith(_UNSAFE_ATTRIBUTE_PREFIXES) + ) + + +def _db_operation(attributes: Any) -> Optional[str]: + operation = _first_string(attributes, ("db.operation.name", "db.operation")) + if operation is None: + statement = _first_string(attributes, ("db.query.text", "db.statement")) + match = _STATEMENT_KEYWORD.match(statement or "") + operation = match.group(1).upper() if match else None + else: + # Only the leading keyword is bounded, as for a statement. + words = operation.split() + operation = words[0] if words else None + return operation + + +def _db_metric_attributes(span: Any, attributes: Any, system: str) -> Dict[str, Any]: + from opentelemetry.trace import StatusCode + + metric_attributes: Dict[str, Any] = {"db.system.name": system} + operation = _db_operation(attributes) + collection = _first_string( + attributes, + ( + "db.collection.name", + "db.mongodb.collection", + "db.sql.table", + "db.cassandra.table", + ), + ) + namespace = _first_string(attributes, ("db.namespace", "db.name")) + address = _first_string(attributes, ("server.address", "net.peer.name")) + port = attributes.get("server.port", attributes.get("net.peer.port")) + if operation: + metric_attributes["db.operation.name"] = operation + if collection: + metric_attributes["db.collection.name"] = collection + if namespace: + metric_attributes["db.namespace"] = namespace + if address: + metric_attributes["server.address"] = address + if isinstance(port, int) and not isinstance(port, bool): + metric_attributes["server.port"] = port + if span.status.status_code == StatusCode.ERROR: + metric_attributes["error.type"] = ( + _first_string(attributes, ("error.type",)) or "_OTHER" + ) + return metric_attributes + + +def _instrument_metrics_libraries( + instrumentors: List[Any], + areas: Dict[str, bool], + host: str, + tracer_provider: Any, + no_op_tracer_provider: Any, + bounded_meter_provider: Any, + stopped: threading.Event, +) -> None: + posthog_url_pattern = _posthog_url_pattern(host) + wanted = set(_instrumentor_names(areas)) + with _stable_http_semconv(): + for entry_point in entry_points(group="opentelemetry_instrumentor"): + if entry_point.name not in wanted: + continue + if entry_point.name == "django" and not _django_settings_configured(): + # Without settings, the Django instrumentor configures empty + # ones, and the app's own settings.configure() then fails. + # In AppConfig.ready() the settings are configured. + log.debug( + "Metrics autocapture skipped django: its settings are not configured yet" + ) + continue + try: + _instrument_metric_library( + entry_point, + instrumentors, + tracer_provider, + no_op_tracer_provider, + bounded_meter_provider, + stopped, + posthog_url_pattern, + ) + except Exception: + log.debug( + "Metrics autocapture skipped %s", + entry_point.name, + exc_info=True, + ) + + +def _instrument_metric_library( + entry_point: Any, + instrumentors: List[Any], + tracer_provider: Any, + no_op_tracer_provider: Any, + bounded_meter_provider: Any, + stopped: threading.Event, + posthog_url_pattern: str, +) -> None: + kwargs: Dict[str, Any] = { + "tracer_provider": tracer_provider + if entry_point.name in _DB_INSTRUMENTORS + else no_op_tracer_provider, + "meter_provider": bounded_meter_provider, + } + environ: Dict[str, Optional[str]] = {} + if entry_point.name in _HTTP_CLIENT_INSTRUMENTORS: + # PostHog's own uploads, including this exporter's, are not app traffic. + variable, excluded = _excluded_urls(entry_point.name, posthog_url_pattern) + kwargs["excluded_urls"] = excluded + environ[variable] = excluded + with _patched_environ(environ): + instrumentor_class = entry_point.load() + instrumentor = _new_metric_instrumentor(instrumentor_class, entry_point.name) + if instrumentor is None: + return + instrumentor.instrument(**kwargs) + if instrumentor.is_instrumented_by_opentelemetry: + instrumentors.append(instrumentor) + _disable_propagation(instrumentor_class) + if entry_point.name == "aiohttp-client": + _gate_aiohttp_trace_configs( + bounded_meter_provider, stopped, posthog_url_pattern + ) + if entry_point.name == "flask": + _track_flask_apps( + instrumentor_class, + { + "tracer_provider": no_op_tracer_provider, + "meter_provider": bounded_meter_provider, + }, + ) + + +def _new_metric_instrumentor(instrumentor_class: Any, name: str) -> Any: + # Instrumentors are singletons, and creating one runs + # `__init__` again on the existing instance. That would + # reset the config of an instance that the app uses. + existing = getattr(instrumentor_class, "_instance", None) + if existing is not None and existing.is_instrumented_by_opentelemetry: + return None + instrumentor = ( + instrumentor_class(config=_RUNTIME_CONFIG) + if name == "system_metrics" + else instrumentor_class() + ) + if instrumentor.is_instrumented_by_opentelemetry: + # The app instrumented this library itself. + return None + return instrumentor + + +def _autocapture_metric_reader( + otlp: Any, + sdk_metrics: Any, + sdk_metrics_export: Any, + host: str, + api_key: str, + is_enabled: Callable[[], bool], + export_interval_seconds: Optional[float], +) -> Any: + exporter_base: Any = otlp.OTLPMetricExporter + delta = sdk_metrics_export.AggregationTemporality.DELTA + cumulative = sdk_metrics_export.AggregationTemporality.CUMULATIVE + + class _GatedExporter(exporter_base): + # The exporter still sends while the client is disabled unless it is gated here. + def export(self, metrics_data, timeout_millis=10_000, **kwargs): + if not is_enabled(): + return sdk_metrics_export.MetricExportResult.SUCCESS + return super().export(metrics_data, timeout_millis=timeout_millis, **kwargs) + + exporter = _GatedExporter( + endpoint=f"{host}/i/v1/metrics", + headers={"Authorization": f"Bearer {api_key}"}, + timeout=_EXPORT_TIMEOUT_SECONDS, + compression=_import_module( + "opentelemetry.exporter.otlp.proto.http" + ).Compression.NoCompression, + session=_metrics_export_session(api_key), + # Delta, like the `posthog.metrics` wire shape; values that go + # up and down stay cumulative. + preferred_temporality={ + sdk_metrics.Counter: delta, + sdk_metrics.Histogram: delta, + sdk_metrics.ObservableCounter: delta, + sdk_metrics.UpDownCounter: cumulative, + sdk_metrics.ObservableUpDownCounter: cumulative, + sdk_metrics.ObservableGauge: cumulative, + }, + preferred_aggregation={ + sdk_metrics.Histogram: _import_module( + "opentelemetry.sdk.metrics.view" + ).ExplicitBucketHistogramAggregation(), + }, + ) + reader = sdk_metrics_export.PeriodicExportingMetricReader( + exporter, + export_interval_millis=(export_interval_seconds or 10.0) * 1000, + ) + return reader + + +def _autocapture_resource( + sdk_resources: Any, service_name: Optional[str], resource_attributes: Dict[str, Any] +) -> Any: + # The same resource as `client.metrics`: the OTEL_SERVICE_NAME and + # OTEL_RESOURCE_ATTRIBUTES of the app are not read. + resource = sdk_resources.Resource( + { + **resource_attributes, + "service.name": service_name or "unknown_service", + "telemetry.sdk.language": "python", + "telemetry.sdk.name": "opentelemetry", + "telemetry.sdk.version": _import_module( + "opentelemetry.sdk.version" + ).__version__, + "telemetry.distro.name": "posthog-python", + "telemetry.distro.version": VERSION, + } + ) + + return resource + + +def _autocapture_providers_available(metrics_api: Any, trace_api: Any) -> bool: + if not _is_default_provider( + metrics_api.get_meter_provider() + ) or not _is_default_provider(trace_api.get_tracer_provider()): + log.warning( + "OpenTelemetry is already set up in this process, so metrics autocapture does not start. " + "Point your OTLP metrics exporter at PostHog instead: https://posthog.com/docs/metrics" + ) + return False + + return True diff --git a/posthog/ai/anthropic/_anthropic_stream.py b/posthog/ai/anthropic/_anthropic_stream.py index 7c76cc369..f02ee9bf9 100644 --- a/posthog/ai/anthropic/_anthropic_stream.py +++ b/posthog/ai/anthropic/_anthropic_stream.py @@ -53,38 +53,10 @@ def consume(self, event: Any) -> None: event_usage = extract_anthropic_usage_from_event(event) merge_usage_stats(self.usage_stats, event_usage) if getattr(event, "type", None) == "message_delta": - usage = getattr(event, "usage", None) - self._apply_cumulative_input_usage(usage) - output_tokens = getattr(usage, "output_tokens", None) - if isinstance(output_tokens, int) and not isinstance(output_tokens, bool): - # output_tokens on a message_delta is cumulative too, so the - # incremental merge above must not stack successive deltas - # (server tools can emit several in one stream). Keep the - # latest total; a field the event omits leaves the prior one. - self.usage_stats["output_tokens"] = output_tokens - # thinking tokens on a message_delta are cumulative as well - thinking_tokens = extract_anthropic_usage_from_event(event).get( - "reasoning_tokens" - ) - if thinking_tokens is not None: - self.usage_stats["reasoning_tokens"] = thinking_tokens + self._apply_delta_usage(event) if getattr(event, "type", None) == "content_block_start": - block, tool = handle_anthropic_content_block_start(event) - - self._blocks_by_index.append(block or {}) - - if block: - self.content_blocks.append(block) - if block.get("type") in ("text", "thinking"): - self.current_text_block = block - else: - self.current_text_block = None - - if tool: - tool_id = tool["block"].get("id") - if tool_id: - self.tools_in_progress[tool_id] = tool + self._start_block(event) delta_text = handle_anthropic_text_delta(event, self.current_text_block) if delta_text: @@ -105,3 +77,37 @@ def consume(self, event: Any) -> None: delta_stop_reason = getattr(delta, "stop_reason", None) if delta_stop_reason is not None: self.stop_reason = delta_stop_reason + + def _apply_delta_usage(self, event: Any) -> None: + usage = getattr(event, "usage", None) + self._apply_cumulative_input_usage(usage) + output_tokens = getattr(usage, "output_tokens", None) + if isinstance(output_tokens, int) and not isinstance(output_tokens, bool): + # output_tokens on a message_delta is cumulative too, so the + # incremental merge above must not stack successive deltas + # (server tools can emit several in one stream). Keep the + # latest total; a field the event omits leaves the prior one. + self.usage_stats["output_tokens"] = output_tokens + # thinking tokens on a message_delta are cumulative as well + thinking_tokens = extract_anthropic_usage_from_event(event).get( + "reasoning_tokens" + ) + if thinking_tokens is not None: + self.usage_stats["reasoning_tokens"] = thinking_tokens + + def _start_block(self, event: Any) -> None: + block, tool = handle_anthropic_content_block_start(event) + + self._blocks_by_index.append(block or {}) + + if block: + self.content_blocks.append(block) + if block.get("type") in ("text", "thinking"): + self.current_text_block = block + else: + self.current_text_block = None + + if tool: + tool_id = tool["block"].get("id") + if tool_id: + self.tools_in_progress[tool_id] = tool diff --git a/posthog/ai/anthropic/anthropic_converter.py b/posthog/ai/anthropic/anthropic_converter.py index 1ee525e72..b4734d206 100644 --- a/posthog/ai/anthropic/anthropic_converter.py +++ b/posthog/ai/anthropic/anthropic_converter.py @@ -6,7 +6,7 @@ """ import json -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Literal, Optional, Tuple from posthog.ai.media import to_plain from posthog.ai.types import ( @@ -42,57 +42,9 @@ def format_anthropic_response(response: Any) -> List[FormattedMessage]: # Process content blocks from the response if hasattr(response, "content"): for choice in response.content: - if ( - hasattr(choice, "type") - and choice.type == "text" - and hasattr(choice, "text") - and choice.text - ): - text_content: FormattedTextContent = { - "type": "text", - "text": choice.text, - } - content.append(text_content) - - elif ( - hasattr(choice, "type") - and choice.type == "tool_use" - and hasattr(choice, "name") - and hasattr(choice, "id") - ): - function_call: FormattedFunctionCall = { - "type": "function", - "id": choice.id, - "function": { - "name": choice.name, - "arguments": getattr(choice, "input", {}), - }, - } - content.append(function_call) - - elif getattr(choice, "type", None) == "thinking": - content.append( - { - "type": "thinking", - "thinking": getattr(choice, "thinking", None), - "signature": getattr(choice, "signature", None), - } - ) - - elif getattr(choice, "type", None) == "redacted_thinking": - content.append( - { - "type": "redacted_thinking", - "data": getattr(choice, "data", None), - } - ) - - else: - # Catches blocks the branches above skip on falsy values (e.g. TextBlock(text="")) - # so empty-but-valid content survives instead of being silently dropped. - plain = to_plain(choice) - if isinstance(plain, dict) and plain.get("type"): - content.append(plain) + block = _format_anthropic_response_block(choice) + if block is not None: + content.append(block) if content: message: FormattedMessage = { @@ -272,15 +224,7 @@ def extract_anthropic_usage_from_response(response: Any) -> TokenUsage: if output_tokens is not None: result["output_tokens"] = output_tokens - if hasattr(response.usage, "cache_read_input_tokens"): - cache_read = response.usage.cache_read_input_tokens - if cache_read and cache_read > 0: - result["cache_read_input_tokens"] = cache_read - - if hasattr(response.usage, "cache_creation_input_tokens"): - cache_creation = response.usage.cache_creation_input_tokens - if cache_creation and cache_creation > 0: - result["cache_creation_input_tokens"] = cache_creation + _add_anthropic_cache_usage(result, response.usage) thinking_tokens = _extract_thinking_tokens(response.usage) if thinking_tokens > 0: @@ -312,21 +256,7 @@ def extract_anthropic_usage_from_event(event: Any) -> TokenUsage: usage: TokenUsage = TokenUsage() - # Handle usage stats from message_start event - if hasattr(event, "type") and event.type == "message_start": - if hasattr(event, "message") and hasattr(event.message, "usage"): - usage["input_tokens"] = getattr(event.message.usage, "input_tokens", 0) - usage["cache_creation_input_tokens"] = getattr( - event.message.usage, "cache_creation_input_tokens", 0 - ) - usage["cache_read_input_tokens"] = getattr( - event.message.usage, "cache_read_input_tokens", 0 - ) - # Capture raw usage metadata for backend processing - # Serialize to dict here in the converter (not in utils) - serialized = serialize_raw_usage(event.message.usage) - if serialized: - usage["raw_usage"] = serialized + usage.update(_extract_anthropic_start_usage(event)) # Handle usage stats from message_delta event if hasattr(event, "usage") and event.usage: @@ -374,42 +304,7 @@ def handle_anthropic_content_block_start( if not hasattr(event, "content_block"): return None, None - block = event.content_block - - if not hasattr(block, "type"): - return None, None - - if block.type == "text": - content_block: StreamingContentBlock = {"type": "text", "text": ""} - return content_block, None - - elif block.type == "tool_use": - tool_block: StreamingContentBlock = { - "type": "function", - "id": getattr(block, "id", ""), - "function": {"name": getattr(block, "name", ""), "arguments": {}}, - } - tool_in_progress: ToolInProgress = {"block": tool_block, "input_string": ""} - return tool_block, tool_in_progress - - elif block.type == "thinking": - thinking_block: StreamingContentBlock = { - "type": "thinking", - "thinking": getattr(block, "thinking", "") or "", - } - signature = getattr(block, "signature", None) - if signature: - thinking_block["signature"] = signature - return thinking_block, None - - elif block.type == "redacted_thinking": - redacted_block: StreamingContentBlock = { - "type": "redacted_thinking", - "data": getattr(block, "data", None), - } - return redacted_block, None - - return None, None + return _start_anthropic_block(event.content_block) def handle_anthropic_text_delta( @@ -442,24 +337,7 @@ def handle_anthropic_text_delta( return delta_text - if hasattr(event, "delta") and hasattr(event.delta, "thinking"): - delta_thinking = event.delta.thinking or "" - - if current_block is not None and current_block.get("type") == "thinking": - thinking_val = current_block.get("thinking") - current_block["thinking"] = (thinking_val or "") + delta_thinking - - return None - - if hasattr(event, "delta") and hasattr(event.delta, "signature"): - delta_signature = event.delta.signature or "" - - if current_block is not None and current_block.get("type") == "thinking": - signature_val = current_block.get("signature") - current_block["signature"] = (signature_val or "") + delta_signature - - return None - + _accumulate_anthropic_thinking_delta(event, current_block) return None @@ -487,13 +365,7 @@ def handle_anthropic_tool_delta( ): return - if hasattr(event, "index") and event.index < len(content_blocks): - block = content_blocks[event.index] - - if block.get("type") == "function" and block.get("id") in tools_in_progress: - tool = tools_in_progress[block["id"]] - partial_json = getattr(event.delta, "partial_json", "") - tool["input_string"] += partial_json + _append_anthropic_tool_json(event, content_blocks, tools_in_progress) def finalize_anthropic_tool_input( @@ -570,3 +442,157 @@ def format_anthropic_streaming_output_complete( "content": [{"type": "text", "text": accumulated_content}], } ] + + +def _format_anthropic_response_block(choice: Any) -> Optional[FormattedContentItem]: + if ( + hasattr(choice, "type") + and choice.type == "text" + and hasattr(choice, "text") + and choice.text + ): + text_content: FormattedTextContent = { + "type": "text", + "text": choice.text, + } + return text_content + + elif ( + hasattr(choice, "type") + and choice.type == "tool_use" + and hasattr(choice, "name") + and hasattr(choice, "id") + ): + function_call: FormattedFunctionCall = { + "type": "function", + "id": choice.id, + "function": { + "name": choice.name, + "arguments": getattr(choice, "input", {}), + }, + } + return function_call + + return _format_anthropic_reasoning_block(choice) + + +def _format_anthropic_reasoning_block(choice: Any) -> Optional[FormattedContentItem]: + if getattr(choice, "type", None) == "thinking": + return { + "type": "thinking", + "thinking": getattr(choice, "thinking", None), + "signature": getattr(choice, "signature", None), + } + + elif getattr(choice, "type", None) == "redacted_thinking": + return { + "type": "redacted_thinking", + "data": getattr(choice, "data", None), + } + + else: + # Catches blocks the branches above skip on falsy values (e.g. TextBlock(text="")) + # so empty-but-valid content survives instead of being silently dropped. + plain = to_plain(choice) + if isinstance(plain, dict) and plain.get("type"): + return plain + + return None + + +def _add_anthropic_cache_usage(result: TokenUsage, usage: Any) -> None: + if hasattr(usage, "cache_read_input_tokens"): + cache_read = usage.cache_read_input_tokens + if cache_read and cache_read > 0: + result["cache_read_input_tokens"] = cache_read + + if hasattr(usage, "cache_creation_input_tokens"): + cache_creation = usage.cache_creation_input_tokens + if cache_creation and cache_creation > 0: + result["cache_creation_input_tokens"] = cache_creation + + +def _extract_anthropic_start_usage(event: Any) -> TokenUsage: + usage = TokenUsage() + # Handle usage stats from message_start event + if hasattr(event, "type") and event.type == "message_start": + if hasattr(event, "message") and hasattr(event.message, "usage"): + usage["input_tokens"] = getattr(event.message.usage, "input_tokens", 0) + usage["cache_creation_input_tokens"] = getattr( + event.message.usage, "cache_creation_input_tokens", 0 + ) + usage["cache_read_input_tokens"] = getattr( + event.message.usage, "cache_read_input_tokens", 0 + ) + # Capture raw usage metadata for backend processing + # Serialize to dict here in the converter (not in utils) + serialized = serialize_raw_usage(event.message.usage) + if serialized: + usage["raw_usage"] = serialized + + return usage + + +def _start_anthropic_block( + block: Any, +) -> Tuple[Optional[StreamingContentBlock], Optional[ToolInProgress]]: + if not hasattr(block, "type"): + return None, None + + if block.type == "text": + content_block: StreamingContentBlock = {"type": "text", "text": ""} + return content_block, None + + elif block.type == "tool_use": + tool_block: StreamingContentBlock = { + "type": "function", + "id": getattr(block, "id", ""), + "function": {"name": getattr(block, "name", ""), "arguments": {}}, + } + tool_in_progress: ToolInProgress = {"block": tool_block, "input_string": ""} + return tool_block, tool_in_progress + + elif block.type == "thinking": + thinking_block: StreamingContentBlock = { + "type": "thinking", + "thinking": getattr(block, "thinking", "") or "", + } + signature = getattr(block, "signature", None) + if signature: + thinking_block["signature"] = signature + return thinking_block, None + + elif block.type == "redacted_thinking": + redacted_block: StreamingContentBlock = { + "type": "redacted_thinking", + "data": getattr(block, "data", None), + } + return redacted_block, None + + return None, None + + +def _accumulate_anthropic_thinking_delta( + event: Any, current_block: Optional[StreamingContentBlock] +) -> None: + fields: Tuple[Literal["thinking", "signature"], ...] = ("thinking", "signature") + for field in fields: + if hasattr(event, "delta") and hasattr(event.delta, field): + value = getattr(event.delta, field) or "" + if current_block is not None and current_block.get("type") == "thinking": + current_block[field] = (current_block.get(field) or "") + value + return + + +def _append_anthropic_tool_json( + event: Any, + content_blocks: List[StreamingContentBlock], + tools_in_progress: Dict[str, ToolInProgress], +) -> None: + if hasattr(event, "index") and event.index < len(content_blocks): + block = content_blocks[event.index] + + if block.get("type") == "function" and block.get("id") in tools_in_progress: + tool = tools_in_progress[block["id"]] + partial_json = getattr(event.delta, "partial_json", "") + tool["input_string"] += partial_json diff --git a/posthog/ai/claude_agent_sdk/client.py b/posthog/ai/claude_agent_sdk/client.py index f9a718d80..5d3d3d458 100644 --- a/posthog/ai/claude_agent_sdk/client.py +++ b/posthog/ai/claude_agent_sdk/client.py @@ -23,9 +23,10 @@ "Please install the Claude Agent SDK to use this feature: 'pip install claude-agent-sdk'" ) -from posthog.ai.claude_agent_sdk.formatting import ( +from .formatting import ( + _format_user_input, format_assistant_blocks, - format_tool_result_content, + format_tool_result_content as format_tool_result_content, ) from posthog.ai.claude_agent_sdk.processor import ( PostHogClaudeAgentProcessor, @@ -135,95 +136,77 @@ async def receive_response(self): """Instrumented receive_response -- yields all messages, emits PostHog events.""" async for message in self._client.receive_response(): try: - if isinstance(message, StreamEvent): - self._tracker.process_stream_event(message) - - if self._tracker.has_completed_generation(): - gen = self._tracker.pop_generation() - self._generation_index += 1 - self._current_generation_span_id = gen.span_id - self._processor._emit_generation( - gen, - self._trace_id, - self._generation_index, - self._current_input, - self._pending_output or None, - self._distinct_id, - self._extra_props, - self._privacy, - self._groups, - ) - self._current_input = self._next_input - self._next_input = None - self._pending_output = [] - - elif isinstance(message, AssistantMessage): - self._tracker.set_model(message.model) - parent_id = ( - self._tracker.current_span_id - or self._current_generation_span_id - ) - for block in message.content: - if isinstance(block, ToolUseBlock): - self._processor._emit_tool_span( - block, - self._trace_id, - parent_id, - self._distinct_id, - self._extra_props, - self._privacy, - self._groups, - ) - output_content = format_assistant_blocks(message.content) - if output_content: - self._pending_output = [ - {"role": "assistant", "content": output_content} - ] - - elif isinstance(message, UserMessage): - content = message.content - if isinstance(content, str): - self._next_input = [{"role": "user", "content": content}] - elif isinstance(content, list): - formatted: List[Dict[str, Any]] = [] - for block in content: - if hasattr(block, "tool_use_id"): - formatted.append( - { - "type": "tool_result", - "tool_use_id": block.tool_use_id, - "content": format_tool_result_content( - block, self._processor._client - ), - } - ) - elif hasattr(block, "text"): - formatted.append({"type": "text", "text": block.text}) - if formatted: - self._next_input = [{"role": "user", "content": formatted}] - - elif isinstance(message, ResultMessage): - if not self._tracker.had_any_stream_events: - self._processor._emit_generation_from_result( - message, - self._trace_id, - self._tracker.last_model, - self._query_start, - self._current_input, - self._pending_output, - self._distinct_id, - self._extra_props, - self._privacy, - self._groups, - ) - # Don't emit trace here -- wait for disconnect/close - # so multi-turn sessions get one trace at the end - + self._process_message(message) except Exception as e: log.debug(f"PostHog instrumentation error (non-fatal): {e}") - yield message + def _process_message(self, message: Any) -> None: + if isinstance(message, StreamEvent): + self._tracker.process_stream_event(message) + + if self._tracker.has_completed_generation(): + gen = self._tracker.pop_generation() + self._generation_index += 1 + self._current_generation_span_id = gen.span_id + self._processor._emit_generation( + gen, + self._trace_id, + self._generation_index, + self._current_input, + self._pending_output or None, + self._distinct_id, + self._extra_props, + self._privacy, + self._groups, + ) + self._current_input = self._next_input + self._next_input = None + self._pending_output = [] + + elif isinstance(message, AssistantMessage): + self._process_assistant_message(message) + + elif isinstance(message, UserMessage): + self._next_input = _format_user_input( + message.content, self._processor._client, self._next_input + ) + + elif isinstance(message, ResultMessage): + if not self._tracker.had_any_stream_events: + self._processor._emit_generation_from_result( + message, + self._trace_id, + self._tracker.last_model, + self._query_start, + self._current_input, + self._pending_output, + self._distinct_id, + self._extra_props, + self._privacy, + self._groups, + ) + # Don't emit trace here -- wait for disconnect/close + # so multi-turn sessions get one trace at the end + + def _process_assistant_message(self, message: "AssistantMessage") -> None: + self._tracker.set_model(message.model) + parent_id = self._tracker.current_span_id or self._current_generation_span_id + for block in message.content: + if isinstance(block, ToolUseBlock): + self._processor._emit_tool_span( + block, + self._trace_id, + parent_id, + self._distinct_id, + self._extra_props, + self._privacy, + self._groups, + ) + output_content = format_assistant_blocks(message.content) + if output_content: + self._pending_output = [{"role": "assistant", "content": output_content}] + async def disconnect(self) -> None: """ Disconnect the underlying client and emit the final PostHog trace event. diff --git a/posthog/ai/claude_agent_sdk/formatting.py b/posthog/ai/claude_agent_sdk/formatting.py index eea13c269..a99c8cbd3 100644 --- a/posthog/ai/claude_agent_sdk/formatting.py +++ b/posthog/ai/claude_agent_sdk/formatting.py @@ -1,4 +1,4 @@ -from typing import Any, Dict, List +from typing import Any, Dict, List, Optional try: from claude_agent_sdk import ToolUseBlock @@ -53,3 +53,26 @@ def format_assistant_blocks(blocks: Any) -> List[Dict[str, Any]]: else: out.append(to_plain(block)) return out + + +def _format_user_input( + content: Any, client: Any, previous: Optional[List[Dict[str, Any]]] +) -> Optional[List[Dict[str, Any]]]: + if isinstance(content, str): + return [{"role": "user", "content": content}] + if isinstance(content, list): + formatted: List[Dict[str, Any]] = [] + for block in content: + if hasattr(block, "tool_use_id"): + formatted.append( + { + "type": "tool_result", + "tool_use_id": block.tool_use_id, + "content": format_tool_result_content(block, client), + } + ) + elif hasattr(block, "text"): + formatted.append({"type": "text", "text": block.text}) + if formatted: + return [{"role": "user", "content": formatted}] + return previous diff --git a/posthog/ai/claude_agent_sdk/processor.py b/posthog/ai/claude_agent_sdk/processor.py index d5405ec66..022ad8cc5 100644 --- a/posthog/ai/claude_agent_sdk/processor.py +++ b/posthog/ai/claude_agent_sdk/processor.py @@ -25,9 +25,10 @@ ) from posthog import setup -from posthog.ai.claude_agent_sdk.formatting import ( +from .formatting import ( + _format_user_input, format_assistant_blocks, - format_tool_result_content, + format_tool_result_content as format_tool_result_content, ) from posthog.ai.media import ensure_serializable as _ensure_serializable from posthog.ai.utils import ( @@ -91,31 +92,7 @@ def process_stream_event(self, event: "StreamEvent") -> None: self._current.raw_usage = dict(usage) elif event_type == "message_delta" and self._current is not None: - usage = raw.get("usage", {}) - self._current.raw_usage = {**(self._current.raw_usage or {}), **usage} - # message_delta usage is cumulative: output tokens, and with server - # tools (web search, ...) the input and cache counts grow past the - # message_start values. Keep the larger count; a field the delta - # omits keeps the message_start value. - if usage.get("output_tokens"): - self._current.output_tokens = usage["output_tokens"] - for field_name in ( - "input_tokens", - "cache_read_input_tokens", - "cache_creation_input_tokens", - ): - delta_value = usage.get(field_name) - current_value = getattr(self._current, field_name) - if isinstance(delta_value, int) and delta_value > (current_value or 0): - setattr(self._current, field_name, delta_value) - server_tool_use = usage.get("server_tool_use") or {} - web_search_requests = server_tool_use.get("web_search_requests") - if isinstance(web_search_requests, int) and web_search_requests > 0: - self._current.web_search_count = web_search_requests - # Extract stop reason from message_delta - delta_stop_reason = raw.get("delta", {}).get("stop_reason") - if delta_stop_reason is not None: - self._current.stop_reason = delta_stop_reason + self._process_usage_delta(raw) elif event_type == "message_stop" and self._current is not None: self._current.end_time = time.time() @@ -123,6 +100,38 @@ def process_stream_event(self, event: "StreamEvent") -> None: self._last_model = self._current.model self._current = None + def _process_usage_delta(self, raw: Dict[str, Any]) -> None: + assert self._current is not None + usage = raw.get("usage", {}) + self._current.raw_usage = {**(self._current.raw_usage or {}), **usage} + # message_delta usage is cumulative: output tokens, and with server + # tools (web search, ...) the input and cache counts grow past the + # message_start values. Keep the larger count; a field the delta + # omits keeps the message_start value. + if usage.get("output_tokens"): + self._current.output_tokens = usage["output_tokens"] + self._update_cumulative_input_counts(usage) + server_tool_use = usage.get("server_tool_use") or {} + web_search_requests = server_tool_use.get("web_search_requests") + if isinstance(web_search_requests, int) and web_search_requests > 0: + self._current.web_search_count = web_search_requests + # Extract stop reason from message_delta + delta_stop_reason = raw.get("delta", {}).get("stop_reason") + if delta_stop_reason is not None: + self._current.stop_reason = delta_stop_reason + + def _update_cumulative_input_counts(self, usage: Dict[str, Any]) -> None: + assert self._current is not None + for field_name in ( + "input_tokens", + "cache_read_input_tokens", + "cache_creation_input_tokens", + ): + delta_value = usage.get(field_name) + current_value = getattr(self._current, field_name) + if isinstance(delta_value, int) and delta_value > (current_value or 0): + setattr(self._current, field_name, delta_value) + def set_model(self, model: str) -> None: self._last_model = model @@ -265,19 +274,36 @@ async def query( elif not options.include_partial_messages: options = replace(options, include_partial_messages=True) + async for message in self._instrument_query( + prompt, + options, + transport, + distinct_id_override, + trace_id, + extra_props, + privacy, + groups, + ): + yield message + + async def _instrument_query( + self, + prompt: Any, + options: ClaudeAgentOptions, + transport: Any, + distinct_id_override: Any, + trace_id: str, + extra_props: Dict[str, Any], + privacy: bool, + groups: Dict[str, Any], + ): tracker = _GenerationTracker() query_start = time.time() generation_index = 0 current_generation_span_id: Optional[str] = None # Track input/output for generation events - initial_input: List[Dict[str, Any]] = [] - if isinstance(prompt, str): - initial_input = [{"role": "user", "content": prompt}] - if options and options.system_prompt and isinstance(options.system_prompt, str): - initial_input = [ - {"role": "system", "content": options.system_prompt} - ] + initial_input + initial_input, current_input = _query_inputs(prompt, options) # Two-slot input tracking: # - current_input: input for the generation currently in progress @@ -287,7 +313,6 @@ async def query( # message_start → content_blocks → AssistantMessage → UserMessage(tool result) → message_stop # So UserMessage arrives *before* message_stop. When message_stop fires we emit # with current_input, then promote next_input → current_input for the next turn. - current_input: Optional[List[Dict[str, Any]]] = initial_input or None next_input: Optional[List[Dict[str, Any]]] = None # Accumulate assistant output per generation @@ -324,74 +349,33 @@ async def query( pending_output = [] elif isinstance(message, AssistantMessage): - tracker.set_model(message.model) - # Use the in-progress generation's span_id as parent for tool spans. - # AssistantMessage arrives before message_stop, so current_generation_span_id - # would be stale (from the previous turn). tracker.current_span_id gives us - # the correct in-progress generation. - parent_id = tracker.current_span_id or current_generation_span_id - for block in message.content: - if isinstance(block, ToolUseBlock): - self._emit_tool_span( - block, - trace_id, - parent_id, - distinct_id_override, - extra_props, - privacy, - groups, - ) - output_content = format_assistant_blocks(message.content) - if output_content: - pending_output = [ - {"role": "assistant", "content": output_content} - ] + pending_output = self._process_assistant_message( + message, + tracker, + current_generation_span_id, + trace_id, + distinct_id_override, + extra_props, + privacy, + groups, + pending_output, + ) elif isinstance(message, UserMessage): # UserMessages carry tool results. They arrive *before* message_stop # for the current turn, so queue them as input for the *next* generation. - content = message.content - if isinstance(content, str): - next_input = [{"role": "user", "content": content}] - elif isinstance(content, list): - formatted: List[Dict[str, Any]] = [] - for block in content: - if hasattr(block, "tool_use_id"): - formatted.append( - { - "type": "tool_result", - "tool_use_id": block.tool_use_id, - "content": format_tool_result_content( - block, self._client - ), - } - ) - elif hasattr(block, "text"): - formatted.append({"type": "text", "text": block.text}) - if formatted: - next_input = [{"role": "user", "content": formatted}] + next_input = _format_user_input( + message.content, self._client, next_input + ) elif isinstance(message, ResultMessage): - # Fallback: if no StreamEvents were received, emit a single - # generation from ResultMessage aggregate data - if not tracker.had_any_stream_events: - self._emit_generation_from_result( - message, - trace_id, - tracker.last_model, - query_start, - initial_input, - pending_output, - distinct_id_override, - extra_props, - privacy, - groups, - ) - - self._emit_trace( + self._process_query_result( message, + tracker, trace_id, query_start, + initial_input, + pending_output, distinct_id_override, extra_props, privacy, @@ -403,6 +387,79 @@ async def query( yield message + def _process_query_result( + self, + message: "ResultMessage", + tracker: _GenerationTracker, + trace_id: str, + query_start: float, + initial_input: List[Dict[str, Any]], + pending_output: List[Dict[str, Any]], + distinct_id_override: Any, + extra_props: Dict[str, Any], + privacy: bool, + groups: Dict[str, Any], + ) -> None: + # Fallback: if no StreamEvents were received, emit a single + # generation from ResultMessage aggregate data + if not tracker.had_any_stream_events: + self._emit_generation_from_result( + message, + trace_id, + tracker.last_model, + query_start, + initial_input, + pending_output, + distinct_id_override, + extra_props, + privacy, + groups, + ) + + self._emit_trace( + message, + trace_id, + query_start, + distinct_id_override, + extra_props, + privacy, + groups, + ) + + def _process_assistant_message( + self, + message: "AssistantMessage", + tracker: _GenerationTracker, + current_generation_span_id: Optional[str], + trace_id: str, + distinct_id: Any, + extra_props: Dict[str, Any], + privacy: bool, + groups: Dict[str, Any], + pending_output: List[Dict[str, Any]], + ) -> List[Dict[str, Any]]: + tracker.set_model(message.model) + # Use the in-progress generation's span_id as parent for tool spans. + # AssistantMessage arrives before message_stop, so current_generation_span_id + # would be stale (from the previous turn). tracker.current_span_id gives us + # the correct in-progress generation. + parent_id = tracker.current_span_id or current_generation_span_id + for block in message.content: + if isinstance(block, ToolUseBlock): + self._emit_tool_span( + block, + trace_id, + parent_id, + distinct_id, + extra_props, + privacy, + groups, + ) + output_content = format_assistant_blocks(message.content) + if output_content: + pending_output = [{"role": "assistant", "content": output_content}] + return pending_output + def _emit_generation( self, gen: _GenerationData, @@ -441,6 +498,26 @@ def _emit_generation( **extra_props, } + self._add_generation_content( + properties, input_messages, output_choices, privacy + ) + + _add_generation_usage(properties, gen) + + if resolved_id is None: + properties["$process_person_profile"] = False + + self._capture_event( + "$ai_generation", properties, resolved_id or trace_id, groups + ) + + def _add_generation_content( + self, + properties: Dict[str, Any], + input_messages: Optional[List[Dict[str, Any]]], + output_choices: Optional[List[Dict[str, Any]]], + privacy: bool, + ) -> None: if input_messages is not None: properties["$ai_input"] = _with_privacy_mode( self._client, @@ -454,27 +531,6 @@ def _emit_generation( finalize_ai_content(output_choices, self._client), ) - if gen.cache_read_input_tokens: - properties["$ai_cache_read_input_tokens"] = gen.cache_read_input_tokens - if gen.cache_creation_input_tokens: - properties["$ai_cache_creation_input_tokens"] = ( - gen.cache_creation_input_tokens - ) - if gen.web_search_count: - properties["$ai_web_search_count"] = gen.web_search_count - if gen.raw_usage: - properties["$ai_usage"] = gen.raw_usage - - if gen.stop_reason is not None: - properties["$ai_stop_reason"] = gen.stop_reason - - if resolved_id is None: - properties["$process_person_profile"] = False - - self._capture_event( - "$ai_generation", properties, resolved_id or trace_id, groups - ) - def _emit_generation_from_result( self, result: "ResultMessage", @@ -516,30 +572,11 @@ def _emit_generation_from_result( **extra_props, } - if input_messages is not None: - properties["$ai_input"] = _with_privacy_mode( - self._client, - privacy, - finalize_ai_content(input_messages, self._client), - ) - if output_choices is not None: - properties["$ai_output_choices"] = _with_privacy_mode( - self._client, - privacy, - finalize_ai_content(output_choices, self._client), - ) - - cache_read = usage.get("cache_read_input_tokens") - cache_creation = usage.get("cache_creation_input_tokens") - if cache_read: - properties["$ai_cache_read_input_tokens"] = cache_read - if cache_creation: - properties["$ai_cache_creation_input_tokens"] = cache_creation - if usage: - properties["$ai_usage"] = dict(usage) + self._add_generation_content( + properties, input_messages, output_choices, privacy + ) - if result.total_cost_usd is not None: - properties["$ai_total_cost_usd"] = result.total_cost_usd + _add_result_usage(properties, usage, result) if resolved_id is None: properties["$process_person_profile"] = False @@ -639,3 +676,47 @@ def _resolve_distinct_id( return str(override) # Fall back to instance default return self._get_distinct_id(result) + + +def _query_inputs( + prompt: Any, options: ClaudeAgentOptions +) -> tuple[List[Dict[str, Any]], Optional[List[Dict[str, Any]]]]: + initial_input: List[Dict[str, Any]] = [] + if isinstance(prompt, str): + initial_input = [{"role": "user", "content": prompt}] + if options and options.system_prompt and isinstance(options.system_prompt, str): + initial_input = [ + {"role": "system", "content": options.system_prompt} + ] + initial_input + + return initial_input, initial_input or None + + +def _add_generation_usage(properties: Dict[str, Any], gen: _GenerationData) -> None: + if gen.cache_read_input_tokens: + properties["$ai_cache_read_input_tokens"] = gen.cache_read_input_tokens + if gen.cache_creation_input_tokens: + properties["$ai_cache_creation_input_tokens"] = gen.cache_creation_input_tokens + if gen.web_search_count: + properties["$ai_web_search_count"] = gen.web_search_count + if gen.raw_usage: + properties["$ai_usage"] = gen.raw_usage + + if gen.stop_reason is not None: + properties["$ai_stop_reason"] = gen.stop_reason + + +def _add_result_usage( + properties: Dict[str, Any], usage: Dict[str, Any], result: "ResultMessage" +) -> None: + cache_read = usage.get("cache_read_input_tokens") + cache_creation = usage.get("cache_creation_input_tokens") + if cache_read: + properties["$ai_cache_read_input_tokens"] = cache_read + if cache_creation: + properties["$ai_cache_creation_input_tokens"] = cache_creation + if usage: + properties["$ai_usage"] = dict(usage) + + if result.total_cost_usd is not None: + properties["$ai_total_cost_usd"] = result.total_cost_usd diff --git a/posthog/ai/evaluations/_async_datasets.py b/posthog/ai/evaluations/_async_datasets.py index 80cc6418c..6593a919c 100644 --- a/posthog/ai/evaluations/_async_datasets.py +++ b/posthog/ai/evaluations/_async_datasets.py @@ -4,7 +4,7 @@ from dataclasses import dataclass, field from datetime import datetime -from typing import AsyncIterator, Literal, Sequence +from typing import AsyncIterator, Literal, Sequence, cast from uuid import UUID from ._dataset_serialization import ( @@ -387,10 +387,15 @@ async def snapshot( return AsyncDatasetSnapshot( dataset, selected, dataset.current_revision_id, self ) + return await self._historical_snapshot(dataset, selected) + + async def _historical_snapshot( + self, dataset: Dataset, selected: int + ) -> AsyncDatasetSnapshot: # Revisions are consecutive and newest first. Concurrent writes can # shift their offsets, so verify the result and scan on a miss. page = await self.list_revisions( - dataset.id, limit=1, offset=dataset.current_revision - selected + dataset.id, limit=1, offset=cast(int, dataset.current_revision) - selected ) for candidate in page.results: if candidate.revision == selected: diff --git a/posthog/ai/evaluations/_client.py b/posthog/ai/evaluations/_client.py index 475a856a3..55c92c98e 100644 --- a/posthog/ai/evaluations/_client.py +++ b/posthog/ai/evaluations/_client.py @@ -69,19 +69,23 @@ def _experiment_body(name: str, options: ExperimentOptions) -> bytes: for key, value in options.items(): if key in ("id", "started_at"): continue - if key == "run_source": - if value is not None and value not in ("ci", "local", "scheduled"): - raise ValueError("run_source must be ci, local, scheduled, or None.") - data[key] = value - elif key in ("expected_item_count", "expected_result_count"): - data[key] = _count(value, key) - elif key == "dataset_revision_id": - data[key] = None if value is None else _uuid(value) - else: - data[key] = _identifier(value, key) + data[key] = _experiment_option(key, value) return _encode(data) +def _experiment_option(key: str, value: Any) -> Any: + if key == "run_source": + if value is not None and value not in ("ci", "local", "scheduled"): + raise ValueError("run_source must be ci, local, scheduled, or None.") + return value + elif key in ("expected_item_count", "expected_result_count"): + return _count(value, key) + elif key == "dataset_revision_id": + return None if value is None else _uuid(value) + else: + return _identifier(value, key) + + @dataclass(frozen=True) class _Chunk: start: int @@ -95,6 +99,26 @@ def _upload_body(items: list[bytes], results: list[bytes]) -> bytes: ) +def _result_declarations(results: tuple[EvaluationResult, ...]) -> dict[str, bytes]: + identities: set[tuple[str, str]] = set() + declarations: dict[str, bytes] = {} + for result in results: + if not isinstance(result, EvaluationResult): + raise TypeError("upload_results expects EvaluationResult objects.") + key = (result.item_id, result.scorer_version_id) + if key in identities: + raise ValueError( + "Each item/scorer-version pair must occur only once in a bulk upload." + ) + identities.add(key) + if isinstance(result.item, EvaluationItem): + previous = declarations.setdefault(result.item_id, result.item._json) + if previous != result.item._json: + raise ValueError("Conflicting declarations for the same item UUID.") + + return declarations + + def _group_ends(results: tuple[EvaluationResult, ...]) -> list[int]: # A calculation only names a version, so ingestion-only clients cannot # discover its dependencies. Keep every supplied result for that item in @@ -119,25 +143,43 @@ def _group_ends(results: tuple[EvaluationResult, ...]) -> list[int]: return ends +def _group_extra( + group_results: list[bytes], + new_items: list[bytes], + encoded_results: list[bytes], + items: list[bytes], +) -> int: + extra = sum(map(len, group_results)) + len(group_results) - (not encoded_results) + if new_items: + extra += sum(map(len, new_items)) + len(new_items) - (not items) + return extra + + +def _encoded_group( + group: tuple[EvaluationResult, ...], declarations: dict[str, bytes] +) -> tuple[list[bytes], dict[str, bytes]]: + return ( + [result._json for result in group], + { + result.item_id: declarations[result.item_id] + for result in group + if result.item_id in declarations + }, + ) + + +def _group_fits(result_count: int, item_count: int, size: int) -> bool: + return ( + result_count <= _MAX_RESULTS + and item_count <= _MAX_ITEMS + and size <= _MAX_REQUEST_BYTES + ) + + def _chunks(results: tuple[EvaluationResult, ...]) -> list[_Chunk]: # Validate the finite submission before sending any chunk. Receipts and # prepared bodies use memory proportional to this caller-sized sequence. - identities: set[tuple[str, str]] = set() - declarations: dict[str, bytes] = {} - for result in results: - if not isinstance(result, EvaluationResult): - raise TypeError("upload_results expects EvaluationResult objects.") - key = (result.item_id, result.scorer_version_id) - if key in identities: - raise ValueError( - "Each item/scorer-version pair must occur only once in a bulk upload." - ) - identities.add(key) - if isinstance(result.item, EvaluationItem): - previous = declarations.setdefault(result.item_id, result.item._json) - if previous != result.item._json: - raise ValueError("Conflicting declarations for the same item UUID.") - + declarations = _result_declarations(results) chunks: list[_Chunk] = [] item_ids: set[str] = set() items: list[bytes] = [] @@ -147,27 +189,15 @@ def _chunks(results: tuple[EvaluationResult, ...]) -> list[_Chunk]: group_start = 0 for end in _group_ends(results): group = results[group_start:end] - group_results = [result._json for result in group] - group_items = { - result.item_id: declarations[result.item_id] - for result in group - if result.item_id in declarations - } + group_results, group_items = _encoded_group(group, declarations) while True: new_items = [body for id, body in group_items.items() if id not in item_ids] - extra = ( - sum(map(len, group_results)) - + len(group_results) - - (not encoded_results) - ) - if new_items: - extra += sum(map(len, new_items)) + len(new_items) - (not items) - fits = ( - len(encoded_results) + len(group) <= _MAX_RESULTS - and len(items) + len(new_items) <= _MAX_ITEMS - and size + extra <= _MAX_REQUEST_BYTES - ) - if fits: + extra = _group_extra(group_results, new_items, encoded_results, items) + if _group_fits( + len(encoded_results) + len(group), + len(items) + len(new_items), + size + extra, + ): break if not encoded_results: raise ValueError( diff --git a/posthog/ai/evaluations/_dataset_serialization.py b/posthog/ai/evaluations/_dataset_serialization.py index c95fb5aea..b96d2c6bb 100644 --- a/posthog/ai/evaluations/_dataset_serialization.py +++ b/posthog/ai/evaluations/_dataset_serialization.py @@ -97,14 +97,9 @@ def _item( identity, owner = _uuid(data["id"]), _uuid(data["dataset"]) introduced = _integer(data["dataset_revision"]) is_archived = _boolean(data["archived"]) - if (id is not None and identity != id) or ( - dataset_id is not None and owner != dataset_id - ): - raise ValueError("Mismatched dataset item identity.") - if revision is not None and introduced > revision: - raise ValueError("The item version is newer than the requested revision.") - if archived is not None and is_archived != archived: - raise ValueError("The item does not match the requested archive filter.") + _validate_item_filters( + identity, owner, introduced, is_archived, id, dataset_id, revision, archived + ) if data["input"] is None: raise ValueError("Dataset inputs cannot be null.") return DatasetItem( @@ -134,6 +129,26 @@ def _item( ) +def _validate_item_filters( + identity: str, + owner: str, + introduced: int, + is_archived: bool, + id: str | None, + dataset_id: str | None, + revision: int | None, + archived: bool | None, +) -> None: + if (id is not None and identity != id) or ( + dataset_id is not None and owner != dataset_id + ): + raise ValueError("Mismatched dataset item identity.") + if revision is not None and introduced > revision: + raise ValueError("The item version is newer than the requested revision.") + if archived is not None and is_archived != archived: + raise ValueError("The item does not match the requested archive filter.") + + def _parse(parser: Callable[[dict[str, Any]], _T], data: dict[str, Any]) -> _T: return _parse_response( parser, data, detail="The dataset API returned an invalid response." @@ -197,12 +212,7 @@ def _body(fields: dict[str, Any]) -> bytes: data = { key: value for key, value in fields.items() if not isinstance(value, _Unset) } - for key in ("name", "description"): - if key in data: - value = _text(data[key]) - maximum = 400 if key == "name" else 10_000 - if len(value) > maximum or (key == "name" and not value.strip()): - raise ValueError(f"Invalid dataset {key}.") + _validate_dataset_text(data) if "input" in data and data["input"] is None: raise ValueError("Dataset inputs cannot be null.") if "metadata" in data: @@ -213,6 +223,15 @@ def _body(fields: dict[str, Any]) -> bytes: return _encode(data) +def _validate_dataset_text(data: dict[str, Any]) -> None: + for key in ("name", "description"): + if key in data: + value = _text(data[key]) + maximum = 400 if key == "name" else 10_000 + if len(value) > maximum or (key == "name" and not value.strip()): + raise ValueError(f"Invalid dataset {key}.") + + def _create_item_body( dataset_id: str, *, diff --git a/posthog/ai/evaluations/_datasets.py b/posthog/ai/evaluations/_datasets.py index cfe359a2e..a2a364907 100644 --- a/posthog/ai/evaluations/_datasets.py +++ b/posthog/ai/evaluations/_datasets.py @@ -4,7 +4,7 @@ from dataclasses import dataclass, field from datetime import datetime -from typing import Iterator, Literal, Sequence +from typing import Iterator, Literal, Sequence, cast from uuid import UUID from ._dataset_serialization import ( @@ -381,10 +381,13 @@ def snapshot( and dataset.current_revision_id is not None ): return DatasetSnapshot(dataset, selected, dataset.current_revision_id, self) + return self._historical_snapshot(dataset, selected) + + def _historical_snapshot(self, dataset: Dataset, selected: int) -> DatasetSnapshot: # Revisions are consecutive and newest first. Concurrent writes can # shift their offsets, so verify the result and scan on a miss. page = self.list_revisions( - dataset.id, limit=1, offset=dataset.current_revision - selected + dataset.id, limit=1, offset=cast(int, dataset.current_revision) - selected ) for candidate in page.results: if candidate.revision == selected: diff --git a/posthog/ai/evaluations/_serialization.py b/posthog/ai/evaluations/_serialization.py index 83aadb280..c651bad11 100644 --- a/posthog/ai/evaluations/_serialization.py +++ b/posthog/ai/evaluations/_serialization.py @@ -109,19 +109,15 @@ def _encode(value: object, *, sort_keys: bool = True) -> bytes: ) from exc +def _invalid_json_key(key: object) -> bool: + return not isinstance(key, str) or "\x00" in key + + def _validate_json(value: object, depth: int = 1) -> None: if isinstance(value, (dict, list)): if depth > 32: raise ValueError("Payload JSON nesting must not exceed 32 levels.") - children: Iterable[object] - if isinstance(value, dict): - if any(not isinstance(key, str) or "\x00" in key for key in value): - raise ValueError( - "JSON object keys must be strings without null characters." - ) - children = value.values() - else: - children = value + children = _json_children(value) for child in children: _validate_json(child, depth + 1) elif isinstance(value, str): @@ -131,6 +127,19 @@ def _validate_json(value: object, depth: int = 1) -> None: raise ValueError("Provide JSON values, without automatic object conversion.") +def _json_children(value: dict | list) -> Iterable[object]: + children: Iterable[object] + if isinstance(value, dict): + if any(_invalid_json_key(key) for key in value): + raise ValueError( + "JSON object keys must be strings without null characters." + ) + children = value.values() + else: + children = value + return children + + def _payload( explicit: dict[str, JSONValue] | _Unset, fields: dict[str, JSONValue | _Unset], @@ -149,43 +158,32 @@ def _payload( supplied = explicit elif not supplied: return _UNSET + _validate_payload_fields(supplied) + _validate_json(supplied) + encoded = _encode(supplied) + if len(encoded) > limit: + raise ValueError(f"Payload exceeds {limit} bytes of UTF-8 JSON.") + return json.loads(encoded) + + +def _validate_payload_fields(supplied: dict[str, JSONValue]) -> None: metadata = supplied.get("metadata") if metadata is not None and not isinstance(metadata, dict): raise ValueError("metadata must be a JSON object or None.") for field in ("reasoning", "error_message"): if supplied.get(field) is not None and not isinstance(supplied[field], str): raise ValueError(f"{field} must be a string or None.") - _validate_json(supplied) - encoded = _encode(supplied) - if len(encoded) > limit: - raise ValueError(f"Payload exceeds {limit} bytes of UTF-8 JSON.") - return json.loads(encoded) def _score(value: object) -> bool | float | list[str]: if type(value) is bool: return value if type(value) in (int, float): - try: - number = float(cast(Union[int, float], value)) - except OverflowError as exc: - raise ValueError( - "Numeric scores must fit a finite binary64 number." - ) from exc - if not math.isfinite(number): - raise ValueError("Numeric scores must be finite.") - if type(value) is int and number != value: - raise ValueError( - "Integer scores must be exactly representable as a binary64 number." - ) - return number + return _numeric_score(value) if ( isinstance(value, list) and value - and all( - isinstance(key, str) and key and len(key) <= 128 and "\x00" not in key - for key in value - ) + and all(_valid_category_key(key) for key in value) ): if len(set(value)) != len(value): raise ValueError("Categorical scores must contain distinct keys.") @@ -195,6 +193,24 @@ def _score(value: object) -> bool | float | list[str]: ) +def _numeric_score(value: object) -> float: + try: + number = float(cast(Union[int, float], value)) + except OverflowError as exc: + raise ValueError("Numeric scores must fit a finite binary64 number.") from exc + if not math.isfinite(number): + raise ValueError("Numeric scores must be finite.") + if type(value) is int and number != value: + raise ValueError( + "Integer scores must be exactly representable as a binary64 number." + ) + return number + + +def _valid_category_key(key: object) -> bool: + return isinstance(key, str) and bool(key) and len(key) <= 128 and "\x00" not in key + + def _count(value: object, field: str) -> int | None: if value is not None and (type(value) is not int or not 0 <= value <= 2**63 - 1): raise ValueError( diff --git a/posthog/ai/evaluations/_transport.py b/posthog/ai/evaluations/_transport.py index f6489c502..1feab76f0 100644 --- a/posthog/ai/evaluations/_transport.py +++ b/posthog/ai/evaluations/_transport.py @@ -7,8 +7,8 @@ import time from datetime import datetime, timezone from email.utils import parsedate_to_datetime -from typing import Any -from urllib.parse import urlsplit, urlunsplit +from typing import Any, cast +from urllib.parse import SplitResult, urlsplit, urlunsplit import requests @@ -26,6 +26,15 @@ def _normalize_host(host: str | None) -> str: parsed = urlsplit((host or "https://us.posthog.com").strip()) + _validate_host(parsed) + # Accessing port also validates malformed port numbers before any I/O. + netloc = parsed.netloc + if parsed.port in {None, 443} and parsed.scheme == "https": + netloc = _CLOUD_HOSTS.get(cast(str, parsed.hostname), netloc) + return urlunsplit((parsed.scheme, netloc, parsed.path.rstrip("/"), "", "")) + + +def _validate_host(parsed: SplitResult) -> None: if ( parsed.scheme not in {"http", "https"} or not parsed.hostname @@ -35,11 +44,6 @@ def _normalize_host(host: str | None) -> str: or parsed.fragment ): raise ValueError("host must be an absolute HTTP(S) URL without credentials") - # Accessing port also validates malformed port numbers before any I/O. - netloc = parsed.netloc - if parsed.port in {None, 443} and parsed.scheme == "https": - netloc = _CLOUD_HOSTS.get(parsed.hostname, netloc) - return urlunsplit((parsed.scheme, netloc, parsed.path.rstrip("/"), "", "")) def _validate_options( @@ -57,6 +61,10 @@ def _validate_options( or any(character.isspace() for character in secret_key) ): raise ValueError("secret_key must be a nonempty credential without whitespace") + _validate_retry_options(timeout, max_retries) + + +def _validate_retry_options(timeout: float, max_retries: int) -> None: if ( isinstance(timeout, bool) or not isinstance(timeout, (int, float)) diff --git a/posthog/ai/evaluations/_types.py b/posthog/ai/evaluations/_types.py index 7365ffb8a..dab1d367f 100644 --- a/posthog/ai/evaluations/_types.py +++ b/posthog/ai/evaluations/_types.py @@ -193,6 +193,70 @@ def from_dict(cls, data: Mapping[str, Any]) -> EvaluationItem: return cls(**dict(data)) +def _has_calculation_metadata( + value: ScoreValue | None, + status: ResultStatus, + error_code: str | None, + evaluator_trace_id: str | None, + evaluated_at: datetime | str | None, + fields: tuple[Any, ...], +) -> bool: + return ( + value is not None + or status != "ok" + or error_code is not None + or evaluator_trace_id is not None + or evaluated_at is not None + or any(not isinstance(field, _Unset) for field in fields) + ) + + +def _validate_calculation( + calculate: bool, + value: ScoreValue | None, + status: ResultStatus, + error_code: str | None, + evaluator_trace_id: str | None, + evaluated_at: datetime | str | None, + fields: tuple[Any, ...], +) -> None: + if not isinstance(calculate, bool): + raise ValueError("calculate must be a boolean.") + if calculate and _has_calculation_metadata( + value, status, error_code, evaluator_trace_id, evaluated_at, fields + ): + raise ValueError( + "A calculation accepts only item, scorer_version_id, and calculate=True." + ) + + +def _add_result_metadata( + data: dict[str, Any], + error_code: str | None, + evaluator_trace_id: str | None, + evaluated_at: datetime | str | None, +) -> None: + if error_code is not None: + data["error_code"] = _identifier(error_code, "error_code", 128) + if evaluator_trace_id is not None: + data["evaluator_trace_id"] = _identifier( + evaluator_trace_id, "evaluator_trace_id" + ) + if evaluated_at is not None: + data["evaluated_at"] = _timestamp(evaluated_at) + + +def _validate_result_status( + status: ResultStatus, value: ScoreValue | None, error_code: str | None +) -> None: + if status not in ("ok", "error", "skipped", "not_applicable"): + raise ValueError("Unsupported result status.") + if status != "ok" and value is not None: + raise ValueError("Only an ok result may contain a score.") + if status != "error" and error_code is not None: + raise ValueError("Only an error result may contain an error_code.") + + @dataclass(frozen=True, init=False) class EvaluationResult: """One scorer outcome for an item and an exact scorer-version UUID. @@ -229,28 +293,16 @@ def __init__( ) -> None: item_id = item.id if isinstance(item, EvaluationItem) else _uuid(item) version_id = _uuid(scorer_version_id) - if not isinstance(calculate, bool): - raise ValueError("calculate must be a boolean.") - if calculate and ( - value is not None - or status != "ok" - or error_code is not None - or evaluator_trace_id is not None - or evaluated_at is not None - or any( - not isinstance(field, _Unset) - for field in (reasoning, error_message, metadata, payload) - ) - ): - raise ValueError( - "A calculation accepts only item, scorer_version_id, and calculate=True." - ) - if status not in ("ok", "error", "skipped", "not_applicable"): - raise ValueError("Unsupported result status.") - if status != "ok" and value is not None: - raise ValueError("Only an ok result may contain a score.") - if status != "error" and error_code is not None: - raise ValueError("Only an error result may contain an error_code.") + _validate_calculation( + calculate, + value, + status, + error_code, + evaluator_trace_id, + evaluated_at, + (reasoning, error_message, metadata, payload), + ) + _validate_result_status(status, value, error_code) data: dict[str, Any] = { "item_id": item_id, "scorer_version_id": version_id, @@ -261,14 +313,7 @@ def __init__( data["status"] = status if status == "ok" and not calculate: data["value"] = _score(value) - if error_code is not None: - data["error_code"] = _identifier(error_code, "error_code", 128) - if evaluator_trace_id is not None: - data["evaluator_trace_id"] = _identifier( - evaluator_trace_id, "evaluator_trace_id" - ) - if evaluated_at is not None: - data["evaluated_at"] = _timestamp(evaluated_at) + _add_result_metadata(data, error_code, evaluator_trace_id, evaluated_at) prepared = _payload( payload, { @@ -279,8 +324,7 @@ def __init__( _MAX_RESULT_BYTES, ) if not isinstance(prepared, _Unset): - if status != "error" and prepared.get("error_message") is not None: - raise ValueError("Only an error result may contain an error_message.") + _validate_result_payload(status, prepared) data["payload"] = prepared object.__setattr__( self, "item", item if isinstance(item, EvaluationItem) else item_id @@ -473,16 +517,7 @@ def _upload_receipt( for row in data["items"] ) outcomes = tuple(_result_receipt(_object(row)) for row in data["results"]) - if len(items) != len({item.id for item in items}) or { - item.id for item in items - } != {result.item_id for result in results}: - raise ValueError("Incomplete item acknowledgments.") - if [(result.item_id, result.scorer_version_id) for result in outcomes] != [ - (result.item_id, result.scorer_version_id) for result in results - ]: - raise ValueError("Incomplete result acknowledgments.") - if len({result.id for result in outcomes}) != len(outcomes): - raise ValueError("Duplicate result identities in acknowledgment.") + _validate_upload_identities(items, outcomes, results) if any( result.calculate and outcome.status is None for result, outcome in zip(results, outcomes) @@ -495,3 +530,33 @@ def _upload_receipt( raise EvaluationAPIError( code="invalid_response", persistence="unknown" ) from None + + +def _validate_upload_identities( + items: tuple[ItemReceipt, ...], + outcomes: tuple[ResultReceipt, ...], + results: tuple[EvaluationResult, ...], +) -> None: + _validate_item_acknowledgments(items, results) + if [(result.item_id, result.scorer_version_id) for result in outcomes] != [ + (result.item_id, result.scorer_version_id) for result in results + ]: + raise ValueError("Incomplete result acknowledgments.") + if len({result.id for result in outcomes}) != len(outcomes): + raise ValueError("Duplicate result identities in acknowledgment.") + + +def _validate_result_payload( + status: ResultStatus, payload: dict[str, JSONValue] +) -> None: + if status != "error" and payload.get("error_message") is not None: + raise ValueError("Only an error result may contain an error_message.") + + +def _validate_item_acknowledgments( + items: tuple[ItemReceipt, ...], results: tuple[EvaluationResult, ...] +) -> None: + if len(items) != len({item.id for item in items}) or { + item.id for item in items + } != {result.item_id for result in results}: + raise ValueError("Incomplete item acknowledgments.") diff --git a/posthog/ai/gemini/gemini_converter.py b/posthog/ai/gemini/gemini_converter.py index 81b4f630b..6d409ee40 100644 --- a/posthog/ai/gemini/gemini_converter.py +++ b/posthog/ai/gemini/gemini_converter.py @@ -71,36 +71,7 @@ def _format_part(part: Any) -> Optional[FormattedContentItem]: if "file_data" in plain: media = _format_media_payload(plain["file_data"]) return {"type": _kind_from_mime(media.get("mime_type")), "file_data": media} - # Gemini-native function_call/function_response parts are normalized to the - # provider-agnostic tool-call/tool-result blocks. Emitting the raw Gemini - # shape leaves them unrenderable and invisible to evals. - if "function_call" in plain: - call = to_plain(plain["function_call"]) or {} - block: Dict[str, Any] = { - "type": "function", - "function": { - "name": call.get("name"), - "arguments": call.get("args"), - }, - } - if isinstance(call.get("id"), str): - block["id"] = call["id"] - return block - if "function_response" in plain: - response = to_plain(plain["function_response"]) or {} - response_block: Dict[str, Any] = { - "type": "function", - "tool_name": response.get("name") or "", - "content": response.get("response"), - } - if isinstance(response.get("id"), str): - response_block["tool_use_id"] = response["id"] - return response_block - if not plain: - return None - key = next(iter(plain)) - fallback: Dict[str, Any] = {"type": key, key: to_plain(plain[key])} - return cast(FormattedContentItem, fallback) + return _format_gemini_tool_part(plain) class GeminiPart(TypedDict, total=False): @@ -157,23 +128,15 @@ def _format_dict_message(item: Dict[str, Any]) -> FormattedMessage: # Handle dict with content field if "content" in item: - content = item["content"] - - if isinstance(content, list): - # If content is a list, format it as content blocks - content_blocks = _format_parts_as_content_blocks(content) - return {"role": item.get("role", "user"), "content": content_blocks} - - elif not isinstance(content, str): - content = str(content) - - return {"role": item.get("role", "user"), "content": content} + # Lists become content blocks; other non-string content is stringified. + return { + "role": item.get("role", "user"), + "content": _format_message_content(item["content"]), + } if "role" not in item: plain = to_plain(item) - if isinstance(plain, dict) and _BARE_PART_KEYS.intersection( - normalize_part_keys(plain) - ): + if _is_bare_part(plain): return {"role": "user", "content": _format_parts_as_content_blocks([item])} # Handle dict with text field @@ -198,11 +161,7 @@ def _format_object_message(item: Any) -> FormattedMessage: # Handle object with parts attribute if hasattr(item, "parts") and hasattr(item.parts, "__iter__"): content_blocks = _format_parts_as_content_blocks(list(item.parts)) - role = getattr(item, "role", "user") if hasattr(item, "role") else "user" - - # Ensure role is a string - if not isinstance(role, str): - role = "user" + role = _object_message_role(item) return {"role": role, "content": content_blocks} @@ -210,38 +169,20 @@ def _format_object_message(item: Any) -> FormattedMessage: # be caught before the "text" branch below, which would otherwise treat an # unset `.text` as empty content and drop any other part kind it carries plain = to_plain(item) - if isinstance(plain, dict) and _BARE_PART_KEYS.intersection( - normalize_part_keys(plain) - ): + if _is_bare_part(plain): return {"role": "user", "content": _format_parts_as_content_blocks([item])} # Handle object with text attribute if hasattr(item, "text"): - role = getattr(item, "role", "user") if hasattr(item, "role") else "user" - - # Ensure role is a string - if not isinstance(role, str): - role = "user" + role = _object_message_role(item) return {"role": role, "content": item.text} # Handle object with content attribute if hasattr(item, "content"): - role = getattr(item, "role", "user") if hasattr(item, "role") else "user" - - # Ensure role is a string - if not isinstance(role, str): - role = "user" + role = _object_message_role(item) - content = item.content - - if isinstance(content, list): - content_blocks = _format_parts_as_content_blocks(content) - return {"role": role, "content": content_blocks} - - elif not isinstance(content, str): - content = str(content) - return {"role": role, "content": content} + return {"role": role, "content": _format_message_content(item.content)} # Fallback to string representation return {"role": "user", "content": str(item)} @@ -265,55 +206,9 @@ def format_gemini_response(response: Any) -> List[FormattedMessage]: if hasattr(response, "candidates") and response.candidates: for candidate in response.candidates: - if hasattr(candidate, "content") and candidate.content: - content: List[FormattedContentItem] = [] - - if hasattr(candidate.content, "parts") and candidate.content.parts: - for part in candidate.content.parts: - # Checked ahead of _format_part so loosely-specced MagicMock - # fixtures (which report a truthy .text but aren't real Part - # objects) still resolve to a text block — must stay ahead of - # the _format_part delegation below. - text = getattr(part, "text", None) - if isinstance(text, str) and text: - # `is True` so loosely-specced mocks (whose .thought is a - # truthy Mock) still land on the text branch below. - if getattr(part, "thought", None) is True: - content.append({"type": "thinking", "thinking": text}) - else: - content.append({"type": "text", "text": text}) - continue - - if hasattr(part, "function_call") and part.function_call: - function_call = part.function_call - content.append( - _function_call_block( - function_call.name, - function_call.args, - getattr(function_call, "id", None), - ) - ) - continue - - block = _format_part(part) - if block is not None: - content.append(block) - - if content: - output.append( - { - "role": "assistant", - "content": content, - } - ) - - elif hasattr(candidate, "text") and candidate.text: - output.append( - { - "role": "assistant", - "content": [{"type": "text", "text": candidate.text}], - } - ) + message = _format_response_candidate(candidate) + if message is not None: + output.append(message) elif hasattr(response, "text") and response.text: output.append( @@ -479,40 +374,10 @@ def extract_gemini_web_search_count(response: Any) -> int: # Check for grounding_metadata in candidates if hasattr(response, "candidates") and response.candidates: for candidate in response.candidates: - if ( - hasattr(candidate, "grounding_metadata") - and candidate.grounding_metadata - ): - grounding_metadata = candidate.grounding_metadata - - # Check if web_search_queries exists and is non-empty - if hasattr(grounding_metadata, "web_search_queries"): - queries = grounding_metadata.web_search_queries - - if queries is not None and len(queries) > 0: - return 1 - - # Check if grounding_chunks exists and is non-empty - if hasattr(grounding_metadata, "grounding_chunks"): - chunks = grounding_metadata.grounding_chunks - - if chunks is not None and len(chunks) > 0: - return 1 - - # Also check for google_search or grounding in function call names - if hasattr(candidate, "content") and candidate.content: - if hasattr(candidate.content, "parts") and candidate.content.parts: - for part in candidate.content.parts: - if hasattr(part, "function_call") and part.function_call: - function_name = getattr( - part.function_call, "name", "" - ).lower() - - if ( - "google_search" in function_name - or "grounding" in function_name - ): - return 1 + if _has_grounding_metadata(candidate): + return 1 + if _has_search_function(candidate): + return 1 return 0 @@ -556,23 +421,7 @@ def _extract_usage_from_metadata( output_tokens=getattr(metadata, "candidates_token_count", 0), ) - # Add cache tokens if present (don't add if 0) - if hasattr(metadata, "cached_content_token_count"): - cache_tokens = metadata.cached_content_token_count - if cache_tokens and cache_tokens > 0: - usage["cache_read_input_tokens"] = cache_tokens - # Gemini counts cached_content_token_count inside prompt_token_count, so - # declare the accounting model rather than leaving ingestion to infer it. - # Under explicit context caching the two counts come from separate - # measurements and can disagree by a few percent, which makes inference - # from the token counts alone unreliable. - usage["cache_reporting_exclusive"] = False - - # Add reasoning tokens if present (don't add if 0) - if hasattr(metadata, "thoughts_token_count"): - reasoning_tokens = metadata.thoughts_token_count - if reasoning_tokens and reasoning_tokens > 0: - usage["reasoning_tokens"] = reasoning_tokens + _add_gemini_detail_usage(usage, metadata) # Capture raw usage metadata for backend processing # Serialize to dict here in the converter (not in utils) @@ -665,23 +514,7 @@ def extract_gemini_content_from_chunk( if hasattr(chunk, "candidates") and chunk.candidates: for candidate in chunk.candidates: - if hasattr(candidate, "content") and candidate.content: - if hasattr(candidate.content, "parts") and candidate.content.parts: - for part in candidate.content.parts: - if hasattr(part, "function_call") and part.function_call: - function_call = part.function_call - blocks.append( - _function_call_block( - function_call.name, - function_call.args, - getattr(function_call, "id", None), - ) - ) - continue - - block = _format_part(part) - if block is not None: - blocks.append(block) + blocks.extend(_format_candidate_parts(candidate, streaming=True)) if not blocks and hasattr(chunk, "text") and chunk.text: blocks.append({"type": "text", "text": chunk.text}) @@ -711,60 +544,8 @@ def format_gemini_streaming_output( } ] - # Handle list input if isinstance(accumulated_content, list): - content: List[FormattedContentItem] = [] - text_parts = [] - - for item in accumulated_content: - if isinstance(item, str): - # Legacy support: accumulate strings - text_parts.append(item) - elif isinstance(item, dict): - # New format: content blocks - if item.get("type") == "text": - text_parts.append(item.get("text", "")) - elif item.get("type") == "function": - # If we have accumulated text, add it first - if text_parts: - content.append( - { - "type": "text", - "text": "".join(text_parts), - } - ) - text_parts = [] - - # Add the function call - function_block: Dict[str, Any] = { - "type": "function", - "function": item.get("function", {}), - } - if isinstance(item.get("id"), str): - function_block["id"] = item["id"] - content.append(function_block) - else: - if text_parts: - content.append( - { - "type": "text", - "text": "".join(text_parts), - } - ) - text_parts = [] - - content.append(item) - - # Add any remaining text - if text_parts: - content.append( - { - "type": "text", - "text": "".join(text_parts), - } - ) - - # If we have content, return it + content = _merge_streaming_blocks(accumulated_content) if content: return [{"role": "assistant", "content": content}] @@ -788,3 +569,235 @@ def extract_gemini_embedding_token_count(response) -> Optional[int]: total += int(token_count) reported = True return total if reported else None + + +def _format_gemini_tool_part(plain: Dict[str, Any]) -> Optional[FormattedContentItem]: + # Gemini-native function_call/function_response parts are normalized to the + # provider-agnostic tool-call/tool-result blocks. Emitting the raw Gemini + # shape leaves them unrenderable and invisible to evals. + if "function_call" in plain: + call = to_plain(plain["function_call"]) or {} + block: Dict[str, Any] = { + "type": "function", + "function": { + "name": call.get("name"), + "arguments": call.get("args"), + }, + } + if isinstance(call.get("id"), str): + block["id"] = call["id"] + return block + if "function_response" in plain: + response = to_plain(plain["function_response"]) or {} + response_block: Dict[str, Any] = { + "type": "function", + "tool_name": response.get("name") or "", + "content": response.get("response"), + } + if isinstance(response.get("id"), str): + response_block["tool_use_id"] = response["id"] + return response_block + if not plain: + return None + key = next(iter(plain)) + fallback: Dict[str, Any] = {"type": key, key: to_plain(plain[key])} + return cast(FormattedContentItem, fallback) + + +def _format_message_content(content: Any) -> Any: + if isinstance(content, list): + return _format_parts_as_content_blocks(content) + if not isinstance(content, str): + return str(content) + return content + + +def _is_bare_part(plain: Any) -> bool: + return isinstance(plain, dict) and bool( + _BARE_PART_KEYS.intersection(normalize_part_keys(plain)) + ) + + +def _object_message_role(item: Any) -> str: + role = getattr(item, "role", "user") if hasattr(item, "role") else "user" + # Ensure role is a string + return role if isinstance(role, str) else "user" + + +def _format_response_part(part: Any) -> Optional[FormattedContentItem]: + # Checked ahead of _format_part so loosely-specced MagicMock + # fixtures (which report a truthy .text but aren't real Part + # objects) still resolve to a text block — must stay ahead of + # the _format_part delegation below. + text = getattr(part, "text", None) + if isinstance(text, str) and text: + # `is True` so loosely-specced mocks (whose .thought is a + # truthy Mock) still land on the text branch below. + if getattr(part, "thought", None) is True: + return {"type": "thinking", "thinking": text} + else: + return {"type": "text", "text": text} + + return _format_streaming_part(part) + + +def _format_response_candidate(candidate: Any) -> Optional[FormattedMessage]: + if hasattr(candidate, "content") and candidate.content: + content = _format_candidate_parts(candidate, streaming=False) + + if content: + return { + "role": "assistant", + "content": content, + } + + elif hasattr(candidate, "text") and candidate.text: + return { + "role": "assistant", + "content": [{"type": "text", "text": candidate.text}], + } + + return None + + +def _has_grounding_metadata(candidate: Any) -> bool: + if hasattr(candidate, "grounding_metadata") and candidate.grounding_metadata: + grounding_metadata = candidate.grounding_metadata + + # Check if web_search_queries exists and is non-empty + if hasattr(grounding_metadata, "web_search_queries"): + queries = grounding_metadata.web_search_queries + + if queries is not None and len(queries) > 0: + return True + + # Check if grounding_chunks exists and is non-empty + if hasattr(grounding_metadata, "grounding_chunks"): + chunks = grounding_metadata.grounding_chunks + + if chunks is not None and len(chunks) > 0: + return True + + return False + + +def _has_search_function(candidate: Any) -> bool: + # Also check for google_search or grounding in function call names + if hasattr(candidate, "content") and candidate.content: + if hasattr(candidate.content, "parts") and candidate.content.parts: + for part in candidate.content.parts: + if _is_search_function_part(part): + return True + return False + + +def _add_gemini_detail_usage(usage: TokenUsage, metadata: Any) -> None: + # Add cache tokens if present (don't add if 0) + if hasattr(metadata, "cached_content_token_count"): + cache_tokens = metadata.cached_content_token_count + if cache_tokens and cache_tokens > 0: + usage["cache_read_input_tokens"] = cache_tokens + # Gemini counts cached_content_token_count inside prompt_token_count, so + # declare the accounting model rather than leaving ingestion to infer it. + # Under explicit context caching the two counts come from separate + # measurements and can disagree by a few percent, which makes inference + # from the token counts alone unreliable. + usage["cache_reporting_exclusive"] = False + + # Add reasoning tokens if present (don't add if 0) + if hasattr(metadata, "thoughts_token_count"): + reasoning_tokens = metadata.thoughts_token_count + if reasoning_tokens and reasoning_tokens > 0: + usage["reasoning_tokens"] = reasoning_tokens + + +def _format_streaming_part(part: Any) -> Optional[FormattedContentItem]: + if hasattr(part, "function_call") and part.function_call: + function_call = part.function_call + return _function_call_block( + function_call.name, + function_call.args, + getattr(function_call, "id", None), + ) + + return _format_part(part) + + +def _merge_streaming_blocks( + accumulated_content: List[Any], +) -> List[FormattedContentItem]: + content: List[FormattedContentItem] = [] + text_parts = [] + + for item in accumulated_content: + if isinstance(item, str): + # Legacy support: accumulate strings + text_parts.append(item) + elif isinstance(item, dict): + # New format: content blocks + if item.get("type") == "text": + text_parts.append(item.get("text", "")) + else: + # If we have accumulated text, add it first + if text_parts: + content.append( + { + "type": "text", + "text": "".join(text_parts), + } + ) + text_parts = [] + + if item.get("type") == "function": + content.append(_format_streaming_function(item)) + else: + content.append(item) + + # Add any remaining text + if text_parts: + content.append( + { + "type": "text", + "text": "".join(text_parts), + } + ) + + return content + + +def _format_streaming_function(item: Dict[str, Any]) -> FormattedContentItem: + # Add the function call + function_block: Dict[str, Any] = { + "type": "function", + "function": item.get("function", {}), + } + if isinstance(item.get("id"), str): + function_block["id"] = item["id"] + return function_block + + +def _format_candidate_parts( + candidate: Any, streaming: bool +) -> List[FormattedContentItem]: + content: List[FormattedContentItem] = [] + if not (hasattr(candidate, "content") and candidate.content): + return content + if hasattr(candidate.content, "parts") and candidate.content.parts: + for part in candidate.content.parts: + block = ( + _format_streaming_part(part) + if streaming + else _format_response_part(part) + ) + if block is not None: + content.append(block) + return content + + +def _is_search_function_part(part: Any) -> bool: + if hasattr(part, "function_call") and part.function_call: + function_name = getattr(part.function_call, "name", "").lower() + + if "google_search" in function_name or "grounding" in function_name: + return True + return False diff --git a/posthog/ai/langchain/callbacks.py b/posthog/ai/langchain/callbacks.py index f670d6794..0589f472c 100644 --- a/posthog/ai/langchain/callbacks.py +++ b/posthog/ai/langchain/callbacks.py @@ -39,6 +39,7 @@ ToolMessage, ) from langchain_core.outputs import ChatGeneration, LLMResult +from langchain_core.outputs import Generation as _Generation from pydantic import BaseModel from posthog import setup @@ -641,33 +642,7 @@ def _capture_generation( parent_run_id: Optional[UUID] = None, include_parent_id: bool = True, ): - # The served tier comes from the response, because a requested tier can be refused. - model_params = run.model_params - served_tier = None - if isinstance(output, LLMResult) and isinstance(output.llm_output, dict): - served_tier = output.llm_output.get("service_tier") - if served_tier is not None: - model_params = {**(model_params or {}), "service_tier": served_tier} - - event_properties = { - "$ai_trace_id": trace_id, - "$ai_span_id": run_id, - "$ai_span_name": run.name, - "$ai_provider": run.provider, - "$ai_model": run.model, - "$ai_model_parameters": model_params, - # The explicit served-tier signal cost processing prices from. - **({"$ai_service_tier": served_tier} if served_tier is not None else {}), - "$ai_input": with_privacy_mode( - self._ph_client, - self._privacy_mode, - finalize_ai_content(run.input, self._ph_client), - ), - "$ai_http_status": 200, - "$ai_latency": run.latency, - "$ai_base_url": run.base_url, - "$ai_framework": "langchain", - } + event_properties = self._generation_properties(trace_id, run_id, run, output) if include_parent_id: event_properties["$ai_parent_id"] = parent_run_id @@ -696,60 +671,11 @@ def _capture_generation( output, event_properties ) else: - # Add usage - usage = _parse_usage(output, run.provider, run.model) - # Omitted when the provider never reported a count: absent means - # unknown, 0 is a report of nothing. - if usage.input_tokens is not None: - event_properties["$ai_input_tokens"] = usage.input_tokens - if usage.output_tokens is not None: - event_properties["$ai_output_tokens"] = usage.output_tokens - if usage.cache_write_tokens is not None: - event_properties["$ai_cache_creation_input_tokens"] = ( - usage.cache_write_tokens - ) - if ( - usage.cache_write_5m_tokens is not None - and usage.cache_write_1h_tokens is not None - ): - event_properties["$ai_cache_creation_5m_input_tokens"] = ( - usage.cache_write_5m_tokens - ) - event_properties["$ai_cache_creation_1h_input_tokens"] = ( - usage.cache_write_1h_tokens - ) - if usage.cache_read_tokens is not None: - event_properties["$ai_cache_read_input_tokens"] = ( - usage.cache_read_tokens - ) - if usage.reasoning_tokens is not None: - event_properties["$ai_reasoning_tokens"] = usage.reasoning_tokens - if usage.web_search_count is not None and usage.web_search_count > 0: - event_properties["$ai_web_search_count"] = usage.web_search_count - - # Generation results - generation_result = output.generations[-1] - if isinstance(generation_result[-1], ChatGeneration): - completions = [ - _convert_message_to_dict(cast(ChatGeneration, generation).message) - for generation in generation_result - ] - else: - completions = [ - _extract_raw_response(generation) - for generation in generation_result - ] - event_properties["$ai_output_choices"] = with_privacy_mode( - self._ph_client, - self._privacy_mode, - finalize_ai_content(completions, self._ph_client), + _add_generation_usage( + event_properties, _parse_usage(output, run.provider, run.model) ) - # Extract the stop reason from the generation and its metadata - if output.generations and output.generations[-1]: - stop_reason = _extract_stop_reason(output.generations[-1][-1]) - if stop_reason is not None: - event_properties["$ai_stop_reason"] = stop_reason + self._add_generation_output(event_properties, output) _capture_ai_event( self._ph_client, @@ -759,6 +685,68 @@ def _capture_generation( groups=self._groups, ) + def _generation_properties( + self, + trace_id: Any, + run_id: UUID, + run: GenerationMetadata, + output: Union[LLMResult, BaseException], + ) -> dict[str, Any]: + # The served tier comes from the response, because a requested tier can be refused. + model_params = run.model_params + served_tier = None + if isinstance(output, LLMResult) and isinstance(output.llm_output, dict): + served_tier = output.llm_output.get("service_tier") + if served_tier is not None: + model_params = {**(model_params or {}), "service_tier": served_tier} + + event_properties = { + "$ai_trace_id": trace_id, + "$ai_span_id": run_id, + "$ai_span_name": run.name, + "$ai_provider": run.provider, + "$ai_model": run.model, + "$ai_model_parameters": model_params, + # The explicit served-tier signal cost processing prices from. + **({"$ai_service_tier": served_tier} if served_tier is not None else {}), + "$ai_input": with_privacy_mode( + self._ph_client, + self._privacy_mode, + finalize_ai_content(run.input, self._ph_client), + ), + "$ai_http_status": 200, + "$ai_latency": run.latency, + "$ai_base_url": run.base_url, + "$ai_framework": "langchain", + } + return event_properties + + def _add_generation_output( + self, event_properties: dict[str, Any], output: LLMResult + ) -> None: + # Generation results + generation_result = output.generations[-1] + if isinstance(generation_result[-1], ChatGeneration): + completions = [ + _convert_message_to_dict(cast(ChatGeneration, generation).message) + for generation in generation_result + ] + else: + completions = [ + _extract_raw_response(generation) for generation in generation_result + ] + event_properties["$ai_output_choices"] = with_privacy_mode( + self._ph_client, + self._privacy_mode, + finalize_ai_content(completions, self._ph_client), + ) + + # Extract the stop reason from the generation and its metadata + if output.generations and output.generations[-1]: + stop_reason = _extract_stop_reason(output.generations[-1][-1]) + if stop_reason is not None: + event_properties["$ai_stop_reason"] = stop_reason + def _log_debug_event( self, event_name: str, @@ -822,6 +810,18 @@ def _convert_lc_tool_calls_to_oai( def _convert_message_to_dict(message: BaseMessage) -> dict[str, Any]: + message_dict = _message_role_and_content(message) + + if message.additional_kwargs: + message_dict.update(message.additional_kwargs) + + if "content" in message_dict and not message_dict["content"]: + message_dict["content"] = "" + + return message_dict + + +def _message_role_and_content(message: BaseMessage) -> dict[str, Any]: # assistant message if isinstance(message, HumanMessage): message_dict = {"role": "user", "content": message.content} @@ -840,12 +840,6 @@ def _convert_message_to_dict(message: BaseMessage) -> dict[str, Any]: else: message_dict = {"role": message.type, "content": str(message.content)} - if message.additional_kwargs: - message_dict.update(message.additional_kwargs) - - if "content" in message_dict and not message_dict["content"]: - message_dict["content"] = "" - return message_dict @@ -885,63 +879,9 @@ def _parse_usage_model( if isinstance(usage, BaseModel): usage = usage.__dict__ - conversion_list = [ - # https://pypi.org/project/langchain-anthropic/ (works also for Bedrock-Anthropic) - ("input_tokens", "input"), - ("output_tokens", "output"), - ("cache_creation_input_tokens", "cache_write"), - ("cache_read_input_tokens", "cache_read"), - # https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/get-token-count - ("prompt_token_count", "input"), - ("candidates_token_count", "output"), - ("cached_content_token_count", "cache_read"), - ("thoughts_token_count", "reasoning"), - # Bedrock: https://docs.aws.amazon.com/bedrock/latest/userguide/monitoring-cw.html#runtime-cloudwatch-metrics - ("inputTokenCount", "input"), - ("outputTokenCount", "output"), - ("cacheCreationInputTokenCount", "cache_write"), - ("cacheReadInputTokenCount", "cache_read"), - # Bedrock Anthropic - ("prompt_tokens", "input"), - ("completion_tokens", "output"), - ("cache_creation_input_tokens", "cache_write"), - ("cache_read_input_tokens", "cache_read"), - # langchain-ibm https://pypi.org/project/langchain-ibm/ - ("input_token_count", "input"), - ("generated_token_count", "output"), - ] - - parsed_usage = {} - for model_key, type_key in conversion_list: - if model_key in usage: - captured_count = usage[model_key] - final_count = ( - sum(captured_count) - if isinstance(captured_count, list) - else captured_count - ) # For Bedrock, the token count is a list when streamed - - parsed_usage[type_key] = final_count - - # Caching (OpenAI & langchain 0.3.9+) - if "input_token_details" in usage and isinstance( - usage["input_token_details"], dict - ): - input_token_details = usage["input_token_details"] - parsed_usage["cache_write"] = input_token_details.get("cache_creation") - cache_write_ttl = _extract_cache_creation_ttl_breakdown(input_token_details) - if cache_write_ttl is not None: - cache_write_5m, cache_write_1h = cache_write_ttl - parsed_usage["cache_write_5m"] = cache_write_5m - parsed_usage["cache_write_1h"] = cache_write_1h - parsed_usage["cache_write"] = cache_write_5m + cache_write_1h - parsed_usage["cache_read"] = input_token_details.get("cache_read") + parsed_usage = _flat_usage_counts(usage) - # Reasoning (OpenAI & langchain 0.3.9+) - if "output_token_details" in usage and isinstance( - usage["output_token_details"], dict - ): - parsed_usage["reasoning"] = usage["output_token_details"].get("reasoning") + _add_usage_details(parsed_usage, usage) # Anthropic reports the exact number of web searches of a response web_search_requests = _extract_web_search_requests(usage) @@ -964,6 +904,13 @@ def _parse_usage_model( cache_write_1h_tokens=parsed_usage.get("cache_write_1h"), web_search_count=parsed_usage.get("web_search"), ) + _subtract_anthropic_cache(normalized_usage, provider, model) + return normalized_usage + + +def _subtract_anthropic_cache( + normalized_usage: ModelUsage, provider: Optional[str], model: Optional[str] +) -> None: # For Anthropic providers, LangChain reports input_tokens as the sum of all input tokens. # Our cost calculation expects them to be separate for Anthropic, so we subtract cache tokens. # Both cache_read and cache_write tokens should be subtracted since Anthropic's raw API @@ -971,11 +918,7 @@ def _parse_usage_model( # For other providers (OpenAI, etc.), input_tokens already excludes cache tokens as expected. # Match logic consistent with plugin-server: exact match on provider, substring # match on model, or a Claude model under another provider (e.g. Vertex AI) - is_anthropic = False - if provider and provider.lower() == "anthropic": - is_anthropic = True - elif model and ("anthropic" in model.lower() or model.lower().startswith("claude")): - is_anthropic = True + is_anthropic = _is_anthropic_model(provider, model) if is_anthropic and normalized_usage.input_tokens: cache_tokens = (normalized_usage.cache_read_tokens or 0) + ( @@ -985,7 +928,70 @@ def _parse_usage_model( normalized_usage.input_tokens = max( normalized_usage.input_tokens - cache_tokens, 0 ) - return normalized_usage + + +def _add_usage_details(parsed_usage: dict, usage: dict) -> None: + # Caching (OpenAI & langchain 0.3.9+) + if "input_token_details" in usage and isinstance( + usage["input_token_details"], dict + ): + input_token_details = usage["input_token_details"] + parsed_usage["cache_write"] = input_token_details.get("cache_creation") + cache_write_ttl = _extract_cache_creation_ttl_breakdown(input_token_details) + if cache_write_ttl is not None: + cache_write_5m, cache_write_1h = cache_write_ttl + parsed_usage["cache_write_5m"] = cache_write_5m + parsed_usage["cache_write_1h"] = cache_write_1h + parsed_usage["cache_write"] = cache_write_5m + cache_write_1h + parsed_usage["cache_read"] = input_token_details.get("cache_read") + + # Reasoning (OpenAI & langchain 0.3.9+) + if "output_token_details" in usage and isinstance( + usage["output_token_details"], dict + ): + parsed_usage["reasoning"] = usage["output_token_details"].get("reasoning") + + +def _flat_usage_counts(usage: dict) -> dict: + conversion_list = [ + # https://pypi.org/project/langchain-anthropic/ (works also for Bedrock-Anthropic) + ("input_tokens", "input"), + ("output_tokens", "output"), + ("cache_creation_input_tokens", "cache_write"), + ("cache_read_input_tokens", "cache_read"), + # https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/get-token-count + ("prompt_token_count", "input"), + ("candidates_token_count", "output"), + ("cached_content_token_count", "cache_read"), + ("thoughts_token_count", "reasoning"), + # Bedrock: https://docs.aws.amazon.com/bedrock/latest/userguide/monitoring-cw.html#runtime-cloudwatch-metrics + ("inputTokenCount", "input"), + ("outputTokenCount", "output"), + ("cacheCreationInputTokenCount", "cache_write"), + ("cacheReadInputTokenCount", "cache_read"), + # Bedrock Anthropic + ("prompt_tokens", "input"), + ("completion_tokens", "output"), + ("cache_creation_input_tokens", "cache_write"), + ("cache_read_input_tokens", "cache_read"), + # langchain-ibm https://pypi.org/project/langchain-ibm/ + ("input_token_count", "input"), + ("generated_token_count", "output"), + ] + + parsed_usage = {} + for model_key, type_key in conversion_list: + if model_key in usage: + captured_count = usage[model_key] + final_count = ( + sum(captured_count) + if isinstance(captured_count, list) + else captured_count + ) # For Bedrock, the token count is a list when streamed + + parsed_usage[type_key] = final_count + + return parsed_usage def _parse_usage( @@ -1022,45 +1028,9 @@ def _parse_usage( llm_usage = _parse_usage_model(generation["usage"], provider, model) break - for generation_chunk in generation: - if generation_chunk.generation_info and ( - "usage_metadata" in generation_chunk.generation_info - ): - llm_usage = _parse_usage_model( - generation_chunk.generation_info["usage_metadata"], - provider, - model, - ) - break - - message_chunk = getattr(generation_chunk, "message", {}) - response_metadata = getattr(message_chunk, "response_metadata", {}) - - bedrock_anthropic_usage = ( - response_metadata.get("usage", None) # for Bedrock-Anthropic - if isinstance(response_metadata, dict) - else None - ) - bedrock_titan_usage = ( - response_metadata.get( - "amazon-bedrock-invocationMetrics", None - ) # for Bedrock-Titan - if isinstance(response_metadata, dict) - else None - ) - # LangChain's standard usage, which also covers Ollama - usage_metadata = getattr(message_chunk, "usage_metadata", None) - - # Prefer the standard usage: its input_tokens include cache reads - # and writes, as the Anthropic subtraction in _parse_usage_model - # expects. ChatAnthropic also copies the raw API usage, whose - # input_tokens already exclude the cache, into response_metadata. - chunk_usage = ( - usage_metadata or bedrock_anthropic_usage or bedrock_titan_usage - ) - if chunk_usage: - llm_usage = _parse_usage_model(chunk_usage, provider, model) - break + parsed = _generation_usage(generation, provider, model) + if parsed is not None: + llm_usage = parsed if llm_usage.web_search_count is None: llm_usage.web_search_count = web_search_count @@ -1118,3 +1088,88 @@ def _stringify_exception(exception: BaseException) -> str: if description: return f"{exception.__class__.__name__}: {description}" return exception.__class__.__name__ + + +def _add_generation_usage( + event_properties: dict[str, Any], usage: "ModelUsage" +) -> None: + # Omitted when the provider never reported a count: absent means unknown, + # 0 is a report of nothing. + for field, property_name in ( + ("input_tokens", "$ai_input_tokens"), + ("output_tokens", "$ai_output_tokens"), + ("cache_write_tokens", "$ai_cache_creation_input_tokens"), + ): + value = getattr(usage, field) + if value is not None: + event_properties[property_name] = value + if ( + usage.cache_write_5m_tokens is not None + and usage.cache_write_1h_tokens is not None + ): + event_properties["$ai_cache_creation_5m_input_tokens"] = ( + usage.cache_write_5m_tokens + ) + event_properties["$ai_cache_creation_1h_input_tokens"] = ( + usage.cache_write_1h_tokens + ) + for field, property_name in ( + ("cache_read_tokens", "$ai_cache_read_input_tokens"), + ("reasoning_tokens", "$ai_reasoning_tokens"), + ): + value = getattr(usage, field) + if value is not None: + event_properties[property_name] = value + if usage.web_search_count is not None and usage.web_search_count > 0: + event_properties["$ai_web_search_count"] = usage.web_search_count + + +def _generation_usage( + generation: list[_Generation], provider: Optional[str], model: Optional[str] +) -> Optional[ModelUsage]: + for generation_chunk in generation: + if generation_chunk.generation_info and ( + "usage_metadata" in generation_chunk.generation_info + ): + return _parse_usage_model( + generation_chunk.generation_info["usage_metadata"], + provider, + model, + ) + + message_chunk = getattr(generation_chunk, "message", {}) + response_metadata = getattr(message_chunk, "response_metadata", {}) + + bedrock_anthropic_usage = ( + response_metadata.get("usage", None) # for Bedrock-Anthropic + if isinstance(response_metadata, dict) + else None + ) + bedrock_titan_usage = ( + response_metadata.get( + "amazon-bedrock-invocationMetrics", None + ) # for Bedrock-Titan + if isinstance(response_metadata, dict) + else None + ) + # LangChain's standard usage, which also covers Ollama + usage_metadata = getattr(message_chunk, "usage_metadata", None) + + # Prefer the standard usage: its input_tokens include cache reads + # and writes, as the Anthropic subtraction in _parse_usage_model + # expects. ChatAnthropic also copies the raw API usage, whose + # input_tokens already exclude the cache, into response_metadata. + chunk_usage = usage_metadata or bedrock_anthropic_usage or bedrock_titan_usage + if chunk_usage: + return _parse_usage_model(chunk_usage, provider, model) + return None + + +def _is_anthropic_model(provider: Optional[str], model: Optional[str]) -> bool: + is_anthropic = False + if provider and provider.lower() == "anthropic": + is_anthropic = True + elif model and ("anthropic" in model.lower() or model.lower().startswith("claude")): + is_anthropic = True + + return is_anthropic diff --git a/posthog/ai/langchain/middleware.py b/posthog/ai/langchain/middleware.py index 8cf282a87..e434c8473 100644 --- a/posthog/ai/langchain/middleware.py +++ b/posthog/ai/langchain/middleware.py @@ -252,22 +252,9 @@ def _finish_model( if not isinstance(run, GenerationMetadata): return - output: LLMResult | BaseException - if isinstance(result, BaseException): - output = result - else: - generations = [ - ChatGeneration(message=message) - for message in result.result - if isinstance(message, AIMessage) - ] - if not generations: - return - metadata = generations[-1].message.response_metadata - output = LLMResult( - generations=[generations], - llm_output=metadata if isinstance(metadata, dict) else None, - ) + output = _model_output(result) + if output is None: + return root_id = _root_id(state) self._safely_call( @@ -368,4 +355,24 @@ def _public_state(state: Mapping[str, Any]) -> dict[str, Any]: } +def _model_output( + result: ModelResponse[Any] | BaseException, +) -> LLMResult | BaseException | None: + if isinstance(result, BaseException): + return result + else: + generations = [ + ChatGeneration(message=message) + for message in result.result + if isinstance(message, AIMessage) + ] + if not generations: + return None + metadata = generations[-1].message.response_metadata + return LLMResult( + generations=[generations], + llm_output=metadata if isinstance(metadata, dict) else None, + ) + + __all__ = ["PostHogMiddleware"] diff --git a/posthog/ai/media.py b/posthog/ai/media.py index 6c4b4f009..ef227061e 100644 --- a/posthog/ai/media.py +++ b/posthog/ai/media.py @@ -16,18 +16,22 @@ def to_plain(obj: Any) -> Any: if isinstance(obj, dict): - return {k: v for k, v in obj.items() if v is not None} + return _without_none(obj) model_dump = getattr(obj, "model_dump", None) if callable(model_dump): try: return model_dump(exclude_none=True) except TypeError: - return {k: v for k, v in model_dump().items() if v is not None} + return _without_none(model_dump()) if dataclasses.is_dataclass(obj) and not isinstance(obj, type): - return {k: v for k, v in dataclasses.asdict(obj).items() if v is not None} + return _without_none(dataclasses.asdict(obj)) return obj +def _without_none(value: dict) -> dict: + return {k: v for k, v in value.items() if v is not None} + + def ensure_serializable(obj: Any) -> Any: """Ensure an object is JSON-serializable, converting to str as fallback. diff --git a/posthog/ai/openai/_streaming.py b/posthog/ai/openai/_streaming.py index 3a7d059b4..49234bee0 100644 --- a/posthog/ai/openai/_streaming.py +++ b/posthog/ai/openai/_streaming.py @@ -26,10 +26,7 @@ class _ResponsesStreamState: def process_chunk(self, chunk: Any) -> None: response = getattr(chunk, "response", None) - if response and self.model is None and hasattr(response, "model"): - self.model = response.model - if response and self.service_tier is None: - self.service_tier = getattr(response, "service_tier", None) + self._record_response_metadata(response) chunk_usage = extract_openai_usage_from_chunk(chunk, "responses") if chunk_usage: @@ -46,6 +43,12 @@ def process_chunk(self, chunk: Any) -> None: if stop_reason is not None: self.stop_reason = stop_reason + def _record_response_metadata(self, response: Any) -> None: + if response and self.model is None and hasattr(response, "model"): + self.model = response.model + if response and self.service_tier is None: + self.service_tier = getattr(response, "service_tier", None) + @dataclass class _ChoiceStream: @@ -82,25 +85,28 @@ def process_chunk(self, chunk: Any) -> None: merge_usage_stats(self.usage_stats, chunk_usage) for choice in getattr(chunk, "choices", None) or []: - index = getattr(choice, "index", None) - if not isinstance(index, int): - index = 0 - view = _ChoiceStream([choice]) - - content = extract_openai_content_from_chunk(view, "chat") - if content is not None: - self._outputs.setdefault(index, []).append(content) - - chunk_tool_calls = extract_openai_tool_calls_from_chunk(view) - if chunk_tool_calls: - accumulate_openai_tool_calls( - self._tool_calls.setdefault(index, {}), chunk_tool_calls - ) - - # Like a non-streamed completion, the stop reason is the first choice's. - finish_reason = getattr(choice, "finish_reason", None) - if finish_reason is not None and index == 0: - self.stop_reason = finish_reason + self._process_choice(choice) + + def _process_choice(self, choice: Any) -> None: + index = getattr(choice, "index", None) + if not isinstance(index, int): + index = 0 + view = _ChoiceStream([choice]) + + content = extract_openai_content_from_chunk(view, "chat") + if content is not None: + self._outputs.setdefault(index, []).append(content) + + chunk_tool_calls = extract_openai_tool_calls_from_chunk(view) + if chunk_tool_calls: + accumulate_openai_tool_calls( + self._tool_calls.setdefault(index, {}), chunk_tool_calls + ) + + # Like a non-streamed completion, the stop reason is the first choice's. + finish_reason = getattr(choice, "finish_reason", None) + if finish_reason is not None and index == 0: + self.stop_reason = finish_reason @property def tool_calls(self) -> Optional[List[Dict[str, Any]]]: diff --git a/posthog/ai/openai/openai_converter.py b/posthog/ai/openai/openai_converter.py index 6faf1a6e9..72f6dc457 100644 --- a/posthog/ai/openai/openai_converter.py +++ b/posthog/ai/openai/openai_converter.py @@ -37,39 +37,7 @@ def _format_responses_output_items(items: Any) -> List[FormattedContentItem]: item_type = _item_attr(item, "type") if item_type == "message": - message_content = _item_attr(item, "content") - if isinstance(message_content, list): - for content_item in message_content: - content_item_type = _item_attr(content_item, "type") - content_item_text = _item_attr(content_item, "text") - content_item_refusal = _item_attr(content_item, "refusal") - - if content_item_type == "output_text" and ( - content_item_text is not None - ): - content.append({"type": "text", "text": content_item_text}) - - elif content_item_type == "refusal" and ( - content_item_refusal is not None - ): - content.append( - {"type": "refusal", "refusal": content_item_refusal} - ) - - elif content_item_text is not None: - content.append({"type": "text", "text": content_item_text}) - - elif content_item_type == "input_image" and ( - _item_attr(content_item, "image_url") is not None - ): - image_content: FormattedImageContent = { - "type": "image", - "image": _item_attr(content_item, "image_url"), - } - content.append(image_content) - - elif message_content is not None: - content.append({"type": "text", "text": str(message_content)}) + content.extend(_format_response_message_content(item)) elif item_type == "function_call": call_id = _item_attr(item, "call_id") @@ -139,63 +107,9 @@ def format_openai_response(response: Any) -> List[FormattedMessage]: # Handle Chat Completions response format if hasattr(response, "choices"): - content: List[FormattedContentItem] = [] - role = "assistant" - - for choice in response.choices: - if hasattr(choice, "message") and choice.message: - if choice.message.role: - role = choice.message.role - - if choice.message.content: - content.append( - { - "type": "text", - "text": choice.message.content, - } - ) - - # A refused request carries its text in `refusal` and leaves `content` empty - refusal = getattr(choice.message, "refusal", None) - if refusal: - content.append({"type": "refusal", "refusal": refusal}) - - if hasattr(choice.message, "tool_calls") and choice.message.tool_calls: - for tool_call in choice.message.tool_calls: - # Custom tools carry their free-form text in `custom.input`, - # with no `function` object. - is_custom = getattr(tool_call, "type", None) == "custom" - call = getattr( - tool_call, "custom" if is_custom else "function", None - ) - if call is None: - continue - content.append( - { - "type": "function", - "id": tool_call.id, - "function": { - "name": call.name, - "arguments": call.input - if is_custom - else call.arguments, - }, - } - ) - - # Handle audio output (gpt-4o-audio-preview) - if hasattr(choice.message, "audio") and choice.message.audio: - # Convert Pydantic model to dict to capture all fields from OpenAI - audio_dict = choice.message.audio.model_dump() - content.append({"type": "audio", **audio_dict}) - - if content: - output.append( - { - "role": role, - "content": content, - } - ) + message = _format_chat_completion_choices(response.choices) + if message is not None: + output.append(message) # Handle Responses API format if hasattr(response, "output"): @@ -233,53 +147,13 @@ def format_openai_input( if messages is not None: for msg in messages: - plain = to_plain(msg) - if not isinstance(plain, dict): - plain = {"role": "user", "content": str(plain)} - - formatted: Dict[str, Any] = { - "role": plain.get("role", "user"), - "content": plain.get("content"), - } - - for key in ("tool_calls", "tool_call_id", "name", "audio", "refusal"): - if plain.get(key) is not None: - formatted[key] = ( - to_plain(plain[key]) if key == "audio" else plain[key] - ) - - formatted_messages.append(cast(FormattedMessage, formatted)) + formatted_messages.append(_format_chat_input_message(msg)) # Handle Responses API format if input_data is not None: if isinstance(input_data, list): for item in input_data: - if not isinstance(item, (dict, str)): - item = to_plain(item) - - if ( - isinstance(item, dict) - and "type" in item - and "role" not in item - and "content" not in item - ): - formatted_messages.append(cast(FormattedMessage, to_plain(item))) - continue - - role = "user" - content = "" - - if isinstance(item, dict): - role = item.get("role", "user") - content = item.get("content", "") - - elif isinstance(item, str): - content = item - - else: - content = str(item) - - formatted_messages.append({"role": role, "content": content}) + formatted_messages.append(_format_response_input_item(item)) elif isinstance(input_data, str): formatted_messages.append({"role": "user", "content": input_data}) @@ -367,93 +241,15 @@ def extract_openai_web_search_count(response: Any) -> int: Number of web search requests (exact count or binary 1/0) """ - # Priority 1: Check for exact count in Responses API output - if hasattr(response, "output"): - web_search_count = 0 - - for item in response.output: - if hasattr(item, "type") and item.type == "web_search_call": - web_search_count += 1 - - web_search_count = max(0, web_search_count) - - if web_search_count > 0: - return web_search_count - - # Priority 2: Binary detection (returns 1 or 0) - - # Check root-level indicators (Perplexity) - if hasattr(response, "citations"): - citations = getattr(response, "citations") - - if citations and len(citations) > 0: - return 1 - - if hasattr(response, "search_results"): - search_results = getattr(response, "search_results") - - if search_results and len(search_results) > 0: - return 1 - - if hasattr(response, "usage") and hasattr(response.usage, "search_context_size"): - if response.usage.search_context_size: - return 1 - - # Check for url_citation annotations in choices (Chat Completions) - if hasattr(response, "choices"): - for choice in response.choices: - # Check message.annotations (non-streaming or final chunk) - if hasattr(choice, "message") and hasattr(choice.message, "annotations"): - annotations = choice.message.annotations - - if annotations: - for annotation in annotations: - # Support both dict and object formats - annotation_type = ( - annotation.get("type") - if isinstance(annotation, dict) - else getattr(annotation, "type", None) - ) - - if annotation_type == "url_citation": - return 1 - - # Check delta.annotations (streaming chunks) - if hasattr(choice, "delta") and hasattr(choice.delta, "annotations"): - annotations = choice.delta.annotations - - if annotations: - for annotation in annotations: - # Support both dict and object formats - annotation_type = ( - annotation.get("type") - if isinstance(annotation, dict) - else getattr(annotation, "type", None) - ) - - if annotation_type == "url_citation": - return 1 - - # Check for url_citation annotations in output (Responses API) - if hasattr(response, "output"): - for item in response.output: - if hasattr(item, "content") and isinstance(item.content, list): - for content_item in item.content: - if hasattr(content_item, "annotations"): - annotations = content_item.annotations - - if annotations: - for annotation in annotations: - # Support both dict and object formats - annotation_type = ( - annotation.get("type") - if isinstance(annotation, dict) - else getattr(annotation, "type", None) - ) - - if annotation_type == "url_citation": - return 1 - + count = _count_response_web_search_calls(response) + if count > 0: + return count + if _has_root_web_search(response): + return 1 + if _has_choice_web_citations(response): + return 1 + if _has_response_web_citations(response): + return 1 return 0 @@ -482,49 +278,7 @@ def extract_openai_usage_from_response(response: Any) -> TokenUsage: if not hasattr(response, "usage") or not response.usage: return TokenUsage() - cached_tokens = None - input_tokens = None - output_tokens = None - reasoning_tokens = None - - # Responses API format - if hasattr(response.usage, "input_tokens"): - input_tokens = response.usage.input_tokens - if hasattr(response.usage, "output_tokens"): - output_tokens = response.usage.output_tokens - if hasattr(response.usage, "input_tokens_details") and hasattr( - response.usage.input_tokens_details, "cached_tokens" - ): - cached_tokens = response.usage.input_tokens_details.cached_tokens - if hasattr(response.usage, "output_tokens_details") and hasattr( - response.usage.output_tokens_details, "reasoning_tokens" - ): - reasoning_tokens = response.usage.output_tokens_details.reasoning_tokens - - # Chat Completions format - if hasattr(response.usage, "prompt_tokens"): - input_tokens = response.usage.prompt_tokens - if hasattr(response.usage, "completion_tokens"): - output_tokens = response.usage.completion_tokens - if hasattr(response.usage, "prompt_tokens_details") and hasattr( - response.usage.prompt_tokens_details, "cached_tokens" - ): - cached_tokens = response.usage.prompt_tokens_details.cached_tokens - if hasattr(response.usage, "completion_tokens_details") and hasattr( - response.usage.completion_tokens_details, "reasoning_tokens" - ): - reasoning_tokens = response.usage.completion_tokens_details.reasoning_tokens - - result = TokenUsage() - if input_tokens is not None: - result["input_tokens"] = input_tokens - if output_tokens is not None: - result["output_tokens"] = output_tokens - - if cached_tokens is not None and cached_tokens > 0: - result["cache_read_input_tokens"] = cached_tokens - if reasoning_tokens is not None and reasoning_tokens > 0: - result["reasoning_tokens"] = reasoning_tokens + result = _extract_openai_response_token_usage(response.usage) web_search_count = extract_openai_web_search_count(response) if web_search_count > 0: @@ -577,74 +331,11 @@ def extract_openai_usage_from_chunk( if not hasattr(chunk, "usage") or not chunk.usage: return usage - # Chat Completions API uses prompt_tokens and completion_tokens - # Standardize to input_tokens and output_tokens - usage["input_tokens"] = getattr(chunk.usage, "prompt_tokens", 0) - usage["output_tokens"] = getattr(chunk.usage, "completion_tokens", 0) - - # Handle cached tokens - if hasattr(chunk.usage, "prompt_tokens_details") and hasattr( - chunk.usage.prompt_tokens_details, "cached_tokens" - ): - cached = chunk.usage.prompt_tokens_details.cached_tokens - if cached is not None: - usage["cache_read_input_tokens"] = cached - - # Handle reasoning tokens - if hasattr(chunk.usage, "completion_tokens_details") and hasattr( - chunk.usage.completion_tokens_details, "reasoning_tokens" - ): - reasoning = chunk.usage.completion_tokens_details.reasoning_tokens - if reasoning is not None: - usage["reasoning_tokens"] = reasoning - - # Capture raw usage metadata for backend processing - # Serialize to dict here in the converter (not in utils) - serialized = serialize_raw_usage(chunk.usage) - if serialized: - usage["raw_usage"] = serialized + usage.update(_extract_openai_stream_token_usage(chunk.usage, "chat")) + _add_openai_raw_usage(usage, chunk.usage) elif provider_type == "responses": - # For Responses API, usage is only in chunk.response.usage on the terminal - # event. A run cut short (e.g. by max_output_tokens) ends on - # response.incomplete instead of response.completed, and is still billed. - if getattr(chunk, "type", None) in _RESPONSES_TERMINAL_EVENT_TYPES: - if ( - hasattr(chunk, "response") - and hasattr(chunk.response, "usage") - and chunk.response.usage - ): - response_usage = chunk.response.usage - usage["input_tokens"] = getattr(response_usage, "input_tokens", 0) - usage["output_tokens"] = getattr(response_usage, "output_tokens", 0) - - # Handle cached tokens - if hasattr(response_usage, "input_tokens_details") and hasattr( - response_usage.input_tokens_details, "cached_tokens" - ): - cached = response_usage.input_tokens_details.cached_tokens - if cached is not None: - usage["cache_read_input_tokens"] = cached - - # Handle reasoning tokens - if hasattr(response_usage, "output_tokens_details") and hasattr( - response_usage.output_tokens_details, "reasoning_tokens" - ): - reasoning = response_usage.output_tokens_details.reasoning_tokens - if reasoning is not None: - usage["reasoning_tokens"] = reasoning - - # Extract web search count from the complete response - if hasattr(chunk, "response"): - web_search_count = extract_openai_web_search_count(chunk.response) - if web_search_count > 0: - usage["web_search_count"] = web_search_count - - # Capture raw usage metadata for backend processing - # Serialize to dict here in the converter (not in utils) - serialized = serialize_raw_usage(response_usage) - if serialized: - usage["raw_usage"] = serialized + usage.update(_extract_openai_response_chunk_usage(chunk)) return usage @@ -669,28 +360,7 @@ def extract_openai_content_from_chunk( """ if provider_type == "chat": - # Chat Completions API format - if ( - hasattr(chunk, "choices") - and chunk.choices - and len(chunk.choices) > 0 - and chunk.choices[0].delta - ): - delta = chunk.choices[0].delta - - if delta.content: - return delta.content - - audio_delta = getattr(delta, "audio", None) - if audio_delta is not None: - plain_audio = to_plain(audio_delta) - if isinstance(plain_audio, dict): - return {"type": "audio", **plain_audio} - return {"type": "audio"} - - refusal_delta = getattr(delta, "refusal", None) - if refusal_delta: - return {"type": "refusal", "refusal": refusal_delta} + return _extract_openai_chat_content(chunk) elif provider_type == "responses": # Responses API format @@ -714,37 +384,14 @@ def extract_openai_tool_calls_from_chunk(chunk: Any) -> Optional[List[Dict[str, List of tool call deltas if present, None otherwise """ if ( - hasattr(chunk, "choices") - and chunk.choices - and len(chunk.choices) > 0 - and chunk.choices[0].delta + _has_openai_chat_delta(chunk) and hasattr(chunk.choices[0].delta, "tool_calls") and chunk.choices[0].delta.tool_calls ): tool_calls = [] for tool_call in chunk.choices[0].delta.tool_calls: - tc_dict = { - "index": getattr(tool_call, "index", None), - } - - if hasattr(tool_call, "id") and tool_call.id: - tc_dict["id"] = tool_call.id - - if hasattr(tool_call, "type") and tool_call.type: - tc_dict["type"] = tool_call.type - - if hasattr(tool_call, "function") and tool_call.function: - function_dict = {} - if hasattr(tool_call.function, "name") and tool_call.function.name: - function_dict["name"] = tool_call.function.name - if ( - hasattr(tool_call.function, "arguments") - and tool_call.function.arguments - ): - function_dict["arguments"] = tool_call.function.arguments - tc_dict["function"] = function_dict + tool_calls.append(_format_openai_tool_delta(tool_call)) - tool_calls.append(tc_dict) return tool_calls return None @@ -768,27 +415,7 @@ def accumulate_openai_tool_calls( chunk_tool_calls: List of tool call deltas from current chunk """ for tool_call_delta in chunk_tool_calls: - index = tool_call_delta.get("index") - if index is None: - # Some OpenAI-compatible providers omit the index. A delta with a new id - # or a function name starts a call, and one with neither continues the - # latest call. Those calls get keys of their own, so they can never - # collide with an index the provider sends later. - call_id = tool_call_delta.get("id") - index = next( - ( - key - for key, tc in accumulated_tool_calls.items() - if call_id and tc["id"] == call_id - ), - None, - ) - if index is None: - has_name = bool((tool_call_delta.get("function") or {}).get("name")) - if accumulated_tool_calls and not call_id and not has_name: - index = next(reversed(accumulated_tool_calls)) - else: - index = f"no-index-{len(accumulated_tool_calls)}" + index = _openai_tool_delta_index(accumulated_tool_calls, tool_call_delta) # Initialize tool call if first time seeing this index if index not in accumulated_tool_calls: @@ -801,22 +428,7 @@ def accumulate_openai_tool_calls( }, } - # Update with new data from delta - tc = accumulated_tool_calls[index] - - if "id" in tool_call_delta and tool_call_delta["id"]: - tc["id"] = tool_call_delta["id"] - - if "type" in tool_call_delta and tool_call_delta["type"]: - tc["type"] = tool_call_delta["type"] - - if "function" in tool_call_delta: - func_delta = tool_call_delta["function"] - if "name" in func_delta and func_delta["name"]: - tc["function"]["name"] = func_delta["name"] - if "arguments" in func_delta and func_delta["arguments"]: - # Arguments are sent incrementally, concatenate them - tc["function"]["arguments"] += func_delta["arguments"] + _apply_openai_tool_delta(accumulated_tool_calls[index], tool_call_delta) def format_openai_streaming_output( @@ -837,93 +449,12 @@ def format_openai_streaming_output( """ if provider_type == "chat": - content_items: List[FormattedContentItem] = [] - - # Add text content if present - if isinstance(accumulated_content, str) and accumulated_content: - content_items.append({"type": "text", "text": accumulated_content}) - elif isinstance(accumulated_content, list): - text_parts: List[str] = [] - audio_id: Optional[str] = None - audio_data_parts: List[str] = [] - audio_transcript_parts: List[str] = [] - refusal_parts: List[str] = [] - - for item in accumulated_content: - if isinstance(item, str): - if item: - text_parts.append(item) - elif isinstance(item, dict) and item.get("type") == "audio": - if audio_id is None and item.get("id"): - audio_id = item["id"] - if item.get("data"): - audio_data_parts.append(item["data"]) - if item.get("transcript"): - audio_transcript_parts.append(item["transcript"]) - elif isinstance(item, dict) and item.get("type") == "refusal": - if item.get("refusal"): - refusal_parts.append(item["refusal"]) - - if text_parts: - content_items.append({"type": "text", "text": "".join(text_parts)}) - - if audio_data_parts or audio_transcript_parts: - audio_block: Dict[str, Any] = {"type": "audio"} - if audio_id is not None: - audio_block["id"] = audio_id - if audio_data_parts: - audio_block["data"] = "".join(audio_data_parts) - if audio_transcript_parts: - audio_block["transcript"] = "".join(audio_transcript_parts) - content_items.append(audio_block) - - if refusal_parts: - content_items.append( - {"type": "refusal", "refusal": "".join(refusal_parts)} - ) - - # Add tool calls if present - if tool_calls: - for tool_call in tool_calls: - if "function" in tool_call: - function_call: FormattedFunctionCall = { - "type": "function", - "id": tool_call.get("id", ""), - "function": tool_call["function"], - } - content_items.append(function_call) - - # Return formatted message with content - if content_items: - return [{"role": "assistant", "content": content_items}] - else: - # Empty response - return [{"role": "assistant", "content": []}] + return _format_openai_chat_stream_output(accumulated_content, tool_calls) elif provider_type == "responses": - if isinstance(accumulated_content, list) and not accumulated_content: - return [] - if isinstance(accumulated_content, list) and accumulated_content: - items: List[Any] = [] - for entry in accumulated_content: - if isinstance(entry, list): - items.extend(entry) - else: - items.append(entry) - - content_items = _format_responses_output_items(items) - role = _responses_output_role(items) - - if content_items: - return [{"role": role, "content": content_items}] - return [] - elif isinstance(accumulated_content, str): - return [ - { - "role": "assistant", - "content": [{"type": "text", "text": accumulated_content}], - } - ] + output = _format_openai_responses_stream_output(accumulated_content) + if output is not None: + return output # Fallback for any other format return [ @@ -950,3 +481,558 @@ def format_openai_streaming_input( from posthog.ai.utils import merge_system_prompt return merge_system_prompt(kwargs, "openai") + + +def _format_response_message_content(item: Any) -> List[FormattedContentItem]: + content: List[FormattedContentItem] = [] + message_content = _item_attr(item, "content") + if isinstance(message_content, list): + for content_item in message_content: + block = _format_response_content_item(content_item) + if block is not None: + content.append(block) + + elif message_content is not None: + content.append({"type": "text", "text": str(message_content)}) + + return content + + +def _format_response_content_item(content_item: Any) -> Optional[FormattedContentItem]: + content_item_type = _item_attr(content_item, "type") + content_item_text = _item_attr(content_item, "text") + content_item_refusal = _item_attr(content_item, "refusal") + + if content_item_type == "output_text" and (content_item_text is not None): + return {"type": "text", "text": content_item_text} + + elif content_item_type == "refusal" and (content_item_refusal is not None): + return {"type": "refusal", "refusal": content_item_refusal} + + elif content_item_text is not None: + return {"type": "text", "text": content_item_text} + + elif content_item_type == "input_image" and ( + _item_attr(content_item, "image_url") is not None + ): + image_content: FormattedImageContent = { + "type": "image", + "image": _item_attr(content_item, "image_url"), + } + return image_content + + return None + + +def _format_chat_message(message: Any) -> List[FormattedContentItem]: + content: List[FormattedContentItem] = [] + if message.content: + content.append( + { + "type": "text", + "text": message.content, + } + ) + + # A refused request carries its text in `refusal` and leaves `content` empty + refusal = getattr(message, "refusal", None) + if refusal: + content.append({"type": "refusal", "refusal": refusal}) + + if hasattr(message, "tool_calls") and message.tool_calls: + for tool_call in message.tool_calls: + block = _format_chat_tool_call(tool_call) + if block is not None: + content.append(block) + + # Handle audio output (gpt-4o-audio-preview) + if hasattr(message, "audio") and message.audio: + # Convert Pydantic model to dict to capture all fields from OpenAI + audio_dict = message.audio.model_dump() + content.append({"type": "audio", **audio_dict}) + + return content + + +def _format_chat_tool_call(tool_call: Any) -> Optional[FormattedContentItem]: + # Custom tools carry their free-form text in `custom.input`, + # with no `function` object. + is_custom = getattr(tool_call, "type", None) == "custom" + call = getattr(tool_call, "custom" if is_custom else "function", None) + if call is None: + return None + return { + "type": "function", + "id": tool_call.id, + "function": { + "name": call.name, + "arguments": call.input if is_custom else call.arguments, + }, + } + + +def _format_chat_input_message(msg: Any) -> FormattedMessage: + plain = to_plain(msg) + if not isinstance(plain, dict): + plain = {"role": "user", "content": str(plain)} + + formatted: Dict[str, Any] = { + "role": plain.get("role", "user"), + "content": plain.get("content"), + } + + for key in ("tool_calls", "tool_call_id", "name", "audio", "refusal"): + if plain.get(key) is not None: + formatted[key] = to_plain(plain[key]) if key == "audio" else plain[key] + + return cast(FormattedMessage, formatted) + + +def _format_response_input_item(item: Any) -> FormattedMessage: + if not isinstance(item, (dict, str)): + item = to_plain(item) + + if ( + isinstance(item, dict) + and "type" in item + and "role" not in item + and "content" not in item + ): + return cast(FormattedMessage, to_plain(item)) + + role = "user" + content = "" + + if isinstance(item, dict): + role = item.get("role", "user") + content = item.get("content", "") + + elif isinstance(item, str): + content = item + + else: + content = str(item) + + return {"role": role, "content": content} + + +def _count_response_web_search_calls(response: Any) -> int: + # Priority 1: exact count in Responses API output. + count = 0 + if hasattr(response, "output"): + for item in response.output: + if hasattr(item, "type") and item.type == "web_search_call": + count += 1 + return max(0, count) + + +def _has_root_web_search(response: Any) -> bool: + # Priority 2: binary detection, including Perplexity root-level indicators. + for field in ("citations", "search_results"): + if hasattr(response, field): + values = getattr(response, field) + if values and len(values) > 0: + return True + if hasattr(response, "usage") and hasattr(response.usage, "search_context_size"): + if response.usage.search_context_size: + return True + return False + + +def _has_url_citation_annotations(item: Any) -> bool: + if hasattr(item, "annotations"): + annotations = item.annotations + if annotations: + for annotation in annotations: + if _item_attr(annotation, "type") == "url_citation": + return True + return False + + +def _has_choice_web_citations(response: Any) -> bool: + if hasattr(response, "choices"): + for choice in response.choices: + # Check message before delta, including streaming chunks. + for field in ("message", "delta"): + if hasattr(choice, field): + if _has_url_citation_annotations(getattr(choice, field)): + return True + return False + + +def _has_response_web_citations(response: Any) -> bool: + if hasattr(response, "output"): + for item in response.output: + if hasattr(item, "content") and isinstance(item.content, list): + for content_item in item.content: + if _has_url_citation_annotations(content_item): + return True + return False + + +def _extract_openai_response_token_usage(usage: Any) -> TokenUsage: + # Read Responses fields first, then Chat Completions fields. The latter + # override only fields they report, including explicitly null values. + counts = _read_openai_response_usage_fields(usage, "responses") + counts.update(_read_openai_response_usage_fields(usage, "chat")) + result: Dict[str, Any] = {} + for field in ("input_tokens", "output_tokens"): + value = counts.get(field) + if value is not None: + result[field] = value + _add_openai_response_details(result, counts) + return cast(TokenUsage, result) + + +def _read_openai_response_usage_fields(usage: Any, api_type: str) -> Dict[str, Any]: + if api_type == "responses": + token_fields = ( + ("input_tokens", "input_tokens"), + ("output_tokens", "output_tokens"), + ) + detail_fields = ( + ("cache_read_input_tokens", "input_tokens_details", "cached_tokens"), + ("reasoning_tokens", "output_tokens_details", "reasoning_tokens"), + ) + else: + token_fields = ( + ("input_tokens", "prompt_tokens"), + ("output_tokens", "completion_tokens"), + ) + detail_fields = ( + ("cache_read_input_tokens", "prompt_tokens_details", "cached_tokens"), + ("reasoning_tokens", "completion_tokens_details", "reasoning_tokens"), + ) + counts = {} + for output, field in token_fields: + if hasattr(usage, field): + counts[output] = getattr(usage, field) + for output, field, detail in detail_fields: + if hasattr(usage, field) and hasattr(getattr(usage, field), detail): + counts[output] = getattr(getattr(usage, field), detail) + return counts + + +def _add_openai_response_details( + result: Dict[str, Any], counts: Dict[str, Any] +) -> None: + for field in ("cache_read_input_tokens", "reasoning_tokens"): + value = counts.get(field) + if value is not None and value > 0: + result[field] = value + + +def _extract_openai_stream_token_usage(raw: Any, provider_type: str) -> TokenUsage: + if provider_type == "chat": + input_field, output_field = "prompt_tokens", "completion_tokens" + input_details, output_details = ( + "prompt_tokens_details", + "completion_tokens_details", + ) + else: + input_field, output_field = "input_tokens", "output_tokens" + input_details, output_details = "input_tokens_details", "output_tokens_details" + usage: Dict[str, Any] = { + "input_tokens": getattr(raw, input_field, 0), + "output_tokens": getattr(raw, output_field, 0), + } + # Unlike non-streaming usage, explicitly reported zero details are retained. + for output, field, detail in ( + ("cache_read_input_tokens", input_details, "cached_tokens"), + ("reasoning_tokens", output_details, "reasoning_tokens"), + ): + if hasattr(raw, field) and hasattr(getattr(raw, field), detail): + value = getattr(getattr(raw, field), detail) + if value is not None: + usage[output] = value + return cast(TokenUsage, usage) + + +def _add_openai_raw_usage(usage: TokenUsage, raw: Any) -> None: + # Capture raw usage metadata for backend processing. Serialize in the converter. + serialized = serialize_raw_usage(raw) + if serialized: + usage["raw_usage"] = serialized + + +def _has_openai_chat_delta(chunk: Any) -> bool: + return bool( + hasattr(chunk, "choices") + and chunk.choices + and len(chunk.choices) > 0 + and chunk.choices[0].delta + ) + + +def _format_openai_tool_delta(tool_call: Any) -> Dict[str, Any]: + tc_dict = { + "index": getattr(tool_call, "index", None), + } + + if hasattr(tool_call, "id") and tool_call.id: + tc_dict["id"] = tool_call.id + + if hasattr(tool_call, "type") and tool_call.type: + tc_dict["type"] = tool_call.type + + if hasattr(tool_call, "function") and tool_call.function: + tc_dict["function"] = _format_openai_function_delta(tool_call.function) + + return tc_dict + + +def _format_openai_function_delta(function: Any) -> Dict[str, Any]: + function_dict = {} + if hasattr(function, "name") and function.name: + function_dict["name"] = function.name + if hasattr(function, "arguments") and function.arguments: + function_dict["arguments"] = function.arguments + return function_dict + + +def _openai_tool_delta_index( + accumulated_tool_calls: Dict[Union[int, str], Dict[str, Any]], + tool_call_delta: Dict[str, Any], +) -> Union[int, str]: + index = tool_call_delta.get("index") + if index is None: + # Some OpenAI-compatible providers omit the index. A delta with a new id + # or a function name starts a call, and one with neither continues the + # latest call. Those calls get keys of their own, so they can never + # collide with an index the provider sends later. + call_id = tool_call_delta.get("id") + index = _openai_tool_index_by_id(accumulated_tool_calls, call_id) + + if index is None: + has_name = bool((tool_call_delta.get("function") or {}).get("name")) + if accumulated_tool_calls and not call_id and not has_name: + index = next(reversed(accumulated_tool_calls)) + else: + index = f"no-index-{len(accumulated_tool_calls)}" + + return index + + +def _apply_openai_tool_delta( + tc: Dict[str, Any], tool_call_delta: Dict[str, Any] +) -> None: + # Update with new data from delta + + for field in ("id", "type"): + if field in tool_call_delta and tool_call_delta[field]: + tc[field] = tool_call_delta[field] + + if "function" in tool_call_delta: + func_delta = tool_call_delta["function"] + if "name" in func_delta and func_delta["name"]: + tc["function"]["name"] = func_delta["name"] + if "arguments" in func_delta and func_delta["arguments"]: + # Arguments are sent incrementally, concatenate them + tc["function"]["arguments"] += func_delta["arguments"] + + +def _format_openai_chat_stream_output( + accumulated_content: Any, tool_calls: Optional[List[Dict[str, Any]]] +) -> List[FormattedMessage]: + content_items: List[FormattedContentItem] = [] + + # Add text content if present + if isinstance(accumulated_content, str) and accumulated_content: + content_items.append({"type": "text", "text": accumulated_content}) + elif isinstance(accumulated_content, list): + content_items.extend(_merge_openai_chat_stream_parts(accumulated_content)) + + # Add tool calls if present + if tool_calls: + for tool_call in tool_calls: + if "function" in tool_call: + function_call: FormattedFunctionCall = { + "type": "function", + "id": tool_call.get("id", ""), + "function": tool_call["function"], + } + content_items.append(function_call) + + # Return formatted message with content + if content_items: + return [{"role": "assistant", "content": content_items}] + else: + # Empty response + return [{"role": "assistant", "content": []}] + + +def _merge_openai_chat_stream_parts( + accumulated_content: List[Any], +) -> List[FormattedContentItem]: + text_parts: List[str] = [] + audio_id: Optional[str] = None + audio_data_parts: List[str] = [] + audio_transcript_parts: List[str] = [] + refusal_parts: List[str] = [] + + for item in accumulated_content: + if isinstance(item, str): + if item: + text_parts.append(item) + elif isinstance(item, dict) and item.get("type") == "audio": + audio_id = _append_openai_audio_delta( + item, audio_id, audio_data_parts, audio_transcript_parts + ) + elif isinstance(item, dict) and item.get("type") == "refusal": + if item.get("refusal"): + refusal_parts.append(item["refusal"]) + + return _format_openai_chat_stream_parts( + text_parts, audio_id, audio_data_parts, audio_transcript_parts, refusal_parts + ) + + +def _append_openai_audio_delta( + item: Dict[str, Any], + audio_id: Optional[str], + data_parts: List[str], + transcript_parts: List[str], +) -> Optional[str]: + if audio_id is None and item.get("id"): + audio_id = item["id"] + if item.get("data"): + data_parts.append(item["data"]) + if item.get("transcript"): + transcript_parts.append(item["transcript"]) + return audio_id + + +def _format_openai_chat_stream_parts( + text_parts: List[str], + audio_id: Optional[str], + audio_data_parts: List[str], + audio_transcript_parts: List[str], + refusal_parts: List[str], +) -> List[FormattedContentItem]: + content_items: List[FormattedContentItem] = [] + if text_parts: + content_items.append({"type": "text", "text": "".join(text_parts)}) + + if audio_data_parts or audio_transcript_parts: + audio_block: Dict[str, Any] = {"type": "audio"} + if audio_id is not None: + audio_block["id"] = audio_id + if audio_data_parts: + audio_block["data"] = "".join(audio_data_parts) + if audio_transcript_parts: + audio_block["transcript"] = "".join(audio_transcript_parts) + content_items.append(audio_block) + + if refusal_parts: + content_items.append({"type": "refusal", "refusal": "".join(refusal_parts)}) + + return content_items + + +def _format_openai_responses_stream_output( + accumulated_content: Any, +) -> Optional[List[FormattedMessage]]: + if isinstance(accumulated_content, list) and not accumulated_content: + return [] + if isinstance(accumulated_content, list) and accumulated_content: + items: List[Any] = [] + for entry in accumulated_content: + if isinstance(entry, list): + items.extend(entry) + else: + items.append(entry) + + content_items = _format_responses_output_items(items) + role = _responses_output_role(items) + + if content_items: + return [{"role": role, "content": content_items}] + return [] + elif isinstance(accumulated_content, str): + return [ + { + "role": "assistant", + "content": [{"type": "text", "text": accumulated_content}], + } + ] + + return None + + +def _format_chat_completion_choices(choices: Any) -> Optional[FormattedMessage]: + content: List[FormattedContentItem] = [] + role = "assistant" + + for choice in choices: + if hasattr(choice, "message") and choice.message: + if choice.message.role: + role = choice.message.role + content.extend(_format_chat_message(choice.message)) + + if content: + return { + "role": role, + "content": content, + } + + return None + + +def _extract_openai_response_chunk_usage(chunk: Any) -> TokenUsage: + usage = TokenUsage() + # For Responses API, usage is only in chunk.response.usage on the terminal + # event. A run cut short (e.g. by max_output_tokens) ends on + # response.incomplete instead of response.completed, and is still billed. + if getattr(chunk, "type", None) in _RESPONSES_TERMINAL_EVENT_TYPES: + if ( + hasattr(chunk, "response") + and hasattr(chunk.response, "usage") + and chunk.response.usage + ): + response_usage = chunk.response.usage + usage.update( + _extract_openai_stream_token_usage(response_usage, "responses") + ) + # Extract web search count from the complete response. + if hasattr(chunk, "response"): + web_search_count = extract_openai_web_search_count(chunk.response) + if web_search_count > 0: + usage["web_search_count"] = web_search_count + _add_openai_raw_usage(usage, response_usage) + + return usage + + +def _extract_openai_chat_content(chunk: Any) -> Optional[Any]: + # Chat Completions API format + if _has_openai_chat_delta(chunk): + delta = chunk.choices[0].delta + + if delta.content: + return delta.content + + audio_delta = getattr(delta, "audio", None) + if audio_delta is not None: + plain_audio = to_plain(audio_delta) + if isinstance(plain_audio, dict): + return {"type": "audio", **plain_audio} + return {"type": "audio"} + + refusal_delta = getattr(delta, "refusal", None) + if refusal_delta: + return {"type": "refusal", "refusal": refusal_delta} + + return None + + +def _openai_tool_index_by_id( + accumulated_tool_calls: Dict[Union[int, str], Dict[str, Any]], call_id: Any +) -> Optional[Union[int, str]]: + return next( + ( + key + for key, tc in accumulated_tool_calls.items() + if call_id and tc["id"] == call_id + ), + None, + ) diff --git a/posthog/ai/openai_agents/processor.py b/posthog/ai/openai_agents/processor.py index 951dd95e2..5dd8ed40a 100644 --- a/posthog/ai/openai_agents/processor.py +++ b/posthog/ai/openai_agents/processor.py @@ -248,21 +248,7 @@ def on_trace_end(self, trace: Trace) -> None: "$ai_framework": "openai-agents", } - if latency is not None: - properties["$ai_latency"] = latency - - # The Agents SDK group_id links traces from one conversation, which is - # exactly what PostHog calls a session. $ai_group_id is still emitted - # for anyone already querying it. - if group_id: - properties["$ai_session_id"] = group_id - properties["$ai_group_id"] = group_id - - # Include trace metadata if present - if metadata: - properties["$ai_trace_metadata"] = self._with_privacy_mode( - _ensure_serializable(metadata) - ) + self._add_trace_details(properties, latency, group_id, metadata) if distinct_id is None: properties["$process_person_profile"] = False @@ -275,6 +261,29 @@ def on_trace_end(self, trace: Trace) -> None: except Exception as e: log.debug(f"Error in on_trace_end: {e}") + def _add_trace_details( + self, + properties: Dict[str, Any], + latency: Optional[float], + group_id: Any, + metadata: Any, + ) -> None: + if latency is not None: + properties["$ai_latency"] = latency + + # The Agents SDK group_id links traces from one conversation, which is + # exactly what PostHog calls a session. $ai_group_id is still emitted + # for anyone already querying it. + if group_id: + properties["$ai_session_id"] = group_id + properties["$ai_group_id"] = group_id + + # Include trace metadata if present + if metadata: + properties["$ai_trace_metadata"] = self._with_privacy_mode( + _ensure_serializable(metadata) + ) + def on_span_start(self, span: Span[Any]) -> None: """Called when a new span begins.""" try: @@ -292,15 +301,7 @@ def on_span_end(self, span: Span[Any]) -> None: parent_id = span.parent_id span_data = span.span_data - # Calculate latency - start_time = self._span_start_times.pop(span_id, None) - if start_time: - latency = time.time() - start_time - else: - # Fall back to parsing timestamps - started = _parse_iso_timestamp(span.started_at) - ended = _parse_iso_timestamp(span.ended_at) - latency = (ended - started) if (started and ended) else 0 + latency = self._span_latency(span, span_id) # Get user-provided distinct ID from trace metadata (resolved at trace start). # None means no user-provided ID — use trace_id as fallback in personless mode, @@ -311,175 +312,84 @@ def on_span_end(self, span: Span[Any]) -> None: # Get group_id from trace metadata for linking group_id = self._get_group_id(trace_id) - # Get error info if present - error_info = span.error - error_properties = {} - if error_info: - if isinstance(error_info, dict): - error_message = error_info.get("message", str(error_info)) - error_type_raw = error_info.get("type", "") - else: - error_message = str(error_info) - error_type_raw = "" - - # Categorize error type for cross-provider filtering/alerting - error_type = "unknown" - if ( - "ModelBehaviorError" in error_type_raw - or "ModelBehaviorError" in error_message - ): - error_type = "model_behavior_error" - elif "UserError" in error_type_raw or "UserError" in error_message: - error_type = "user_error" - elif ( - "InputGuardrailTripwireTriggered" in error_type_raw - or "InputGuardrailTripwireTriggered" in error_message - ): - error_type = "input_guardrail_triggered" - elif ( - "OutputGuardrailTripwireTriggered" in error_type_raw - or "OutputGuardrailTripwireTriggered" in error_message - ): - error_type = "output_guardrail_triggered" - elif ( - "MaxTurnsExceeded" in error_type_raw - or "MaxTurnsExceeded" in error_message - ): - error_type = "max_turns_exceeded" - - error_properties = { - "$ai_is_error": True, - "$ai_error": ( - self._summarize_span_error(error_info) - if self._privacy_enabled() - else error_message - ), - "$ai_error_type": error_type, - } + error_properties = self._span_error_properties(span.error) # Personless mode: no user-provided distinct_id, fallback to trace_id if distinct_id is None: error_properties["$process_person_profile"] = False distinct_id = trace_id - # Dispatch based on span data type - if isinstance(span_data, GenerationSpanData): - self._handle_generation_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) - elif isinstance(span_data, FunctionSpanData): - self._handle_function_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) - elif isinstance(span_data, AgentSpanData): - self._handle_agent_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) - elif isinstance(span_data, HandoffSpanData): - self._handle_handoff_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) - elif isinstance(span_data, GuardrailSpanData): - self._handle_guardrail_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) - elif isinstance(span_data, ResponseSpanData): - self._handle_response_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) - elif isinstance(span_data, CustomSpanData): - self._handle_custom_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) - elif isinstance( - span_data, (TranscriptionSpanData, SpeechSpanData, SpeechGroupSpanData) - ): - self._handle_audio_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) - elif isinstance(span_data, MCPListToolsSpanData): - self._handle_mcp_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) - else: - # Unknown span type - capture as generic span - self._handle_generic_span( - span_data, - trace_id, - span_id, - parent_id, - latency, - distinct_id, - group_id, - error_properties, - ) + handler = self._span_handler(span_data) + handler( + span_data, + trace_id, + span_id, + parent_id, + latency, + distinct_id, + group_id, + error_properties, + ) except Exception as e: log.debug(f"Error in on_span_end: {e}") + def _span_latency(self, span: Span[Any], span_id: str) -> float: + # Calculate latency + start_time = self._span_start_times.pop(span_id, None) + if start_time: + return time.time() - start_time + else: + # Fall back to parsing timestamps + started = _parse_iso_timestamp(span.started_at) + ended = _parse_iso_timestamp(span.ended_at) + return (ended - started) if (started and ended) else 0 + + def _span_error_properties(self, error_info: Any) -> Dict[str, Any]: + # Get error info if present + error_properties = {} + if error_info: + if isinstance(error_info, dict): + error_message = error_info.get("message", str(error_info)) + error_type_raw = error_info.get("type", "") + else: + error_message = str(error_info) + error_type_raw = "" + + error_type = _categorize_span_error(error_type_raw, error_message) + + error_properties = { + "$ai_is_error": True, + "$ai_error": ( + self._summarize_span_error(error_info) + if self._privacy_enabled() + else error_message + ), + "$ai_error_type": error_type, + } + + return error_properties + + def _span_handler(self, span_data: Any) -> Callable[..., None]: + for span_types, handler_name in ( + (GenerationSpanData, "_handle_generation_span"), + (FunctionSpanData, "_handle_function_span"), + (AgentSpanData, "_handle_agent_span"), + (HandoffSpanData, "_handle_handoff_span"), + (GuardrailSpanData, "_handle_guardrail_span"), + (ResponseSpanData, "_handle_response_span"), + (CustomSpanData, "_handle_custom_span"), + ( + (TranscriptionSpanData, SpeechSpanData, SpeechGroupSpanData), + "_handle_audio_span", + ), + (MCPListToolsSpanData, "_handle_mcp_span"), + ): + if isinstance(span_data, span_types): + return getattr(self, handler_name) + # Unknown span type - capture as generic span. + return self._handle_generic_span + def _base_properties( self, trace_id: str, @@ -554,20 +464,19 @@ def _handle_generation_span( _ensure_serializable(span_data.output), self._client ) ), - **({"$ai_input_tokens": input_tokens} if input_tokens is not None else {}), - **( - {"$ai_output_tokens": output_tokens} - if output_tokens is not None - else {} - ), - # Sum of the reported sides; omitted when neither side was reported. - **( - {"$ai_total_tokens": (input_tokens or 0) + (output_tokens or 0)} - if input_tokens is not None or output_tokens is not None - else {} - ), + **_token_properties(input_tokens, output_tokens), } + self._add_generation_usage_details(properties, usage, span_data) + + self._capture_event("$ai_generation", properties, distinct_id) + + def _add_generation_usage_details( + self, + properties: Dict[str, Any], + usage: Dict[str, Any], + span_data: GenerationSpanData, + ) -> None: # Add optional token fields if present. The Agents SDK nests cached # tokens under the usage details fields; flat keys are kept for custom # models. Nested reasoning is not forwarded: compatible providers count @@ -601,8 +510,6 @@ def _handle_generation_span( if finish_reason is not None: properties["$ai_stop_reason"] = finish_reason - self._capture_event("$ai_generation", properties, distinct_id) - def _handle_function_span( self, span_data: FunctionSpanData, @@ -727,14 +634,9 @@ def _handle_response_span( response = span_data.response response_id = response.id if response else None - # Try to extract usage from response - usage = getattr(response, "usage", None) if response else None - total_cost_usd = getattr(usage, "cost", None) if usage else None - # None when the response never reported a count: absent means unknown, - # 0 is a report of nothing. - input_tokens = getattr(usage, "input_tokens", None) if usage else None - output_tokens = getattr(usage, "output_tokens", None) if usage else None - + usage, total_cost_usd, input_tokens, output_tokens = _response_usage_counts( + response + ) # Try to extract model from response model = getattr(response, "model", None) if response else None @@ -747,18 +649,7 @@ def _handle_response_span( "$ai_input": self._with_privacy_mode( finalize_ai_content(_ensure_serializable(span_data.input), self._client) ), - **({"$ai_input_tokens": input_tokens} if input_tokens is not None else {}), - **( - {"$ai_output_tokens": output_tokens} - if output_tokens is not None - else {} - ), - # Sum of the reported sides; omitted when neither side was reported. - **( - {"$ai_total_tokens": (input_tokens or 0) + (output_tokens or 0)} - if input_tokens is not None or output_tokens is not None - else {} - ), + **_token_properties(input_tokens, output_tokens), } if total_cost_usd is not None: @@ -837,6 +728,20 @@ def _handle_audio_span( "$ai_span_type": span_type, } + self._add_audio_metadata(properties, span_data) + + self._add_audio_input(properties, span_data, span_type) + + if hasattr(span_data, "output") and isinstance(span_data.output, str): + properties["$ai_output_state"] = self._with_privacy_mode( + finalize_ai_content( + _ensure_serializable(span_data.output), self._client + ) + ) + + self._capture_event("$ai_span", properties, distinct_id) + + def _add_audio_metadata(self, properties: Dict[str, Any], span_data: Any) -> None: # Add model info if available if hasattr(span_data, "model") and span_data.model: properties["$ai_model"] = span_data.model @@ -857,6 +762,9 @@ def _handle_audio_span( if hasattr(span_data, "output_format"): properties["audio_output_format"] = span_data.output_format + def _add_audio_input( + self, properties: Dict[str, Any], span_data: Any, span_type: str + ) -> None: # Capture the input. For speech (TTS) spans the input is the text to # synthesize. For transcription spans the input is the base64-encoded # audio — a bare string with no key/parent context the structural @@ -883,15 +791,6 @@ def _handle_audio_span( ) ) - if hasattr(span_data, "output") and isinstance(span_data.output, str): - properties["$ai_output_state"] = self._with_privacy_mode( - finalize_ai_content( - _ensure_serializable(span_data.output), self._client - ) - ) - - self._capture_event("$ai_span", properties, distinct_id) - def _redact_audio_model_config(self, model_config: Any) -> Any: # The STT prompt and TTS instructions are user-authored text. if not isinstance(model_config, dict) or not self._privacy_enabled(): @@ -976,3 +875,43 @@ def force_flush(self) -> None: self._client.flush() except Exception as e: log.debug(f"Error in force_flush: {e}") + + +def _categorize_span_error(error_type_raw: str, error_message: str) -> str: + # Ordered categories preserve precedence when a message names several errors. + for name, category in ( + ("ModelBehaviorError", "model_behavior_error"), + ("UserError", "user_error"), + ("InputGuardrailTripwireTriggered", "input_guardrail_triggered"), + ("OutputGuardrailTripwireTriggered", "output_guardrail_triggered"), + ("MaxTurnsExceeded", "max_turns_exceeded"), + ): + if name in error_type_raw or name in error_message: + return category + return "unknown" + + +def _token_properties(input_tokens: Any, output_tokens: Any) -> Dict[str, Any]: + properties = {} + if input_tokens is not None: + properties["$ai_input_tokens"] = input_tokens + if output_tokens is not None: + properties["$ai_output_tokens"] = output_tokens + # Sum of the reported sides; omitted when neither side was reported. + if input_tokens is not None or output_tokens is not None: + properties["$ai_total_tokens"] = (input_tokens or 0) + (output_tokens or 0) + return properties + + +def _response_usage_counts( + response: Any, +) -> tuple[Any, Optional[float], Optional[int], Optional[int]]: + # Try to extract usage from response + usage = getattr(response, "usage", None) if response else None + total_cost_usd = getattr(usage, "cost", None) if usage else None + # None when the response never reported a count: absent means unknown, + # 0 is a report of nothing. + input_tokens = getattr(usage, "input_tokens", None) if usage else None + output_tokens = getattr(usage, "output_tokens", None) if usage else None + + return usage, total_cost_usd, input_tokens, output_tokens diff --git a/posthog/ai/otel/_privacy.py b/posthog/ai/otel/_privacy.py index 5a2114ee5..8b87b4a3a 100644 --- a/posthog/ai/otel/_privacy.py +++ b/posthog/ai/otel/_privacy.py @@ -213,13 +213,7 @@ def _redact_tool_definitions( return None if drop_unparseable else value redacted: List[Any] = [] for item in value: - definition = ( - _redact_tool_definition_json(item, drop_unparseable) - if isinstance(item, str) - else None - if drop_unparseable - else item - ) + definition = _redact_tool_definition_item(item, drop_unparseable) if definition is not None: redacted.append(definition) if len(redacted) == len(value) and all(a is b for a, b in zip(redacted, value)): @@ -227,6 +221,16 @@ def _redact_tool_definitions( return redacted +def _redact_tool_definition_item(item: Any, drop_unparseable: bool) -> Any: + return ( + _redact_tool_definition_json(item, drop_unparseable) + if isinstance(item, str) + else None + if drop_unparseable + else item + ) + + def _is_tool_definition_attribute(key: str) -> bool: return ( key in _TOOL_DEFINITION_ATTRIBUTES diff --git a/posthog/ai/otel/_request_context.py b/posthog/ai/otel/_request_context.py index b34bf4c61..dc0018c5a 100644 --- a/posthog/ai/otel/_request_context.py +++ b/posthog/ai/otel/_request_context.py @@ -102,9 +102,7 @@ def with_request_context(span: ReadableSpan, context: RequestContext) -> Readabl def to_attribute_value(value: Any) -> Optional[AttributeValue]: """Return ``value`` as an OpenTelemetry attribute value, JSON-encoding anything OTel can't hold.""" - if value is None or (isinstance(value, str) and not value): - return None - if isinstance(value, float) and not math.isfinite(value): + if _invalid_attribute_value(value): return None if _is_out_of_int64_range(value): return str(value) @@ -112,6 +110,18 @@ def to_attribute_value(value: Any) -> Optional[AttributeValue]: return value if isinstance(value, (list, tuple)) and _is_homogeneous(value): return list(value) + return _json_attribute_value(value) + + +def _invalid_attribute_value(value: Any) -> bool: + return ( + value is None + or (isinstance(value, str) and not value) + or (isinstance(value, float) and not math.isfinite(value)) + ) + + +def _json_attribute_value(value: Any) -> Optional[AttributeValue]: try: encoded = json.dumps(value, allow_nan=False, default=_encode_string_like) except (TypeError, ValueError): diff --git a/posthog/ai/prompts.py b/posthog/ai/prompts.py index 3a785f0ce..6b40c4a62 100644 --- a/posthog/ai/prompts.py +++ b/posthog/ai/prompts.py @@ -17,6 +17,8 @@ from dataclasses import dataclass from typing import Any, Dict, List, Literal, Optional, Union, overload +from requests import Response as _Response + from posthog.capture_v1 import _parse_retry_after from posthog.request import USER_AGENT, _get_session from posthog.utils import remove_trailing_slash @@ -462,6 +464,42 @@ def get_all(self, *, label: Optional[str] = None) -> Dict[str, PromptResult]: self._maybe_capture_error(error, name="*", version=None, label=label) raise + resolved_rows, skipped = self._resolve_prompt_rows(rows, label) + + now = time.time() + results: Dict[str, PromptResult] = {} + for row in resolved_rows: + config = _extract_config(row) + self._cache[_cache_key(row["name"], None, label)] = CachedPrompt( + prompt=row["prompt"], + fetched_at=now, + name=row["name"], + version=row["version"], + label=label, + config=config, + ) + results[row["name"]] = PromptResult( + source="api", + prompt=row["prompt"], + name=row["name"], + version=row["version"], + label=label, + config=copy.deepcopy(config), + ) + + if skipped: + log.warning( + "[PostHog Prompts] Skipped %d prompt(s) that did not resolve label %r: %s", + len(skipped), + label, + ", ".join(skipped), + ) + + return results + + def _resolve_prompt_rows( + self, rows: List[Dict[str, Any]], label: Optional[str] + ) -> tuple[List[Dict[str, Any]], List[str]]: reference = _prompt_list_reference(label) # Validate every row before caching any, so a rejected batch leaves @@ -514,36 +552,7 @@ def get_all(self, *, label: Optional[str] = None) -> Dict[str, PromptResult]: self._maybe_capture_error(compat_error, name="*", version=None, label=label) raise compat_error - now = time.time() - results: Dict[str, PromptResult] = {} - for row in resolved_rows: - config = _extract_config(row) - self._cache[_cache_key(row["name"], None, label)] = CachedPrompt( - prompt=row["prompt"], - fetched_at=now, - name=row["name"], - version=row["version"], - label=label, - config=config, - ) - results[row["name"]] = PromptResult( - source="api", - prompt=row["prompt"], - name=row["name"], - version=row["version"], - label=label, - config=copy.deepcopy(config), - ) - - if skipped: - log.warning( - "[PostHog Prompts] Skipped %d prompt(s) that did not resolve label %r: %s", - len(skipped), - label, - ", ".join(skipped), - ) - - return results + return resolved_rows, skipped def _get_internal( self, @@ -569,38 +578,9 @@ def _get_internal( cached = self._cache.get(cache_key) now = time.time() - if cached is not None: - is_fresh = (now - cached.fetched_at) < ttl - - if is_fresh: - return PromptResult( - source="cache", - prompt=cached.prompt, - name=cached.name, - version=cached.version, - label=cached.label, - # Copied so a caller mutating result.config can't pollute the - # cache entry that later cache hits are served from. - config=copy.deepcopy(cached.config), - ) - - # A failed refetch left this entry in cooldown. Serving it keeps one - # throttled client from turning every later get() into another - # request, which is what holds it against the limit. A zero TTL is - # an explicit request to refetch on every read, so it opts out. - if ( - ttl > 0 - and cached.retry_not_before is not None - and now < cached.retry_not_before - ): - return PromptResult( - source="stale_cache", - prompt=cached.prompt, - name=cached.name, - version=cached.version, - label=cached.label, - config=copy.deepcopy(cached.config), - ) + cached_result = _cached_prompt_result(cached, now, ttl) + if cached_result is not None: + return cached_result # Try to fetch from API try: @@ -669,11 +649,7 @@ def _fetch_prompt_once( self._in_flight[cache_key] = pending if not is_leader: - pending.done.wait() - if pending.error is not None: - raise pending.error - assert pending.result is not None - return pending.result + return _wait_for_prompt(pending) try: data = self._fetch_prompt_from_api(name, version, label) @@ -851,17 +827,7 @@ def _fetch_prompt_list_from_api(self, label: Optional[str]) -> List[Dict[str, An response = _get_session().get(url, headers=headers, timeout=10) - if not response.ok: - if response.status_code == 401: - raise _authentication_error(reference) - if response.status_code == 403: - raise _access_denied_error(reference) - raise PromptFetchError( - f"[PostHog Prompts] Failed to fetch {reference}: HTTP {response.status_code}", - _parse_retry_after_seconds(response.headers.get("Retry-After")) - if response.status_code == 429 - else None, - ) + _raise_prompt_response_error(response, reference) try: data = response.json() @@ -877,18 +843,7 @@ def _fetch_prompt_list_from_api(self, label: Optional[str]) -> List[Dict[str, An rows.extend(data["results"]) - # The Authorization header goes to every followed link, so a link - # off the configured host must never be requested. - next_url = data.get("next") - if next_url is not None and ( - not isinstance(next_url, str) - or not _is_same_origin(next_url, self._host) - ): - raise Exception( - f"[PostHog Prompts] Refusing to follow a pagination link off the " - f"configured host while fetching {reference}." - ) - url = next_url + url = _prompt_next_url(data, self._host, reference) pages += 1 return rows @@ -954,16 +909,91 @@ def _fetch_prompt_from_api( else None, ) - try: - data = response.json() - except Exception: - raise Exception( - f"[PostHog Prompts] Invalid response format for {prompt_title}" + return _prompt_response_data(response, prompt_title) + + +def _cached_prompt_result( + cached: Optional[CachedPrompt], now: float, ttl: float +) -> Optional[PromptResult]: + if cached is not None: + is_fresh = (now - cached.fetched_at) < ttl + + if is_fresh: + return PromptResult( + source="cache", + prompt=cached.prompt, + name=cached.name, + version=cached.version, + label=cached.label, + # Copied so a caller mutating result.config can't pollute the + # cache entry that later cache hits are served from. + config=copy.deepcopy(cached.config), ) - if not _is_prompt_api_response(data): - raise Exception( - f"[PostHog Prompts] Invalid response format for {prompt_title}" + # A failed refetch left this entry in cooldown. Serving it keeps one + # throttled client from turning every later get() into another + # request, which is what holds it against the limit. A zero TTL is + # an explicit request to refetch on every read, so it opts out. + if ( + ttl > 0 + and cached.retry_not_before is not None + and now < cached.retry_not_before + ): + return PromptResult( + source="stale_cache", + prompt=cached.prompt, + name=cached.name, + version=cached.version, + label=cached.label, + config=copy.deepcopy(cached.config), ) - return data + return None + + +def _wait_for_prompt(pending: _InFlightFetch) -> CachedPrompt: + pending.done.wait() + if pending.error is not None: + raise pending.error + assert pending.result is not None + return pending.result + + +def _raise_prompt_response_error(response: _Response, reference: str) -> None: + if not response.ok: + if response.status_code == 401: + raise _authentication_error(reference) + if response.status_code == 403: + raise _access_denied_error(reference) + raise PromptFetchError( + f"[PostHog Prompts] Failed to fetch {reference}: HTTP {response.status_code}", + _parse_retry_after_seconds(response.headers.get("Retry-After")) + if response.status_code == 429 + else None, + ) + + +def _prompt_response_data(response: _Response, prompt_title: str) -> Dict[str, Any]: + try: + data = response.json() + except Exception: + raise Exception(f"[PostHog Prompts] Invalid response format for {prompt_title}") + + if not _is_prompt_api_response(data): + raise Exception(f"[PostHog Prompts] Invalid response format for {prompt_title}") + + return data + + +def _prompt_next_url(data: Dict[str, Any], host: str, reference: str) -> Optional[str]: + # The Authorization header goes to every followed link, so a link + # off the configured host must never be requested. + next_url = data.get("next") + if next_url is not None and ( + not isinstance(next_url, str) or not _is_same_origin(next_url, host) + ): + raise Exception( + f"[PostHog Prompts] Refusing to follow a pagination link off the " + f"configured host while fetching {reference}." + ) + return next_url diff --git a/posthog/ai/utils.py b/posthog/ai/utils.py index 874ff3fcb..dfc4c8c90 100644 --- a/posthog/ai/utils.py +++ b/posthog/ai/utils.py @@ -35,6 +35,10 @@ ) +def _is_token_count(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value >= 0 + + def _extract_cache_creation_ttl_breakdown( token_details: Any, ) -> Optional[Tuple[int, int]]: @@ -46,11 +50,7 @@ def _extract_cache_creation_ttl_breakdown( token_details.get("ephemeral_5m_input_tokens"), token_details.get("ephemeral_1h_input_tokens"), ) - if not any(value is not None for value in values) or not all( - isinstance(value, int) and not isinstance(value, bool) and value >= 0 - for value in values - if value is not None - ): + if not all(_is_token_count(value) for value in values if value is not None): return None breakdown = (values[0] or 0, values[1] or 0) @@ -131,19 +131,15 @@ def serialize_raw_usage(raw_usage: Any) -> Optional[Dict[str, Any]]: if isinstance(raw_usage, dict): return raw_usage - # Try Pydantic model_dump() (OpenAI/Anthropic) - if hasattr(raw_usage, "model_dump") and callable(raw_usage.model_dump): - try: - return raw_usage.model_dump() - except Exception: - pass - - # Try to_dict() (some protobuf objects) - if hasattr(raw_usage, "to_dict") and callable(raw_usage.to_dict): - try: - return raw_usage.to_dict() - except Exception: - pass + # Try Pydantic model_dump() first, then protobuf-style to_dict(). + for method_name in ("model_dump", "to_dict"): + if hasattr(raw_usage, method_name) and callable( + getattr(raw_usage, method_name) + ): + try: + return getattr(raw_usage, method_name)() + except Exception: + pass # Try __dict__ / vars() for simple objects try: @@ -151,6 +147,10 @@ def serialize_raw_usage(raw_usage: Any) -> Optional[Dict[str, Any]]: except Exception: pass + return _raw_usage_string(raw_usage) + + +def _raw_usage_string(raw_usage: Any) -> Optional[Dict[str, Any]]: # Last resort: convert to string representation # This ensures we always return something rather than failing try: @@ -174,81 +174,55 @@ def merge_usage_stats( source: TokenUsage that may contain None values mode: Either "incremental" or "cumulative" """ + fields = ( + "input_tokens", + "output_tokens", + "cache_read_input_tokens", + "cache_creation_input_tokens", + "reasoning_tokens", + ) + target_fields = cast(Dict[str, Any], target) + source_fields = cast(Dict[str, Any], source) if mode == "incremental": - # Add new values to existing totals - source_input = source.get("input_tokens") - if source_input is not None: - current = target.get("input_tokens") or 0 - target["input_tokens"] = current + source_input - - source_output = source.get("output_tokens") - if source_output is not None: - current = target.get("output_tokens") or 0 - target["output_tokens"] = current + source_output - - source_cache_read = source.get("cache_read_input_tokens") - if source_cache_read is not None: - current = target.get("cache_read_input_tokens") or 0 - target["cache_read_input_tokens"] = current + source_cache_read - - source_cache_creation = source.get("cache_creation_input_tokens") - if source_cache_creation is not None: - current = target.get("cache_creation_input_tokens") or 0 - target["cache_creation_input_tokens"] = current + source_cache_creation - - source_reasoning = source.get("reasoning_tokens") - if source_reasoning is not None: - current = target.get("reasoning_tokens") or 0 - target["reasoning_tokens"] = current + source_reasoning - - source_web_search = source.get("web_search_count") - if source_web_search is not None: - current = target.get("web_search_count") or 0 - target["web_search_count"] = max(current, source_web_search) - - # Carried across, never accumulated: this describes the provider's accounting - # model, so it is the same on every chunk. - source_exclusive = source.get("cache_reporting_exclusive") - if source_exclusive is not None: - target["cache_reporting_exclusive"] = source_exclusive - - # Merge raw_usage to avoid losing data from earlier events - # For Anthropic streaming: message_start has input tokens, message_delta has output - # Note: raw_usage is already serialized by converters, so it's a dict - source_raw_usage = source.get("raw_usage") - if source_raw_usage is not None and isinstance(source_raw_usage, dict): - current_raw_value = target.get("raw_usage") - current_raw: Dict[str, Any] = ( - current_raw_value if isinstance(current_raw_value, dict) else {} - ) - target["raw_usage"] = {**current_raw, **source_raw_usage} - + for field in fields: + value = source_fields.get(field) + if value is not None: + target_fields[field] = (target_fields.get(field) or 0) + value + _merge_incremental_usage_metadata(target, source) elif mode == "cumulative": - # Replace with latest values (already cumulative) - if source.get("input_tokens") is not None: - target["input_tokens"] = source["input_tokens"] - if source.get("output_tokens") is not None: - target["output_tokens"] = source["output_tokens"] - if source.get("cache_read_input_tokens") is not None: - target["cache_read_input_tokens"] = source["cache_read_input_tokens"] - if source.get("cache_creation_input_tokens") is not None: - target["cache_creation_input_tokens"] = source[ - "cache_creation_input_tokens" - ] - if source.get("reasoning_tokens") is not None: - target["reasoning_tokens"] = source["reasoning_tokens"] - if source.get("web_search_count") is not None: - target["web_search_count"] = source["web_search_count"] - if source.get("cache_reporting_exclusive") is not None: - target["cache_reporting_exclusive"] = source["cache_reporting_exclusive"] - # Note: raw_usage is already serialized by converters, so it's a dict - if source.get("raw_usage") is not None: - target["raw_usage"] = source["raw_usage"] - + for field in ( + *fields, + "web_search_count", + "cache_reporting_exclusive", + "raw_usage", + ): + if source_fields.get(field) is not None: + target_fields[field] = source_fields[field] else: raise ValueError(f"Invalid mode: {mode}. Must be 'incremental' or 'cumulative'") +def _merge_incremental_usage_metadata(target: TokenUsage, source: TokenUsage) -> None: + source_web_search = source.get("web_search_count") + if source_web_search is not None: + target["web_search_count"] = max( + target.get("web_search_count") or 0, source_web_search + ) + # Carried across, never accumulated: this describes the provider's accounting + # model, so it is the same on every chunk. + source_exclusive = source.get("cache_reporting_exclusive") + if source_exclusive is not None: + target["cache_reporting_exclusive"] = source_exclusive + # Anthropic message_start and message_delta report different parts of usage. + # Converters have already serialized raw_usage, so merge dicts without losing + # fields from earlier chunks. + source_raw_usage = source.get("raw_usage") + if source_raw_usage is not None and isinstance(source_raw_usage, dict): + current_raw_value = target.get("raw_usage") + current_raw = current_raw_value if isinstance(current_raw_value, dict) else {} + target["raw_usage"] = {**current_raw, **source_raw_usage} + + def get_model_params( kwargs: Dict[str, Any], served_service_tier: Optional[str] = None ) -> Dict[str, Any]: @@ -410,49 +384,56 @@ def merge_system_prompt( elif provider == "openai": from posthog.ai.openai.openai_converter import format_openai_input - # For OpenAI, handle both Chat Completions and Responses API - messages_param = kwargs.get("messages") - input_param = kwargs.get("input") + return _merge_openai_system_prompt(kwargs, format_openai_input) - # Get base formatted messages - messages = format_openai_input(messages_param, input_param) + # Default case - return empty list + return [] - # Check if system prompt is provided as a separate parameter - if kwargs.get("system") is not None: - has_system = any(msg.get("role") == "system" for msg in messages) - if not has_system: - system_msg = cast( - FormattedMessage, - {"role": "system", "content": kwargs.get("system")}, - ) - messages = [system_msg] + messages - - # For Responses API, add instructions to the system prompt if provided - if kwargs.get("instructions") is not None: - # Find the system message if it exists - system_idx = next( - (i for i, msg in enumerate(messages) if msg.get("role") == "system"), - None, - ) - if system_idx is not None: - # Append instructions to existing system message - system_content = messages[system_idx].get("content", "") - messages[system_idx]["content"] = ( - f"{system_content}\n\n{kwargs.get('instructions')}" - ) - else: - # Create a new system message with instructions - instruction_msg = cast( - FormattedMessage, - {"role": "system", "content": kwargs.get("instructions")}, - ) - messages = [instruction_msg] + messages +def _merge_openai_system_prompt( + kwargs: Dict[str, Any], + format_openai_input: Callable[..., List[FormattedMessage]], +) -> List[FormattedMessage]: + # For OpenAI, handle both Chat Completions and Responses API + messages_param = kwargs.get("messages") + input_param = kwargs.get("input") + + # Get base formatted messages + messages = format_openai_input(messages_param, input_param) + + # Check if system prompt is provided as a separate parameter + if kwargs.get("system") is not None: + has_system = any(msg.get("role") == "system" for msg in messages) + if not has_system: + system_msg = cast( + FormattedMessage, + {"role": "system", "content": kwargs.get("system")}, + ) + messages = [system_msg] + messages + + # For Responses API, add instructions to the system prompt if provided + if kwargs.get("instructions") is not None: + # Find the system message if it exists + system_idx = next( + (i for i, msg in enumerate(messages) if msg.get("role") == "system"), + None, + ) - return messages + if system_idx is not None: + # Append instructions to existing system message + system_content = messages[system_idx].get("content", "") + messages[system_idx]["content"] = ( + f"{system_content}\n\n{kwargs.get('instructions')}" + ) + else: + # Create a new system message with instructions + instruction_msg = cast( + FormattedMessage, + {"role": "system", "content": kwargs.get("instructions")}, + ) + messages = [instruction_msg] + messages - # Default case - return empty list - return [] + return messages def _get_http_status(exc: BaseException) -> int: @@ -490,7 +471,6 @@ def call_llm_and_track_usage( response = None error = None http_status = 200 - usage: TokenUsage = TokenUsage() error_params: Dict[str, Any] = {} with new_context(client=ph_client, capture_exceptions=False): @@ -510,128 +490,21 @@ def call_llm_and_track_usage( # enable_exception_autocapture is True, similar to LangChain callbacks. # See _capture_exception_and_update_properties in langchain/callbacks.py finally: - end_time = time.time() - latency = end_time - start_time - - if posthog_trace_id is None: - posthog_trace_id = str(uuid.uuid4()) - - # Check if we have a real user distinct_id (from param or outer context) - has_person_distinct_id = ( - posthog_distinct_id is not None - or contexts.get_context_distinct_id() is not None - ) - - if not has_person_distinct_id: - # Fall back to trace_id as distinct_id when no real user id is available. - identify_context(posthog_trace_id) - - if response and ( - hasattr(response, "usage") - or (provider == "gemini" and hasattr(response, "usage_metadata")) - ): - usage = get_usage(response, provider) - - messages = merge_system_prompt(kwargs, provider) - sanitized_messages = finalize_ai_content(messages, ph_client) - - tag("$ai_provider", provider) - tag("$ai_model", kwargs.get("model") or getattr(response, "model", None)) - served_service_tier = getattr(response, "service_tier", None) - tag("$ai_model_parameters", get_model_params(kwargs, served_service_tier)) - if served_service_tier is not None: - # The explicit served-tier signal cost processing prices from. - tag("$ai_service_tier", served_service_tier) - tag( - "$ai_input", - with_privacy_mode(ph_client, posthog_privacy_mode, sanitized_messages), + _capture_llm_call( + start_time, + response, + posthog_trace_id, + posthog_distinct_id, + ph_client, + provider, + kwargs, + posthog_privacy_mode, + http_status, + base_url, + posthog_properties, + error_params, + posthog_groups, ) - tag( - "$ai_output_choices", - with_privacy_mode( - ph_client, - posthog_privacy_mode, - finalize_ai_content(format_response(response, provider), ph_client), - ), - ) - tag("$ai_http_status", http_status) - # Omitted when the provider never reported a count: absent means - # unknown, 0 is a report of nothing. - input_tokens = usage.get("input_tokens") - if input_tokens is not None: - tag("$ai_input_tokens", input_tokens) - output_tokens = usage.get("output_tokens") - if output_tokens is not None: - tag("$ai_output_tokens", output_tokens) - tag("$ai_latency", latency) - tag("$ai_trace_id", posthog_trace_id) - tag("$ai_base_url", str(base_url)) - warn_if_posthog_ai_gateway(base_url) - - available_tool_calls = extract_available_tool_calls(provider, kwargs) - - if available_tool_calls: - tag("$ai_tools", available_tool_calls) - - cache_read = usage.get("cache_read_input_tokens") - if cache_read is not None and cache_read > 0: - tag("$ai_cache_read_input_tokens", cache_read) - - cache_creation = usage.get("cache_creation_input_tokens") - if cache_creation is not None and cache_creation > 0: - tag("$ai_cache_creation_input_tokens", cache_creation) - - cache_reporting_exclusive = usage.get("cache_reporting_exclusive") - if cache_reporting_exclusive is not None: - tag("$ai_cache_reporting_exclusive", cache_reporting_exclusive) - - reasoning = usage.get("reasoning_tokens") - if reasoning is not None and reasoning > 0: - tag("$ai_reasoning_tokens", reasoning) - - web_search_count = usage.get("web_search_count") - if web_search_count is not None and web_search_count > 0: - tag("$ai_web_search_count", web_search_count) - - raw_usage = usage.get("raw_usage") - if raw_usage is not None: - # Already serialized by converters - tag("$ai_usage", raw_usage) - - stop_reason = extract_stop_reason(response, provider) - if stop_reason is not None: - tag("$ai_stop_reason", stop_reason) - - if not has_person_distinct_id: - tag("$process_person_profile", False) - - # Process instructions for Responses API - if provider == "openai" and kwargs.get("instructions") is not None: - tag( - "$ai_instructions", - with_privacy_mode( - ph_client, posthog_privacy_mode, kwargs.get("instructions") - ), - ) - - # send the event to posthog - if hasattr(ph_client, "capture") and callable(ph_client.capture): - sdk_tags = get_tags() - merged_properties = { - **sdk_tags, - **(posthog_properties or {}), - **(error_params or {}), - } - merged_properties["$ai_tokens_source"] = _get_tokens_source( - sdk_tags, posthog_properties - ) - _capture_ai_event( - ph_client, - "$ai_generation", - distinct_id=contexts.get_context_distinct_id(), - properties=merged_properties, - groups=posthog_groups, - ) if error: raise error @@ -655,7 +528,6 @@ async def call_llm_and_track_usage_async( response = None error = None http_status = 200 - usage: TokenUsage = TokenUsage() error_params: Dict[str, Any] = {} with new_context(client=ph_client, capture_exceptions=False): @@ -682,128 +554,21 @@ async def call_llm_and_track_usage_async( # enable_exception_autocapture is True, similar to LangChain callbacks. # See _capture_exception_and_update_properties in langchain/callbacks.py finally: - end_time = time.time() - latency = end_time - start_time - - if posthog_trace_id is None: - posthog_trace_id = str(uuid.uuid4()) - - # Check if we have a real user distinct_id (from param or outer context) - has_person_distinct_id = ( - posthog_distinct_id is not None - or contexts.get_context_distinct_id() is not None - ) - - if not has_person_distinct_id: - # Fall back to trace_id as distinct_id when no real user id is available. - identify_context(posthog_trace_id) - - if response and ( - hasattr(response, "usage") - or (provider == "gemini" and hasattr(response, "usage_metadata")) - ): - usage = get_usage(response, provider) - - messages = merge_system_prompt(kwargs, provider) - sanitized_messages = finalize_ai_content(messages, ph_client) - - tag("$ai_provider", provider) - tag("$ai_model", kwargs.get("model") or getattr(response, "model", None)) - served_service_tier = getattr(response, "service_tier", None) - tag("$ai_model_parameters", get_model_params(kwargs, served_service_tier)) - if served_service_tier is not None: - # The explicit served-tier signal cost processing prices from. - tag("$ai_service_tier", served_service_tier) - tag( - "$ai_input", - with_privacy_mode(ph_client, posthog_privacy_mode, sanitized_messages), - ) - tag( - "$ai_output_choices", - with_privacy_mode( - ph_client, - posthog_privacy_mode, - finalize_ai_content(format_response(response, provider), ph_client), - ), + _capture_llm_call( + start_time, + response, + posthog_trace_id, + posthog_distinct_id, + ph_client, + provider, + kwargs, + posthog_privacy_mode, + http_status, + base_url, + posthog_properties, + error_params, + posthog_groups, ) - tag("$ai_http_status", http_status) - # Omitted when the provider never reported a count: absent means - # unknown, 0 is a report of nothing. - input_tokens = usage.get("input_tokens") - if input_tokens is not None: - tag("$ai_input_tokens", input_tokens) - output_tokens = usage.get("output_tokens") - if output_tokens is not None: - tag("$ai_output_tokens", output_tokens) - tag("$ai_latency", latency) - tag("$ai_trace_id", posthog_trace_id) - tag("$ai_base_url", str(base_url)) - warn_if_posthog_ai_gateway(base_url) - - available_tool_calls = extract_available_tool_calls(provider, kwargs) - - if available_tool_calls: - tag("$ai_tools", available_tool_calls) - - cache_read = usage.get("cache_read_input_tokens") - if cache_read is not None and cache_read > 0: - tag("$ai_cache_read_input_tokens", cache_read) - - cache_creation = usage.get("cache_creation_input_tokens") - if cache_creation is not None and cache_creation > 0: - tag("$ai_cache_creation_input_tokens", cache_creation) - - cache_reporting_exclusive = usage.get("cache_reporting_exclusive") - if cache_reporting_exclusive is not None: - tag("$ai_cache_reporting_exclusive", cache_reporting_exclusive) - - reasoning = usage.get("reasoning_tokens") - if reasoning is not None and reasoning > 0: - tag("$ai_reasoning_tokens", reasoning) - - web_search_count = usage.get("web_search_count") - if web_search_count is not None and web_search_count > 0: - tag("$ai_web_search_count", web_search_count) - - raw_usage = usage.get("raw_usage") - if raw_usage is not None: - # Already serialized by converters - tag("$ai_usage", raw_usage) - - stop_reason = extract_stop_reason(response, provider) - if stop_reason is not None: - tag("$ai_stop_reason", stop_reason) - - if not has_person_distinct_id: - tag("$process_person_profile", False) - - # Process instructions for Responses API - if provider == "openai" and kwargs.get("instructions") is not None: - tag( - "$ai_instructions", - with_privacy_mode( - ph_client, posthog_privacy_mode, kwargs.get("instructions") - ), - ) - - # send the event to posthog - if hasattr(ph_client, "capture") and callable(ph_client.capture): - sdk_tags = get_tags() - merged_properties = { - **sdk_tags, - **(posthog_properties or {}), - **(error_params or {}), - } - merged_properties["$ai_tokens_source"] = _get_tokens_source( - sdk_tags, posthog_properties - ) - _capture_ai_event( - ph_client, - "$ai_generation", - distinct_id=contexts.get_context_distinct_id(), - properties=merged_properties, - groups=posthog_groups, - ) if error: raise error @@ -811,6 +576,178 @@ async def call_llm_and_track_usage_async( return response +def _capture_llm_call( + start_time: float, + response: Any, + posthog_trace_id: Optional[str], + posthog_distinct_id: Optional[str], + ph_client: PostHogClient, + provider: str, + kwargs: Dict[str, Any], + posthog_privacy_mode: bool, + http_status: int, + base_url: str, + posthog_properties: Optional[Dict[str, Any]], + error_params: Dict[str, Any], + posthog_groups: Optional[Dict[str, Any]], +) -> None: + usage: TokenUsage = TokenUsage() + end_time = time.time() + latency = end_time - start_time + + if posthog_trace_id is None: + posthog_trace_id = str(uuid.uuid4()) + + # Check if we have a real user distinct_id (from param or outer context) + has_person_distinct_id = ( + posthog_distinct_id is not None + or contexts.get_context_distinct_id() is not None + ) + + if not has_person_distinct_id: + # Fall back to trace_id as distinct_id when no real user id is available. + identify_context(posthog_trace_id) + + if response and ( + hasattr(response, "usage") + or (provider == "gemini" and hasattr(response, "usage_metadata")) + ): + usage = get_usage(response, provider) + + _tag_llm_content(response, provider, kwargs, ph_client, posthog_privacy_mode) + tag("$ai_http_status", http_status) + _tag_reported_token_counts(usage) + tag("$ai_latency", latency) + tag("$ai_trace_id", posthog_trace_id) + tag("$ai_base_url", str(base_url)) + warn_if_posthog_ai_gateway(base_url) + + available_tool_calls = extract_available_tool_calls(provider, kwargs) + + if available_tool_calls: + tag("$ai_tools", available_tool_calls) + + _tag_optional_usage(usage) + _capture_tagged_llm_event( + response, + provider, + kwargs, + ph_client, + posthog_privacy_mode, + has_person_distinct_id, + posthog_properties, + error_params, + posthog_groups, + ) + + +def _tag_llm_content( + response: Any, + provider: str, + kwargs: Dict[str, Any], + ph_client: PostHogClient, + posthog_privacy_mode: bool, +) -> None: + messages = merge_system_prompt(kwargs, provider) + sanitized_messages = finalize_ai_content(messages, ph_client) + + tag("$ai_provider", provider) + tag("$ai_model", kwargs.get("model") or getattr(response, "model", None)) + served_service_tier = getattr(response, "service_tier", None) + tag("$ai_model_parameters", get_model_params(kwargs, served_service_tier)) + if served_service_tier is not None: + # The explicit served-tier signal cost processing prices from. + tag("$ai_service_tier", served_service_tier) + tag( + "$ai_input", + with_privacy_mode(ph_client, posthog_privacy_mode, sanitized_messages), + ) + tag( + "$ai_output_choices", + with_privacy_mode( + ph_client, + posthog_privacy_mode, + finalize_ai_content(format_response(response, provider), ph_client), + ), + ) + + +def _tag_reported_token_counts(usage: TokenUsage) -> None: + # Omitted when the provider never reported a count: absent means + # unknown, 0 is a report of nothing. + input_tokens = usage.get("input_tokens") + if input_tokens is not None: + tag("$ai_input_tokens", input_tokens) + output_tokens = usage.get("output_tokens") + if output_tokens is not None: + tag("$ai_output_tokens", output_tokens) + + +def _tag_optional_usage(usage: TokenUsage) -> None: + for field in ("cache_read_input_tokens", "cache_creation_input_tokens"): + value = cast(Optional[int], usage.get(field)) + if value is not None and value > 0: + tag(f"$ai_{field}", value) + exclusive = usage.get("cache_reporting_exclusive") + if exclusive is not None: + tag("$ai_cache_reporting_exclusive", exclusive) + for field in ("reasoning_tokens", "web_search_count"): + value = cast(Optional[int], usage.get(field)) + if value is not None and value > 0: + tag(f"$ai_{field}", value) + raw_usage = usage.get("raw_usage") + if raw_usage is not None: + # Already serialized by converters + tag("$ai_usage", raw_usage) + + +def _capture_tagged_llm_event( + response: Any, + provider: str, + kwargs: Dict[str, Any], + ph_client: PostHogClient, + posthog_privacy_mode: bool, + has_person_distinct_id: bool, + posthog_properties: Optional[Dict[str, Any]], + error_params: Dict[str, Any], + posthog_groups: Optional[Dict[str, Any]], +) -> None: + stop_reason = extract_stop_reason(response, provider) + if stop_reason is not None: + tag("$ai_stop_reason", stop_reason) + + if not has_person_distinct_id: + tag("$process_person_profile", False) + + # Process instructions for Responses API + if provider == "openai" and kwargs.get("instructions") is not None: + tag( + "$ai_instructions", + with_privacy_mode( + ph_client, posthog_privacy_mode, kwargs.get("instructions") + ), + ) + + # send the event to posthog + if hasattr(ph_client, "capture") and callable(ph_client.capture): + sdk_tags = get_tags() + merged_properties = { + **sdk_tags, + **(posthog_properties or {}), + **(error_params or {}), + } + merged_properties["$ai_tokens_source"] = _get_tokens_source( + sdk_tags, posthog_properties + ) + _capture_ai_event( + ph_client, + "$ai_generation", + distinct_id=contexts.get_context_distinct_id(), + properties=merged_properties, + groups=posthog_groups, + ) + + def finalize_ai_content(value: Any, ph_client: Any = None) -> Any: """Single choke point for AI content properties: structural media redaction (or bytes->base64 passthrough when the client opted into multimodal capture). @@ -1074,46 +1011,9 @@ def capture_streaming_event( input_tokens = event_data["usage_stats"].get("input_tokens") output_tokens = event_data["usage_stats"].get("output_tokens") - # Build base event properties - event_properties = { - "$ai_provider": event_data["provider"], - "$ai_model": event_data["model"], - "$ai_model_parameters": get_model_params( - event_data["kwargs"], event_data.get("service_tier") - ), - **( - {"$ai_service_tier": event_data["service_tier"]} - if event_data.get("service_tier") is not None - else {} - ), - "$ai_input": with_privacy_mode( - ph_client, - event_data["privacy_mode"], - finalize_ai_content(event_data["formatted_input"], ph_client), - ), - "$ai_output_choices": with_privacy_mode( - ph_client, - event_data["privacy_mode"], - finalize_ai_content(event_data["formatted_output"], ph_client), - ), - "$ai_http_status": (_get_http_status(error) if error is not None else 200), - **({"$ai_input_tokens": input_tokens} if input_tokens is not None else {}), - **({"$ai_output_tokens": output_tokens} if output_tokens is not None else {}), - "$ai_latency": event_data["latency"], - "$ai_trace_id": trace_id, - "$ai_base_url": str(event_data["base_url"]), - **(event_data.get("properties") or {}), - **( - { - "$ai_is_error": True, - "$ai_error": _format_ai_error( - ph_client, event_data["privacy_mode"], error - ), - } - if error is not None - else {} - ), - } + event_properties = _streaming_base_properties( + ph_client, event_data, trace_id, error, input_tokens, output_tokens + ) warn_if_posthog_ai_gateway(event_data["base_url"]) @@ -1134,6 +1034,44 @@ def capture_streaming_event( if available_tools: event_properties["$ai_tools"] = available_tools + _add_streaming_usage(event_properties, event_data, input_tokens, output_tokens) + + # Add stop reason if present + stop_reason = event_data.get("stop_reason") + if stop_reason is not None: + event_properties["$ai_stop_reason"] = stop_reason + + # Handle provider-specific fields + if ( + event_data["provider"] == "openai" + and event_data["kwargs"].get("instructions") is not None + ): + event_properties["$ai_instructions"] = with_privacy_mode( + ph_client, + event_data["privacy_mode"], + event_data["kwargs"]["instructions"], + ) + + if event_data.get("distinct_id") is None: + event_properties["$process_person_profile"] = False + + # Send event to PostHog + if hasattr(ph_client, "capture"): + _capture_ai_event( + ph_client, + "$ai_generation", + distinct_id=event_data.get("distinct_id") or trace_id, + properties=event_properties, + groups=event_data.get("groups"), + ) + + +def _add_streaming_usage( + event_properties: Dict[str, Any], + event_data: StreamingEventData, + input_tokens: Optional[int], + output_tokens: Optional[int], +) -> None: # Add optional token fields. The zero-defaults below only apply when the # provider reported usage at all: a stream interrupted before any report # has nothing to default, and a fabricated 0 would read as a report of @@ -1151,42 +1089,54 @@ def capture_streaming_event( if isinstance(reasoning, int) and reasoning > 0: event_properties["$ai_reasoning_tokens"] = reasoning else: - optional_token_fields = [ - "cache_read_input_tokens", - "cache_creation_input_tokens", - "reasoning_tokens", - ] + _add_optional_streaming_tokens(event_properties, event_data, usage_was_reported) - for field in optional_token_fields: - value = event_data["usage_stats"].get(field) - property_name = f"$ai_{field}" + _add_streaming_usage_metadata(event_properties, event_data["usage_stats"]) - # OpenAI async streams historically included these fields even when 0. - # Keep those defaults in the shared path so they are not mistaken for - # caller-supplied token passthrough properties. - if ( - event_data["provider"] == "openai" - and usage_was_reported - and field - in { - "cache_read_input_tokens", - "reasoning_tokens", - } - ): - event_properties.setdefault( - property_name, event_data["usage_stats"].get(field, 0) - ) - elif value is not None and isinstance(value, int) and value > 0: - event_properties[property_name] = value - cache_reporting_exclusive = event_data["usage_stats"].get( - "cache_reporting_exclusive" - ) +def _add_optional_streaming_tokens( + event_properties: Dict[str, Any], + event_data: StreamingEventData, + usage_was_reported: bool, +) -> None: + optional_token_fields = [ + "cache_read_input_tokens", + "cache_creation_input_tokens", + "reasoning_tokens", + ] + + for field in optional_token_fields: + value = event_data["usage_stats"].get(field) + property_name = f"$ai_{field}" + + # OpenAI async streams historically included these fields even when 0. + # Keep those defaults in the shared path so they are not mistaken for + # caller-supplied token passthrough properties. + if ( + event_data["provider"] == "openai" + and usage_was_reported + and field + in { + "cache_read_input_tokens", + "reasoning_tokens", + } + ): + event_properties.setdefault( + property_name, event_data["usage_stats"].get(field, 0) + ) + elif value is not None and isinstance(value, int) and value > 0: + event_properties[property_name] = value + + +def _add_streaming_usage_metadata( + event_properties: Dict[str, Any], usage: TokenUsage +) -> None: + cache_reporting_exclusive = usage.get("cache_reporting_exclusive") if cache_reporting_exclusive is not None: event_properties["$ai_cache_reporting_exclusive"] = cache_reporting_exclusive # Add web search count if present (all providers) - web_search_count = event_data["usage_stats"].get("web_search_count") + web_search_count = usage.get("web_search_count") if ( web_search_count is not None and isinstance(web_search_count, int) @@ -1195,36 +1145,57 @@ def capture_streaming_event( event_properties["$ai_web_search_count"] = web_search_count # Add raw usage metadata if present (all providers) - raw_usage = event_data["usage_stats"].get("raw_usage") + raw_usage = usage.get("raw_usage") if raw_usage is not None: # Already serialized by converters event_properties["$ai_usage"] = raw_usage - # Add stop reason if present - stop_reason = event_data.get("stop_reason") - if stop_reason is not None: - event_properties["$ai_stop_reason"] = stop_reason - # Handle provider-specific fields - if ( - event_data["provider"] == "openai" - and event_data["kwargs"].get("instructions") is not None - ): - event_properties["$ai_instructions"] = with_privacy_mode( +def _streaming_base_properties( + ph_client: PostHogClient, + event_data: StreamingEventData, + trace_id: str, + error: Optional[BaseException], + input_tokens: Optional[int], + output_tokens: Optional[int], +) -> Dict[str, Any]: + # Build base event properties + return { + "$ai_provider": event_data["provider"], + "$ai_model": event_data["model"], + "$ai_model_parameters": get_model_params( + event_data["kwargs"], event_data.get("service_tier") + ), + **( + {"$ai_service_tier": event_data["service_tier"]} + if event_data.get("service_tier") is not None + else {} + ), + "$ai_input": with_privacy_mode( ph_client, event_data["privacy_mode"], - event_data["kwargs"]["instructions"], - ) - - if event_data.get("distinct_id") is None: - event_properties["$process_person_profile"] = False - - # Send event to PostHog - if hasattr(ph_client, "capture"): - _capture_ai_event( + finalize_ai_content(event_data["formatted_input"], ph_client), + ), + "$ai_output_choices": with_privacy_mode( ph_client, - "$ai_generation", - distinct_id=event_data.get("distinct_id") or trace_id, - properties=event_properties, - groups=event_data.get("groups"), - ) + event_data["privacy_mode"], + finalize_ai_content(event_data["formatted_output"], ph_client), + ), + "$ai_http_status": (_get_http_status(error) if error is not None else 200), + **({"$ai_input_tokens": input_tokens} if input_tokens is not None else {}), + **({"$ai_output_tokens": output_tokens} if output_tokens is not None else {}), + "$ai_latency": event_data["latency"], + "$ai_trace_id": trace_id, + "$ai_base_url": str(event_data["base_url"]), + **(event_data.get("properties") or {}), + **( + { + "$ai_is_error": True, + "$ai_error": _format_ai_error( + ph_client, event_data["privacy_mode"], error + ), + } + if error is not None + else {} + ), + } diff --git a/posthog/async_client.py b/posthog/async_client.py index 7e5c3b3ff..ae63d0853 100644 --- a/posthog/async_client.py +++ b/posthog/async_client.py @@ -10,7 +10,8 @@ import warnings import weakref from datetime import datetime, timezone -from typing import Any, Callable, Dict, Mapping, Optional, Union +from functools import partial as _partial +from typing import AbstractSet, Any, Callable, Dict, Mapping, Optional, Union from uuid import UUID, uuid4 from typing_extensions import Unpack @@ -165,24 +166,7 @@ def __init__( capture_compression, gzip_fallback=gzip ) self.capture_trace_context = capture_trace_context - if personal_api_key is not None and secret_key is None: - warnings.warn( - "`personal_api_key` is deprecated; use `secret_key` instead.", - DeprecationWarning, - stacklevel=2, - ) - elif personal_api_key is not None and secret_key is not None: - self.log.warning( - "[FEATURE FLAGS] Both secret_key and personal_api_key were provided; " - "using secret_key." - ) - resolved_secret_key = secret_key if secret_key is not None else personal_api_key - self.secret_key = ( - resolved_secret_key.strip() - if isinstance(resolved_secret_key, str) - else resolved_secret_key - ) or None - self.personal_api_key = self.secret_key + self._configure_secret_key(secret_key, personal_api_key) _validate_options( email_request_timeout_seconds, email_request_max_retries, migrated_from ) @@ -203,35 +187,16 @@ def __init__( self._feature_flag_evaluations_host_cache: Optional[ _FeatureFlagEvaluationsHost ] = None - self.log_captured_exceptions = log_captured_exceptions - self.capture_exception_code_variables = capture_exception_code_variables - self.code_variables_mask_patterns = ( - code_variables_mask_patterns - if code_variables_mask_patterns is not None - else DEFAULT_CODE_VARIABLES_MASK_PATTERNS - ) - self.code_variables_ignore_patterns = ( - code_variables_ignore_patterns - if code_variables_ignore_patterns is not None - else DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS - ) - self.code_variables_mask_url_credentials = ( - code_variables_mask_url_credentials - if code_variables_mask_url_credentials is not None - else DEFAULT_CODE_VARIABLES_MASK_URL_CREDENTIALS + self._configure_exception_capture( + log_captured_exceptions, + capture_exception_code_variables, + code_variables_mask_patterns, + code_variables_ignore_patterns, + code_variables_mask_url_credentials, + code_variables_detect_secrets, + in_app_modules, + project_root, ) - self.code_variables_detect_secrets = ( - code_variables_detect_secrets - if code_variables_detect_secrets is not None - else DEFAULT_CODE_VARIABLES_DETECT_SECRETS - ) - self.in_app_modules = in_app_modules - self.project_root = project_root - if self.project_root is None: - try: - self.project_root = os.getcwd() - except Exception: - self.project_root = None if before_send is not None and not callable(before_send): self.log.warning("before_send is not callable, it will be ignored") @@ -269,6 +234,69 @@ def __init__( self._duplicate_client_registry_key: Optional[tuple[str, str]] = None self._register_duplicate_client() + def _configure_secret_key( + self, secret_key: Optional[str], personal_api_key: Optional[str] + ) -> None: + if personal_api_key is not None and secret_key is None: + warnings.warn( + "`personal_api_key` is deprecated; use `secret_key` instead.", + DeprecationWarning, + stacklevel=3, + ) + elif personal_api_key is not None and secret_key is not None: + self.log.warning( + "[FEATURE FLAGS] Both secret_key and personal_api_key were provided; " + "using secret_key." + ) + resolved_secret_key = secret_key if secret_key is not None else personal_api_key + self.secret_key = ( + resolved_secret_key.strip() + if isinstance(resolved_secret_key, str) + else resolved_secret_key + ) or None + self.personal_api_key = self.secret_key + + def _configure_exception_capture( + self, + log_captured_exceptions: bool, + capture_exception_code_variables: bool, + code_variables_mask_patterns, + code_variables_ignore_patterns, + code_variables_mask_url_credentials, + code_variables_detect_secrets, + in_app_modules: Optional[list[str]], + project_root: Optional[str], + ) -> None: + self.log_captured_exceptions = log_captured_exceptions + self.capture_exception_code_variables = capture_exception_code_variables + self.code_variables_mask_patterns = ( + code_variables_mask_patterns + if code_variables_mask_patterns is not None + else DEFAULT_CODE_VARIABLES_MASK_PATTERNS + ) + self.code_variables_ignore_patterns = ( + code_variables_ignore_patterns + if code_variables_ignore_patterns is not None + else DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS + ) + self.code_variables_mask_url_credentials = ( + code_variables_mask_url_credentials + if code_variables_mask_url_credentials is not None + else DEFAULT_CODE_VARIABLES_MASK_URL_CREDENTIALS + ) + self.code_variables_detect_secrets = ( + code_variables_detect_secrets + if code_variables_detect_secrets is not None + else DEFAULT_CODE_VARIABLES_DETECT_SECRETS + ) + self.in_app_modules = in_app_modules + self.project_root = project_root + if self.project_root is None: + try: + self.project_root = os.getcwd() + except Exception: + self.project_root = None + _emails: Optional[AsyncEmails] = None @property @@ -428,28 +456,40 @@ def _enqueue_prepared_event(self, prepared: dict[str, Any]) -> bool: self._ensure_workers_started() self._queue.put_nowait(queued_event) return True + return self._enqueue_from_thread(self._loop, queued_event, running_loop) + + def _enqueue_from_thread( + self, + loop: asyncio.AbstractEventLoop, + queued_event: _QueuedEvent, + running_loop: Optional[asyncio.AbstractEventLoop], + ) -> bool: if running_loop is not None: raise RuntimeError("AsyncClient cannot be shared across event loops") - if self._loop_thread_id == threading.get_ident() or not self._loop.is_running(): + if self._loop_thread_id == threading.get_ident() or not loop.is_running(): raise RuntimeError("AsyncClient event loop is not running") admitted: concurrent.futures.Future[bool] = concurrent.futures.Future() - def enqueue_on_bound_loop() -> None: - try: - if not self._accepting or self._closed: - admitted.set_result(False) - return - self._ensure_workers_started() - self._queue.put_nowait(queued_event) - except BaseException as error: - admitted.set_exception(error) - else: - admitted.set_result(True) - - self._loop.call_soon_threadsafe(enqueue_on_bound_loop) + loop.call_soon_threadsafe( + _partial(self._enqueue_on_bound_loop, queued_event, admitted) + ) return admitted.result() + def _enqueue_on_bound_loop( + self, queued_event: _QueuedEvent, admitted: concurrent.futures.Future[bool] + ) -> None: + try: + if not self._accepting or self._closed: + admitted.set_result(False) + return + self._ensure_workers_started() + self._queue.put_nowait(queued_event) + except BaseException as error: + admitted.set_exception(error) + else: + admitted.set_result(True) + def _normalize_uuid(self, msg: dict[str, Any]) -> str: raw_uuid = msg.pop("uuid", None) if raw_uuid is not None: @@ -477,19 +517,28 @@ def _prepare_event( if self.disabled or not self._accepting: return None, None - timestamp = msg.get("timestamp") - if timestamp is None: - timestamp = datetime.now(tz=timezone.utc) - try: - msg["timestamp"] = _normalize_timestamp(timestamp) - except ValueError: - self.log.warning( - "Invalid timestamp %r. Falling back to the current UTC time.", - timestamp, - ) - msg["timestamp"] = datetime.now(tz=timezone.utc).isoformat() + msg["timestamp"] = self._event_timestamp(msg.get("timestamp")) sent_uuid = self._normalize_uuid(msg) + self._add_capture_metadata(msg, disable_geoip) + # After every enrichment step, so a super property never changes or adds + # config version 2 flag attribution. + if pinned_properties is not None: + msg["properties"] = pinned_properties.apply(msg["properties"]) + if property_allowlist is not None: + msg["properties"] = { + key: value + for key, value in msg["properties"].items() + if key in property_allowlist + } + + msg["distinct_id"] = _stringify_id(msg.get("distinct_id")) + cleaned = clean(msg) + return cleaned, sent_uuid + + def _add_capture_metadata( + self, msg: dict[str, Any], disable_geoip: Optional[bool] + ) -> None: properties = msg.setdefault("properties", {}) properties["$lib"] = "posthog-python" properties["$lib_version"] = VERSION @@ -504,20 +553,19 @@ def _prepare_event( msg["properties"].setdefault("$release_id", self._release_id) if self.is_server: msg["properties"]["$is_server"] = True - # After every enrichment step, so a super property never changes or adds - # config version 2 flag attribution. - if pinned_properties is not None: - msg["properties"] = pinned_properties.apply(msg["properties"]) - if property_allowlist is not None: - msg["properties"] = { - key: value - for key, value in msg["properties"].items() - if key in property_allowlist - } - msg["distinct_id"] = _stringify_id(msg.get("distinct_id")) - cleaned = clean(msg) - return cleaned, sent_uuid + def _event_timestamp(self, value: Any) -> str: + timestamp = value + if timestamp is None: + timestamp = datetime.now(tz=timezone.utc) + try: + return _normalize_timestamp(timestamp) + except ValueError: + self.log.warning( + "Invalid timestamp %r. Falling back to the current UTC time.", + timestamp, + ) + return datetime.now(tz=timezone.utc).isoformat() async def _process_event(self, msg: dict[str, Any]) -> Optional[dict[str, Any]]: if self.before_send is None: @@ -623,13 +671,10 @@ async def capture_immediate( self, event: str, **kwargs: Unpack[OptionalCaptureArgs] ) -> Optional[str]: """Capture one event and wait until its delivery attempt completes.""" - current = asyncio.current_task() - if current is None: # pragma: no cover - async functions always have a task + admitted = self._start_immediate_call() + if admitted is None: return None - if not self._accepting: - return None - completion = self._start_inflight_operation() - self._immediate_callers[current] = self._immediate_callers.get(current, 0) + 1 + current, completion = admitted error_batch: list[dict[str, Any]] = [] try: msg, disable_geoip, property_allowlist, pinned_properties = ( @@ -646,33 +691,14 @@ async def capture_immediate( error_batch = [processed] if not self.send: return sent_uuid - try: - event_size = await _serialized_event_size(processed) - except Exception: - self.log.error( - "unable to serialize immediate event for sizing, dropping" - ) - return None - if event_size > MAX_MSG_SIZE: - self.log.error( - "Event %s (%d bytes) exceeds the %dKiB limit, dropping.", - processed.get("event"), - event_size, - MAX_MSG_SIZE // 1024, - ) + if not await self._immediate_event_is_sendable(processed): return None consumer = self._new_consumer() await consumer.request(error_batch) return sent_uuid except Exception as error: - if self.on_error: - try: - await _invoke_callback(self.on_error, error, error_batch) - except Exception as callback_error: - self.log.error( - "on_error handler failed (%s)", type(callback_error).__name__ - ) + await self._notify_immediate_error(error, error_batch) if self.debug: raise self.log.error( @@ -682,12 +708,56 @@ async def capture_immediate( ) return None finally: - remaining_calls = self._immediate_callers[current] - 1 - if remaining_calls: - self._immediate_callers[current] = remaining_calls - else: - del self._immediate_callers[current] - self._finish_inflight_operation(completion) + self._finish_immediate_call(current, completion) + + def _start_immediate_call( + self, + ) -> Optional[tuple[asyncio.Task[Any], asyncio.Future[None]]]: + current = asyncio.current_task() + if current is None: # pragma: no cover - async functions always have a task + return None + if not self._accepting: + return None + completion = self._start_inflight_operation() + self._immediate_callers[current] = self._immediate_callers.get(current, 0) + 1 + return current, completion + + def _finish_immediate_call( + self, current: asyncio.Task[Any], completion: asyncio.Future[None] + ) -> None: + remaining_calls = self._immediate_callers[current] - 1 + if remaining_calls: + self._immediate_callers[current] = remaining_calls + else: + del self._immediate_callers[current] + self._finish_inflight_operation(completion) + + async def _notify_immediate_error( + self, error: Exception, error_batch: list[dict[str, Any]] + ) -> None: + if self.on_error: + try: + await _invoke_callback(self.on_error, error, error_batch) + except Exception as callback_error: + self.log.error( + "on_error handler failed (%s)", type(callback_error).__name__ + ) + + async def _immediate_event_is_sendable(self, processed: dict[str, Any]) -> bool: + try: + event_size = await _serialized_event_size(processed) + except Exception: + self.log.error("unable to serialize immediate event for sizing, dropping") + return False + if event_size > MAX_MSG_SIZE: + self.log.error( + "Event %s (%d bytes) exceeds the %dKiB limit, dropping.", + processed.get("event"), + event_size, + MAX_MSG_SIZE // 1024, + ) + return False + return True def _build_person_properties_event( self, event: str, property_key: str, kwargs: OptionalSetArgs @@ -829,16 +899,8 @@ def capture_exception( ) -> Optional[str]: """Capture an exception. This method never raises, including in debug mode.""" try: - if exception is not None and exception_is_already_captured(exception): - self.log.debug("Exception already captured, skipping") - return None - exc_info = ( - exc_info_from_error(exception) - if exception is not None - else sys.exc_info() - ) - if exc_info is None or exc_info == (None, None, None): - self.log.warning("No exception information available") + exc_info = self._exception_info(exception) + if exc_info is None: return None exceptions = exceptions_from_error_tuple(exc_info) @@ -852,43 +914,7 @@ def capture_exception( "$exception_list": exceptions, **(kwargs.get("properties") or {}), } - context_enabled = get_capture_exception_code_variables_context() - context_mask = get_code_variables_mask_patterns_context() - context_ignore = get_code_variables_ignore_patterns_context() - context_mask_url_credentials = ( - get_code_variables_mask_url_credentials_context() - ) - context_detect_secrets = get_code_variables_detect_secrets_context() - enabled = ( - context_enabled - if context_enabled is not None - else self.capture_exception_code_variables - ) - if enabled: - try_attach_code_variables_to_frames( - exceptions, - exc_info, - mask_patterns=( - context_mask - if context_mask is not None - else self.code_variables_mask_patterns - ), - ignore_patterns=( - context_ignore - if context_ignore is not None - else self.code_variables_ignore_patterns - ), - mask_url_credentials=( - context_mask_url_credentials - if context_mask_url_credentials is not None - else self.code_variables_mask_url_credentials - ), - detect_secrets=( - context_detect_secrets - if context_detect_secrets is not None - else self.code_variables_detect_secrets - ), - ) + self._attach_exception_code_variables(exceptions, exc_info) if self.log_captured_exceptions: self.log.exception(exception, extra=kwargs) @@ -909,6 +935,56 @@ def capture_exception( self.log.exception("Failed to capture exception: %s", error) return None + def _attach_exception_code_variables(self, exceptions, exc_info) -> None: + context_enabled = get_capture_exception_code_variables_context() + context_mask = get_code_variables_mask_patterns_context() + context_ignore = get_code_variables_ignore_patterns_context() + context_mask_url_credentials = get_code_variables_mask_url_credentials_context() + context_detect_secrets = get_code_variables_detect_secrets_context() + enabled = ( + context_enabled + if context_enabled is not None + else self.capture_exception_code_variables + ) + if enabled: + try_attach_code_variables_to_frames( + exceptions, + exc_info, + mask_patterns=( + context_mask + if context_mask is not None + else self.code_variables_mask_patterns + ), + ignore_patterns=( + context_ignore + if context_ignore is not None + else self.code_variables_ignore_patterns + ), + mask_url_credentials=( + context_mask_url_credentials + if context_mask_url_credentials is not None + else self.code_variables_mask_url_credentials + ), + detect_secrets=( + context_detect_secrets + if context_detect_secrets is not None + else self.code_variables_detect_secrets + ), + ) + + def _exception_info(self, exception: Optional[ExceptionArg]): + if exception is not None and exception_is_already_captured(exception): + self.log.debug("Exception already captured, skipping") + return None + exc_info = ( + exc_info_from_error(exception) if exception is not None else sys.exc_info() + ) + if exc_info is None or exc_info == (None, None, None): + self.log.warning("No exception information available") + return None + + return exc_info + def _get_feature_flag_evaluations_host(self) -> _FeatureFlagEvaluationsHost: if self._feature_flag_evaluations_host_cache is None: self._feature_flag_evaluations_host_cache = _FeatureFlagEvaluationsHost( @@ -974,10 +1050,7 @@ async def evaluate_flags( ``unresolved_flags`` is always empty. """ host = self._get_feature_flag_evaluations_host() - if distinct_id is None: - distinct_id = _get_context_distinct_id() - if device_id is None: - device_id = _get_context_device_id() + distinct_id, device_id = _evaluation_context_ids(distinct_id, device_id) if distinct_id is None or distinct_id == "" or self.disabled: return FeatureFlagEvaluations(host=host, distinct_id="", flags={}) @@ -991,12 +1064,6 @@ async def evaluate_flags( disable_geoip=disable_geoip, ) - records: dict[str, _EvaluatedFlagRecord] = {} - request_id: Optional[str] = None - evaluated_at: Optional[int] = None - errors_while_computing = False - quota_limited = False - minimal_flag_called_events = False requested_keys = set(flag_keys) if flag_keys else None if not self._accepting: return FeatureFlagEvaluations( @@ -1006,12 +1073,43 @@ async def evaluate_flags( groups=resolved_groups, disable_geoip=disable_geoip, ) + return await self._request_flag_snapshot( + host, + distinct_id, + requested_keys, + groups=resolved_groups, + person_properties=person_properties, + group_properties=group_properties, + disable_geoip=disable_geoip, + flag_keys=flag_keys, + device_id=device_id, + ) + + async def _request_flag_snapshot( + self, + host: _FeatureFlagEvaluationsHost, + distinct_id: ID_TYPES, + requested_keys: Optional[AbstractSet[str]], + *, + groups: Mapping[str, Union[str, int]], + person_properties: Optional[Dict[str, Any]], + group_properties: Optional[Dict[str, Dict[str, Any]]], + disable_geoip: Optional[bool], + flag_keys: Optional[list[str]], + device_id: Optional[str], + ) -> FeatureFlagEvaluations: + records: dict[str, _EvaluatedFlagRecord] = {} + request_id: Optional[str] = None + evaluated_at: Optional[int] = None + errors_while_computing = False + quota_limited = False + minimal_flag_called_events = False completion = self._start_inflight_operation() try: response = await self._get_flags_decision( distinct_id, - groups=resolved_groups, + groups=groups, person_properties=person_properties, group_properties=group_properties, disable_geoip=disable_geoip, @@ -1049,7 +1147,7 @@ async def evaluate_flags( host=host, distinct_id=str(distinct_id), flags=records, - groups=resolved_groups, + groups=groups, disable_geoip=disable_geoip, request_id=request_id, evaluated_at=evaluated_at, @@ -1237,13 +1335,7 @@ async def shutdown(self) -> None: self._accepting = False errors: list[Exception] = [] - pending_operations = [ - completion - for completion in self._inflight_operations - if not completion.done() - ] - if pending_operations: - await asyncio.gather(*pending_operations, return_exceptions=True) + await self._wait_for_inflight_operations() try: await self.flush(timeout_seconds=None) @@ -1251,37 +1343,9 @@ async def shutdown(self) -> None: self.log.exception("Failed to flush async capture queue") errors.append(error) - try: - live_workers = [task for task in self._worker_tasks if not task.done()] - for _ in live_workers: - await self._queue.put(_STOP) - if self._worker_tasks: - await asyncio.gather(*self._worker_tasks, return_exceptions=True) - except Exception as error: - self.log.exception("Failed to stop async capture workers") - errors.append(error) - finally: - self._worker_tasks.clear() - self._consumers.clear() - - try: - await self._close_transport() - except Exception as error: - self.log.exception("Failed to close async capture transport") - errors.append(error) - - if self._emails is not None: - try: - await self._emails.aclose() - except Exception as error: - self.log.exception("Failed to close the async email transport") - errors.append(error) + await self._stop_workers(errors) - try: - self._unregister_duplicate_client() - except Exception as error: - self.log.exception("Failed to unregister async client") - errors.append(error) + await self._close_resources(errors) self.distinct_ids_feature_flags_reported.clear() self._experiment_exposures_reported.clear() @@ -1289,6 +1353,49 @@ async def shutdown(self) -> None: if errors and self.debug: raise errors[0] + async def _close_resources(self, errors: list[Exception]) -> None: + try: + await self._close_transport() + except Exception as error: + self.log.exception("Failed to close async capture transport") + errors.append(error) + + if self._emails is not None: + try: + await self._emails.aclose() + except Exception as error: + self.log.exception("Failed to close the async email transport") + errors.append(error) + + try: + self._unregister_duplicate_client() + except Exception as error: + self.log.exception("Failed to unregister async client") + errors.append(error) + + async def _stop_workers(self, errors: list[Exception]) -> None: + try: + live_workers = [task for task in self._worker_tasks if not task.done()] + for _ in live_workers: + await self._queue.put(_STOP) + if self._worker_tasks: + await asyncio.gather(*self._worker_tasks, return_exceptions=True) + except Exception as error: + self.log.exception("Failed to stop async capture workers") + errors.append(error) + finally: + self._worker_tasks.clear() + self._consumers.clear() + + async def _wait_for_inflight_operations(self) -> None: + pending_operations = [ + completion + for completion in self._inflight_operations + if not completion.done() + ] + if pending_operations: + await asyncio.gather(*pending_operations, return_exceptions=True) + async def join(self) -> None: await self.shutdown() @@ -1297,3 +1404,13 @@ class AsyncPosthog(AsyncClient): """Customer-facing name for :class:`AsyncClient`.""" pass + + +def _evaluation_context_ids( + distinct_id: Optional[ID_TYPES], device_id: Optional[str] +) -> tuple[Optional[ID_TYPES], Optional[str]]: + if distinct_id is None: + distinct_id = _get_context_distinct_id() + if device_id is None: + device_id = _get_context_device_id() + return distinct_id, device_id diff --git a/posthog/capture_compression.py b/posthog/capture_compression.py index 7b6760d06..41e3d8e1d 100644 --- a/posthog/capture_compression.py +++ b/posthog/capture_compression.py @@ -108,6 +108,10 @@ def _resolve_capture_compression( fallback = CaptureCompression.GZIP if gzip_fallback else CaptureCompression.NONE + return _resolve_env_compression(fallback) + + +def _resolve_env_compression(fallback: CaptureCompression) -> CaptureCompression: raw = os.environ.get(CAPTURE_COMPRESSION_ENV_VAR) if raw is None or raw.strip() == "": return fallback diff --git a/posthog/capture_v1.py b/posthog/capture_v1.py index 8f29cd706..fb8afa7aa 100644 --- a/posthog/capture_v1.py +++ b/posthog/capture_v1.py @@ -166,18 +166,7 @@ def _to_v1_event(msg: dict) -> dict: """ properties = dict(msg.get("properties") or {}) - # Relocate top-level $set/$set_once into properties; v1 has no top-level - # form. On the unusual collision where properties already carries the key, - # the properties value wins. - for key in _RELOCATE_TO_PROPERTIES: - top_val = msg.get(key) - if top_val is None: - continue - existing = properties.get(key) - if isinstance(top_val, dict) and isinstance(existing, dict): - properties[key] = {**top_val, **existing} - elif key not in properties: - properties[key] = top_val + _relocate_v1_properties(msg, properties) for key in _STRIP_FROM_PROPERTIES: properties.pop(key, None) @@ -403,21 +392,9 @@ def _parse_v1_response(res: "requests.Response") -> _V1ParsedResponse: # don't loop forever re-sending against a broken success. return _V1ParsedResponse(status, True, retry_after, malformed=True) - message = "" - try: - payload = res.json() - if isinstance(payload, dict): - message = ( - payload.get("error_description") - or payload.get("error") - or payload.get("detail") - or "" - ) - except (ValueError, AttributeError): - pass - if not message: - message = res.text or f"capture v1 request failed with status {status}" - return _V1ParsedResponse(status, False, retry_after, error_message=message) + return _V1ParsedResponse( + status, False, retry_after, error_message=_v1_error_message(res, status) + ) def _backoff(attempt_index: int, retry_after: Optional[float]) -> None: @@ -536,78 +513,155 @@ def _send_v1_batch( parsed = _parse_v1_response(res) if parsed.is_success: - if parsed.malformed: - raise CaptureV1Error( - parsed.status_code, - "capture v1 returned a success status with an unparseable body", - request_id=request_id, - attempts=attempt, - drops=all_drops, - ) - results = parsed.results or {} - _log_result_summary(request_id, attempt, results) - - retry_events: list[dict] = [] - retry_uuids: list[str] = [] - for event, uid in zip(pending_events, pending_uuids): - directive = results.get(uid) - if directive is None: - # Absent from the map: treated as accepted (matches posthog-rs). - continue - if directive.result == _RESULT_RETRY: - retry_events.append(event) - retry_uuids.append(uid) - elif directive.result == _RESULT_DROP: - # Terminal per-event rejection; keep it so it is surfaced - # even when the rest of the batch succeeds (see below). - all_drops.append((uid, directive.details)) - # ok / warning / unrecognized -> terminal success. - - if not retry_uuids: - # Nothing left to resend. If the server dropped any events, - # surface them via on_error even though the request was a 2xx — - # a success status does not mean every event was delivered. - if all_drops: - raise CaptureV1Error( - parsed.status_code, - f"{len(all_drops)} event(s) dropped by the server", - request_id=request_id, - attempts=attempt, - drops=all_drops, - ) + pending_events, pending_uuids = _apply_v1_results( + parsed, + pending_events, + pending_uuids, + all_drops, + request_id, + attempt, + last_attempt, + ) + if not pending_uuids: return - if last_attempt: - raise CaptureV1Error( - parsed.status_code, - f"{len(retry_uuids)} event(s) still pending retry after {attempt} attempt(s)", - request_id=request_id, - attempts=attempt, - retry_exhausted=retry_uuids, - drops=all_drops, - ) - pending_events, pending_uuids = retry_events, retry_uuids _backoff(attempt_index, parsed.retry_after) continue # Non-2xx. Retryable transient statuses back off; everything else # (400/401/402/413/415/...) is terminal. Any drops collected from a # prior 2xx attempt ride along so on_error still sees them. - v1_error = CaptureV1Error( + last_exc = _v1_batch_failure( + parsed, request_id, attempt, all_drops, last_attempt + ) + _backoff(attempt_index, parsed.retry_after) + + # Unreachable in practice (every branch returns or continues). + if last_exc: + raise last_exc + + +def _relocate_v1_properties(msg: dict, properties: dict) -> None: + # Relocate top-level $set/$set_once into properties; v1 has no top-level + # form. On the unusual collision where properties already carries the key, + # the properties value wins. + for key in _RELOCATE_TO_PROPERTIES: + top_val = msg.get(key) + if top_val is None: + continue + existing = properties.get(key) + if isinstance(top_val, dict) and isinstance(existing, dict): + properties[key] = {**top_val, **existing} + elif key not in properties: + properties[key] = top_val + + +def _v1_error_message(res: "requests.Response", status: int) -> str: + message = "" + try: + payload = res.json() + if isinstance(payload, dict): + message = ( + payload.get("error_description") + or payload.get("error") + or payload.get("detail") + or "" + ) + except (ValueError, AttributeError): + pass + if not message: + message = res.text or f"capture v1 request failed with status {status}" + return message + + +def _apply_v1_results( + parsed: _V1ParsedResponse, + pending_events: list[dict], + pending_uuids: list[str], + all_drops: list[tuple[str, Optional[str]]], + request_id: str, + attempt: int, + last_attempt: bool, +) -> tuple[list[dict], list[str]]: + if parsed.malformed: + raise CaptureV1Error( parsed.status_code, - parsed.error_message, - retry_after=parsed.retry_after, + "capture v1 returned a success status with an unparseable body", request_id=request_id, attempts=attempt, drops=all_drops, ) - if parsed.status_code in _RETRYABLE_STATUSES: - last_exc = v1_error - if last_attempt: - raise v1_error - _backoff(attempt_index, parsed.retry_after) + results = parsed.results or {} + _log_result_summary(request_id, attempt, results) + + retry_events, retry_uuids = _partition_v1_results( + pending_events, pending_uuids, results, all_drops + ) + + if not retry_uuids: + # Nothing left to resend. If the server dropped any events, + # surface them via on_error even though the request was a 2xx — + # a success status does not mean every event was delivered. + if all_drops: + raise CaptureV1Error( + parsed.status_code, + f"{len(all_drops)} event(s) dropped by the server", + request_id=request_id, + attempts=attempt, + drops=all_drops, + ) + return [], [] + if last_attempt: + raise CaptureV1Error( + parsed.status_code, + f"{len(retry_uuids)} event(s) still pending retry after {attempt} attempt(s)", + request_id=request_id, + attempts=attempt, + retry_exhausted=retry_uuids, + drops=all_drops, + ) + return retry_events, retry_uuids + + +def _partition_v1_results( + pending_events: list[dict], + pending_uuids: list[str], + results: dict[str, _V1EventResult], + all_drops: list[tuple[str, Optional[str]]], +) -> tuple[list[dict], list[str]]: + retry_events: list[dict] = [] + retry_uuids: list[str] = [] + for event, uid in zip(pending_events, pending_uuids): + directive = results.get(uid) + if directive is None: + # Absent from the map: treated as accepted (matches posthog-rs). continue - raise v1_error + if directive.result == _RESULT_RETRY: + retry_events.append(event) + retry_uuids.append(uid) + elif directive.result == _RESULT_DROP: + # Terminal per-event rejection; keep it so it is surfaced + # even when the rest of the batch succeeds (see below). + all_drops.append((uid, directive.details)) + # ok / warning / unrecognized -> terminal success. - # Unreachable in practice (every branch returns or continues). - if last_exc: - raise last_exc + return retry_events, retry_uuids + + +def _v1_batch_failure( + parsed: _V1ParsedResponse, + request_id: str, + attempt: int, + all_drops: list[tuple[str, Optional[str]]], + last_attempt: bool, +) -> CaptureV1Error: + error = CaptureV1Error( + parsed.status_code, + parsed.error_message, + retry_after=parsed.retry_after, + request_id=request_id, + attempts=attempt, + drops=all_drops, + ) + if parsed.status_code not in _RETRYABLE_STATUSES or last_attempt: + raise error + return error diff --git a/posthog/client.py b/posthog/client.py index 35380d979..73181a82c 100644 --- a/posthog/client.py +++ b/posthog/client.py @@ -11,6 +11,7 @@ import warnings import weakref from contextvars import ContextVar +from dataclasses import dataclass as _dataclass from datetime import datetime, timedelta, timezone from typing import ( Any, @@ -178,6 +179,32 @@ _atexit_deadline_lock = threading.Lock() +@_dataclass +class _FlagReadResult: + """Per-read result and attribution, including metadata retained on remote failure.""" + + result: Optional[FeatureFlagResult] = None + details: Optional[FeatureFlag] = None + request_id: Optional[str] = None + evaluated_at: Optional[int] = None + error: Optional[str] = None + minimal_flag_called_events: bool = False + # Only a read whose value came from details may attribute a v2 experiment split. + value_from_details: bool = False + + +@_dataclass +class _FlagEvaluationResult: + """Mutable only during one evaluation pass, then handed to its snapshot.""" + + records: Dict[str, _EvaluatedFlagRecord] + request_id: Optional[str] = None + evaluated_at: Optional[int] = None + errors_while_computing: bool = False + quota_limited: bool = False + minimal_flag_called_events: bool = False + + class _LocalEvaluationSnapshot(FlagDefinitionCacheData): flags_by_key: Dict[str, Any] flag_definition_version: int @@ -526,6 +553,12 @@ def _rule_attribution(details: Optional[FeatureFlag]) -> Optional[_RuleAttributi if _v4_field(metadata, "config_version") != 2: return None reason_code = (details.reason.code if details.reason else None) or None + return _rule_attribution_from_metadata(details, metadata, reason_code) + + +def _rule_attribution_from_metadata( + details: FeatureFlag, metadata: FlagMetadata, reason_code: Optional[str] +) -> _RuleAttribution: allowed_rule_types = _RULE_TYPES_BY_REASON_CODE.get(reason_code or "") if _v4_field(details, "failed") is True or allowed_rule_types is None: return _RuleAttribution(reason_code, None, None, None) @@ -708,56 +741,112 @@ def _capture_flag_events( ) if reported_flags is not None: - if attribution is not None: - properties.pop("$feature_flag_reason", None) - properties.update(attribution.flag_called_properties()) - # Record the server's experiment signal when known, so minimization's impact - # can be measured by segmenting on it. - if has_experiment is not None: - properties["$feature_flag_has_experiment"] = has_experiment - - # Minimize iff the server-controlled gate is on AND the flag is known to have - # no linked experiment. Any missing signal (gate absent, has_experiment - # missing) fails safe to the full legacy shape. - should_minimize = minimal_flag_called_events and has_experiment is False - # Only thread the internal allowlist through when minimizing, so the - # full-property path's capture() call signature stays unchanged. - extra_capture_kwargs: Dict[str, Any] = {} - if should_minimize: - extra_capture_kwargs["_property_allowlist"] = ( - _MINIMAL_FLAG_CALLED_EVENT_PROPERTIES - if attribution is None - else _MINIMAL_V2_FLAG_CALLED_EVENT_PROPERTIES - ) + _capture_flag_called_event( + capture, + reported_flags, + feature_flag_reported_key, + distinct_id=distinct_id, + properties=properties, + capture_groups=capture_groups, + disable_geoip=disable_geoip, + has_experiment=has_experiment, + minimal_flag_called_events=minimal_flag_called_events, + attribution=attribution, + flag_identity=flag_identity, + ) + + _capture_experiment_exposure( + capture, + exposures_reported, + distinct_id=distinct_id, + key=key, + groups_key=groups_key, + properties=properties, + capture_groups=capture_groups, + disable_geoip=disable_geoip, + attribution=attribution, + flag_identity=flag_identity, + ) + + +def _capture_flag_called_event( + capture, + reported_flags, + feature_flag_reported_key, + *, + distinct_id, + properties, + capture_groups, + disable_geoip, + has_experiment, + minimal_flag_called_events, + attribution, + flag_identity, +) -> None: + if attribution is not None: + properties.pop("$feature_flag_reason", None) + properties.update(attribution.flag_called_properties()) + # Record the server's experiment signal when known, so minimization's impact + # can be measured by segmenting on it. + if has_experiment is not None: + properties["$feature_flag_has_experiment"] = has_experiment + + # Minimize iff the server-controlled gate is on AND the flag is known to have + # no linked experiment. Any missing signal (gate absent, has_experiment + # missing) fails safe to the full legacy shape. + should_minimize = minimal_flag_called_events and has_experiment is False + # Only thread the internal allowlist through when minimizing, so the + # full-property path's capture() call signature stays unchanged. + extra_capture_kwargs: Dict[str, Any] = {} + if should_minimize: + extra_capture_kwargs["_property_allowlist"] = ( + _MINIMAL_FLAG_CALLED_EVENT_PROPERTIES + if attribution is None + else _MINIMAL_V2_FLAG_CALLED_EVENT_PROPERTIES + ) + + if attribution is None: + # Config version 1 events are sent and deduped as before. + capture( + "$feature_flag_called", + distinct_id=distinct_id, + properties=properties, + groups=capture_groups, + disable_geoip=disable_geoip, + **extra_capture_kwargs, + ) + reported_flags.add(feature_flag_reported_key) + else: + _capture_once( + capture, + reported_flags, + feature_flag_reported_key, + "$feature_flag_called", + distinct_id=distinct_id, + properties=properties, + groups=capture_groups, + disable_geoip=disable_geoip, + _pinned_properties=_PinnedProperties( + _V2_FLAG_CALLED_PINNED, + {**attribution.flag_called_properties(), **flag_identity}, + ), + **extra_capture_kwargs, + ) - if attribution is None: - # Config version 1 events are sent and deduped as before. - capture( - "$feature_flag_called", - distinct_id=distinct_id, - properties=properties, - groups=capture_groups, - disable_geoip=disable_geoip, - **extra_capture_kwargs, - ) - reported_flags.add(feature_flag_reported_key) - else: - _capture_once( - capture, - reported_flags, - feature_flag_reported_key, - "$feature_flag_called", - distinct_id=distinct_id, - properties=properties, - groups=capture_groups, - disable_geoip=disable_geoip, - _pinned_properties=_PinnedProperties( - _V2_FLAG_CALLED_PINNED, - {**attribution.flag_called_properties(), **flag_identity}, - ), - **extra_capture_kwargs, - ) +def _capture_experiment_exposure( + capture, + exposures_reported, + *, + distinct_id, + key, + groups_key, + properties, + capture_groups, + disable_geoip, + attribution, + flag_identity, +) -> None: if attribution is None or attribution.variant_key is None: return @@ -1013,6 +1102,29 @@ def join(self) -> None: ) errors.append(error) + self._stop_consumers(errors) + try: + self.discard_undrainable_queued_work() + except Exception as error: + self.log.exception( + "Failed to discard queued %s lane work during lifecycle cleanup", + self.name, + ) + errors.append(error) + if drain_requested: + try: + self._drain_signal.complete() + except Exception as error: + self.log.exception( + "Failed to complete %s lane drain during lifecycle cleanup", + self.name, + ) + errors.append(error) + + if errors: + raise errors[0] + + def _stop_consumers(self, errors: list[Exception]) -> None: for consumer in self.consumers: try: consumer._pause(drain=True) @@ -1034,26 +1146,6 @@ def join(self) -> None: self.name, ) errors.append(error) - try: - self.discard_undrainable_queued_work() - except Exception as error: - self.log.exception( - "Failed to discard queued %s lane work during lifecycle cleanup", - self.name, - ) - errors.append(error) - if drain_requested: - try: - self._drain_signal.complete() - except Exception as error: - self.log.exception( - "Failed to complete %s lane drain during lifecycle cleanup", - self.name, - ) - errors.append(error) - - if errors: - raise errors[0] def reset_sync_send_state_after_fork(self) -> None: """Replace sync-send state inherited from threads that did not survive fork.""" @@ -1458,75 +1550,25 @@ def __init__( self._logged_untyped_flags_response = False self.capture_trace_context = capture_trace_context - self.capture_exception_code_variables = capture_exception_code_variables - self.code_variables_mask_patterns = ( - code_variables_mask_patterns - if code_variables_mask_patterns is not None - else DEFAULT_CODE_VARIABLES_MASK_PATTERNS + self._configure_exception_properties( + capture_exception_code_variables, + code_variables_mask_patterns, + code_variables_ignore_patterns, + code_variables_mask_url_credentials, + code_variables_detect_secrets, + in_app_modules, + project_root, ) - self.code_variables_ignore_patterns = ( - code_variables_ignore_patterns - if code_variables_ignore_patterns is not None - else DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS - ) - self.code_variables_mask_url_credentials = ( - code_variables_mask_url_credentials - if code_variables_mask_url_credentials is not None - else DEFAULT_CODE_VARIABLES_MASK_URL_CREDENTIALS - ) - self.code_variables_detect_secrets = ( - code_variables_detect_secrets - if code_variables_detect_secrets is not None - else DEFAULT_CODE_VARIABLES_DETECT_SECRETS - ) - self.in_app_modules = in_app_modules - if project_root is None: - try: - project_root = os.getcwd() - except Exception: - project_root = None - - self.project_root = project_root - - if personal_api_key is not None and secret_key is None: - warnings.warn( - "`personal_api_key` is deprecated; use `secret_key` instead. " - "`secret_key` accepts a Personal API Key or a Project Secret API Key.", - DeprecationWarning, - stacklevel=2, - ) - elif secret_key is not None and personal_api_key is not None: - self.log.warning( - "[FEATURE FLAGS] Both `secret_key` and `personal_api_key` were " - "provided; using `secret_key` and ignoring `personal_api_key`." - ) - resolved_secret_key = secret_key if secret_key is not None else personal_api_key - self.secret_key = ( - resolved_secret_key.strip() - if isinstance(resolved_secret_key, str) - else resolved_secret_key - ) or None - self.personal_api_key = self.secret_key - _validate_options( - email_request_timeout_seconds, email_request_max_retries, migrated_from + self._configure_credentials( + personal_api_key, + secret_key, + app_host, + email_request_timeout_seconds, + email_request_max_retries, + migrated_from, ) - self.app_host = app_host - self.email_request_timeout_seconds = email_request_timeout_seconds - self.email_request_max_retries = email_request_max_retries - self.migrated_from = migrated_from - if debug: - # Ensures that debug level messages are logged when debug mode is on. - # Otherwise, defaults to WARNING level. See https://docs.python.org/3/howto/logging.html#what-happens-if-no-configuration-is-provided - logging.basicConfig() - self.log.setLevel(logging.DEBUG) - else: - self.log.setLevel(logging.WARNING) - - if not self.api_key: - self.log.error( - "api_key is empty after trimming whitespace; check your project API key" - ) + self._configure_logging(debug) self._set_before_send(before_send) @@ -1592,13 +1634,107 @@ def __init__( self._metrics_autocapture_tried = False self._start_metrics_autocapture_once(metrics) + self._register_fork_handler() + + self._warn_if_duplicate_async_client() + + def _register_fork_handler(self) -> None: if hasattr(os, "register_at_fork"): weak_self = weakref.ref(self) os.register_at_fork( after_in_child=lambda: Client._reinit_after_fork_weak(weak_self) ) - self._warn_if_duplicate_async_client() + def _configure_exception_properties( + self, + capture_exception_code_variables, + code_variables_mask_patterns, + code_variables_ignore_patterns, + code_variables_mask_url_credentials, + code_variables_detect_secrets, + in_app_modules, + project_root, + ) -> None: + self.capture_exception_code_variables = capture_exception_code_variables + self.code_variables_mask_patterns = ( + code_variables_mask_patterns + if code_variables_mask_patterns is not None + else DEFAULT_CODE_VARIABLES_MASK_PATTERNS + ) + self.code_variables_ignore_patterns = ( + code_variables_ignore_patterns + if code_variables_ignore_patterns is not None + else DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS + ) + self.code_variables_mask_url_credentials = ( + code_variables_mask_url_credentials + if code_variables_mask_url_credentials is not None + else DEFAULT_CODE_VARIABLES_MASK_URL_CREDENTIALS + ) + self.code_variables_detect_secrets = ( + code_variables_detect_secrets + if code_variables_detect_secrets is not None + else DEFAULT_CODE_VARIABLES_DETECT_SECRETS + ) + self.in_app_modules = in_app_modules + + if project_root is None: + try: + project_root = os.getcwd() + except Exception: + project_root = None + + self.project_root = project_root + + def _configure_credentials( + self, + personal_api_key, + secret_key, + app_host, + email_request_timeout_seconds, + email_request_max_retries, + migrated_from, + ) -> None: + if personal_api_key is not None and secret_key is None: + warnings.warn( + "`personal_api_key` is deprecated; use `secret_key` instead. " + "`secret_key` accepts a Personal API Key or a Project Secret API Key.", + DeprecationWarning, + stacklevel=3, + ) + elif secret_key is not None and personal_api_key is not None: + self.log.warning( + "[FEATURE FLAGS] Both `secret_key` and `personal_api_key` were " + "provided; using `secret_key` and ignoring `personal_api_key`." + ) + resolved_secret_key = secret_key if secret_key is not None else personal_api_key + self.secret_key = ( + resolved_secret_key.strip() + if isinstance(resolved_secret_key, str) + else resolved_secret_key + ) or None + self.personal_api_key = self.secret_key + _validate_options( + email_request_timeout_seconds, email_request_max_retries, migrated_from + ) + self.app_host = app_host + self.email_request_timeout_seconds = email_request_timeout_seconds + self.email_request_max_retries = email_request_max_retries + self.migrated_from = migrated_from + + def _configure_logging(self, debug) -> None: + if debug: + # Ensures that debug level messages are logged when debug mode is on. + # Otherwise, defaults to WARNING level. See https://docs.python.org/3/howto/logging.html#what-happens-if-no-configuration-is-provided + logging.basicConfig() + self.log.setLevel(logging.DEBUG) + else: + self.log.setLevel(logging.WARNING) + + if not self.api_key: + self.log.error( + "api_key is empty after trimming whitespace; check your project API key" + ) def _start_metrics_autocapture_once(self, metrics_config: Any) -> None: """Starts metrics autocapture when the ``metrics`` option asks for it. A @@ -2122,35 +2258,19 @@ def _get_flags_decision( if self.disabled: return normalize_flags_response({}) - groups = groups or {} - person_properties = person_properties or {} - group_properties = group_properties or {} - - if distinct_id is None: - distinct_id = get_context_distinct_id() - - if device_id is None: - device_id = get_context_device_id() + request_data = self._flags_request_data( + distinct_id, + groups, + person_properties, + group_properties, + disable_geoip, + device_id, + ) - if disable_geoip is None: - disable_geoip = self.disable_geoip - - if not groups: - groups = {} - - request_data: Dict[str, Any] = { - "distinct_id": distinct_id, - "groups": groups, - "person_properties": person_properties, - "group_properties": group_properties, - "geoip_disable": disable_geoip, - "device_id": device_id, - } - - if flag_keys_to_evaluate: - request_data["flag_keys_to_evaluate"] = flag_keys_to_evaluate - if self._sdk_info != _USER_AGENT: - request_data["_user_agent"] = self._sdk_info + if flag_keys_to_evaluate: + request_data["flag_keys_to_evaluate"] = flag_keys_to_evaluate + if self._sdk_info != _USER_AGENT: + request_data["_user_agent"] = self._sdk_info resp_data = flags( self.api_key, @@ -2174,6 +2294,42 @@ def _get_flags_decision( ) return response + def _flags_request_data( + self, + distinct_id, + groups, + person_properties, + group_properties, + disable_geoip, + device_id, + ): + groups = groups or {} + person_properties = person_properties or {} + group_properties = group_properties or {} + + if distinct_id is None: + distinct_id = get_context_distinct_id() + + if device_id is None: + device_id = get_context_device_id() + + if disable_geoip is None: + disable_geoip = self.disable_geoip + + if not groups: + groups = {} + + request_data: Dict[str, Any] = { + "distinct_id": distinct_id, + "groups": groups, + "person_properties": person_properties, + "group_properties": group_properties, + "geoip_disable": disable_geoip, + "device_id": device_id, + } + + return request_data + @no_throw() def capture( self, event: str, **kwargs: Unpack[OptionalCaptureArgs] @@ -2278,13 +2434,7 @@ def _capture( pinned_properties = kwargs.get("_pinned_properties", None) before_send_drops = kwargs.get("_before_send_drops", None) - properties = {**(properties or {}), **system_context()} - - if self.capture_trace_context: - properties = {**_get_current_otel_span_properties(), **properties} - - properties = add_context_tags(properties) - assert properties is not None # Type hint for mypy + properties = self._capture_properties(properties) (distinct_id, personless) = get_identity_state(distinct_id) @@ -2316,78 +2466,9 @@ def _capture( ) extra_properties = flags_snapshot._get_event_properties() else: - feature_variants: Optional[dict[str, Union[bool, str]]] = {} - - # Parse and normalize send_feature_flags parameter - flag_options = self._parse_send_feature_flags(send_feature_flags) - - if flag_options["should_send"]: - warnings.warn( - "`send_feature_flags` is deprecated and will be removed in a future major " - "version. Pass a `flags` snapshot from `posthog.evaluate_flags(...)` instead " - "— it avoids a second `/flags` request per capture and guarantees the event " - "carries the exact flag values your code branched on.", - DeprecationWarning, - stacklevel=2, - ) - try: - if flag_options["only_evaluate_locally"] is True: - # Local evaluation explicitly requested - feature_variants = self.get_all_flags( - distinct_id, - groups=(groups or {}), - person_properties=flag_options["person_properties"], - group_properties=flag_options["group_properties"], - disable_geoip=disable_geoip, - only_evaluate_locally=True, - flag_keys_to_evaluate=flag_options["flag_keys_filter"], - ) - elif flag_options["only_evaluate_locally"] is False: - # Remote evaluation explicitly requested - feature_variants = self.get_feature_variants( - distinct_id, - groups, - person_properties=flag_options["person_properties"], - group_properties=flag_options["group_properties"], - disable_geoip=disable_geoip, - flag_keys_to_evaluate=flag_options["flag_keys_filter"], - ) - elif self.feature_flags: - # Local flags available, prefer local evaluation - feature_variants = self.get_all_flags( - distinct_id, - groups=(groups or {}), - person_properties=flag_options["person_properties"], - group_properties=flag_options["group_properties"], - disable_geoip=disable_geoip, - only_evaluate_locally=True, - flag_keys_to_evaluate=flag_options["flag_keys_filter"], - ) - else: - # Fall back to remote evaluation - feature_variants = self.get_feature_variants( - distinct_id, - groups, - person_properties=flag_options["person_properties"], - group_properties=flag_options["group_properties"], - disable_geoip=disable_geoip, - flag_keys_to_evaluate=flag_options["flag_keys_filter"], - ) - except Exception as e: - self.log.exception( - f"[FEATURE FLAGS] Unable to get feature variants: {e}" - ) - - for feature, variant in (feature_variants or {}).items(): - extra_properties[f"$feature/{feature}"] = variant - - active_feature_flags = [ - key - for (key, value) in (feature_variants or {}).items() - if value is not False - ] - if active_feature_flags: - extra_properties["$active_feature_flags"] = active_feature_flags + extra_properties = self._capture_legacy_flag_properties( + distinct_id, groups, disable_geoip, send_feature_flags + ) if extra_properties: properties = {**extra_properties, **properties} @@ -2402,6 +2483,100 @@ def _capture( before_send_drops=before_send_drops, ) + def _capture_properties(self, properties): + properties = {**(properties or {}), **system_context()} + + if self.capture_trace_context: + properties = {**_get_current_otel_span_properties(), **properties} + + properties = add_context_tags(properties) + assert properties is not None # Type hint for mypy + return properties + + def _capture_legacy_flag_properties( + self, distinct_id, groups, disable_geoip, send_feature_flags + ): + extra_properties: dict[str, Any] = {} + feature_variants: Optional[dict[str, Union[bool, str]]] = {} + + # Parse and normalize send_feature_flags parameter + flag_options = self._parse_send_feature_flags(send_feature_flags) + + if flag_options["should_send"]: + warnings.warn( + "`send_feature_flags` is deprecated and will be removed in a future major " + "version. Pass a `flags` snapshot from `posthog.evaluate_flags(...)` instead " + "— it avoids a second `/flags` request per capture and guarantees the event " + "carries the exact flag values your code branched on.", + DeprecationWarning, + stacklevel=3, + ) + try: + feature_variants = self._evaluate_capture_flags( + distinct_id, groups, disable_geoip, flag_options + ) + except Exception as e: + self.log.exception( + f"[FEATURE FLAGS] Unable to get feature variants: {e}" + ) + + for feature, variant in (feature_variants or {}).items(): + extra_properties[f"$feature/{feature}"] = variant + + active_feature_flags = [ + key + for (key, value) in (feature_variants or {}).items() + if value is not False + ] + if active_feature_flags: + extra_properties["$active_feature_flags"] = active_feature_flags + + return extra_properties + + def _evaluate_capture_flags(self, distinct_id, groups, disable_geoip, flag_options): + if flag_options["only_evaluate_locally"] is True: + # Local evaluation explicitly requested + return self.get_all_flags( + distinct_id, + groups=(groups or {}), + person_properties=flag_options["person_properties"], + group_properties=flag_options["group_properties"], + disable_geoip=disable_geoip, + only_evaluate_locally=True, + flag_keys_to_evaluate=flag_options["flag_keys_filter"], + ) + elif flag_options["only_evaluate_locally"] is False: + # Remote evaluation explicitly requested + return self.get_feature_variants( + distinct_id, + groups, + person_properties=flag_options["person_properties"], + group_properties=flag_options["group_properties"], + disable_geoip=disable_geoip, + flag_keys_to_evaluate=flag_options["flag_keys_filter"], + ) + elif self.feature_flags: + # Local flags available, prefer local evaluation + return self.get_all_flags( + distinct_id, + groups=(groups or {}), + person_properties=flag_options["person_properties"], + group_properties=flag_options["group_properties"], + disable_geoip=disable_geoip, + only_evaluate_locally=True, + flag_keys_to_evaluate=flag_options["flag_keys_filter"], + ) + else: + # Fall back to remote evaluation + return self.get_feature_variants( + distinct_id, + groups, + person_properties=flag_options["person_properties"], + group_properties=flag_options["group_properties"], + disable_geoip=disable_geoip, + flag_keys_to_evaluate=flag_options["flag_keys_filter"], + ) + def _parse_send_feature_flags(self, send_feature_flags) -> SendFeatureFlagsOptions: """ Parse and normalize send_feature_flags parameter into a standard format. @@ -2727,134 +2902,17 @@ def capture_exception( try: properties = properties or {} - # Check if this exception has already been captured - if exception is not None and exception_is_already_captured(exception): - self.log.debug("Exception already captured, skipping") - return None - - if exception is not None: - exc_info = exc_info_from_error(exception) - else: - exc_info = sys.exc_info() - - if exc_info is None or exc_info == (None, None, None): - self.log.warning("No exception information available") + exc_info = self._exception_info(exception) + if exc_info is None: return None - # Format stack trace for cymbal - capture_metadata_input = dict(kwargs).get("_capture_metadata") - capture_metadata = ( - capture_metadata_input - if isinstance(capture_metadata_input, dict) - else {} - ) - mechanism = capture_metadata.get("mechanism") - all_exceptions_with_trace = exceptions_from_error_tuple( - exc_info, mechanism=mechanism if isinstance(mechanism, dict) else None - ) - - # Add in-app property to frames in the exceptions - event = handle_in_app( - { - "exception": { - "values": all_exceptions_with_trace, - }, - }, - in_app_include=self.in_app_modules, - project_root=self.project_root, - ) - all_exceptions_with_trace_and_in_app = event["exception"]["values"] - - reserved_properties = { - "$exception_list", - "$exception_level", - "$exception_source", - "$debug_images", - "$exception_handled", - "$exception_types", - "$exception_values", - "$exception_sources", - "$exception_functions", - "$exception_fingerprint_version", - "$exception_fingerprint_record", - "$exception_issue_id", - "$exception_release", - "$cymbal_errors", - } - reserved_property_overrides = reserved_properties.intersection(properties) - if reserved_property_overrides: - try: - warnings.warn( - "Reserved exception properties passed through " - "`capture_exception(properties=...)` currently override " - "SDK-owned metadata, but this behavior is deprecated and will " - "be removed in the next major version: " - + ", ".join(sorted(reserved_property_overrides)), - DeprecationWarning, - stacklevel=2, - ) - except DeprecationWarning: - # capture_exception must not drop an event when applications - # promote deprecation warnings to errors. - pass - - caller_properties = properties - properties = { - **_get_current_otel_span_properties(), - "$exception_list": all_exceptions_with_trace_and_in_app, - "$exception_level": _normalize_exception_level( - capture_metadata.get("level") - ) - or "error", - } - source = capture_metadata.get("source") - if isinstance(source, str) and source: - properties["$exception_source"] = source - properties.update(caller_properties) - - context_enabled = get_capture_exception_code_variables_context() - context_mask = get_code_variables_mask_patterns_context() - context_ignore = get_code_variables_ignore_patterns_context() - context_mask_url_credentials = ( - get_code_variables_mask_url_credentials_context() + properties, all_exceptions_with_trace_and_in_app = ( + self._exception_properties(exc_info, properties, kwargs) ) - context_detect_secrets = get_code_variables_detect_secrets_context() - enabled = ( - context_enabled - if context_enabled is not None - else self.capture_exception_code_variables - ) - mask_patterns = ( - context_mask - if context_mask is not None - else self.code_variables_mask_patterns - ) - ignore_patterns = ( - context_ignore - if context_ignore is not None - else self.code_variables_ignore_patterns - ) - mask_url_credentials = ( - context_mask_url_credentials - if context_mask_url_credentials is not None - else self.code_variables_mask_url_credentials + self._attach_exception_code_variables( + all_exceptions_with_trace_and_in_app, exc_info ) - detect_secrets = ( - context_detect_secrets - if context_detect_secrets is not None - else self.code_variables_detect_secrets - ) - - if enabled: - try_attach_code_variables_to_frames( - all_exceptions_with_trace_and_in_app, - exc_info, - mask_patterns=mask_patterns, - ignore_patterns=ignore_patterns, - mask_url_credentials=mask_url_credentials, - detect_secrets=detect_secrets, - ) if self.log_captured_exceptions: self.log.exception(exception, extra=kwargs) @@ -2883,6 +2941,140 @@ def capture_exception( self.log.exception(f"Failed to capture exception: {e}") return None + def _exception_info(self, exception): + # Check if this exception has already been captured + if exception is not None and exception_is_already_captured(exception): + self.log.debug("Exception already captured, skipping") + return None + + if exception is not None: + exc_info = exc_info_from_error(exception) + else: + exc_info = sys.exc_info() + + if exc_info is None or exc_info == (None, None, None): + self.log.warning("No exception information available") + return None + + return exc_info + + def _exception_properties(self, exc_info, properties, kwargs): + # Format stack trace for cymbal + capture_metadata_input = dict(kwargs).get("_capture_metadata") + capture_metadata = ( + capture_metadata_input if isinstance(capture_metadata_input, dict) else {} + ) + mechanism = capture_metadata.get("mechanism") + all_exceptions_with_trace = exceptions_from_error_tuple( + exc_info, mechanism=mechanism if isinstance(mechanism, dict) else None + ) + + # Add in-app property to frames in the exceptions + event = handle_in_app( + { + "exception": { + "values": all_exceptions_with_trace, + }, + }, + in_app_include=self.in_app_modules, + project_root=self.project_root, + ) + all_exceptions_with_trace_and_in_app = event["exception"]["values"] + + reserved_properties = { + "$exception_list", + "$exception_level", + "$exception_source", + "$debug_images", + "$exception_handled", + "$exception_types", + "$exception_values", + "$exception_sources", + "$exception_functions", + "$exception_fingerprint_version", + "$exception_fingerprint_record", + "$exception_issue_id", + "$exception_release", + "$cymbal_errors", + } + reserved_property_overrides = reserved_properties.intersection(properties) + if reserved_property_overrides: + try: + warnings.warn( + "Reserved exception properties passed through " + "`capture_exception(properties=...)` currently override " + "SDK-owned metadata, but this behavior is deprecated and will " + "be removed in the next major version: " + + ", ".join(sorted(reserved_property_overrides)), + DeprecationWarning, + stacklevel=3, + ) + except DeprecationWarning: + # capture_exception must not drop an event when applications + # promote deprecation warnings to errors. + pass + + caller_properties = properties + properties = { + **_get_current_otel_span_properties(), + "$exception_list": all_exceptions_with_trace_and_in_app, + "$exception_level": _normalize_exception_level( + capture_metadata.get("level") + ) + or "error", + } + source = capture_metadata.get("source") + if isinstance(source, str) and source: + properties["$exception_source"] = source + properties.update(caller_properties) + + return properties, all_exceptions_with_trace_and_in_app + + def _attach_exception_code_variables( + self, all_exceptions_with_trace_and_in_app, exc_info + ): + context_enabled = get_capture_exception_code_variables_context() + context_mask = get_code_variables_mask_patterns_context() + context_ignore = get_code_variables_ignore_patterns_context() + context_mask_url_credentials = get_code_variables_mask_url_credentials_context() + context_detect_secrets = get_code_variables_detect_secrets_context() + + enabled = ( + context_enabled + if context_enabled is not None + else self.capture_exception_code_variables + ) + mask_patterns = ( + context_mask + if context_mask is not None + else self.code_variables_mask_patterns + ) + ignore_patterns = ( + context_ignore + if context_ignore is not None + else self.code_variables_ignore_patterns + ) + mask_url_credentials = ( + context_mask_url_credentials + if context_mask_url_credentials is not None + else self.code_variables_mask_url_credentials + ) + detect_secrets = ( + context_detect_secrets + if context_detect_secrets is not None + else self.code_variables_detect_secrets + ) + + if enabled: + try_attach_code_variables_to_frames( + all_exceptions_with_trace_and_in_app, + exc_info, + mask_patterns=mask_patterns, + ignore_patterns=ignore_patterns, + mask_url_credentials=mask_url_credentials, + detect_secrets=detect_secrets, + ) + @classmethod def _reinit_client_registry_after_fork(cls): """Replace the inherited registry lock once in each forked child.""" @@ -2982,6 +3174,9 @@ def _reinit_after_fork(self): reset_sessions() # Start child threads only after replacing every lock they can touch. + self._restart_flag_poller_after_fork(terminal_requested) + + def _restart_flag_poller_after_fork(self, terminal_requested): if terminal_requested: self.poller = None elif self.enable_local_evaluation: @@ -3026,6 +3221,30 @@ def _enqueue( if self.disabled: return None + self._normalize_event_timestamp(msg) + + self._normalize_event_uuid(msg) + + self._enrich_event_properties( + msg, disable_geoip, property_allowlist, pinned_properties + ) + + msg = clean(msg) + + msg = self._run_before_send(msg, before_send_drops) + if msg is None: + return None + + # Re-normalized after before_send, which may have replaced or removed + # msg["uuid"], so the returned uuid always matches the wire event. + self._normalize_event_uuid(msg) + sent_uuid = msg["uuid"] + + self.log.debug("queueing: %s", msg) + + return self._submit_event(msg, lane, sent_uuid) + + def _normalize_event_timestamp(self, msg): timestamp = msg["timestamp"] if timestamp is None: timestamp = datetime.now(tz=timezone.utc) @@ -3039,8 +3258,9 @@ def _enqueue( ) msg["timestamp"] = datetime.now(tz=timezone.utc).isoformat() - self._normalize_event_uuid(msg) - + def _enrich_event_properties( + self, msg, disable_geoip, property_allowlist, pinned_properties + ): if not msg.get("properties"): msg["properties"] = {} msg["properties"]["$lib"] = self._library_id @@ -3065,6 +3285,11 @@ def _enqueue( if self.is_server: msg["properties"]["$is_server"] = True + self._filter_event_properties(msg, property_allowlist, pinned_properties) + + msg["distinct_id"] = stringify_id(msg.get("distinct_id", None)) + + def _filter_event_properties(self, msg, property_allowlist, pinned_properties): # Applied after every enrichment step (system context, context tags, super # properties, $lib/$lib_version) so the final event shape is exactly the # allowlist regardless of where a property came from. @@ -3078,10 +3303,7 @@ def _enqueue( k: v for k, v in msg["properties"].items() if k in property_allowlist } - msg["distinct_id"] = stringify_id(msg.get("distinct_id", None)) - - msg = clean(msg) - + def _run_before_send(self, msg, before_send_drops): if self.before_send: try: modified_msg = self.before_send(msg) @@ -3097,13 +3319,9 @@ def _enqueue( self.log.exception(f"Error in before_send callback: {e}") return None - # Re-normalized after before_send, which may have replaced or removed - # msg["uuid"], so the returned uuid always matches the wire event. - self._normalize_event_uuid(msg) - sent_uuid = msg["uuid"] - - self.log.debug("queueing: %s", msg) + return msg + def _submit_event(self, msg, lane, sent_uuid): # if send is False, return msg as if it was successfully queued, unless # shutdown has already closed this lane's admission. if not self.send: @@ -3119,35 +3337,7 @@ def _enqueue( if self.sync_mode: self.log.debug("enqueued with blocking %s.", msg["event"]) - def send_sync() -> None: - # Sync mode bypasses the lane's queue but keeps its wire config: - # the AI lane is pinned to v0, so its events post to the AI - # endpoint regardless of `capture_mode`. - if lane.capture_mode == CaptureMode.V1: - _send_v1_batch( - self.api_key, - self.host, - [msg], - compression=self.capture_compression, - timeout=self.timeout, - max_retries=self.max_retries, - historical_migration=self.historical_migration, - sdk_info=self._sdk_info, - ) - return - - batch_post( - self.api_key, - self.host, - gzip=self.gzip, - timeout=self.timeout, - batch=[msg], - historical_migration=self.historical_migration, - path=lane.endpoint, - **self._request_identity_kwargs(), - ) - - if lane.run_sync_if_open(send_sync): + if lane.run_sync_if_open(lambda: self._send_sync(msg, lane)): return sent_uuid self.log.warning( "%s lane received event %s after shutdown, dropping it", @@ -3182,6 +3372,34 @@ def send_sync() -> None: ) return None + def _send_sync(self, msg, lane) -> None: + # Sync mode bypasses the lane's queue but keeps its wire config: + # the AI lane is pinned to v0, so its events post to the AI + # endpoint regardless of `capture_mode`. + if lane.capture_mode == CaptureMode.V1: + _send_v1_batch( + self.api_key, + self.host, + [msg], + compression=self.capture_compression, + timeout=self.timeout, + max_retries=self.max_retries, + historical_migration=self.historical_migration, + sdk_info=self._sdk_info, + ) + return + + batch_post( + self.api_key, + self.host, + gzip=self.gzip, + timeout=self.timeout, + batch=[msg], + historical_migration=self.historical_migration, + path=lane.endpoint, + **self._request_identity_kwargs(), + ) + @property def metrics(self) -> PostHogMetrics: """ @@ -3230,30 +3448,33 @@ def _traces_pipeline(self) -> Optional[PostHogTraces]: # Re-checked under the lock, which shutdown takes before it # reads the pipeline, so neither can miss the other. if self._traces is None and not self._shutdown_requested: - try: - config = resolve_traces_config( - self._traces_config, host_resource_attributes() - ) - drops = DropLog(config.flush_interval) - self._traces = PostHogTraces( - self, - config, - self._tracing_context, - self._active_span_var, - SpanExporter(self, config, drops), - drops, - ) - # Sync mode has no exit hook for events; spans still - # queue for the timer, so they need their own. - if self.sync_mode and self.send: - atexit.register(self._atexit_spans) - except Exception: - # Off rather than defaults: defaults would drop a - # before_span_send hook and export unscrubbed spans. - self.log.exception("Error initializing traces; tracing is off") - self._traces_config = False + self._initialize_traces_pipeline() return self._traces + def _initialize_traces_pipeline(self) -> None: + try: + config = resolve_traces_config( + self._traces_config, host_resource_attributes() + ) + drops = DropLog(config.flush_interval) + self._traces = PostHogTraces( + self, + config, + self._tracing_context, + self._active_span_var, + SpanExporter(self, config, drops), + drops, + ) + # Sync mode has no exit hook for events; spans still + # queue for the timer, so they need their own. + if self.sync_mode and self.send: + atexit.register(self._atexit_spans) + except Exception: + # Off rather than defaults: defaults would drop a + # before_span_send hook and export unscrubbed spans. + self.log.exception("Error initializing traces; tracing is off") + self._traces_config = False + def _tracing_context(self) -> Dict[str, Optional[str]]: # The request context's identity, which the Django middleware fills # from the X-POSTHOG-* headers: the span's person/session join keys. @@ -3393,14 +3614,7 @@ def flush(self, timeout_seconds: Optional[float] = 10) -> None: if include_metrics_autocapture else None ) - deadline: Optional[float] = None - if timeout_seconds is None: - for lane in self._lanes: - lane.flush(None) - else: - deadline = time.monotonic() + timeout_seconds - for lane in self._lanes: - lane.flush(max(0.0, deadline - time.monotonic())) + deadline = self._flush_lanes(timeout_seconds) if metrics_flush is not None: metrics_flush( None if deadline is None else max(0.0, deadline - time.monotonic()) @@ -3413,6 +3627,17 @@ def flush(self, timeout_seconds: Optional[float] = 10) -> None: self.log.exception("error flushing queue: %s", e) return + def _flush_lanes(self, timeout_seconds): + deadline: Optional[float] = None + if timeout_seconds is None: + for lane in self._lanes: + lane.flush(None) + else: + deadline = time.monotonic() + timeout_seconds + for lane in self._lanes: + lane.flush(max(0.0, deadline - time.monotonic())) + return deadline + def _start_metrics_autocapture_flush( self, ) -> Optional[Callable[[Optional[float]], None]]: @@ -3607,6 +3832,9 @@ def _join_once( # means every worker cleanup step was attempted once. self._workers_joined = True + self._close_lifecycle_resources(errors) + + def _close_lifecycle_resources(self, errors: list[Exception]) -> None: if not self._join_cleanup_complete: if self.poller: self._run_lifecycle_cleanup( @@ -3705,15 +3933,7 @@ def _shutdown_once(self, errors: list[Exception]) -> None: def _run_lifecycle(self, require_shutdown: bool = False) -> None: while True: with self._lifecycle_condition: - if require_shutdown and self._shutdown_complete: - if self.debug and self._lifecycle_cleanup_failed: - raise RuntimeError("client lifecycle cleanup failed") - return - if not require_shutdown and ( - self._join_cleanup_complete or self._shutdown_complete - ): - if self.debug and self._lifecycle_cleanup_failed: - raise RuntimeError("client lifecycle cleanup failed") + if self._lifecycle_has_completed(require_shutdown): return if self._lifecycle_owner is not None: if self._is_lifecycle_callback_thread() or ( @@ -3725,47 +3945,66 @@ def _run_lifecycle(self, require_shutdown: bool = False) -> None: self._lifecycle_owner = threading.current_thread() try: - errors: list[Exception] = [] - while True: - with self._lifecycle_lock: - run_shutdown = self._shutdown_requested - - if run_shutdown: - self._shutdown_once(errors) - else: - self._join_once(errors) - - with self._lifecycle_condition: - if ( - self._shutdown_requested - and not self._shutdown_complete - and not run_shutdown - ): - continue - if errors: - self._lifecycle_cleanup_failed = True - raise errors[0] - self._lifecycle_owner = None - self._lifecycle_condition.notify_all() - return + self._finish_lifecycle() + return except BaseException: with self._lifecycle_condition: self._lifecycle_owner = None self._lifecycle_condition.notify_all() raise - @no_throw() - def _atexit(self) -> None: - """Make a bounded delivery attempt, then stop daemon workers.""" - with self._lifecycle_condition: - # A daemon lifecycle worker already owns cleanup. Do not wait for it - # at interpreter exit; the process must remain free to terminate. - if self._lifecycle_owner is not None: - return - self._lifecycle_owner = threading.current_thread() + def _lifecycle_has_completed(self, require_shutdown: bool) -> bool: + if require_shutdown and self._shutdown_complete: + self._raise_lifecycle_failure() + return True + if not require_shutdown and ( + self._join_cleanup_complete or self._shutdown_complete + ): + self._raise_lifecycle_failure() + return True + return False - try: - try: + def _raise_lifecycle_failure(self) -> None: + if self.debug and self._lifecycle_cleanup_failed: + raise RuntimeError("client lifecycle cleanup failed") + + def _finish_lifecycle(self) -> None: + errors: list[Exception] = [] + while True: + with self._lifecycle_lock: + run_shutdown = self._shutdown_requested + + if run_shutdown: + self._shutdown_once(errors) + else: + self._join_once(errors) + + with self._lifecycle_condition: + if ( + self._shutdown_requested + and not self._shutdown_complete + and not run_shutdown + ): + continue + if errors: + self._lifecycle_cleanup_failed = True + raise errors[0] + self._lifecycle_owner = None + self._lifecycle_condition.notify_all() + return + + @no_throw() + def _atexit(self) -> None: + """Make a bounded delivery attempt, then stop daemon workers.""" + with self._lifecycle_condition: + # A daemon lifecycle worker already owns cleanup. Do not wait for it + # at interpreter exit; the process must remain free to terminate. + if self._lifecycle_owner is not None: + return + self._lifecycle_owner = threading.current_thread() + + try: + try: for lane in self._lanes: lane.close() @@ -4065,18 +4304,7 @@ def _local_evaluation_snapshot(self) -> _LocalEvaluationSnapshot: } def _load_feature_flags(self): - should_fetch = True - if self._flag_definition_cache_provider: - try: - should_fetch = self._resolve_flag_definition_cache_provider_result( - self._flag_definition_cache_provider.should_fetch_flag_definitions() - ) - except Exception as e: - self.log.error( - f"[FEATURE FLAGS] Cache provider should_fetch error: {e}" - ) - # Fail-safe: fetch from API if cache provider errors - should_fetch = True + should_fetch = self._should_fetch_flag_definitions() # If not fetching, try to get from cache if not should_fetch and self._flag_definition_cache_provider: @@ -4110,6 +4338,22 @@ def _load_feature_flags(self): if should_fetch: self._fetch_feature_flags_from_api() + def _should_fetch_flag_definitions(self): + should_fetch = True + if self._flag_definition_cache_provider: + try: + should_fetch = self._resolve_flag_definition_cache_provider_result( + self._flag_definition_cache_provider.should_fetch_flag_definitions() + ) + except Exception as e: + self.log.error( + f"[FEATURE FLAGS] Cache provider should_fetch error: {e}" + ) + # Fail-safe: fetch from API if cache provider errors + should_fetch = True + + return should_fetch + def _fetch_feature_flags_from_api(self): """Fetch feature flags from the PostHog API.""" personal_api_key = self.personal_api_key @@ -4127,171 +4371,194 @@ def _fetch_feature_flags_from_api(self): cache_data_to_store: Optional[FlagDefinitionCacheData] = None old_fingerprint: Optional[str] = None try: - request_get = _get_with_identity if self._request_identity_kwargs() else get - response = request_get( - personal_api_key, - f"/flags/definitions?token={self.api_key}&send_cohorts", - self.host, - timeout=10, - etag=request_etag, - **self._request_identity_kwargs(), + response, fingerprint = self._request_flag_definitions( + personal_api_key, request_etag ) - - # Canonical serialization can be expensive; do it before publication. - fingerprint = ( - self._hash_flag_definitions(response.data) - if response.data is not None and not response.not_modified - else None + published, old_fingerprint, cache_data_to_store = ( + self._publish_flag_definitions_response( + response, fingerprint, fetch_generation, request_etag + ) + ) + if not published: + return + self._warn_unresolvable_flags() + self._store_flag_definitions_if_current( + cache_data_to_store, fetch_generation ) + except APIError as e: with self._flag_definition_publication_lock: - if fetch_generation <= self._flag_definition_published_generation: - self.log.debug( - "[FEATURE FLAGS] Ignoring stale flag definition response" - ) - self._last_feature_flag_poll = datetime.now(tz=timezone.utc) - return + if ( + fetch_generation > self._flag_definition_published_generation + and e.status in (401, 402) + ): + old_fingerprint = self._flag_definition_fingerprint + debug_error = self._handle_flag_definition_api_error( + e, fetch_generation + ) + if debug_error is not None: + raise debug_error + except Exception as e: + self.log.warning( + "[FEATURE FLAGS] Fetching feature flags failed with following error. We will retry in %s seconds." + % self.poll_interval + ) + self.log.warning(e) + finally: + # Legacy readers ignore snapshot metadata. Cleanup is best effort and + # must not hold the publication lock, including when debug raises. + if isinstance(self.flag_cache, RedisFlagCache): + self.flag_cache._invalidate_snapshot(old_fingerprint) - # A 304 is valid only for the ETag used by this request. Another - # overlapping response may already have installed newer definitions. - if response.not_modified: - if self._flags_etag != request_etag: - self.log.debug( - "[FEATURE FLAGS] Ignoring stale 304 flag definition response" - ) - self._last_feature_flag_poll = datetime.now(tz=timezone.utc) - return + self._last_feature_flag_poll = datetime.now(tz=timezone.utc) - self._flags_etag = response.etag - self._flag_definition_published_generation = fetch_generation - self._flag_definition_cache_generation = fetch_generation - self.log.debug( - "[FEATURE FLAGS] Flags not modified (304), using cached data" - ) - self._last_feature_flag_poll = datetime.now(tz=timezone.utc) - return + def _request_flag_definitions(self, personal_api_key, request_etag): + request_get = _get_with_identity if self._request_identity_kwargs() else get + response = request_get( + personal_api_key, + f"/flags/definitions?token={self.api_key}&send_cohorts", + self.host, + timeout=10, + etag=request_etag, + **self._request_identity_kwargs(), + ) - if response.data is None: - self.log.error( - "[FEATURE FLAGS] Unexpected empty response data in non-304 response" - ) - return + # Canonical serialization can be expensive; do it before publication. + fingerprint = ( + self._hash_flag_definitions(response.data) + if response.data is not None and not response.not_modified + else None + ) + + return response, fingerprint - old_fingerprint = self._update_flag_state( - response.data, _fingerprint=fingerprint + def _publish_flag_definitions_response( + self, response, fingerprint, fetch_generation, request_etag + ): + cache_data_to_store = None + with self._flag_definition_publication_lock: + if fetch_generation <= self._flag_definition_published_generation: + self.log.debug( + "[FEATURE FLAGS] Ignoring stale flag definition response" ) + self._last_feature_flag_poll = datetime.now(tz=timezone.utc) + return False, None, None - if self._flag_definition_cache_provider: - cache_data_to_store = { - "flags": self.feature_flags or [], - "group_type_mapping": self.group_type_mapping or {}, - "cohorts": self.cohorts or {}, - "minimal_flag_called_events": self._minimal_flag_called_events, - "property_matching_version": self._property_matching_version, - } + # A 304 is valid only for the ETag used by this request. Another + # overlapping response may already have installed newer definitions. + if response.not_modified: + if self._flags_etag != request_etag: + self.log.debug( + "[FEATURE FLAGS] Ignoring stale 304 flag definition response" + ) + self._last_feature_flag_poll = datetime.now(tz=timezone.utc) + return False, None, None - # Publish the ETag only after its matching flag state is installed. self._flags_etag = response.etag self._flag_definition_published_generation = fetch_generation self._flag_definition_cache_generation = fetch_generation + self.log.debug( + "[FEATURE FLAGS] Flags not modified (304), using cached data" + ) + self._last_feature_flag_poll = datetime.now(tz=timezone.utc) + return False, None, None - self._warn_unresolvable_flags() + if response.data is None: + self.log.error( + "[FEATURE FLAGS] Unexpected empty response data in non-304 response" + ) + return False, None, None - if cache_data_to_store and self._flag_definition_cache_provider: - # Keep provider I/O out of the publication lock. The separate lock - # preserves cache write order without delaying newer API fetches or - # in-memory publication. - with self._flag_definition_cache_write_lock: - with self._flag_definition_publication_lock: - should_store = ( - fetch_generation == self._flag_definition_cache_generation - ) - if should_store: - try: - self._resolve_flag_definition_cache_provider_result( - self._flag_definition_cache_provider.on_flag_definitions_received( - cache_data_to_store - ) - ) - except Exception as e: - self.log.error( - f"[FEATURE FLAGS] Cache provider store error: {e}" - ) - # Flags are already in memory, so continue normally + old_fingerprint = self._update_flag_state( + response.data, _fingerprint=fingerprint + ) - except APIError as e: - with self._flag_definition_publication_lock: - if fetch_generation <= self._flag_definition_published_generation: - self.log.debug("[FEATURE FLAGS] Ignoring stale API error response") - elif e.status == 401: - detail = ( - f"Error loading feature flags: {e.message}. " - "Please verify both your project_api_key and secret_key. " - "More information: https://posthog.com/docs/api/overview" - ) - self.log.error("[FEATURE FLAGS] %s", detail) - self.feature_flags = [] - self.group_type_mapping = {} - self.cohorts = {} - self._property_matching_version = 1 - old_fingerprint = self._flag_definition_fingerprint - self._flag_definition_fingerprint = "" - self._flags_etag = None - self._flag_definition_published_generation = fetch_generation - self._flag_definition_cache_generation = fetch_generation - - if self.flag_cache: - self.flag_definition_version += 1 - self.flag_cache._advance_generation( - self.flag_definition_version, - self._flag_definition_fingerprint, - ) + if self._flag_definition_cache_provider: + cache_data_to_store = { + "flags": self.feature_flags or [], + "group_type_mapping": self.group_type_mapping or {}, + "cohorts": self.cohorts or {}, + "minimal_flag_called_events": self._minimal_flag_called_events, + "property_matching_version": self._property_matching_version, + } - if self.debug: - raise APIError(status=401, message=detail) - elif e.status == 402: - self.log.warning( - "[FEATURE FLAGS] PostHog feature flags quota limited, resetting feature flag data. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts" + # Publish the ETag only after its matching flag state is installed. + self._flags_etag = response.etag + self._flag_definition_published_generation = fetch_generation + self._flag_definition_cache_generation = fetch_generation + + return True, old_fingerprint, cache_data_to_store + + def _store_flag_definitions_if_current(self, cache_data_to_store, fetch_generation): + if cache_data_to_store and self._flag_definition_cache_provider: + # Keep provider I/O out of the publication lock. The separate lock + # preserves cache write order without delaying newer API fetches or + # in-memory publication. + with self._flag_definition_cache_write_lock: + with self._flag_definition_publication_lock: + should_store = ( + fetch_generation == self._flag_definition_cache_generation ) - # Reset all feature flag data when quota limited - self.feature_flags = [] - self.group_type_mapping = {} - self.cohorts = {} - self._property_matching_version = 1 - old_fingerprint = self._flag_definition_fingerprint - self._flag_definition_fingerprint = "" - self._flags_etag = None - self._flag_definition_published_generation = fetch_generation - self._flag_definition_cache_generation = fetch_generation - - # Invalidate results without waiting for external cache I/O. - if self.flag_cache: - self.flag_definition_version += 1 - self.flag_cache._advance_generation( - self.flag_definition_version, - self._flag_definition_fingerprint, + if should_store: + try: + self._resolve_flag_definition_cache_provider_result( + self._flag_definition_cache_provider.on_flag_definitions_received( + cache_data_to_store + ) ) - - if self.debug: - raise APIError( - status=402, - message="PostHog feature flags quota limited", + except Exception as e: + self.log.error( + f"[FEATURE FLAGS] Cache provider store error: {e}" ) - else: - self.log.error(f"[FEATURE FLAGS] Error loading feature flags: {e}") - except Exception as e: + # Flags are already in memory, so continue normally + + def _handle_flag_definition_api_error(self, e, fetch_generation): + debug_error = None + if fetch_generation <= self._flag_definition_published_generation: + self.log.debug("[FEATURE FLAGS] Ignoring stale API error response") + elif e.status == 401: + detail = ( + f"Error loading feature flags: {e.message}. " + "Please verify both your project_api_key and secret_key. " + "More information: https://posthog.com/docs/api/overview" + ) + self.log.error("[FEATURE FLAGS] %s", detail) + self._clear_flag_definitions_after_api_error(fetch_generation) + + if self.debug: + debug_error = APIError(status=401, message=detail) + elif e.status == 402: self.log.warning( - "[FEATURE FLAGS] Fetching feature flags failed with following error. We will retry in %s seconds." - % self.poll_interval + "[FEATURE FLAGS] PostHog feature flags quota limited, resetting feature flag data. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts" ) - self.log.warning(e) - finally: - # Legacy readers ignore snapshot metadata. Cleanup is best effort and - # must not hold the publication lock, including when debug raises. - if isinstance(self.flag_cache, RedisFlagCache): - self.flag_cache._invalidate_snapshot(old_fingerprint) + # Reset all feature flag data when quota limited + self._clear_flag_definitions_after_api_error(fetch_generation) - self._last_feature_flag_poll = datetime.now(tz=timezone.utc) + if self.debug: + debug_error = APIError( + status=402, + message="PostHog feature flags quota limited", + ) + else: + self.log.error(f"[FEATURE FLAGS] Error loading feature flags: {e}") + return debug_error + + def _clear_flag_definitions_after_api_error(self, fetch_generation): + self.feature_flags = [] + self.group_type_mapping = {} + self.cohorts = {} + self._property_matching_version = 1 + self._flag_definition_fingerprint = "" + self._flags_etag = None + self._flag_definition_published_generation = fetch_generation + self._flag_definition_cache_generation = fetch_generation + + if self.flag_cache: + self.flag_definition_version += 1 + self.flag_cache._advance_generation( + self.flag_definition_version, + self._flag_definition_fingerprint, + ) def load_feature_flags(self): """ @@ -4349,8 +4616,6 @@ def _compute_flag_locally( if _definition_snapshot is not None else self._local_evaluation_snapshot() ) - flags_by_key = snapshot["flags_by_key"] - property_matching_version = snapshot.get("property_matching_version", 1) groups = groups or {} person_properties = person_properties or {} group_properties = group_properties or {} @@ -4369,87 +4634,136 @@ def _compute_flag_locally( flag_filters = feature_flag.get("filters") or {} aggregation_group_type_index = flag_filters.get("aggregation_group_type_index") - group_type_mapping = snapshot["group_type_mapping"] if aggregation_group_type_index is not None: - group_name = group_type_mapping.get(str(aggregation_group_type_index)) + return self._compute_group_flag_locally( + feature_flag, + groups, + group_properties, + warn_on_unknown_groups, + device_id, + snapshot, + evaluation_cache, + aggregation_group_type_index, + ) + else: + return self._compute_person_flag_locally( + feature_flag, + distinct_id, + person_properties, + device_id, + snapshot, + evaluation_cache, + groups, + group_properties, + ) + + def _compute_group_flag_locally( + self, + feature_flag, + groups, + group_properties, + warn_on_unknown_groups, + device_id, + snapshot, + evaluation_cache, + aggregation_group_type_index, + ) -> FlagValue: + group_type_mapping = snapshot["group_type_mapping"] + flags_by_key = snapshot["flags_by_key"] + property_matching_version = snapshot.get("property_matching_version", 1) + group_name = group_type_mapping.get(str(aggregation_group_type_index)) - if not group_name: + if not group_name: + self.log.warning( + f"[FEATURE FLAGS] Unknown group type index {aggregation_group_type_index} for feature flag {feature_flag['key']}" + ) + # failover to `/flags` + raise InconclusiveMatchError( + "Flag has unknown group type index", + reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, + ) + + if group_name not in groups: + # Group flags are never enabled in `groups` aren't passed in + # don't failover to `/flags`, since response will be the same + if warn_on_unknown_groups: self.log.warning( - f"[FEATURE FLAGS] Unknown group type index {aggregation_group_type_index} for feature flag {feature_flag['key']}" + f"[FEATURE FLAGS] Can't compute group feature flag: {feature_flag['key']} without group names passed in" ) - # failover to `/flags` - raise InconclusiveMatchError( - "Flag has unknown group type index", - reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, + else: + self.log.debug( + f"[FEATURE FLAGS] Can't compute group feature flag: {feature_flag['key']} without group names passed in" ) + return False - if group_name not in groups: - # Group flags are never enabled in `groups` aren't passed in - # don't failover to `/flags`, since response will be the same - if warn_on_unknown_groups: - self.log.warning( - f"[FEATURE FLAGS] Can't compute group feature flag: {feature_flag['key']} without group names passed in" - ) - else: - self.log.debug( - f"[FEATURE FLAGS] Can't compute group feature flag: {feature_flag['key']} without group names passed in" - ) - return False + if group_name not in group_properties: + raise InconclusiveMatchError( + f"Flag has no group properties for group '{group_name}'", + reason=UnresolvedFlagReason.MISSING_CONTEXT, + ) + focused_group_properties = group_properties[group_name] + group_key = groups[group_name] + return match_feature_flag_properties( + feature_flag, + group_key, + focused_group_properties, + cohort_properties=snapshot["cohorts"], + flags_by_key=flags_by_key, + property_matching_version=property_matching_version, + evaluation_cache=evaluation_cache, + device_id=device_id, + bucketing_value=group_key, + group_type_mapping=group_type_mapping, + groups=groups, + group_properties=group_properties, + ) - if group_name not in group_properties: - raise InconclusiveMatchError( - f"Flag has no group properties for group '{group_name}'", - reason=UnresolvedFlagReason.MISSING_CONTEXT, - ) - focused_group_properties = group_properties[group_name] - group_key = groups[group_name] - return match_feature_flag_properties( - feature_flag, - group_key, - focused_group_properties, - cohort_properties=snapshot["cohorts"], - flags_by_key=flags_by_key, - property_matching_version=property_matching_version, - evaluation_cache=evaluation_cache, - device_id=device_id, - bucketing_value=group_key, - group_type_mapping=group_type_mapping, - groups=groups, - group_properties=group_properties, + def _compute_person_flag_locally( + self, + feature_flag, + distinct_id, + person_properties, + device_id, + snapshot, + evaluation_cache, + groups, + group_properties, + ) -> FlagValue: + group_type_mapping = snapshot["group_type_mapping"] + flags_by_key = snapshot["flags_by_key"] + property_matching_version = snapshot.get("property_matching_version", 1) + try: + bucketing_value = resolve_bucketing_value( + feature_flag, distinct_id, device_id ) - else: - try: - bucketing_value = resolve_bucketing_value( - feature_flag, distinct_id, device_id - ) - except InconclusiveMatchError as e: - # No condition is checked without a bucketing value, so a cause in - # the definition also applies and outranks missing_context. - e.reason = ( - _get_definition_unresolved_reason( - feature_flag, - flags_by_key, - snapshot["cohorts"], - group_type_mapping, - ) - or e.reason + except InconclusiveMatchError as e: + # No condition is checked without a bucketing value, so a cause in + # the definition also applies and outranks missing_context. + e.reason = ( + _get_definition_unresolved_reason( + feature_flag, + flags_by_key, + snapshot["cohorts"], + group_type_mapping, ) - raise - return match_feature_flag_properties( - feature_flag, - distinct_id, - person_properties, - cohort_properties=snapshot["cohorts"], - flags_by_key=flags_by_key, - property_matching_version=property_matching_version, - evaluation_cache=evaluation_cache, - device_id=device_id, - bucketing_value=bucketing_value, - group_type_mapping=group_type_mapping, - groups=groups, - group_properties=group_properties, + or e.reason ) + raise + return match_feature_flag_properties( + feature_flag, + distinct_id, + person_properties, + cohort_properties=snapshot["cohorts"], + flags_by_key=flags_by_key, + property_matching_version=property_matching_version, + evaluation_cache=evaluation_cache, + device_id=device_id, + bucketing_value=bucketing_value, + group_type_mapping=group_type_mapping, + groups=groups, + group_properties=group_properties, + ) def feature_enabled( self, @@ -4555,20 +4869,33 @@ def _get_feature_flag_result( ) ) # Ensure non-None values for type checking - groups = groups or {} - person_properties = person_properties or {} - group_properties = group_properties or {} - - flag_result = None - flag_details = None - # Whether flag_details supplied the value this read reports. Only then may the - # read report config version 2 attribution or send $experiment_exposure. - value_from_details = False - request_id = None - evaluated_at = None - feature_flag_error: Optional[str] = None - remote_minimal_flag_called_events = False + return self._get_feature_flag_result_with_context( + key, + distinct_id, + override_match_value, + groups or {}, + person_properties or {}, + group_properties or {}, + only_evaluate_locally, + send_feature_flag_events, + disable_geoip, + device_id, + ) + def _get_feature_flag_result_with_context( + self, + key, + distinct_id, + override_match_value, + groups, + person_properties, + group_properties, + only_evaluate_locally, + send_feature_flag_events, + disable_geoip, + device_id, + ): + read = _FlagReadResult() # Resolve device_id from context if not provided if device_id is None: device_id = get_context_device_id() @@ -4584,40 +4911,16 @@ def _get_feature_flag_result( group_properties, device_id, ) - local_definition_version = snapshot["flag_definition_version"] flag_was_locally_evaluated = flag_value is not None if flag_value is not None: - lookup_match_value = ( - override_match_value if override_match_value is not None else flag_value - ) - payload = ( - self._compute_payload_locally( - key, lookup_match_value, _definition_snapshot=snapshot - ) - if lookup_match_value is not None - else None - ) - flag_result = FeatureFlagResult.from_value_and_payload( - key, lookup_match_value, payload + read.result = self._resolve_local_flag_result( + key, + distinct_id, + flag_value, + override_match_value, + snapshot, ) - - # Cache the local evaluation, not a payload lookup override. - cached_flag_result = flag_result - if override_match_value is not None: - cached_flag_result = FeatureFlagResult.from_value_and_payload( - key, - flag_value, - self._compute_payload_locally( - key, flag_value, _definition_snapshot=snapshot - ), - ) - if self.flag_cache and cached_flag_result: - # The cache rejects invalidated generations, including writes - # already in flight when new definitions are published. - self.flag_cache.set_cached_flag( - distinct_id, key, cached_flag_result, local_definition_version - ) elif only_evaluate_locally: if self.feature_flags is None: self.log.warning( @@ -4625,128 +4928,225 @@ def _get_feature_flag_result( "Returning None. You can call load_feature_flags() to load flags explicitly." ) else: - try: - ( - flag_details, - request_id, - evaluated_at, - errors_while_computing, - remote_minimal_flag_called_events, - ) = self._get_feature_flag_details_from_server( - key, - distinct_id, - groups, - person_properties, - group_properties, - disable_geoip, - device_id=device_id, - ) - errors = [] - if errors_while_computing: - errors.append(FeatureFlagError.ERRORS_WHILE_COMPUTING) - if flag_details is None: - errors.append(FeatureFlagError.FLAG_MISSING) - if errors: - feature_flag_error = ",".join(errors) - - flag_result = FeatureFlagResult.from_flag_details( - flag_details, override_match_value - ) + self._get_remote_flag_result( + read, + key, + distinct_id, + groups, + person_properties, + group_properties, + disable_geoip, + device_id, + override_match_value, + snapshot["flag_definition_version"], + ) - if ( - flag_details is not None - and flag_details._malformed_field is not None - ): - # The record could not be read, so it reads as disabled. It must - # not replace the last good cached value, which it falls back to - # like a failed request, and it reports what a failed request - # reports: an unknown error and no request details. - feature_flag_error = FeatureFlagError.UNKNOWN_ERROR - request_id = None - evaluated_at = None - flag_result = ( - self._get_stale_flag_fallback(distinct_id, key) or flag_result - ) - # The request-start generation is an invalidation boundary, not - # a claim about the server's definitions. Refresh rejects late writes. - elif self.flag_cache and flag_result: - self.flag_cache._set_cached_remote_flag( - distinct_id, key, flag_result, local_definition_version - ) + if send_feature_flag_events: + self._capture_flag_read_result( + read, + key, + distinct_id, + snapshot, + flag_was_locally_evaluated, + groups, + disable_geoip, + ) + return read.result - self.log.debug( - f"Successfully computed flag remotely: #{key} -> #{flag_result}" - ) - # A payload lookup for a caller's match_value reports that value, not - # the record's. A failure above falls back to a stale cached value. - value_from_details = ( - flag_details is not None and override_match_value is None - ) - except QuotaLimitError as e: - self.log.warning(f"[FEATURE FLAGS] Quota limit exceeded: {e}") - feature_flag_error = FeatureFlagError.QUOTA_LIMITED - flag_result = self._get_stale_flag_fallback(distinct_id, key) - except RequestsTimeout as e: - self.log.warning(f"[FEATURE FLAGS] Request timed out: {e}") - feature_flag_error = FeatureFlagError.TIMEOUT - flag_result = self._get_stale_flag_fallback(distinct_id, key) - except RequestsConnectionError as e: - self.log.warning(f"[FEATURE FLAGS] Connection error: {e}") - feature_flag_error = FeatureFlagError.CONNECTION_ERROR - flag_result = self._get_stale_flag_fallback(distinct_id, key) - except APIError as e: - self.log.warning(f"[FEATURE FLAGS] API error: {e}") - feature_flag_error = FeatureFlagError.api_error(e.status) - flag_result = self._get_stale_flag_fallback(distinct_id, key) - except Exception as e: - self.log.exception(f"[FEATURE FLAGS] Unable to get flag remotely: {e}") - feature_flag_error = FeatureFlagError.UNKNOWN_ERROR - flag_result = self._get_stale_flag_fallback(distinct_id, key) + def _resolve_local_flag_result( + self, key, distinct_id, flag_value, override_match_value, snapshot + ): + local_definition_version = snapshot["flag_definition_version"] + lookup_match_value = ( + override_match_value if override_match_value is not None else flag_value + ) + payload = ( + self._compute_payload_locally( + key, lookup_match_value, _definition_snapshot=snapshot + ) + if lookup_match_value is not None + else None + ) + flag_result = FeatureFlagResult.from_value_and_payload( + key, lookup_match_value, payload + ) - if send_feature_flag_events: - # Locally-evaluated flags carry has_experiment in the stored definition; - # remotely-evaluated flags carry it in the response metadata. None when - # the server (older deployment) does not report it. - has_experiment: Optional[bool] = None - # Source the gate the same way as has_experiment above; see - # _capture_feature_flag_called_if_needed for why. - minimal_flag_called_events = self._minimal_flag_called_events - # Remotely-evaluated flags carry id and version in the response metadata; - # locally-evaluated flags read them from the definition that produced the value. - local_flag_id: Optional[int] = None - local_flag_version: Optional[int] = None - if flag_was_locally_evaluated: - local_def = snapshot["flags_by_key"].get(key) - if isinstance(local_def, dict): - has_experiment = _parse_has_experiment( - local_def.get("has_experiment") - ) - local_flag_id = local_def.get("id") - local_flag_version = local_def.get("version") - elif isinstance(flag_details, FeatureFlag): - has_experiment = _metadata_has_experiment(flag_details.metadata) - minimal_flag_called_events = remote_minimal_flag_called_events + # Cache the local evaluation, not a payload lookup override. + cached_flag_result = flag_result + if override_match_value is not None: + cached_flag_result = FeatureFlagResult.from_value_and_payload( + key, + flag_value, + self._compute_payload_locally( + key, flag_value, _definition_snapshot=snapshot + ), + ) + if self.flag_cache and cached_flag_result: + # The cache rejects invalidated generations, including writes + # already in flight when new definitions are published. + self.flag_cache.set_cached_flag( + distinct_id, key, cached_flag_result, local_definition_version + ) + return flag_result - self._capture_feature_flag_called( - distinct_id, + def _get_remote_flag_result( + self, + read, + key, + distinct_id, + groups, + person_properties, + group_properties, + disable_geoip, + device_id, + override_match_value, + local_definition_version, + ): + try: + ( + read.details, + read.request_id, + read.evaluated_at, + errors_while_computing, + read.minimal_flag_called_events, + ) = self._get_feature_flag_details_from_server( key, - flag_result.get_value() if flag_result else None, - flag_result.payload if flag_result else None, - flag_was_locally_evaluated, + distinct_id, groups, + person_properties, + group_properties, disable_geoip, - request_id, - evaluated_at, - flag_details, - feature_flag_error, - has_experiment, - minimal_flag_called_events, - local_flag_id=local_flag_id, - local_flag_version=local_flag_version, - value_from_details=value_from_details, + device_id=device_id, + ) + self._resolve_remote_flag_result( + read, + key, + distinct_id, + override_match_value, + local_definition_version, + errors_while_computing, ) - return flag_result + self.log.debug( + f"Successfully computed flag remotely: #{key} -> #{read.result}" + ) + # A payload lookup for a caller's match_value reports that value, not + # the record's. A failure above falls back to a stale cached value. + read.value_from_details = ( + read.details is not None and override_match_value is None + ) + except QuotaLimitError as e: + self.log.warning(f"[FEATURE FLAGS] Quota limit exceeded: {e}") + read.error = FeatureFlagError.QUOTA_LIMITED + read.result = self._get_stale_flag_fallback(distinct_id, key) + except RequestsTimeout as e: + self.log.warning(f"[FEATURE FLAGS] Request timed out: {e}") + read.error = FeatureFlagError.TIMEOUT + read.result = self._get_stale_flag_fallback(distinct_id, key) + except RequestsConnectionError as e: + self.log.warning(f"[FEATURE FLAGS] Connection error: {e}") + read.error = FeatureFlagError.CONNECTION_ERROR + read.result = self._get_stale_flag_fallback(distinct_id, key) + except APIError as e: + self.log.warning(f"[FEATURE FLAGS] API error: {e}") + read.error = FeatureFlagError.api_error(e.status) + read.result = self._get_stale_flag_fallback(distinct_id, key) + except Exception as e: + self.log.exception(f"[FEATURE FLAGS] Unable to get flag remotely: {e}") + read.error = FeatureFlagError.UNKNOWN_ERROR + read.result = self._get_stale_flag_fallback(distinct_id, key) + + def _resolve_remote_flag_result( + self, + read, + key, + distinct_id, + override_match_value, + local_definition_version, + errors_while_computing, + ): + read.error = self._remote_flag_result_error( + errors_while_computing, read.details + ) + + read.result = FeatureFlagResult.from_flag_details( + read.details, override_match_value + ) + + if read.details is not None and read.details._malformed_field is not None: + # The record could not be read, so it reads as disabled. It must + # not replace the last good cached value, which it falls back to + # like a failed request, and it reports what a failed request + # reports: an unknown error and no request details. + read.error = FeatureFlagError.UNKNOWN_ERROR + read.request_id = None + read.evaluated_at = None + read.result = self._get_stale_flag_fallback(distinct_id, key) or read.result + # The request-start generation is an invalidation boundary, not + # a claim about the server's definitions. Refresh rejects late writes. + elif self.flag_cache and read.result: + self.flag_cache._set_cached_remote_flag( + distinct_id, key, read.result, local_definition_version + ) + + @staticmethod + def _remote_flag_result_error(errors_while_computing, flag_details): + errors = [] + if errors_while_computing: + errors.append(FeatureFlagError.ERRORS_WHILE_COMPUTING) + if flag_details is None: + errors.append(FeatureFlagError.FLAG_MISSING) + return ",".join(errors) if errors else None + + def _capture_flag_read_result( + self, + read, + key, + distinct_id, + snapshot, + flag_was_locally_evaluated, + groups, + disable_geoip, + ): + # Locally-evaluated flags carry has_experiment in the stored definition; + # remotely-evaluated flags carry it in the response metadata. None when + # the server (older deployment) does not report it. + has_experiment: Optional[bool] = None + # Source the gate the same way as has_experiment above; see + # _capture_feature_flag_called_if_needed for why. + minimal_flag_called_events = self._minimal_flag_called_events + # Remotely-evaluated flags carry id and version in the response metadata; + # locally-evaluated flags read them from the definition that produced the value. + local_flag_id: Optional[int] = None + local_flag_version: Optional[int] = None + if flag_was_locally_evaluated: + local_def = snapshot["flags_by_key"].get(key) + if isinstance(local_def, dict): + has_experiment = _parse_has_experiment(local_def.get("has_experiment")) + local_flag_id = local_def.get("id") + local_flag_version = local_def.get("version") + elif isinstance(read.details, FeatureFlag): + has_experiment = _metadata_has_experiment(read.details.metadata) + minimal_flag_called_events = read.minimal_flag_called_events + + self._capture_feature_flag_called( + distinct_id, + key, + read.result.get_value() if read.result else None, + read.result.payload if read.result else None, + flag_was_locally_evaluated, + groups, + disable_geoip, + read.request_id, + read.evaluated_at, + read.details, + read.error, + has_experiment, + minimal_flag_called_events, + local_flag_id=local_flag_id, + local_flag_version=local_flag_version, + value_from_details=read.value_from_details, + ) def get_feature_flag_result( self, @@ -5059,14 +5459,7 @@ def _capture_feature_flag_called( properties["$feature_flag_request_id"] = request_id if evaluated_at: properties["$feature_flag_evaluated_at"] = evaluated_at - if isinstance(flag_details, FeatureFlag): - if flag_details.reason and flag_details.reason.description: - properties["$feature_flag_reason"] = flag_details.reason.description - if isinstance(flag_details.metadata, FlagMetadata): - if flag_details.metadata.version: - properties["$feature_flag_version"] = flag_details.metadata.version - if flag_details.metadata.id: - properties["$feature_flag_id"] = flag_details.metadata.id + self._add_remote_flag_called_metadata(properties, flag_details) if local_flag_version: properties["$feature_flag_version"] = local_flag_version if local_flag_id: @@ -5087,6 +5480,17 @@ def _capture_feature_flag_called( value_from_details=value_from_details, ) + @staticmethod + def _add_remote_flag_called_metadata(properties, flag_details): + if isinstance(flag_details, FeatureFlag): + if flag_details.reason and flag_details.reason.description: + properties["$feature_flag_reason"] = flag_details.reason.description + if isinstance(flag_details.metadata, FlagMetadata): + if flag_details.metadata.version: + properties["$feature_flag_version"] = flag_details.metadata.version + if flag_details.metadata.id: + properties["$feature_flag_id"] = flag_details.metadata.id + def _capture_feature_flag_called_if_needed( self, *, @@ -5399,15 +5803,9 @@ def evaluate_flags( """ host = self._get_feature_flag_evaluations_host() - if distinct_id is None: - distinct_id = get_context_distinct_id() - - # Resolve device_id from context when not explicitly provided. The context value - # may be set via tracing headers; the explicit parameter is an override for callers - # who want to bypass it. Used by the remote /flags request for experience-continuity - # flag matching. - if device_id is None: - device_id = get_context_device_id() + distinct_id, device_id = self._resolve_feature_flag_identity( + distinct_id, device_id + ) if not distinct_id or self.disabled: # Empty snapshot. The class short-circuits on empty distinct_id so calling @@ -5431,14 +5829,45 @@ def evaluate_flags( ) ) groups = groups or {} - requested_keys = set(flag_keys) if flag_keys else None + return self._evaluate_flags_with_context( + host, + distinct_id, + groups, + person_properties, + group_properties, + only_evaluate_locally, + disable_geoip, + flag_keys, + device_id, + ) - records: Dict[str, _EvaluatedFlagRecord] = {} - request_id: Optional[str] = None - evaluated_at: Optional[int] = None - errors_while_computing = False - quota_limited = False - locally_evaluated_keys: set[str] = set() + @staticmethod + def _resolve_feature_flag_identity(distinct_id, device_id): + if distinct_id is None: + distinct_id = get_context_distinct_id() + + # Resolve device_id from context when not explicitly provided. The context value + # may be set via tracing headers; the explicit parameter is an override for callers + # who want to bypass it. Used by the remote /flags request for experience-continuity + # flag matching. + if device_id is None: + device_id = get_context_device_id() + + return distinct_id, device_id + + def _evaluate_flags_with_context( + self, + host, + distinct_id, + groups, + person_properties, + group_properties, + only_evaluate_locally, + disable_geoip, + flag_keys, + device_id, + ) -> FeatureFlagEvaluations: + requested_keys = set(flag_keys) if flag_keys else None unresolved: Dict[str, UnresolvedFlagReason] = {} # Try local evaluation first when the poller has loaded definitions. local_person_properties = self._person_properties_for_local_evaluation( @@ -5461,14 +5890,55 @@ def evaluate_flags( minimal_flag_called_events = definition_snapshot.get( "minimal_flag_called_events", False ) - feature_flags_by_key = definition_snapshot["flags_by_key"] - local_flags = local_result.get("featureFlags") or {} - local_payloads = local_result.get("featureFlagPayloads") or {} - if requested_keys and not requested_keys.issubset(local_flags): + result = _FlagEvaluationResult( + records=self._local_evaluation_records(local_result, definition_snapshot), + minimal_flag_called_events=minimal_flag_called_events, + ) + if requested_keys and not requested_keys.issubset(result.records): # A requested flag may have been created since the last definitions poll. # Ask /flags for the caller's original scope unless this is a local-only call. fallback_to_server = True + # Fall back to remote evaluation for any flags the poller couldn't resolve locally. + # Use the flags decision path directly so the resulting records carry id/version/reason + # and fired ``$feature_flag_called`` events match what ``get_feature_flag()`` emits. + if fallback_to_server and not only_evaluate_locally: + self._evaluate_flags_remotely( + result, + distinct_id, + groups, + person_properties, + group_properties, + disable_geoip, + flag_keys, + device_id, + requested_keys, + ) + + return FeatureFlagEvaluations( + host=host, + distinct_id=str(distinct_id), + flags=result.records, + groups=groups, + disable_geoip=disable_geoip, + request_id=result.request_id, + evaluated_at=result.evaluated_at, + errors_while_computing=result.errors_while_computing, + quota_limited=result.quota_limited, + minimal_flag_called_events=result.minimal_flag_called_events, + unresolved_flags={ + key: reason + for key, reason in unresolved.items() + if key not in result.records + }, + ) + + @staticmethod + def _local_evaluation_records(local_result, definition_snapshot): + records: Dict[str, _EvaluatedFlagRecord] = {} + feature_flags_by_key = definition_snapshot["flags_by_key"] + local_flags = local_result.get("featureFlags") or {} + local_payloads = local_result.get("featureFlagPayloads") or {} for key, value in local_flags.items(): flag_def = feature_flags_by_key.get(key) or {} records[key] = _LocalFlagRecord( @@ -5482,62 +5952,62 @@ def evaluate_flags( locally_evaluated=True, has_experiment=_parse_has_experiment(flag_def.get("has_experiment")), ) - locally_evaluated_keys.add(key) - # Fall back to remote evaluation for any flags the poller couldn't resolve locally. - # Use the flags decision path directly so the resulting records carry id/version/reason - # and fired ``$feature_flag_called`` events match what ``get_feature_flag()`` emits. - if fallback_to_server and not only_evaluate_locally: - try: - response = self._get_flags_decision( - distinct_id, - groups=groups, - person_properties=person_properties, - group_properties=group_properties, - disable_geoip=disable_geoip, - flag_keys_to_evaluate=flag_keys, - device_id=device_id, - ) - request_id = response.get("requestId") - raw_evaluated_at = response.get("evaluatedAt") - evaluated_at = ( - raw_evaluated_at if isinstance(raw_evaluated_at, int) else None - ) - errors_while_computing = bool( - response.get("errorsWhileComputingFlags", False) - ) - minimal_flag_called_events = ( - response.get("minimalFlagCalledEvents") is True - ) - for key, detail in response.get("flags", {}).items(): - if requested_keys is not None and key not in requested_keys: - continue - if key in locally_evaluated_keys: - continue - records[key] = _RemoteFlagRecord(detail) - except QuotaLimitError as e: - self.log.warning(f"[FEATURE FLAGS] Quota limit exceeded: {e}") - quota_limited = True - except Exception as e: - self.log.exception( - f"[FEATURE FLAGS] Unable to evaluate flags remotely: {e}" - ) + return records - return FeatureFlagEvaluations( - host=host, - distinct_id=str(distinct_id), - flags=records, - groups=groups, - disable_geoip=disable_geoip, - request_id=request_id, - evaluated_at=evaluated_at, - errors_while_computing=errors_while_computing, - quota_limited=quota_limited, - minimal_flag_called_events=minimal_flag_called_events, - unresolved_flags={ - key: reason for key, reason in unresolved.items() if key not in records - }, - ) + def _evaluate_flags_remotely( + self, + result, + distinct_id, + groups, + person_properties, + group_properties, + disable_geoip, + flag_keys, + device_id, + requested_keys, + ): + local_keys = set(result.records) + try: + response = self._get_flags_decision( + distinct_id, + groups=groups, + person_properties=person_properties, + group_properties=group_properties, + disable_geoip=disable_geoip, + flag_keys_to_evaluate=flag_keys, + device_id=device_id, + ) + result.request_id = response.get("requestId") + raw_evaluated_at = response.get("evaluatedAt") + result.evaluated_at = ( + raw_evaluated_at if isinstance(raw_evaluated_at, int) else None + ) + result.errors_while_computing = bool( + response.get("errorsWhileComputingFlags", False) + ) + result.minimal_flag_called_events = ( + response.get("minimalFlagCalledEvents") is True + ) + self._merge_remote_evaluation_records( + result.records, response, requested_keys, local_keys + ) + except QuotaLimitError as e: + self.log.warning(f"[FEATURE FLAGS] Quota limit exceeded: {e}") + result.quota_limited = True + except Exception as e: + self.log.exception( + f"[FEATURE FLAGS] Unable to evaluate flags remotely: {e}" + ) + + @staticmethod + def _merge_remote_evaluation_records(records, response, requested_keys, local_keys): + for key, detail in response.get("flags", {}).items(): + if requested_keys is not None and key not in requested_keys: + continue + if key in local_keys: + continue + records[key] = _RemoteFlagRecord(detail) _feature_flag_evaluations_host_cache: Optional[_FeatureFlagEvaluationsHost] = None @@ -5573,43 +6043,19 @@ def _get_all_flags_and_payloads_locally( snapshot = self._local_evaluation_snapshot() # If loading in previous line failed if snapshot["flags"]: - # Filter flags based on flag_keys_to_evaluate if provided - flags_to_process = snapshot["flags"] - if flag_keys_to_evaluate: - flag_keys_set = set(flag_keys_to_evaluate) - flags_to_process = [ - flag for flag in snapshot["flags"] if flag["key"] in flag_keys_set - ] - - for flag in flags_to_process: - try: - flags[flag["key"]] = self._compute_flag_locally( - flag, - distinct_id, - groups=groups, - person_properties=person_properties, - group_properties=group_properties, - warn_on_unknown_groups=warn_on_unknown_groups, - device_id=device_id, - _definition_snapshot=snapshot, - ) - matched_payload = self._compute_payload_locally( - flag["key"], - flags[flag["key"]], - _definition_snapshot=snapshot, - ) - if matched_payload is not None: - payloads[flag["key"]] = matched_payload - except (InconclusiveMatchError, RequiresServerEvaluation) as e: - # No need to log this, since it's just telling us to fall back to `/flags` - fallback_to_flags = True - if unresolved is not None: - unresolved[flag["key"]] = e.reason - except Exception as e: - self.log.exception( - f"[FEATURE FLAGS] Error while computing variant and payload: {e}" - ) - fallback_to_flags = True + fallback_to_flags = self._evaluate_local_flag_set( + snapshot, + distinct_id, + groups, + person_properties, + group_properties, + warn_on_unknown_groups, + flag_keys_to_evaluate, + device_id, + unresolved, + flags, + payloads, + ) else: fallback_to_flags = True @@ -5622,6 +6068,67 @@ def _get_all_flags_and_payloads_locally( snapshot, ) + @staticmethod + def _select_flags_for_local_evaluation(snapshot, flag_keys_to_evaluate): + # Filter flags based on flag_keys_to_evaluate if provided + flags_to_process = snapshot["flags"] + if flag_keys_to_evaluate: + flag_keys_set = set(flag_keys_to_evaluate) + flags_to_process = [ + flag for flag in snapshot["flags"] if flag["key"] in flag_keys_set + ] + + return flags_to_process + + def _evaluate_local_flag_set( + self, + snapshot, + distinct_id, + groups, + person_properties, + group_properties, + warn_on_unknown_groups, + flag_keys_to_evaluate, + device_id, + unresolved, + flags, + payloads, + ): + fallback_to_flags = False + flags_to_process = self._select_flags_for_local_evaluation( + snapshot, flag_keys_to_evaluate + ) + for flag in flags_to_process: + try: + flags[flag["key"]] = self._compute_flag_locally( + flag, + distinct_id, + groups=groups, + person_properties=person_properties, + group_properties=group_properties, + warn_on_unknown_groups=warn_on_unknown_groups, + device_id=device_id, + _definition_snapshot=snapshot, + ) + matched_payload = self._compute_payload_locally( + flag["key"], + flags[flag["key"]], + _definition_snapshot=snapshot, + ) + if matched_payload is not None: + payloads[flag["key"]] = matched_payload + except (InconclusiveMatchError, RequiresServerEvaluation) as e: + # No need to log this, since it's just telling us to fall back to `/flags` + fallback_to_flags = True + if unresolved is not None: + unresolved[flag["key"]] = e.reason + except Exception as e: + self.log.exception( + f"[FEATURE FLAGS] Error while computing variant and payload: {e}" + ) + fallback_to_flags = True + return fallback_to_flags + def _initialize_flag_cache(self, cache_url): """Initialize feature flag cache for graceful degradation during service outages. @@ -5672,37 +6179,7 @@ def _initialize_flag_cache(self, cache_url): return FlagCache(size, ttl) elif scheme in ("redis", "rediss"): - try: - # Not worth importing redis if we're not using it - import redis - - redis_url = f"{parsed.scheme}://" - if parsed.username or parsed.password: - redis_url += f"{parsed.username or ''}:{parsed.password or ''}@" - host = parsed.hostname or "localhost" - if ":" in host: - host = f"[{host}]" - redis_url += f"{host}:{parsed.port or 6379}" - if parsed.path: - redis_url += parsed.path - - client = redis.from_url(redis_url) - - # Test connection before using it - client.ping() - - return RedisFlagCache(client, default_ttl=ttl) - - except ImportError: - self.log.warning( - "[FEATURE FLAGS] Redis not available, flag caching disabled" - ) - return None - except Exception as e: - self.log.warning( - f"[FEATURE FLAGS] Redis connection failed: {e}, flag caching disabled" - ) - return None + return self._initialize_redis_flag_cache(parsed, ttl) else: raise ValueError( f"Unknown cache URL scheme: {scheme}. Supported schemes: memory, redis, rediss" @@ -5714,6 +6191,45 @@ def _initialize_flag_cache(self, cache_url): ) return None + def _initialize_redis_flag_cache(self, parsed, ttl): + try: + # Not worth importing redis if we're not using it + import redis + + redis_url = self._redis_flag_cache_url(parsed) + + client = redis.from_url(redis_url) + + # Test connection before using it + client.ping() + + return RedisFlagCache(client, default_ttl=ttl) + + except ImportError: + self.log.warning( + "[FEATURE FLAGS] Redis not available, flag caching disabled" + ) + return None + except Exception as e: + self.log.warning( + f"[FEATURE FLAGS] Redis connection failed: {e}, flag caching disabled" + ) + return None + + @staticmethod + def _redis_flag_cache_url(parsed): + redis_url = f"{parsed.scheme}://" + if parsed.username or parsed.password: + redis_url += f"{parsed.username or ''}:{parsed.password or ''}@" + host = parsed.hostname or "localhost" + if ":" in host: + host = f"[{host}]" + redis_url += f"{host}:{parsed.port or 6379}" + if parsed.path: + redis_url += parsed.path + + return redis_url + def feature_flag_definitions(self): """ Return feature flag definitions loaded for local evaluation. diff --git a/posthog/consumer.py b/posthog/consumer.py index 0190dcf01..d9de6d441 100644 --- a/posthog/consumer.py +++ b/posthog/consumer.py @@ -73,14 +73,17 @@ def draining(self, consumer) -> bool: with self._queue.mutex: return self._requests > 0 and (consumer.running or consumer._drain_on_stop) + def _is_draining_locked(self, consumer) -> bool: + return self._requests > 0 and ( + consumer is None or consumer.running or consumer._drain_on_stop + ) + def get(self, timeout: float, consumer=None): """Get an item, or wake with ``Empty`` when draining or stopping.""" with self._queue.not_empty: deadline = time.monotonic() + timeout while True: - draining = self._requests > 0 and ( - consumer is None or consumer.running or consumer._drain_on_stop - ) + draining = self._is_draining_locked(consumer) if consumer is not None and not consumer.running and not draining: raise Empty if self._queue._qsize(): @@ -213,6 +216,44 @@ def _can_upload(self) -> bool: with self.queue.mutex: return self.running or self._drain_on_stop + def _event_size(self, item) -> Optional[int]: + try: + item_size = len(json.dumps(item, cls=DatetimeSerializer).encode()) + except Exception: + # Callback-modified events can still contain invalid mapping + # keys or circular references. Never log the payload here. + self.log.error("Unable to serialize queued event for sizing, dropping.") + return None + if item_size > self.max_msg_size: + # Log only name and size: AI events may carry unredacted + # multimodal payloads that must not leak into logs. + self.log.error( + "Event %s (%d bytes) exceeds the %dKiB limit for %s, dropping.", + item.get("event") if isinstance(item, dict) else type(item), + item_size, + self.max_msg_size // 1024, + self.endpoint, + ) + return None + return item_size + + def _next_queue_timeout(self, start_time: float) -> Optional[float]: + # While draining we take only what is already queued, never waiting + # for `flush_interval` to elapse or for `flush_at` to be reached. + draining = self._draining() + if not self.running and not draining: + return None + remaining = self.flush_interval - (time.monotonic() - start_time) + if not draining and remaining <= 0: + return None + + return 0 if draining else remaining + + @staticmethod + def _acknowledge(queue, count: int) -> None: + for _ in range(count): + queue.task_done() + def next(self): """Return the next batch of items to upload.""" queue = self.queue @@ -224,47 +265,21 @@ def next(self): try: while len(items) < self.flush_at: - # While draining we take only what is already queued, never waiting - # for `flush_interval` to elapse or for `flush_at` to be reached. - draining = self._draining() - if not self.running and not draining: - break - remaining = self.flush_interval - (time.monotonic() - start_time) - if not draining and remaining <= 0: + timeout = self._next_queue_timeout(start_time) + if timeout is None: break try: if self._drain_signal is not None: item = self._drain_signal.get( - timeout=0 if draining else remaining, + timeout=timeout, consumer=self, ) else: - item = queue.get(block=True, timeout=remaining) + item = queue.get(block=True, timeout=timeout) pending_items += 1 - try: - item_size = len( - json.dumps(item, cls=DatetimeSerializer).encode() - ) - except Exception: - # Callback-modified events can still contain invalid mapping - # keys or circular references. Never log the payload here. - self.log.error( - "Unable to serialize queued event for sizing, dropping." - ) - queue.task_done() - pending_items -= 1 - continue - if item_size > self.max_msg_size: - # Log only name and size: AI events may carry unredacted - # multimodal payloads that must not leak into logs. - self.log.error( - "Event %s (%d bytes) exceeds the %dKiB limit for %s, dropping.", - item.get("event") if isinstance(item, dict) else type(item), - item_size, - self.max_msg_size // 1024, - self.endpoint, - ) + item_size = self._event_size(item) + if item_size is None: queue.task_done() pending_items -= 1 continue @@ -276,13 +291,11 @@ def next(self): except Empty: break except BaseException: - for _ in range(pending_items): - queue.task_done() + self._acknowledge(queue, pending_items) raise if not self._can_upload(): - for _ in range(pending_items): - queue.task_done() + self._acknowledge(queue, pending_items) return [] return items diff --git a/posthog/emails.py b/posthog/emails.py index 141255b17..047119b99 100644 --- a/posthog/emails.py +++ b/posthog/emails.py @@ -535,14 +535,7 @@ def _prepare_code_send(args: Mapping[str, Any]) -> _PreparedSend: raise ValueError( "template_key can only have letters, digits, hyphens (-) and underscores (_), at most 400." ) - content = {"subject": _nonempty_text(args, "subject")} - content.update( - {field: _string(args, field) for field in ("html", "text") if field in args} - ) - if "html" not in content and "text" not in content: - raise TypeError("send() needs html, text or both.") - if not (content.get("html") or content.get("text")): - raise ValueError("html or text must be a nonempty string.") + content = _code_content(args) references, files = _attachments(args.get("attachments", []), content) @@ -561,6 +554,19 @@ def _prepare_code_send(args: Mapping[str, Any]) -> _PreparedSend: ) +def _code_content(args: Mapping[str, Any]) -> dict[str, str]: + content = {"subject": _nonempty_text(args, "subject")} + content.update( + {field: _string(args, field) for field in ("html", "text") if field in args} + ) + if "html" not in content and "text" not in content: + raise TypeError("send() needs html, text or both.") + if not (content.get("html") or content.get("text")): + raise ValueError("html or text must be a nonempty string.") + + return content + + def _sender(args: Mapping[str, Any]) -> dict[str, Any]: sender: dict[str, Any] = {} if "from_" in args: @@ -882,13 +888,7 @@ def _status_path(message_id: Union[str, UUID]) -> str: def _validate_options( timeout: float, max_retries: int, migrated_from: Optional[str] ) -> None: - if ( - isinstance(timeout, bool) - or not isinstance(timeout, (int, float)) - or not math.isfinite(timeout) - or timeout <= 0 - ): - raise ValueError("timeout must be a finite positive number of seconds.") + _validate_timeout(timeout) if ( isinstance(max_retries, bool) or not isinstance(max_retries, int) @@ -903,6 +903,16 @@ def _validate_options( ) +def _validate_timeout(timeout: float) -> None: + if ( + isinstance(timeout, bool) + or not isinstance(timeout, (int, float)) + or not math.isfinite(timeout) + or timeout <= 0 + ): + raise ValueError("timeout must be a finite positive number of seconds.") + + def _text(value: Any) -> Optional[str]: return value if isinstance(value, str) and value else None @@ -912,34 +922,35 @@ def _error_name(status: Optional[int], code: str) -> str: return "missing_api_key" if status is None: return "service_unavailable" if code == "network_error" else "application_error" - if status == 400: - return "validation_error" - if status == 403: - return "invalid_permission" - if status == 404: - return "not_found" - if status == 409: - return ( - "validation_error" - if code == "template_outdated" - else "concurrent_idempotent_requests" - ) - if status == 422: - # The template send route also answers 422 for send checks such as recipient_suppressed. - return ( - "invalid_idempotent_request" - if code == "idempotency_key_reused" - else "validation_error" - ) + if status in (409, 422): + return _idempotency_error_name(status, code) if status == 429: if code in _DAILY_QUOTA_CODES: return "daily_quota_exceeded" return ( "monthly_quota_exceeded" if code in _QUOTA_CODES else "rate_limit_exceeded" ) - if status == 503: - return "service_unavailable" - return "application_error" + return { + 400: "validation_error", + 403: "invalid_permission", + 404: "not_found", + 503: "service_unavailable", + }.get(status, "application_error") + + +def _idempotency_error_name(status: int, code: str) -> str: + if status == 409: + return ( + "validation_error" + if code == "template_outdated" + else "concurrent_idempotent_requests" + ) + # The template send route also answers 422 for send checks such as recipient_suppressed. + return ( + "invalid_idempotent_request" + if code == "idempotency_key_reused" + else "validation_error" + ) def _sdk_error(code: str, message: str, status: Optional[int] = None) -> EmailError: @@ -977,21 +988,23 @@ def _parse_response( return SendEmailResult( id=message_id, replayed=fields.get("replayed") is True, - warnings=tuple( - EmailWarning( - code=_text(warning.get("code")) or "warning", - message=_text(warning.get("detail")) - or _text(warning.get("message")) - or "", - fix=_text(warning.get("fix")), - ) - for warning in (warnings if isinstance(warnings, list) else []) - if isinstance(warning, dict) - ), + warnings=_parse_warnings(warnings), ) raise _response_error(fields, status, retry_after_header) +def _parse_warnings(warnings: Any) -> tuple[EmailWarning, ...]: + return tuple( + EmailWarning( + code=_text(warning.get("code")) or "warning", + message=_text(warning.get("detail")) or _text(warning.get("message")) or "", + fix=_text(warning.get("fix")), + ) + for warning in (warnings if isinstance(warnings, list) else []) + if isinstance(warning, dict) + ) + + def _timestamp(value: Any) -> Optional[datetime]: text = _text(value) if text is None: diff --git a/posthog/exception_utils.py b/posthog/exception_utils.py index a6f5883b2..d462d23cc 100644 --- a/posthog/exception_utils.py +++ b/posthog/exception_utils.py @@ -415,20 +415,7 @@ def get_lines_from_file( ): # type: (...) -> Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]] context_lines = 5 - source = None - if loader is not None and hasattr(loader, "get_source"): - try: - source_str = loader.get_source(module) # type: Optional[str] - except (ImportError, IOError): - source_str = None - if source_str is not None: - source = source_str.splitlines() - - if source is None: - try: - source = linecache.getlines(filename) - except (OSError, IOError): - return [], None, [] + source = _get_source_lines(filename, loader, module) if not source: return [], None, [] @@ -452,6 +439,26 @@ def get_lines_from_file( return [], None, [] +def _get_source_lines(filename, loader, module): + # type: (str, Optional[Any], Optional[str]) -> Optional[List[str]] + source = None + if loader is not None and hasattr(loader, "get_source"): + try: + source_str = loader.get_source(module) # type: Optional[str] + except (ImportError, IOError): + source_str = None + if source_str is not None: + source = source_str.splitlines() + + if source is None: + try: + source = linecache.getlines(filename) + except (OSError, IOError): + return None + + return source + + def get_source_context( frame, # type: FrameType tb_lineno, # type: int @@ -583,14 +590,16 @@ def _valid_mechanism(mechanism): if key not in {"type", "handled", "source", "synthetic", "exception_id", "parent_id"} } - if isinstance(mechanism.get("type"), str) and mechanism["type"]: - result["type"] = mechanism["type"] - if isinstance(mechanism.get("handled"), bool): - result["handled"] = mechanism["handled"] - if isinstance(mechanism.get("source"), str) and mechanism["source"]: - result["source"] = mechanism["source"] - if isinstance(mechanism.get("synthetic"), bool): - result["synthetic"] = mechanism["synthetic"] + for field, field_type in ( + ("type", str), + ("handled", bool), + ("source", str), + ("synthetic", bool), + ): + if isinstance(mechanism.get(field), field_type) and ( + field_type is bool or mechanism[field] + ): + result[field] = mechanism[field] return result @@ -653,9 +662,36 @@ def single_exception_from_error_tuple( Creates a dict that goes into the events `exception.values` list """ exception_value = {} # type: Dict[str, Any] - exception_value["mechanism"] = _valid_mechanism(mechanism) + exception_value["mechanism"] = _exception_mechanism( + exc_value, tb, mechanism, exception_id, parent_id, source + ) + + exception_value["module"] = get_type_module(exc_type) + exception_value["type"] = get_type_name(exc_type) + exception_value["value"] = get_error_message(exc_value) + + max_value_length = DEFAULT_MAX_VALUE_LENGTH # fallback + + frames = [ + serialize_frame( + tb.tb_frame, + tb_lineno=tb.tb_lineno, + max_value_length=max_value_length, + ) + for tb in iter_stacks(tb) + ] + + if frames: + exception_value["stacktrace"] = {"frames": frames, "type": "raw"} + + return exception_value + + +def _exception_mechanism(exc_value, tb, mechanism, exception_id, parent_id, source): + # type: (Optional[BaseException], Optional[TracebackType], Optional[Dict[str, Any]], Optional[int], Optional[int], Optional[str]) -> Dict[str, Any] + result = _valid_mechanism(mechanism) if exception_id is not None: - exception_value["mechanism"]["exception_id"] = exception_id + result["exception_id"] = exception_id if exc_value is not None: errno = get_errno(exc_value) @@ -663,27 +699,15 @@ def single_exception_from_error_tuple( errno = None if errno is not None: - exception_value["mechanism"].setdefault("meta", {}).setdefault( - "errno", {} - ).setdefault("number", errno) - - if isinstance(source, str) and source: - exception_value["mechanism"]["source"] = source - - is_root_exception = exception_id == 0 - if not is_root_exception and parent_id is not None: - exception_value["mechanism"]["parent_id"] = parent_id - exception_value["mechanism"]["type"] = "chained" - exception_value["mechanism"].pop("handled", None) + result.setdefault("meta", {}).setdefault("errno", {}).setdefault( + "number", errno + ) - if is_root_exception: - exception_value["mechanism"].setdefault("type", "generic") - exception_value["mechanism"].setdefault("handled", True) - exception_value["mechanism"].pop("source", None) + _set_exception_linkage(result, exception_id, parent_id, source) # The stack is synthetic only when the SDK built it, which happens for an # exception that was passed to capture without ever being raised. - exception_value["mechanism"].setdefault( + result.setdefault( "synthetic", tb is not None and _is_synthesized_traceback(exc_value, tb), ) @@ -692,27 +716,26 @@ def single_exception_from_error_tuple( exc_value, BaseExceptionGroup ) if is_exception_group: - exception_value["mechanism"]["is_exception_group"] = True + result["is_exception_group"] = True - exception_value["module"] = get_type_module(exc_type) - exception_value["type"] = get_type_name(exc_type) - exception_value["value"] = get_error_message(exc_value) + return result - max_value_length = DEFAULT_MAX_VALUE_LENGTH # fallback - frames = [ - serialize_frame( - tb.tb_frame, - tb_lineno=tb.tb_lineno, - max_value_length=max_value_length, - ) - for tb in iter_stacks(tb) - ] +def _set_exception_linkage(result, exception_id, parent_id, source): + # type: (Dict[str, Any], Optional[int], Optional[int], Optional[str]) -> None + if isinstance(source, str) and source: + result["source"] = source - if frames: - exception_value["stacktrace"] = {"frames": frames, "type": "raw"} + is_root_exception = exception_id == 0 + if not is_root_exception and parent_id is not None: + result["parent_id"] = parent_id + result["type"] = "chained" + result.pop("handled", None) - return exception_value + if is_root_exception: + result.setdefault("type", "generic") + result.setdefault("handled", True) + result.pop("source", None) HAS_CHAINED_EXCEPTIONS = hasattr(Exception, "__suppress_context__") @@ -803,17 +826,7 @@ def _exceptions_from_error( parent_id = exception_id exception_id += 1 - causing_exception = None # type: Optional[BaseException] - relationship = None # type: Optional[str] - should_suppress_context = ( - hasattr(exc_value, "__suppress_context__") and exc_value.__suppress_context__ # type: ignore - ) - if should_suppress_context and exc_value is not None: - causing_exception = getattr(exc_value, "__cause__", None) - relationship = "cause" - else: - causing_exception = getattr(exc_value, "__context__", None) - relationship = "context" + causing_exception, relationship = _exception_cause(exc_value) if causing_exception is not None and exception_id < _MAX_EXCEPTION_ENTRIES: (exception_id, child_exceptions) = _exceptions_from_error( @@ -828,6 +841,32 @@ def _exceptions_from_error( ) exceptions.extend(child_exceptions) + return _append_exception_group_members( + exc_value, exception_id, parent_id, traversal_state, exceptions + ) + + +def _exception_cause(exc_value): + # type: (Optional[BaseException]) -> Tuple[Optional[BaseException], str] + causing_exception = None # type: Optional[BaseException] + relationship = None # type: Optional[str] + should_suppress_context = ( + hasattr(exc_value, "__suppress_context__") and exc_value.__suppress_context__ # type: ignore + ) + if should_suppress_context and exc_value is not None: + causing_exception = getattr(exc_value, "__cause__", None) + relationship = "cause" + else: + causing_exception = getattr(exc_value, "__context__", None) + relationship = "context" + + return causing_exception, relationship + + +def _append_exception_group_members( + exc_value, exception_id, parent_id, traversal_state, exceptions +): + # type: (Optional[BaseException], int, int, _ExceptionTraversalState, List[Dict[str, Any]]) -> Tuple[int, List[Dict[str, Any]]] # Aggregate-member inspection has its own shared budget. Duplicate and cyclic # references still consume it even though they do not produce output entries. # Cause/context traversal does not consume this budget, so the final inspected @@ -923,13 +962,16 @@ def iter_event_stacktraces(event): if "stacktrace" in event: yield event["stacktrace"] if "threads" in event: - for thread in event["threads"].get("values") or (): - if "stacktrace" in thread: - yield thread["stacktrace"] + yield from _iter_nested_stacktraces(event["threads"].get("values") or ()) if "exception" in event: - for exception in event["exception"].get("values") or (): - if "stacktrace" in exception: - yield exception["stacktrace"] + yield from _iter_nested_stacktraces(event["exception"].get("values") or ()) + + +def _iter_nested_stacktraces(entries): + # type: (Any) -> Iterator[Dict[str, Any]] + for entry in entries: + if "stacktrace" in entry: + yield entry["stacktrace"] def iter_event_frames(event): @@ -1429,11 +1471,24 @@ def _is_high_entropy_secret(value): if not _SECRET_REJECT_CHARS.isdisjoint(distinct): return False + if _secret_character_class_count(distinct) < _SECRET_MIN_CHAR_CLASSES: + return False # identifiers, enums, slugs, numbers + + n = len(value) + entropy = 0.0 + for occurrences in counts.values(): + p = occurrences / n + entropy -= p * math.log2(p) + return entropy >= _SECRET_MIN_ENTROPY_BITS + + +def _secret_character_class_count(distinct): + """Count token character classes, rejecting whitespace and pure-hex ids.""" has_lower = has_upper = has_digit = has_symbol = False hex_only = True for ch in distinct: if ch.isspace(): - return False + return 0 if ch.islower(): has_lower = True if ch not in _HEX_DIGITS: @@ -1449,16 +1504,8 @@ def _is_high_entropy_secret(value): hex_only = False if hex_only: # ObjectId / SHA / md5 digest - return False - if (has_lower + has_upper + has_digit + has_symbol) < _SECRET_MIN_CHAR_CLASSES: - return False # identifiers, enums, slugs, numbers - - n = len(value) - entropy = 0.0 - for occurrences in counts.values(): - p = occurrences / n - entropy -= p * math.log2(p) - return entropy >= _SECRET_MIN_ENTROPY_BITS + return 0 + return has_lower + has_upper + has_digit + has_symbol def _looks_like_secret(value): @@ -1656,41 +1703,30 @@ def _mask_mapping(items, config, seen, depth): placeholder, because the key text reaches the output as-is.""" result: Dict[Any, Any] = {} for key, value in items: - if type(key) is str: - out_key = key_str = key - key_is_json_safe = True - else: - try: - key_str = key if isinstance(key, str) else str(key) - except Exception: - # Without the key text, nothing shows whether the key names a secret, so - # the value is redacted too. - result[_redacted_key(result)] = CODE_VARIABLES_REDACTED_VALUE - continue - # json.dumps only accepts str/int/float/bool/None keys; coerce anything else to - # its string form so one exotic key can't make json.dumps fail. That string form - # is a repr, which can embed field values, not only a name. - key_is_json_safe = ( - key is None - or isinstance(key, (str, int)) # bool is an int subclass - or (isinstance(key, float) and math.isfinite(key)) - ) - out_key = key if key_is_json_safe else key_str + try: + key_str = key if isinstance(key, str) else str(key) + except Exception: + # Without the key text, nothing shows whether the key names a secret, so + # the value is redacted too. + result[_redacted_key(result)] = CODE_VARIABLES_REDACTED_VALUE + continue + out_key, key_is_json_safe = _mapping_key(key, key_str) if len(key_str) > _MAX_VALUE_LENGTH_FOR_PATTERN_MATCH: # Too long to scan, so the key text can't be vouched for either. result[_redacted_key(result)] = CODE_VARIABLES_TOO_LONG_VALUE continue key_matches_mask = _matcher_matches(key_str, config.mask) - if key_matches_mask and not _is_field_name(key, key_is_json_safe): - # A name such as `password` is safe to keep, but other text that matches can - # hold the value itself, e.g. `BasicAuth(login='u', password='...')`. - out_key = _redacted_key(result) - elif config.detect_secrets and _looks_like_secret(key_str): - out_key = _redacted_key(result) - elif not key_is_json_safe and _key_parts_fail_masking(key, config, seen, depth): - out_key = _redacted_key(result) - elif isinstance(out_key, str): - out_key = _redact_embedded_credentials(out_key, config) + out_key = _mask_mapping_key( + key, + key_str, + key_is_json_safe, + out_key, + key_matches_mask, + result, + config, + seen, + depth, + ) if out_key in result: # Two keys can end up with the same text, for example URLs that differ only in # their credentials. A placeholder keeps the later entry from overwriting. @@ -1702,6 +1738,45 @@ def _mask_mapping(items, config, seen, depth): return result +def _mapping_key(key, key_str): + if type(key) is str: + return key, True + # json.dumps only accepts str/int/float/bool/None keys; coerce anything else to + # its string form so one exotic key can't make json.dumps fail. That string form + # is a repr, which can embed field values, not only a name. + key_is_json_safe = ( + key is None + or isinstance(key, (str, int)) # bool is an int subclass + or (isinstance(key, float) and math.isfinite(key)) + ) + out_key = key if key_is_json_safe else key_str + return out_key, key_is_json_safe + + +def _mask_mapping_key( + key, + key_str, + key_is_json_safe, + out_key, + key_matches_mask, + result, + config, + seen, + depth, +): + if key_matches_mask and not _is_field_name(key, key_is_json_safe): + # A name such as `password` is safe to keep, but other text that matches can + # hold the value itself, e.g. `BasicAuth(login='u', password='...')`. + out_key = _redacted_key(result) + elif config.detect_secrets and _looks_like_secret(key_str): + out_key = _redacted_key(result) + elif not key_is_json_safe and _key_parts_fail_masking(key, config, seen, depth): + out_key = _redacted_key(result) + elif isinstance(out_key, str): + out_key = _redact_embedded_credentials(out_key, config) + return out_key + + def _mask_value(value, config, seen=None, depth=0): """Turn any Python value into a JSON-safe, masked value. Single source of truth for what gets redacted; the result contains only JSON-native types so it can be handed @@ -1723,10 +1798,18 @@ def _mask_value(value, config, seen=None, depth=0): return value if t is float: # Non-finite floats (NaN/Infinity) are invalid JSON, so render them as strings. - return value if math.isfinite(value) else str(value) + return _mask_float(value) if value is None: return value + return _mask_non_plain_value(value, config, seen, depth) + + +def _mask_float(value): + return value if math.isfinite(value) else str(value) + +def _mask_non_plain_value(value, config, seen, depth): + t = type(value) if t is not dict and t is not list and t is not tuple: # A scalar subclass (e.g. IntEnum, str subclass) - handle before traversing. if isinstance(value, str): @@ -1735,7 +1818,10 @@ def _mask_value(value, config, seen=None, depth=0): return str(value) if isinstance(value, (bool, int, float)): return value + return _mask_traversable_value(value, config, seen, depth) + +def _mask_traversable_value(value, config, seen, depth): if depth >= _MAX_MASK_DEPTH: # Too deep to keep traversing; fail closed rather than repr (which could leak). return CODE_VARIABLES_TOO_LONG_VALUE @@ -1750,7 +1836,11 @@ def _mask_value(value, config, seen=None, depth=0): if len(seen) > _MAX_TOTAL_NODES_TO_MASK: return CODE_VARIABLES_TOO_LONG_VALUE - if t is dict or isinstance(value, dict): + return _mask_collection_or_object(value, config, seen, depth) + + +def _mask_collection_or_object(value, config, seen, depth): + if type(value) is dict or isinstance(value, dict): if len(value) > _MAX_COLLECTION_ITEMS_TO_SCAN: return CODE_VARIABLES_TOO_LONG_VALUE return _mask_mapping(value.items(), config, seen, depth) @@ -1758,24 +1848,35 @@ def _mask_value(value, config, seen=None, depth=0): # namedtuples are tuples but their fields have names: traverse like an object (so a # field named `password` is caught) and emit a dict the encoder can serialize directly. if isinstance(value, tuple) and hasattr(value, "_fields"): - fields = value._fields - if len(fields) > _MAX_COLLECTION_ITEMS_TO_SCAN: - return CODE_VARIABLES_TOO_LONG_VALUE - masked = _mask_mapping(zip(fields, value), config, seen, depth) - masked["__class__"] = _safe_type_name(value) - return masked + return _mask_namedtuple(value, config, seen, depth) if isinstance(value, (list, tuple)): - if len(value) > _MAX_COLLECTION_ITEMS_TO_SCAN: - return CODE_VARIABLES_TOO_LONG_VALUE - masked_items = [_mask_value(item, config, seen, depth + 1) for item in value] - try: - return type(value)(masked_items) - except Exception: - # A list/tuple subclass whose constructor rejects a single iterable; the items - # are already masked, so fall back to a plain list. - return masked_items + return _mask_sequence(value, config, seen, depth) + return _mask_object(value, config, seen, depth) + + +def _mask_sequence(value, config, seen, depth): + if len(value) > _MAX_COLLECTION_ITEMS_TO_SCAN: + return CODE_VARIABLES_TOO_LONG_VALUE + masked_items = [_mask_value(item, config, seen, depth + 1) for item in value] + try: + return type(value)(masked_items) + except Exception: + # A list/tuple subclass whose constructor rejects a single iterable; the items + # are already masked, so fall back to a plain list. + return masked_items + + +def _mask_namedtuple(value, config, seen, depth): + fields = value._fields + if len(fields) > _MAX_COLLECTION_ITEMS_TO_SCAN: + return CODE_VARIABLES_TOO_LONG_VALUE + masked = _mask_mapping(zip(fields, value), config, seen, depth) + masked["__class__"] = _safe_type_name(value) + return masked + +def _mask_object(value, config, seen, depth): # Custom objects: traverse their real attributes so a field named e.g. `password` is # caught by name, rather than repr-scanning (which a custom __repr__ could relabel). attrs = _extract_object_attrs(value) @@ -1813,31 +1914,7 @@ def _encode_variable(value, config, limiter): try: safe = _mask_value(value, config) - if safe is None: - result = "None" - elif isinstance(safe, bool): - result = str(safe) - elif isinstance(safe, float) and not math.isfinite(safe): - # Only reachable when masking is disabled; keep NaN/Infinity out of the JSON. - result = str(safe) - elif isinstance(safe, (int, float)): - # Numbers are emitted as raw JSON numbers, so they skip string truncation. - result_size = len(str(safe)) - if not limiter.can_add(result_size): - return None - limiter.add(result_size) - return safe - elif isinstance(safe, str): - result = safe - else: - # `default` is a safety net for anything _mask_value left non-serializable. - result = json.dumps( - safe, - default=lambda o: _safe_repr(o, config), - allow_nan=False, - ) - - return _finalize(result, limiter, config.max_length) + return _encode_masked_variable(safe, config, limiter) except Exception: # Fail closed: even if json.dumps chokes, re-render through the masking-aware repr. try: @@ -1847,6 +1924,34 @@ def _encode_variable(value, config, limiter): return _finalize(rendered, limiter, config.max_length) +def _encode_masked_variable(safe, config, limiter): + if safe is None: + result = "None" + elif isinstance(safe, bool): + result = str(safe) + elif isinstance(safe, float) and not math.isfinite(safe): + # Only reachable when masking is disabled; keep NaN/Infinity out of the JSON. + result = str(safe) + elif isinstance(safe, (int, float)): + # Numbers are emitted as raw JSON numbers, so they skip string truncation. + result_size = len(str(safe)) + if not limiter.can_add(result_size): + return None + limiter.add(result_size) + return safe + elif isinstance(safe, str): + result = safe + else: + # `default` is a safety net for anything _mask_value left non-serializable. + result = json.dumps( + safe, + default=lambda o: _safe_repr(o, config), + allow_nan=False, + ) + + return _finalize(result, limiter, config.max_length) + + def _is_simple_type(value): return isinstance(value, (type(None), bool, int, float, str)) diff --git a/posthog/feature_flag_evaluations.py b/posthog/feature_flag_evaluations.py index 8ddd10f49..eb4600174 100644 --- a/posthog/feature_flag_evaluations.py +++ b/posthog/feature_flag_evaluations.py @@ -338,13 +338,25 @@ def _record_access(self, key: str, send_feature_flag_events: bool) -> None: return flag = self._flags.get(key) - if flag is None: - response: Optional[FlagValue] = None - elif not flag.enabled: - response = False - else: - response = flag.variant if flag.variant is not None else True + response = _flag_response(flag) + properties = self._get_flag_called_properties(key, flag, response) + self._host.capture_flag_called_event_if_needed( + distinct_id=self._distinct_id, + key=key, + response=response, + groups=self._groups, + disable_geoip=self._disable_geoip, + properties=properties, + has_experiment=flag.has_experiment if flag else None, + minimal_flag_called_events=self._minimal_flag_called_events, + # The record that supplied the value. A remotely evaluated experiment + # split also sends $experiment_exposure, whatever this read returned. + details=flag.details if isinstance(flag, _RemoteFlagRecord) else None, + value_from_details=True, + ) + + def _get_flag_called_properties(self, key, flag, response) -> Dict[str, Any]: properties: Dict[str, Any] = { "$feature_flag": key, "$feature_flag_response": response, @@ -353,20 +365,20 @@ def _record_access(self, key: str, send_feature_flag_events: bool) -> None: } if flag is not None: - if flag.payload is not None: - properties["$feature_flag_payload"] = flag.payload - if flag.id: - properties["$feature_flag_id"] = flag.id - if flag.version: - properties["$feature_flag_version"] = flag.version - if flag.reason: - properties["$feature_flag_reason"] = flag.reason + _add_flag_metadata_properties(properties, flag) if self._request_id: properties["$feature_flag_request_id"] = self._request_id if self._evaluated_at and not (flag and flag.locally_evaluated): properties["$feature_flag_evaluated_at"] = self._evaluated_at + errors = self._get_access_errors(key, flag) + if errors: + properties["$feature_flag_error"] = ",".join(errors) + + return properties + + def _get_access_errors(self, key, flag) -> List[str]: # Build the comma-joined `$feature_flag_error` matching the single-flag path's # granularity: response-level errors (errors-while-computing, quota-limited) are # combined with per-flag errors (flag-missing or local-evaluation-inconclusive) @@ -382,20 +394,26 @@ def _record_access(self, key: str, send_feature_flag_events: bool) -> None: if key in self._unresolved_flags else "flag_missing" ) - if errors: - properties["$feature_flag_error"] = ",".join(errors) + return errors - self._host.capture_flag_called_event_if_needed( - distinct_id=self._distinct_id, - key=key, - response=response, - groups=self._groups, - disable_geoip=self._disable_geoip, - properties=properties, - has_experiment=flag.has_experiment if flag else None, - minimal_flag_called_events=self._minimal_flag_called_events, - # The record that supplied the value. A remotely evaluated experiment - # split also sends $experiment_exposure, whatever this read returned. - details=flag.details if isinstance(flag, _RemoteFlagRecord) else None, - value_from_details=True, - ) + +def _flag_response(flag: Optional[_EvaluatedFlagRecord]) -> Optional[FlagValue]: + if flag is None: + return None + elif not flag.enabled: + return False + else: + return flag.variant if flag.variant is not None else True + + +def _add_flag_metadata_properties( + properties: Dict[str, Any], flag: _EvaluatedFlagRecord +) -> None: + if flag.payload is not None: + properties["$feature_flag_payload"] = flag.payload + if flag.id: + properties["$feature_flag_id"] = flag.id + if flag.version: + properties["$feature_flag_version"] = flag.version + if flag.reason: + properties["$feature_flag_reason"] = flag.reason diff --git a/posthog/feature_flags.py b/posthog/feature_flags.py index 6634ae367..2a5b955cb 100644 --- a/posthog/feature_flags.py +++ b/posthog/feature_flags.py @@ -292,6 +292,41 @@ def evaluate_flag_dependency( _warn_malformed_flag_dependency_once(flag_key, shape_problem) return False + dependency_chain = _get_dependency_chain(property) + _assert_dependency_definitions_loaded( + dependency_chain, flags_by_key, evaluation_cache + ) + _evaluate_dependency_chain( + dependency_chain, + flags_by_key, + evaluation_cache, + distinct_id, + properties, + cohort_properties, + device_id, + property_matching_version, + ) + + # The condition matches iff the referenced flag's value matches the expected + # value. None means inconclusive or not evaluated — distinct from a + # definitive False, which must be allowed to match `expected_value=False`. + actual_value = evaluation_cache.get(flag_key) + if actual_value is None: + # A referenced flag that has no loaded definition or is missing from the + # chain is a definition problem, not an unresolved dependency. + reason = ( + UnresolvedFlagReason.UNRESOLVED_DEPENDENCY + if flag_key in flags_by_key and flag_key in evaluation_cache + else UnresolvedFlagReason.UNSUPPORTED_DEFINITION + ) + raise InconclusiveMatchError( + f"Flag dependency '{flag_key}' was inconclusive or not evaluated", + reason=reason, + ) + return matches_dependency_value(expected_value, actual_value) + + +def _get_dependency_chain(property): # Check if dependency_chain is present - it should always be provided for flag dependencies if "dependency_chain" not in property: # Missing dependency_chain indicates malformed server data @@ -300,6 +335,7 @@ def evaluate_flag_dependency( reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, ) + flag_key = property.get("key") dependency_chain = property["dependency_chain"] if not isinstance(dependency_chain, list): @@ -316,6 +352,12 @@ def evaluate_flag_dependency( reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, ) + return dependency_chain + + +def _assert_dependency_definitions_loaded( + dependency_chain, flags_by_key, evaluation_cache +): # A dependency with no definition outranks one that is only inconclusive, so # check the whole chain before evaluating any of it. missing_dependency = next( @@ -333,86 +375,100 @@ def evaluate_flag_dependency( reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, ) + +def _evaluate_dependency_chain( + dependency_chain, + flags_by_key, + evaluation_cache, + distinct_id, + properties, + cohort_properties, + device_id, + property_matching_version, +): # Evaluate and cache each flag in the chain; members already cached are # skipped. This does not decide the outcome — it only populates the cache. for dep_flag_key in dependency_chain: if dep_flag_key in evaluation_cache: continue + _evaluate_dependency( + dep_flag_key, + flags_by_key, + evaluation_cache, + distinct_id, + properties, + cohort_properties, + device_id, + property_matching_version, + ) - dep_flag = flags_by_key[dep_flag_key] - # Same order as client._compute_flag_locally: an inactive flag is false - # whatever its experience continuity setting. - if not dep_flag.get("active"): - evaluation_cache[dep_flag_key] = False - continue +def _evaluate_dependency( + dep_flag_key, + flags_by_key, + evaluation_cache, + distinct_id, + properties, + cohort_properties, + device_id, + property_matching_version, +): + dep_flag = flags_by_key[dep_flag_key] - if dep_flag.get("ensure_experience_continuity"): - evaluation_cache[dep_flag_key] = None - raise InconclusiveMatchError( - f"Cannot evaluate flag dependency '{dep_flag_key}' - flag has experience continuity enabled", - reason=UnresolvedFlagReason.UNRESOLVED_DEPENDENCY, - ) + # Same order as client._compute_flag_locally: an inactive flag is false + # whatever its experience continuity setting. + if not dep_flag.get("active"): + evaluation_cache[dep_flag_key] = False + return - # Recursively evaluate the dependency - try: - dep_flag_filters = dep_flag.get("filters") or {} - dep_aggregation_group_type_index = dep_flag_filters.get( - "aggregation_group_type_index" - ) - if dep_aggregation_group_type_index is not None: - # Group flags should continue bucketing by the group key - # from the current evaluation context. - dep_bucketing_value = distinct_id - else: - dep_bucketing_value = resolve_bucketing_value( - dep_flag, distinct_id, device_id - ) - dep_result = match_feature_flag_properties( - dep_flag, - distinct_id, - properties, - cohort_properties=cohort_properties, - flags_by_key=flags_by_key, - evaluation_cache=evaluation_cache, - device_id=device_id, - property_matching_version=property_matching_version, - bucketing_value=dep_bucketing_value, - ) - evaluation_cache[dep_flag_key] = dep_result - except RequiresServerEvaluation as e: - # The dependent flag needs the server too, so its later conditions must - # not resolve it locally. Nothing is cached, so another filter on this - # dependency also raises this error. - raise RequiresServerEvaluation( - f"Cannot evaluate flag dependency '{dep_flag_key}': {e}", - reason=UnresolvedFlagReason.UNRESOLVED_DEPENDENCY, - ) from e - except InconclusiveMatchError as e: - # If we can't evaluate a dependency, store None and propagate the error - evaluation_cache[dep_flag_key] = None - raise InconclusiveMatchError( - f"Cannot evaluate flag dependency '{dep_flag_key}': {e}", - reason=UnresolvedFlagReason.UNRESOLVED_DEPENDENCY, - ) from e + if dep_flag.get("ensure_experience_continuity"): + evaluation_cache[dep_flag_key] = None + raise InconclusiveMatchError( + f"Cannot evaluate flag dependency '{dep_flag_key}' - flag has experience continuity enabled", + reason=UnresolvedFlagReason.UNRESOLVED_DEPENDENCY, + ) - # The condition matches iff the referenced flag's value matches the expected - # value. None means inconclusive or not evaluated — distinct from a - # definitive False, which must be allowed to match `expected_value=False`. - actual_value = evaluation_cache.get(flag_key) - if actual_value is None: - # A referenced flag that has no loaded definition or is missing from the - # chain is a definition problem, not an unresolved dependency. - reason = ( - UnresolvedFlagReason.UNRESOLVED_DEPENDENCY - if flag_key in flags_by_key and flag_key in evaluation_cache - else UnresolvedFlagReason.UNSUPPORTED_DEFINITION + # Recursively evaluate the dependency + try: + dep_flag_filters = dep_flag.get("filters") or {} + dep_aggregation_group_type_index = dep_flag_filters.get( + "aggregation_group_type_index" ) - raise InconclusiveMatchError( - f"Flag dependency '{flag_key}' was inconclusive or not evaluated", - reason=reason, + if dep_aggregation_group_type_index is not None: + # Group flags should continue bucketing by the group key + # from the current evaluation context. + dep_bucketing_value = distinct_id + else: + dep_bucketing_value = resolve_bucketing_value( + dep_flag, distinct_id, device_id + ) + dep_result = match_feature_flag_properties( + dep_flag, + distinct_id, + properties, + cohort_properties=cohort_properties, + flags_by_key=flags_by_key, + evaluation_cache=evaluation_cache, + device_id=device_id, + property_matching_version=property_matching_version, + bucketing_value=dep_bucketing_value, ) - return matches_dependency_value(expected_value, actual_value) + evaluation_cache[dep_flag_key] = dep_result + except RequiresServerEvaluation as e: + # The dependent flag needs the server too, so its later conditions must + # not resolve it locally. Nothing is cached, so another filter on this + # dependency also raises this error. + raise RequiresServerEvaluation( + f"Cannot evaluate flag dependency '{dep_flag_key}': {e}", + reason=UnresolvedFlagReason.UNRESOLVED_DEPENDENCY, + ) from e + except InconclusiveMatchError as e: + # If we can't evaluate a dependency, store None and propagate the error + evaluation_cache[dep_flag_key] = None + raise InconclusiveMatchError( + f"Cannot evaluate flag dependency '{dep_flag_key}': {e}", + reason=UnresolvedFlagReason.UNRESOLVED_DEPENDENCY, + ) from e def matches_dependency_value(expected_value, actual_value): @@ -499,19 +555,7 @@ def match_feature_flag_properties( flag_filters = flag.get("filters") or {} if flag_filters.get("feature_enrollment") is True: - enrollment_key = f"$feature_enrollment/{flag.get('key')}" - if flag_filters.get("aggregation_group_type_index") is not None: - raise InconclusiveMatchError( - "Group flag has feature enrollment, which reads person properties", - reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, - ) - if enrollment_key not in properties: - raise InconclusiveMatchError( - f"Flag has feature enrollment and '{enrollment_key}' was not passed", - reason=UnresolvedFlagReason.MISSING_CONTEXT, - ) - enrollment = properties[enrollment_key] - return enrollment is True or enrollment == "true" + return _match_feature_enrollment(flag, flag_filters, properties) # Holdouts are evaluated before release conditions, so a held-out value is excluded # from the flag's targeting entirely rather than being bucketed into a variant. @@ -519,101 +563,89 @@ def match_feature_flag_properties( if holdout_variant is not None: return holdout_variant + return _match_flag_conditions( + flag, + flag_filters, + distinct_id, + properties, + cohort_properties or {}, + flags_by_key, + evaluation_cache, + device_id, + bucketing_value, + group_type_mapping or {}, + groups or {}, + group_properties or {}, + property_matching_version, + ) + + +def _match_flag_conditions( + flag, + flag_filters, + distinct_id, + properties, + cohort_properties, + flags_by_key, + evaluation_cache, + device_id, + bucketing_value, + group_type_mapping, + groups, + group_properties, + property_matching_version, +) -> FlagValue: flag_conditions = flag_filters.get("groups") or [] flag_aggregation = flag_filters.get("aggregation_group_type_index") early_exit_enabled = flag_filters.get("early_exit") inconclusive_reason: Optional[UnresolvedFlagReason] = None - cohort_properties = cohort_properties or {} - groups = groups or {} - group_properties = group_properties or {} - group_type_mapping = group_type_mapping or {} - # Some filters can be explicitly set to null, which require accessing variants like so - flag_variants = (flag_filters.get("multivariate") or {}).get("variants") or [] - valid_variant_keys = [variant["key"] for variant in flag_variants] + valid_variant_keys = _get_valid_variant_keys(flag_filters) for condition in flag_conditions: try: - # Per-condition aggregation overrides only when the condition explicitly - # sets its own aggregation_group_type_index (mixed targeting). - # When absent, use the properties/bucketing already resolved by the caller. - condition_aggregation = condition.get( - "aggregation_group_type_index", flag_aggregation - ) - - # Mixed-override path: condition-level aggregation differs from flag-level. - # This assumes flag-level aggregation is None for mixed flags. - if condition_aggregation != flag_aggregation: - if condition_aggregation is not None: - group_name = group_type_mapping.get(str(condition_aggregation)) - if not group_name or group_name not in groups: - log.debug( - "Skipping group condition for flag '%s': group type index %s not available", - flag.get("key", ""), - condition_aggregation, - ) - continue - if group_name not in group_properties: - inconclusive_reason = _pick_unresolved_reason( - inconclusive_reason, UnresolvedFlagReason.MISSING_CONTEXT - ) - continue - effective_properties = group_properties[group_name] - effective_bucketing = groups[group_name] - else: - effective_properties = properties - effective_bucketing = bucketing_value - else: - effective_properties = properties - effective_bucketing = bucketing_value - - match_result = is_condition_match( + match_result, value = _match_flag_condition( flag, distinct_id, condition, - effective_properties, + properties, cohort_properties, flags_by_key, evaluation_cache, - bucketing_value=effective_bucketing, - device_id=device_id, - property_matching_version=property_matching_version, + device_id, + bucketing_value, + group_type_mapping, + groups, + group_properties, + property_matching_version, + flag_aggregation, + valid_variant_keys, ) - if match_result == ConditionMatch.MATCH: - variant_override = condition.get("variant") - if variant_override and variant_override in valid_variant_keys: - variant = variant_override - else: - variant = get_matching_variant(flag, effective_bucketing) - return variant or True - elif ( - early_exit_enabled - and match_result == ConditionMatch.OUT_OF_ROLLOUT_BOUND - ): - # The condition's property filters (if any) matched and only the rollout check - # failed, so re-evaluating later groups can't change the outcome. If an earlier - # condition was inconclusive, stop here but preserve that result for fallback. - if inconclusive_reason is not None: - break - return False except RequiresServerEvaluation as e: - # Static cohort or other missing server-side data - must fallback to API. - # The loop stops here, so a filter it did not reach can still carry a - # higher-precedence reason in the flag's definition. - try: - definition_reason = _get_definition_unresolved_reason( - flag, flags_by_key or {}, cohort_properties, group_type_mapping - ) - except Exception: - # A malformed definition must not stop the fallback to the server. - definition_reason = None - if definition_reason is not None: - e.reason = _pick_unresolved_reason(e.reason, definition_reason) + _enrich_server_evaluation_reason( + e, + flag, + flags_by_key, + cohort_properties, + group_type_mapping, + ) raise except InconclusiveMatchError as e: # Evaluation error (bad regex, invalid date, missing property, etc.) # Track that we had an inconclusive match, but try other conditions inconclusive_reason = _pick_unresolved_reason(inconclusive_reason, e.reason) + continue + if match_result == ConditionMatch.MATCH: + return value + elif early_exit_enabled and match_result == ConditionMatch.OUT_OF_ROLLOUT_BOUND: + # The condition's property filters (if any) matched and only the rollout check + # failed, so re-evaluating later groups can't change the outcome. If an earlier + # condition was inconclusive, stop here but preserve that result for fallback. + return _unmatched_flag_result(inconclusive_reason) + + return _unmatched_flag_result(inconclusive_reason) + +def _unmatched_flag_result(inconclusive_reason) -> bool: if inconclusive_reason is not None: raise InconclusiveMatchError( "Can't determine if feature flag is enabled or not with given properties", @@ -625,6 +657,143 @@ def match_feature_flag_properties( return False +def _get_condition_context( + flag, + condition, + flag_aggregation, + properties, + bucketing_value, + group_type_mapping, + groups, + group_properties, +): + # Per-condition aggregation overrides only when the condition explicitly + # sets its own aggregation_group_type_index (mixed targeting). + # When absent, use the properties/bucketing already resolved by the caller. + condition_aggregation = condition.get( + "aggregation_group_type_index", flag_aggregation + ) + + # Mixed-override path: condition-level aggregation differs from flag-level. + # This assumes flag-level aggregation is None for mixed flags. + if condition_aggregation != flag_aggregation: + if condition_aggregation is not None: + group_name = group_type_mapping.get(str(condition_aggregation)) + if not group_name or group_name not in groups: + log.debug( + "Skipping group condition for flag '%s': group type index %s not available", + flag.get("key", ""), + condition_aggregation, + ) + return None + if group_name not in group_properties: + raise InconclusiveMatchError( + "Group properties were not passed", + reason=UnresolvedFlagReason.MISSING_CONTEXT, + ) + effective_properties = group_properties[group_name] + effective_bucketing = groups[group_name] + else: + effective_properties = properties + effective_bucketing = bucketing_value + else: + effective_properties = properties + effective_bucketing = bucketing_value + + return effective_properties, effective_bucketing + + +def _match_flag_condition( + flag, + distinct_id, + condition, + properties, + cohort_properties, + flags_by_key, + evaluation_cache, + device_id, + bucketing_value, + group_type_mapping, + groups, + group_properties, + property_matching_version, + flag_aggregation, + valid_variant_keys, +): + context = _get_condition_context( + flag, + condition, + flag_aggregation, + properties, + bucketing_value, + group_type_mapping, + groups, + group_properties, + ) + if context is None: + return ConditionMatch.NO_MATCH, None + effective_properties, effective_bucketing = context + match_result = is_condition_match( + flag, + distinct_id, + condition, + effective_properties, + cohort_properties, + flags_by_key, + evaluation_cache, + bucketing_value=effective_bucketing, + device_id=device_id, + property_matching_version=property_matching_version, + ) + if match_result == ConditionMatch.MATCH: + variant_override = condition.get("variant") + if variant_override and variant_override in valid_variant_keys: + variant = variant_override + else: + variant = get_matching_variant(flag, effective_bucketing) + return match_result, variant or True + return match_result, None + + +def _enrich_server_evaluation_reason( + e, flag, flags_by_key, cohort_properties, group_type_mapping +): + # Static cohort or other missing server-side data - must fallback to API. + # The loop stops here, so a filter it did not reach can still carry a + # higher-precedence reason in the flag's definition. + try: + definition_reason = _get_definition_unresolved_reason( + flag, flags_by_key or {}, cohort_properties, group_type_mapping + ) + except Exception: + # A malformed definition must not stop the fallback to the server. + definition_reason = None + if definition_reason is not None: + e.reason = _pick_unresolved_reason(e.reason, definition_reason) + + +def _get_valid_variant_keys(flag_filters): + # Some filters can be explicitly set to null, which require accessing variants like so + flag_variants = (flag_filters.get("multivariate") or {}).get("variants") or [] + return [variant["key"] for variant in flag_variants] + + +def _match_feature_enrollment(flag, flag_filters, properties) -> bool: + enrollment_key = f"$feature_enrollment/{flag.get('key')}" + if flag_filters.get("aggregation_group_type_index") is not None: + raise InconclusiveMatchError( + "Group flag has feature enrollment, which reads person properties", + reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, + ) + if enrollment_key not in properties: + raise InconclusiveMatchError( + f"Flag has feature enrollment and '{enrollment_key}' was not passed", + reason=UnresolvedFlagReason.MISSING_CONTEXT, + ) + enrollment = properties[enrollment_key] + return enrollment is True or enrollment == "true" + + def _match_condition_filter( prop, properties, @@ -677,57 +846,18 @@ def is_condition_match( ) -> ConditionMatch: rollout_percentage = condition.get("rollout_percentage") if len(condition.get("properties") or []) > 0: - # Filters in a condition have no defined order, so an inconclusive filter does - # not stop the loop: a later filter can still rule the condition out or carry a - # higher-precedence reason. - inconclusive_reason: Optional[UnresolvedFlagReason] = None - server_evaluation_error: Optional[RequiresServerEvaluation] = None - for prop in condition.get("properties"): - try: - matches = _match_condition_filter( - prop, - properties, - cohort_properties, - flags_by_key, - evaluation_cache, - distinct_id, - device_id=device_id, - property_matching_version=property_matching_version, - ) - except RequiresServerEvaluation as e: - # Fall back to the server only when this is the first filter that could - # not be checked, as when the loop stopped there. After another - # inconclusive filter, later conditions must still be able to resolve - # the flag locally. - if inconclusive_reason is None: - server_evaluation_error = e - inconclusive_reason = _pick_unresolved_reason( - inconclusive_reason, e.reason - ) - continue - except InconclusiveMatchError as e: - inconclusive_reason = _pick_unresolved_reason( - inconclusive_reason, e.reason - ) - continue - except Exception: - # After an inconclusive filter, an unexpected error ends the condition - # as inconclusive, so later conditions can still resolve the flag. - if inconclusive_reason is None: - raise - break - if not matches: - return ConditionMatch.NO_MATCH - - # Re-raise the original error type: match_feature_flag_properties stops at it - # and falls back to the server instead of trying later conditions. - if server_evaluation_error is not None: - raise server_evaluation_error - if inconclusive_reason is not None: - raise InconclusiveMatchError( - f"Can't determine if a condition of flag {feature_flag.get('key')} matches", - reason=inconclusive_reason, - ) + if not _match_condition_properties( + feature_flag, + distinct_id, + condition, + properties, + cohort_properties, + flags_by_key, + evaluation_cache, + device_id, + property_matching_version, + ): + return ConditionMatch.NO_MATCH if rollout_percentage is None: return ConditionMatch.MATCH @@ -742,6 +872,71 @@ def is_condition_match( return ConditionMatch.MATCH +def _match_condition_properties( + feature_flag, + distinct_id, + condition, + properties, + cohort_properties, + flags_by_key, + evaluation_cache, + device_id, + property_matching_version, +) -> bool: + # Filters in a condition have no defined order, so an inconclusive filter does + # not stop the loop: a later filter can still rule the condition out or carry a + # higher-precedence reason. + inconclusive_reason: Optional[UnresolvedFlagReason] = None + server_evaluation_error: Optional[RequiresServerEvaluation] = None + for prop in condition.get("properties"): + try: + matches = _match_condition_filter( + prop, + properties, + cohort_properties, + flags_by_key, + evaluation_cache, + distinct_id, + device_id=device_id, + property_matching_version=property_matching_version, + ) + except RequiresServerEvaluation as e: + # Fall back to the server only when this is the first filter that could + # not be checked, as when the loop stopped there. After another + # inconclusive filter, later conditions must still be able to resolve + # the flag locally. + if inconclusive_reason is None: + server_evaluation_error = e + inconclusive_reason = _pick_unresolved_reason(inconclusive_reason, e.reason) + continue + except InconclusiveMatchError as e: + inconclusive_reason = _pick_unresolved_reason(inconclusive_reason, e.reason) + continue + except Exception: + # After an inconclusive filter, an unexpected error ends the condition + # as inconclusive, so later conditions can still resolve the flag. + if inconclusive_reason is None: + raise + break + if not matches: + return False + + _raise_condition_errors(feature_flag, server_evaluation_error, inconclusive_reason) + return True + + +def _raise_condition_errors(feature_flag, server_evaluation_error, inconclusive_reason): + # Re-raise the original error type: match_feature_flag_properties stops at it + # and falls back to the server instead of trying later conditions. + if server_evaluation_error is not None: + raise server_evaluation_error + if inconclusive_reason is not None: + raise InconclusiveMatchError( + f"Can't determine if a condition of flag {feature_flag.get('key')} matches", + reason=inconclusive_reason, + ) + + # Raised when an operator passes the PROPERTY_OPERATORS gate but has no dispatch # branch in match_property. Distinct from the unknown-operator rejection at the top # of the function so the dispatch-completeness test can tell the two apart. @@ -775,6 +970,17 @@ def _format_json_float(value: float, reason: UnresolvedFlagReason) -> str: def _json_value_to_string(value, reason: UnresolvedFlagReason) -> str: + if isinstance(value, list): + return ( + "[" + ",".join(_json_value_to_string(item, reason) for item in value) + "]" + ) + if isinstance(value, dict): + return _json_object_to_string(value, reason) + + return _json_scalar_to_string(value, reason) + + +def _json_scalar_to_string(value, reason: UnresolvedFlagReason) -> str: if value is None: return "null" if isinstance(value, bool): @@ -785,28 +991,25 @@ def _json_value_to_string(value, reason: UnresolvedFlagReason) -> str: return str(value) if isinstance(value, float): return _format_json_float(value, reason) - if isinstance(value, list): - return ( - "[" + ",".join(_json_value_to_string(item, reason) for item in value) + "]" - ) - if isinstance(value, dict): - if not all(isinstance(key, str) for key in value): - raise InconclusiveMatchError( - "Property object keys must be strings for local evaluation", - reason=reason, - ) - items = ( - f"{json.dumps(key, ensure_ascii=False)}:{_json_value_to_string(value[key], reason)}" - for key in sorted(value) - ) - return "{" + ",".join(items) + "}" - raise InconclusiveMatchError( f"Property value of type {type(value).__name__} is not JSON-compatible", reason=reason, ) +def _json_object_to_string(value: dict, reason: UnresolvedFlagReason) -> str: + if not all(isinstance(key, str) for key in value): + raise InconclusiveMatchError( + "Property object keys must be strings for local evaluation", + reason=reason, + ) + items = ( + f"{json.dumps(key, ensure_ascii=False)}:{_json_value_to_string(value[key], reason)}" + for key in sorted(value) + ) + return "{" + ",".join(items) + "}" + + def _value_to_string(value, reason: UnresolvedFlagReason) -> str: if isinstance(value, str): return value @@ -862,159 +1065,202 @@ class _RegexMetadata(NamedTuple): uses_quantifier_or_alternation: bool -@_lru_cache(maxsize=256) -def _compile_regex(pattern: str) -> Optional[_RegexMetadata]: - """Cache only pattern metadata; exceptions are not retained by lru_cache.""" - # Successful re compilation alone does not establish Rust/fancy-regex compatibility. - translated = [] - class_start = None - previous = "" - group_has_quantifier = [] - closed_group_has_quantifier = False - uses_word_class = False - uses_space_class = False - uses_end_anchor = False - uses_quantifier_or_alternation = False - index = 0 - - def defer() -> NoReturn: - raise InconclusiveMatchError( - "Regex requires server evaluation", - reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, - ) +def _defer_regex() -> NoReturn: + raise InconclusiveMatchError( + "Regex requires server evaluation", + reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, + ) - while index < len(pattern): - character = pattern[index] - if 0xD800 <= ord(character) <= 0xDFFF: - defer() - if class_start is None: - uses_end_anchor |= character == "$" - uses_quantifier_or_alternation |= character in "*+?{|" - if character == "(": - group_has_quantifier.append(False) - elif character == ")": - closed_group_has_quantifier = ( - group_has_quantifier.pop() if group_has_quantifier else False - ) - if group_has_quantifier: - group_has_quantifier[-1] |= closed_group_has_quantifier - elif character in "*+?{": - # Strict anchors can turn nested repetition into expensive backtracking. - if previous == ")" and closed_group_has_quantifier: - defer() - if group_has_quantifier: - group_has_quantifier[-1] = True + +class _RegexTranslator: + """Scan Python/Rust shared syntax, retaining the metadata needed at match time.""" + + def __init__(self, pattern: str) -> None: + self.pattern = pattern + self.translated: list[str] = [] + self.class_start: Optional[int] = None + self.previous = "" + self.group_has_quantifier: list[bool] = [] + self.closed_group_has_quantifier = False + self.uses_word_class = False + self.uses_space_class = False + self.uses_end_anchor = False + self.uses_quantifier_or_alternation = False + self.index = 0 + + def translate(self) -> str: + while self.index < len(self.pattern): + character = self.pattern[self.index] + if 0xD800 <= ord(character) <= 0xDFFF: + _defer_regex() + if self.class_start is None: + self._scan_group(character) + self._translate_character(character) + self.index += 1 + return "".join(self.translated) + + def _scan_group(self, character: str) -> None: + self.uses_end_anchor |= character == "$" + self.uses_quantifier_or_alternation |= character in "*+?{|" + if character == "(": + self.group_has_quantifier.append(False) + elif character == ")": + self.closed_group_has_quantifier = ( + self.group_has_quantifier.pop() if self.group_has_quantifier else False + ) + if self.group_has_quantifier: + self.group_has_quantifier[-1] |= self.closed_group_has_quantifier + elif character in "*+?{": + # Strict anchors can turn nested repetition into expensive backtracking. + if self.previous == ")" and self.closed_group_has_quantifier: + _defer_regex() + if self.group_has_quantifier: + self.group_has_quantifier[-1] = True + + def _translate_character(self, character: str) -> None: if character == "\\": - index += 1 - if index == len(pattern): - translated.append("\\") - break - escaped = pattern[index] - if escaped == "x": - digits = pattern[index + 1 : index + 3] - if len(digits) != 2 or any( - c not in "0123456789abcdefABCDEF" for c in digits - ): - defer() - translated.append("\\x" + digits) - index += 3 - previous = "literal" - continue - if escaped in "bB<>" and class_start is None: - # Even short ASCII word-boundary searches can exceed the service's step limit. - defer() - if escaped not in "dDsSwWbfnrt": - if not (0x20 <= ord(escaped) <= 0x7E and not escaped.isalnum()): - defer() - if class_start is not None and escaped not in r"\-[]^.$*+?(){}|": - defer() - uses_word_class |= escaped in "wW" - uses_space_class |= escaped in "sS" - translated.append("\\" + escaped) - previous = "literal" + self._translate_escape() elif character == "[": - if class_start is not None: - defer() - class_start = index - translated.append(character) - elif character == "]" and class_start is not None: - content_start = class_start + ( - 2 if pattern[class_start + 1 : class_start + 2] == "^" else 1 - ) - if index == content_start: - defer() - class_start = None - previous = "literal" - translated.append(character) - elif class_start is not None: - if pattern[index : index + 2] in ("&&", "--", "~~"): - defer() - # Rust and Python disagree on shorthand endpoints in ranges. - if ( - character == "-" - and index + 1 < len(pattern) - and pattern[index + 1] != "]" - ): - if pattern[index + 1 : index + 3] in ( - r"\d", - r"\D", - r"\s", - r"\S", - r"\w", - r"\W", - ) or ( - index >= 2 - and pattern[index - 2] == "\\" - and pattern[index - 1] in "dDsSwW" - ): - defer() - translated.append(character) - elif character == "(" and pattern[index + 1 : index + 2] == "?": - if pattern[index + 2 : index + 3] != ":": - defer() - translated.append("(?:") - index += 2 - previous = "(" + if self.class_start is not None: + _defer_regex() + self.class_start = self.index + self.translated.append(character) + elif character == "]" and self.class_start is not None: + self._close_class() + elif self.class_start is not None: + self._translate_class_character(character) + else: + self._translate_outside_class(character) + + def _translate_escape(self) -> None: + self.index += 1 + if self.index == len(self.pattern): + self.translated.append("\\") + return + escaped = self.pattern[self.index] + if escaped == "x": + self._translate_hex_escape() + return + if escaped in "bB<>" and self.class_start is None: + # Even short ASCII word-boundary searches can exceed the service's step limit. + _defer_regex() + self._assert_escape_supported(escaped) + self.uses_word_class |= escaped in "wW" + self.uses_space_class |= escaped in "sS" + self.translated.append("\\" + escaped) + self.previous = "literal" + + def _translate_hex_escape(self) -> None: + digits = self.pattern[self.index + 1 : self.index + 3] + if len(digits) != 2 or any(c not in "0123456789abcdefABCDEF" for c in digits): + _defer_regex() + self.translated.append("\\x" + digits) + # The outer scan advances the last character of the escape. + self.index += 2 + self.previous = "literal" + + def _assert_escape_supported(self, escaped: str) -> None: + if escaped not in "dDsSwWbfnrt": + if not (0x20 <= ord(escaped) <= 0x7E and not escaped.isalnum()): + _defer_regex() + if self.class_start is not None and escaped not in r"\-[]^.$*+?(){}|": + _defer_regex() + + def _close_class(self) -> None: + assert self.class_start is not None + content_start = self.class_start + ( + 2 if self.pattern[self.class_start + 1 : self.class_start + 2] == "^" else 1 + ) + if self.index == content_start: + _defer_regex() + self.class_start = None + self.previous = "literal" + self.translated.append("]") + + def _translate_class_character(self, character: str) -> None: + if self.pattern[self.index : self.index + 2] in ("&&", "--", "~~"): + _defer_regex() + # Rust and Python disagree on shorthand endpoints in ranges. + if ( + character == "-" + and self.index + 1 < len(self.pattern) + and self.pattern[self.index + 1] != "]" + ): + self._assert_range_supported() + self.translated.append(character) + + def _assert_range_supported(self) -> None: + if self.pattern[self.index + 1 : self.index + 3] in ( + r"\d", + r"\D", + r"\s", + r"\S", + r"\w", + r"\W", + ) or ( + self.index >= 2 + and self.pattern[self.index - 2] == "\\" + and self.pattern[self.index - 1] in "dDsSwW" + ): + _defer_regex() + + def _translate_outside_class(self, character: str) -> None: + if character == "(" and self.pattern[self.index + 1 : self.index + 2] == "?": + if self.pattern[self.index + 2 : self.index + 3] != ":": + _defer_regex() + self.translated.append("(?:") + self.index += 2 + self.previous = "(" elif character == "{": - repetition = re.match(r"\{([0-9]+)(?:,([0-9]*))?\}", pattern[index:]) - if repetition is None or previous in ( - "", - "|", - "(", - "^", - "$", - "empty group", - "quantifier", - ): - defer() - if any( - len(n) > 10 or int(n) > 0xFFFFFFFF for n in repetition.groups() if n - ): - defer() - translated.append(repetition.group()) - index += len(repetition.group()) - 1 - if pattern[index + 1 : index + 2] in ("+", "{"): - defer() - previous = "quantifier" + self._translate_repetition() else: - if character in "*+?": - if previous in ("^", "$", "empty group") or pattern[ - index + 1 : index + 2 - ] in ("+", "{"): - defer() - previous = "quantifier" - else: - previous = ( - "empty group" - if character == ")" and previous in ("(", "empty group") - else character - ) - # Python's $ also matches before a final newline; Rust's default $ is strict. - translated.append(r"\Z" if character == "$" else character) - index += 1 + self._translate_literal_or_quantifier(character) + + def _translate_repetition(self) -> None: + repetition = re.match(r"\{([0-9]+)(?:,([0-9]*))?\}", self.pattern[self.index :]) + if repetition is None or self.previous in ( + "", + "|", + "(", + "^", + "$", + "empty group", + "quantifier", + ): + _defer_regex() + if any(len(n) > 10 or int(n) > 0xFFFFFFFF for n in repetition.groups() if n): + _defer_regex() + self.translated.append(repetition.group()) + self.index += len(repetition.group()) - 1 + if self.pattern[self.index + 1 : self.index + 2] in ("+", "{"): + _defer_regex() + self.previous = "quantifier" + + def _translate_literal_or_quantifier(self, character: str) -> None: + if character in "*+?": + if self.previous in ("^", "$", "empty group") or self.pattern[ + self.index + 1 : self.index + 2 + ] in ("+", "{"): + _defer_regex() + self.previous = "quantifier" + else: + self.previous = ( + "empty group" + if character == ")" and self.previous in ("(", "empty group") + else character + ) + # Python's $ also matches before a final newline; Rust's default $ is strict. + self.translated.append(r"\Z" if character == "$" else character) + +@_lru_cache(maxsize=256) +def _compile_regex(pattern: str) -> Optional[_RegexMetadata]: + """Cache only pattern metadata; exceptions are not retained by lru_cache.""" + # Successful re compilation alone does not establish Rust/fancy-regex compatibility. + translator = _RegexTranslator(pattern) + translated = translator.translate() try: - regex = re.compile("".join(translated)) + regex = re.compile(translated) except re.error: return None except Exception as error: @@ -1025,10 +1271,10 @@ def defer() -> NoReturn: return _RegexMetadata( regex, - uses_word_class, - uses_space_class, - uses_end_anchor, - uses_quantifier_or_alternation, + translator.uses_word_class, + translator.uses_space_class, + translator.uses_end_anchor, + translator.uses_quantifier_or_alternation, ) @@ -1039,42 +1285,42 @@ def _match_regex(pattern: str, value: str) -> Optional[bool]: metadata = _compile_regex(pattern) if metadata is None: return None - ( - regex, - uses_word_class, - uses_space_class, - uses_end_anchor, - uses_quantifier_or_alternation, - ) = metadata + regex = metadata.regex - def defer() -> NoReturn: + _assert_regex_value_supported(metadata, value) + try: + return regex.search(value) is not None + except Exception as error: raise InconclusiveMatchError( - "Regex requires server evaluation", + "Regex execution requires server evaluation", reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, - ) + ) from error + +def _assert_regex_value_supported(metadata: _RegexMetadata, value: str) -> None: # Tightening $ can expose backtracking on a final LF, including repeated alternatives. - if uses_end_anchor and uses_quantifier_or_alternation and value.endswith("\n"): - defer() + if ( + metadata.uses_end_anchor + and metadata.uses_quantifier_or_alternation + and value.endswith("\n") + ): + _defer_regex() # Unicode letters/decimal digits agree, but Rust's word class also includes marks and # joiners, while Python includes other numbers. Python's whitespace adds U+001C..U+001F. if not value.isascii(): - if any(0xD800 <= ord(c) <= 0xDFFF for c in value): - defer() - if uses_word_class and any( - not c.isascii() and not (c.isalpha() or c.isdecimal()) for c in value - ): - defer() - if uses_space_class and any(c in value for c in "\x1c\x1d\x1e\x1f"): - defer() - try: - return regex.search(value) is not None - except Exception as error: - raise InconclusiveMatchError( - "Regex execution requires server evaluation", - reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, - ) from error + _assert_regex_unicode_supported(metadata, value) + if metadata.uses_space_class and any(c in value for c in "\x1c\x1d\x1e\x1f"): + _defer_regex() + + +def _assert_regex_unicode_supported(metadata: _RegexMetadata, value: str) -> None: + if any(0xD800 <= ord(c) <= 0xDFFF for c in value): + _defer_regex() + if metadata.uses_word_class and any( + not c.isascii() and not (c.isalpha() or c.isdecimal()) for c in value + ): + _defer_regex() _TEXT_OPERATORS = ( @@ -1159,7 +1405,12 @@ def _assert_filter_supported(property) -> None: _value_to_string(item, UnresolvedFlagReason.UNSUPPORTED_DEFINITION) elif operator in _TEXT_OPERATORS: _value_to_string(value, UnresolvedFlagReason.UNSUPPORTED_DEFINITION) - elif operator in ("regex", "not_regex"): + else: + _assert_parsed_filter_supported(operator, value) + + +def _assert_parsed_filter_supported(operator, value) -> None: + if operator in ("regex", "not_regex"): pattern = str(value) if pattern: _compile_regex(pattern) @@ -1212,148 +1463,166 @@ def _match_property_value( override_value = property_values[key] if operator in NUMERIC_OPERATORS: - parsed_value = _parse_numeric_filter(value) - parsed_override = _parse_numeric_value(override_value) - if parsed_override is None: - return False - if operator == "gt": - return parsed_override > parsed_value - if operator == "gte": - return parsed_override >= parsed_value - if operator == "lt": - return parsed_override < parsed_value - return parsed_override <= parsed_value + return _match_numeric_property(operator, value, override_value) - if ( + if _is_unmatchable_null(operator, override_value): + return False + + if operator in ("exact", "is_not"): + matched = _match_exact_property( + value, override_value, property_matching_version + ) + return matched if operator == "exact" else not matched + + return _match_scalar_property(operator, value, override_value) + + +def _is_unmatchable_null(operator, override_value) -> bool: + return ( operator not in NONE_VALUES_ALLOWED_OPERATORS and operator not in STRING_OPERATORS and operator != "exact" and override_value is None - ): - return False + ) - if operator in ("exact", "is_not"): - def compute_exact_match(value, override_value): - override_string = _value_to_string( - override_value, UnresolvedFlagReason.MISSING_CONTEXT +def _match_numeric_property(operator, value, override_value) -> bool: + parsed_value = _parse_numeric_filter(value) + parsed_override = _parse_numeric_value(override_value) + if parsed_override is None: + return False + if operator == "gt": + return parsed_override > parsed_value + if operator == "gte": + return parsed_override >= parsed_value + if operator == "lt": + return parsed_override < parsed_value + return parsed_override <= parsed_value + + +def _match_exact_property(value, override_value, property_matching_version) -> bool: + override_string = _value_to_string( + override_value, UnresolvedFlagReason.MISSING_CONTEXT + ).lower() + # Empty filters retain recursive truthiness in both matching modes. + if value == []: + return _is_truthy_property_value(override_value) + if property_matching_version != 2 and _is_truthy_or_falsy_property_value(value): + return _is_truthy_property_value(value) == _is_truthy_property_value( + override_value + ) + + if isinstance(value, list): + return override_string in [ + _value_to_string( + candidate, UnresolvedFlagReason.UNSUPPORTED_DEFINITION ).lower() - # Empty filters retain recursive truthiness in both matching modes. - if value == []: - return _is_truthy_property_value(override_value) - if property_matching_version != 2 and _is_truthy_or_falsy_property_value( - value - ): - return _is_truthy_property_value(value) == _is_truthy_property_value( - override_value - ) + for candidate in value + ] + return ( + _value_to_string(value, UnresolvedFlagReason.UNSUPPORTED_DEFINITION).lower() + == override_string + ) - if isinstance(value, list): - return override_string in [ - _value_to_string( - candidate, UnresolvedFlagReason.UNSUPPORTED_DEFINITION - ).lower() - for candidate in value - ] - return ( - _value_to_string( - value, UnresolvedFlagReason.UNSUPPORTED_DEFINITION - ).lower() - == override_string - ) - if operator == "exact": - return compute_exact_match(value, override_value) - else: - return not compute_exact_match(value, override_value) +def _match_text_property(operator, value, override_value) -> bool: + property_string = _ascii_lower(override_value, UnresolvedFlagReason.MISSING_CONTEXT) + filter_string = _ascii_lower(value, UnresolvedFlagReason.UNSUPPORTED_DEFINITION) - if operator in _TEXT_OPERATORS: - property_string = _ascii_lower( - override_value, UnresolvedFlagReason.MISSING_CONTEXT - ) - filter_string = _ascii_lower(value, UnresolvedFlagReason.UNSUPPORTED_DEFINITION) + if operator in ("icontains", "not_icontains"): + matched = filter_string in property_string + elif operator in ("starts_with", "not_starts_with"): + matched = property_string.startswith(filter_string) + else: + matched = property_string.endswith(filter_string) - if operator in ("icontains", "not_icontains"): - matched = filter_string in property_string - elif operator in ("starts_with", "not_starts_with"): - matched = property_string.startswith(filter_string) - else: - matched = property_string.endswith(filter_string) + return not matched if operator.startswith("not_") else matched - if operator.startswith("not_"): - return not matched - return matched - if operator in ("regex", "not_regex"): - property_string = _value_to_string( - override_value, UnresolvedFlagReason.MISSING_CONTEXT - ) - regex_match = _match_regex(str(value), property_string) - if regex_match is None: - return False - return not regex_match if operator == "not_regex" else regex_match +def _match_regex_property(operator, value, override_value) -> bool: + property_string = _value_to_string( + override_value, UnresolvedFlagReason.MISSING_CONTEXT + ) + regex_match = _match_regex(str(value), property_string) + if regex_match is None: + return False + return not regex_match if operator == "not_regex" else regex_match - if operator in DATE_OPERATORS: - parsed_date = _parse_date_filter(value) - - if isinstance(override_value, datetime.datetime): - override_date = convert_to_datetime_aware(override_value) - if operator == "is_date_before": - return override_date < parsed_date - else: - return override_date > parsed_date - elif isinstance(override_value, datetime.date): - if operator == "is_date_before": - return override_value < parsed_date.date() - else: - return override_value > parsed_date.date() - elif isinstance(override_value, str): - try: - override_date = parse_datetime(override_value) - override_date = convert_to_datetime_aware(override_date) - if operator == "is_date_before": - return override_date < parsed_date - else: - return override_date > parsed_date - except Exception: - raise InconclusiveMatchError( - "The date provided is not a valid format", - reason=UnresolvedFlagReason.MISSING_CONTEXT, - ) - else: - raise InconclusiveMatchError( - "The date provided must be a string or date object", - reason=UnresolvedFlagReason.MISSING_CONTEXT, - ) - if operator in SEMVER_OPERATORS: - flag_semver = _parse_semver_filter(operator, value) +def _match_date_property(operator, value, override_value) -> bool: + parsed_date = _parse_date_filter(value) + + if isinstance(override_value, datetime.datetime): + override_date = convert_to_datetime_aware(override_value) + return _compare_dates(operator, override_date, parsed_date) + elif isinstance(override_value, datetime.date): + return _compare_dates(operator, override_value, parsed_date.date()) + elif isinstance(override_value, str): try: - override_parsed = parse_semver(override_value) - except (ValueError, TypeError): + override_date = parse_datetime(override_value) + override_date = convert_to_datetime_aware(override_date) + return _compare_dates(operator, override_date, parsed_date) + except Exception: raise InconclusiveMatchError( - f"Person property value '{override_value}' is not a valid semver", + "The date provided is not a valid format", reason=UnresolvedFlagReason.MISSING_CONTEXT, ) + else: + raise InconclusiveMatchError( + "The date provided must be a string or date object", + reason=UnresolvedFlagReason.MISSING_CONTEXT, + ) + + +def _compare_dates(operator, override_date, parsed_date) -> bool: + if operator == "is_date_before": + return override_date < parsed_date + return override_date > parsed_date + - if operator in SEMVER_RANGE_OPERATORS: - lower, upper = flag_semver - return lower <= override_parsed < upper - if operator == "semver_eq": - return override_parsed == flag_semver - if operator == "semver_neq": - return override_parsed != flag_semver - if operator == "semver_gt": - return override_parsed > flag_semver - if operator == "semver_gte": - return override_parsed >= flag_semver - if operator == "semver_lt": - return override_parsed < flag_semver - if operator == "semver_lte": - return override_parsed <= flag_semver +def _match_semver_property(operator, value, override_value) -> bool: + flag_semver = _parse_semver_filter(operator, value) + try: + override_parsed = parse_semver(override_value) + except (ValueError, TypeError): + raise InconclusiveMatchError( + f"Person property value '{override_value}' is not a valid semver", + reason=UnresolvedFlagReason.MISSING_CONTEXT, + ) + if operator in SEMVER_RANGE_OPERATORS: + lower, upper = flag_semver + return lower <= override_parsed < upper + if operator == "semver_eq": + return override_parsed == flag_semver + if operator == "semver_neq": + return override_parsed != flag_semver + if operator == "semver_gt": + return override_parsed > flag_semver + if operator == "semver_gte": + return override_parsed >= flag_semver + if operator == "semver_lt": + return override_parsed < flag_semver + if operator == "semver_lte": + return override_parsed <= flag_semver + return _raise_unhandled_operator(operator) + + +def _match_scalar_property(operator, value, override_value) -> bool: + if operator in _TEXT_OPERATORS: + return _match_text_property(operator, value, override_value) + if operator in ("regex", "not_regex"): + return _match_regex_property(operator, value, override_value) + if operator in DATE_OPERATORS: + return _match_date_property(operator, value, override_value) + if operator in SEMVER_OPERATORS: + return _match_semver_property(operator, value, override_value) + return _raise_unhandled_operator(operator) + + +def _raise_unhandled_operator(operator) -> NoReturn: # Unreachable: all operators in PROPERTY_OPERATORS are handled above, - # and unknown operators are rejected at the top of this function. + # and unknown operators are rejected at the top of _match_property_value. raise InconclusiveMatchError( f"Operator {operator} {_UNHANDLED_OPERATOR_MESSAGE}", reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, @@ -1426,19 +1695,7 @@ def match_property_group( device_id=None, property_matching_version: int = 1, ) -> bool: - # The backend serializes its canonical empty PropertyGroup as {}. - if property_group == {}: - return True - if not isinstance(property_group, dict): - raise RequiresServerEvaluation("Cohort property group must be an object") - - property_group_type = property_group.get("type") - if property_group_type not in ("AND", "OR"): - raise RequiresServerEvaluation("Cohort property group type must be AND or OR") - is_and = property_group_type == "AND" - properties = property_group.get("values") - if not isinstance(properties, list): - raise RequiresServerEvaluation("Cohort property group values must be a list") + is_and, properties = _get_property_group_values(property_group) if not properties: return True @@ -1447,58 +1704,18 @@ def match_property_group( for prop in properties: try: - if not isinstance(prop, dict): - raise RequiresServerEvaluation( - "Cohort property group entry must be an object" - ) - - if _is_nested_property_group(prop): - matches = match_property_group( - prop, - property_values, - cohort_properties, - flags_by_key, - evaluation_cache, - distinct_id, - device_id=device_id, - property_matching_version=property_matching_version, - ) - negation = False - elif prop.get("type") == "cohort": - matches = match_cohort( - prop, - property_values, - cohort_properties, - flags_by_key, - evaluation_cache, - distinct_id, - device_id=device_id, - property_matching_version=property_matching_version, - ) - negation = prop.get("negation", False) - elif prop.get("type") == "flag": - matches = evaluate_flag_dependency( - prop, - flags_by_key, - evaluation_cache, - distinct_id, - property_values, - cohort_properties, - device_id=device_id, - property_matching_version=property_matching_version, - ) - negation = prop.get("negation", False) - else: - matches = match_property( - prop, property_values, property_matching_version - ) - negation = prop.get("negation", False) - - effective_match = matches != bool(negation) - if is_and and not effective_match: - decisive_result = False - elif not is_and and effective_match: - decisive_result = True + effective_match = _match_property_group_entry( + prop, + property_values, + cohort_properties, + flags_by_key, + evaluation_cache, + distinct_id, + device_id, + property_matching_version, + ) + if effective_match != is_and: + decisive_result = effective_match except RequiresServerEvaluation: # Static/missing cohorts and malformed definitions always require server evaluation, # even when another branch would otherwise resolve the group locally. @@ -1519,6 +1736,62 @@ def match_property_group( return is_and +def _get_property_group_values(property_group): + # The backend serializes its canonical empty PropertyGroup as {}. + if property_group == {}: + return True, [] + if not isinstance(property_group, dict): + raise RequiresServerEvaluation("Cohort property group must be an object") + + property_group_type = property_group.get("type") + if property_group_type not in ("AND", "OR"): + raise RequiresServerEvaluation("Cohort property group type must be AND or OR") + is_and = property_group_type == "AND" + properties = property_group.get("values") + if not isinstance(properties, list): + raise RequiresServerEvaluation("Cohort property group values must be a list") + return is_and, properties + + +def _match_property_group_entry( + prop, + property_values, + cohort_properties, + flags_by_key, + evaluation_cache, + distinct_id, + device_id, + property_matching_version, +): + if not isinstance(prop, dict): + raise RequiresServerEvaluation("Cohort property group entry must be an object") + if _is_nested_property_group(prop): + matches = match_property_group( + prop, + property_values, + cohort_properties, + flags_by_key, + evaluation_cache, + distinct_id, + device_id=device_id, + property_matching_version=property_matching_version, + ) + negation = False + else: + matches = _match_condition_filter( + prop, + property_values, + cohort_properties, + flags_by_key, + evaluation_cache, + distinct_id, + device_id=device_id, + property_matching_version=property_matching_version, + ) + negation = prop.get("negation", False) + return matches != bool(negation) + + def _get_definition_unresolved_reason( flag, flags_by_key, cohort_properties, group_type_mapping ) -> Optional[UnresolvedFlagReason]: @@ -1533,11 +1806,17 @@ def _get_definition_unresolved_reason( aggregation = flag_filters.get("aggregation_group_type_index") if aggregation is not None and not group_type_mapping.get(str(aggregation)): return UnresolvedFlagReason.UNSUPPORTED_DEFINITION + if _has_unsupported_condition(flag_filters, flags_by_key, cohort_properties): + return UnresolvedFlagReason.UNSUPPORTED_DEFINITION + return None + + +def _has_unsupported_condition(flag_filters, flags_by_key, cohort_properties) -> bool: for condition in flag_filters.get("groups") or []: for prop in condition.get("properties") or []: if _is_unsupported_property(prop, flags_by_key, cohort_properties, set()): - return UnresolvedFlagReason.UNSUPPORTED_DEFINITION - return None + return True + return False def _is_unsupported_property( @@ -1545,13 +1824,7 @@ def _is_unsupported_property( ) -> bool: property_type = prop.get("type") if property_type == "flag": - # A malformed condition shape is a definitive local no-match, not a gap. - if _flag_dependency_shape_problem(prop) is not None: - return False - dependency_chain = prop.get("dependency_chain") - if not isinstance(dependency_chain, list) or not dependency_chain: - return True - return any(not flags_by_key.get(key) for key in dependency_chain) + return _is_unsupported_dependency(prop, flags_by_key) if property_type != "cohort": try: _assert_filter_supported(prop) @@ -1574,6 +1847,16 @@ def _is_unsupported_property( ) +def _is_unsupported_dependency(prop, flags_by_key) -> bool: + # A malformed condition shape is a definitive local no-match, not a gap. + if _flag_dependency_shape_problem(prop) is not None: + return False + dependency_chain = prop.get("dependency_chain") + if not isinstance(dependency_chain, list) or not dependency_chain: + return True + return any(not flags_by_key.get(key) for key in dependency_chain) + + def _is_unsupported_property_group( property_group, flags_by_key, cohort_properties, visited_cohort_ids ) -> bool: diff --git a/posthog/integrations/asgi.py b/posthog/integrations/asgi.py index d58f818db..f20b4779b 100644 --- a/posthog/integrations/asgi.py +++ b/posthog/integrations/asgi.py @@ -120,10 +120,13 @@ def _server_host(scope: Mapping[str, Any]) -> Optional[str]: hostname = _sanitize_text(hostname) if not hostname: return None + return _format_server_host(hostname, port, scope.get("scheme")) + + +def _format_server_host(hostname: str, port: int, scheme: Any) -> str: if ":" in hostname and not hostname.startswith("["): hostname = f"[{hostname}]" - scheme = scope.get("scheme") default_port = (scheme == "http" and port == 80) or ( scheme == "https" and port == 443 ) @@ -148,6 +151,23 @@ def _extract_properties( properties["$user_agent"] = user_agent properties["$raw_user_agent"] = user_agent + ip_address = _client_ip(scope, headers) + if ip_address: + properties["$ip"] = ip_address + + scheme = _sanitize_text(scope.get("scheme"), max_length=16) + host = _decode_header(headers.get(b"host")) or _server_host(scope) + if scheme and host and path: + # Deliberately omit query strings: they commonly contain secrets and + # high-cardinality values. The path remains available separately. + properties["$current_url"] = f"{scheme}://{host}{path}" + + return properties + + +def _client_ip( + scope: Mapping[str, Any], headers: Mapping[bytes, bytes] +) -> Optional[str]: forwarded_for = _decode_header(headers.get(b"x-forwarded-for")) if forwarded_for: ip_address = _sanitize_text(forwarded_for.split(",", 1)[0]) @@ -160,17 +180,7 @@ def _extract_properties( and isinstance(client[0], str) else None ) - if ip_address: - properties["$ip"] = ip_address - - scheme = _sanitize_text(scope.get("scheme"), max_length=16) - host = _decode_header(headers.get(b"host")) or _server_host(scope) - if scheme and host and path: - # Deliberately omit query strings: they commonly contain secrets and - # high-cardinality values. The path remains available separately. - properties["$current_url"] = f"{scheme}://{host}{path}" - - return properties + return ip_address async def _resolve_callback_result(value): @@ -252,13 +262,7 @@ async def __call__(self, scope, receive, send) -> None: _enrich_current_span() - properties = _extract_properties(scope, headers) - if self.extra_properties: - extra_properties = await _resolve_callback_result( - self.extra_properties(scope) - ) - if extra_properties: - properties.update(extra_properties) + properties = await self._request_properties(scope, headers) for key, value in properties.items(): contexts.tag(key, value) @@ -282,3 +286,13 @@ async def __call__(self, scope, receive, send) -> None: exception, _capture_metadata=_CAPTURE_METADATA ) raise + + async def _request_properties(self, scope, headers) -> dict[str, Any]: + properties = _extract_properties(scope, headers) + if self.extra_properties: + extra_properties = await _resolve_callback_result( + self.extra_properties(scope) + ) + if extra_properties: + properties.update(extra_properties) + return properties diff --git a/posthog/integrations/celery.py b/posthog/integrations/celery.py index 0e37379f9..0d59c2a52 100644 --- a/posthog/integrations/celery.py +++ b/posthog/integrations/celery.py @@ -392,18 +392,7 @@ def _handle_task_end( task_properties["error_type"] = type(exception).__name__ task_properties["error_message"] = str(exception) - task_name = task_properties.get("celery_task_name") - should_track = False - if self.capture_task_lifecycle_events or ( - exception and self.capture_exceptions - ): - should_track = self._should_track(task_name, task_properties) - - if exception and self.capture_exceptions and should_track: - self._capture_exception(exception) - - if self.capture_task_lifecycle_events and should_track: - self._capture_event(f"celery task {state}", properties=task_properties) + self._capture_task_end(state, task_properties, exception) except Exception: logger.exception("Failed to process Celery %s state", state) finally: @@ -411,6 +400,22 @@ def _handle_task_end( if ctx is not None: ctx.__exit__(None, None, None) + def _capture_task_end( + self, state: str, task_properties: dict, exception: Any + ) -> None: + task_name = task_properties.get("celery_task_name") + should_track = False + if self.capture_task_lifecycle_events or ( + exception and self.capture_exceptions + ): + should_track = self._should_track(task_name, task_properties) + + if exception and self.capture_exceptions and should_track: + self._capture_exception(exception) + + if self.capture_task_lifecycle_events and should_track: + self._capture_event(f"celery task {state}", properties=task_properties) + def _apply_propagated_identity(self, request: Any) -> None: headers = self._extract_headers(request) distinct_id = headers.get(CONTEXT_DISTINCT_ID_HEADER) diff --git a/posthog/integrations/django.py b/posthog/integrations/django.py index 9c305a75c..a49527181 100644 --- a/posthog/integrations/django.py +++ b/posthog/integrations/django.py @@ -96,6 +96,35 @@ def __init__(self, get_response): from django.conf import settings + self._configure_callbacks(settings) + + capture_exceptions = getattr(settings, "POSTHOG_MW_CAPTURE_EXCEPTIONS", True) + self.capture_exceptions: Optional[bool] = ( + capture_exceptions + if capture_exceptions is None or isinstance(capture_exceptions, bool) + else True + ) + capture_tracing_headers = getattr( + settings, "POSTHOG_MW_CAPTURE_TRACING_HEADERS", None + ) + trust_tracing_headers = getattr( + settings, "POSTHOG_MW_TRUST_TRACING_HEADERS", None + ) + self.capture_tracing_headers = _resolve_capture_tracing_headers( + capture_tracing_headers, + trust_tracing_headers, + canonical_name="POSTHOG_MW_CAPTURE_TRACING_HEADERS", + deprecated_name="POSTHOG_MW_TRUST_TRACING_HEADERS", + ) + + if hasattr(settings, "POSTHOG_MW_CLIENT") and isinstance( + settings.POSTHOG_MW_CLIENT, Client + ): + self.client = cast("Optional[Client]", settings.POSTHOG_MW_CLIENT) + else: + self.client = None + + def _configure_callbacks(self, settings) -> None: extra_properties = ( settings.POSTHOG_MW_EXTRA_PROPERTIES if hasattr(settings, "POSTHOG_MW_EXTRA_PROPERTIES") @@ -128,32 +157,6 @@ def __init__(self, get_response): else None ) - capture_exceptions = getattr(settings, "POSTHOG_MW_CAPTURE_EXCEPTIONS", True) - self.capture_exceptions: Optional[bool] = ( - capture_exceptions - if capture_exceptions is None or isinstance(capture_exceptions, bool) - else True - ) - capture_tracing_headers = getattr( - settings, "POSTHOG_MW_CAPTURE_TRACING_HEADERS", None - ) - trust_tracing_headers = getattr( - settings, "POSTHOG_MW_TRUST_TRACING_HEADERS", None - ) - self.capture_tracing_headers = _resolve_capture_tracing_headers( - capture_tracing_headers, - trust_tracing_headers, - canonical_name="POSTHOG_MW_CAPTURE_TRACING_HEADERS", - deprecated_name="POSTHOG_MW_TRUST_TRACING_HEADERS", - ) - - if hasattr(settings, "POSTHOG_MW_CLIENT") and isinstance( - settings.POSTHOG_MW_CLIENT, Client - ): - self.client = cast("Optional[Client]", settings.POSTHOG_MW_CLIENT) - else: - self.client = None - @property def trust_tracing_headers(self) -> bool: """Deprecated alias for ``capture_tracing_headers``.""" @@ -236,6 +239,9 @@ def _build_tags(self, request, user_id, user_email): tags["$user_agent"] = user_agent tags["$raw_user_agent"] = user_agent + return self._transform_properties(request, tags) + + def _transform_properties(self, request, tags): # Apply application-specific properties, then the optional transform. if self.extra_properties: extra = self.extra_properties(request) diff --git a/posthog/mcp/__init__.py b/posthog/mcp/__init__.py index 9f9db0211..d175ae0d4 100644 --- a/posthog/mcp/__init__.py +++ b/posthog/mcp/__init__.py @@ -248,32 +248,7 @@ def instrument( :param options: Optional :class:`MCPAnalyticsOptions`. """ opts = options or MCPAnalyticsOptions() - server_build = validate_server_build(opts.server_build) - - # Install the logger first so the version advisory below (and any warning) is - # actually visible rather than going to the default no-op sink. - if opts.logger: - set_logger(opts.logger) - - # The wrapping path hooks the official MCP SDK's server internals, so it needs the - # `mcp` package. It's a peer dependency (you already have it — you built the server - # with it), imported lazily here rather than bundled. PostHogMCP (custom dispatchers) - # doesn't need it at all. Raise a clear error rather than a silent no-op below. - try: - import mcp # noqa: F401 - except ImportError: - raise ModuleNotFoundError( - "instrument() needs the MCP SDK. Install it with: pip install 'mcp>=1.26'. " - "(PostHogMCP for custom dispatchers works without it.)" - ) - _warn_if_unsupported_mcp_version() - - # Fail fast on a `collect_feedback` config error (reserved extra key, - # undeclared extra_required) — before the try below, so it raises instead of - # degrading to the no-op handle and first surfacing at tools/list time. - feedback_options = resolve_collect_feedback_options(opts.collect_feedback) - if feedback_options is not None: - get_feedback_tool_descriptor(feedback_options) + server_build = _prepare_instrumentation(opts) key = tracking_key(server) @@ -281,15 +256,9 @@ def instrument( # MCP is an optional peer: load adapters only when instrumentation is # requested, inside the no-crash boundary. Class probes stay major-specific. from ._compatibility import ( - is_fastmcp, is_fastmcp_v2, - is_low_level_server, - is_mcpserver, uses_v2_handler_registry, ) - from ._instrument_fastmcp import instrument_fastmcp - from ._instrument_lowlevel import instrument_fastmcp_v2, instrument_low_level - from ._instrument_v2 import instrument_lowlevel_v2, instrument_mcpserver_v2 from ._raised_tool_error import wrap_tool_dispatch client = _resolve_client(posthog_client) @@ -299,13 +268,7 @@ def instrument( existing_data = get_server_tracking_data(key) data = existing_data if data is None: - sink = McpEventSink(client) if client is not None else None - data = MCPAnalyticsData( - options=opts, - sink=sink, - session_id=new_session_id(), - server_build=server_build, - ) + data = _new_tracking_data(opts, client, server_build) if is_fastmcp_v2(server): wrap_tool_dispatch(server) @@ -322,26 +285,7 @@ def instrument( set_server_tracking_data(key, data) - if is_fastmcp(server): - instrument_fastmcp(server, data) - elif is_mcpserver(server): - instrument_mcpserver_v2(server, data) - elif is_fastmcp_v2(server): - if uses_v2_handler_registry(server._mcp_server): - instrument_lowlevel_v2(server._mcp_server, data) - else: - instrument_fastmcp_v2(server, data) - elif is_low_level_server(server): - if uses_v2_handler_registry(server): - instrument_lowlevel_v2(server, data) - else: - instrument_low_level(server, data) - else: - raise TypeError( - f"Unsupported server type: {type(server)!r}. Pass a high-level server " - "(mcp.server.fastmcp.FastMCP on SDK 1.x, mcp.server.mcpserver.MCPServer " - "on SDK 2.x, or jlowin's fastmcp.FastMCP) or a low-level mcp.server.Server." - ) + _instrument_adapter(server, data) if client is not None: from ._lib_identity import apply_mcp_lib_identity @@ -357,3 +301,77 @@ def instrument( except Exception as error: # noqa: BLE001 log(f"Warning: failed to instrument server - {error}") return _NoopAnalytics() + + +def _instrument_adapter(server: Any, data: MCPAnalyticsData) -> None: + from ._compatibility import ( + is_fastmcp, + is_fastmcp_v2, + is_low_level_server, + is_mcpserver, + uses_v2_handler_registry, + ) + from ._instrument_fastmcp import instrument_fastmcp + from ._instrument_lowlevel import instrument_fastmcp_v2, instrument_low_level + from ._instrument_v2 import instrument_lowlevel_v2, instrument_mcpserver_v2 + + if is_fastmcp(server): + instrument_fastmcp(server, data) + elif is_mcpserver(server): + instrument_mcpserver_v2(server, data) + elif is_fastmcp_v2(server): + if uses_v2_handler_registry(server._mcp_server): + instrument_lowlevel_v2(server._mcp_server, data) + else: + instrument_fastmcp_v2(server, data) + elif is_low_level_server(server): + if uses_v2_handler_registry(server): + instrument_lowlevel_v2(server, data) + else: + instrument_low_level(server, data) + else: + raise TypeError( + f"Unsupported server type: {type(server)!r}. Pass a high-level server " + "(mcp.server.fastmcp.FastMCP on SDK 1.x, mcp.server.mcpserver.MCPServer " + "on SDK 2.x, or jlowin's fastmcp.FastMCP) or a low-level mcp.server.Server." + ) + + +def _new_tracking_data( + opts: MCPAnalyticsOptions, client: Optional[Client], server_build: Optional[str] +) -> MCPAnalyticsData: + sink = McpEventSink(client) if client is not None else None + return MCPAnalyticsData( + options=opts, sink=sink, session_id=new_session_id(), server_build=server_build + ) + + +def _prepare_instrumentation(opts: MCPAnalyticsOptions) -> Optional[str]: + server_build = validate_server_build(opts.server_build) + + # Install the logger first so the version advisory below (and any warning) is + # actually visible rather than going to the default no-op sink. + if opts.logger: + set_logger(opts.logger) + + # The wrapping path hooks the official MCP SDK's server internals, so it needs the + # `mcp` package. It's a peer dependency (you already have it — you built the server + # with it), imported lazily here rather than bundled. PostHogMCP (custom dispatchers) + # doesn't need it at all. Raise a clear error rather than a silent no-op below. + try: + import mcp # noqa: F401 + except ImportError: + raise ModuleNotFoundError( + "instrument() needs the MCP SDK. Install it with: pip install 'mcp>=1.26'. " + "(PostHogMCP for custom dispatchers works without it.)" + ) + _warn_if_unsupported_mcp_version() + + # Fail fast on a `collect_feedback` config error (reserved extra key, + # undeclared extra_required) — before the try below, so it raises instead of + # degrading to the no-op handle and first surfacing at tools/list time. + feedback_options = resolve_collect_feedback_options(opts.collect_feedback) + if feedback_options is not None: + get_feedback_tool_descriptor(feedback_options) + + return server_build diff --git a/posthog/mcp/_capture.py b/posthog/mcp/_capture.py index 857dd2be6..fd2a91d84 100644 --- a/posthog/mcp/_capture.py +++ b/posthog/mcp/_capture.py @@ -15,6 +15,7 @@ from ._internal import MCPAnalyticsData from .logger import log from ._sink import McpCaptureOptions +from .types import UserIdentity from .version import __version__ @@ -53,9 +54,7 @@ def capture_event( "protocol_version": event_input.get("protocol_version"), "client_user_agent": event_input.get("client_user_agent"), "vendor_client": event_input.get("vendor_client"), - "identify_actor_given_id": actor.distinct_id if actor else None, - "identify_actor_data": (actor.properties or {}) if actor else {}, - "groups": actor.groups if actor else None, + **_actor_fields(actor), "resource_name": event_input.get("resource_name"), "tool_category": event_input.get("tool_category"), "tool_description": event_input.get("tool_description"), @@ -83,3 +82,11 @@ def capture_event( def log_capture_skipped() -> None: log("Warning: Server tracking data not found. Event will not be published.") + + +def _actor_fields(actor: Optional[UserIdentity]) -> Dict[str, Any]: + return { + "identify_actor_given_id": actor.distinct_id if actor else None, + "identify_actor_data": (actor.properties or {}) if actor else {}, + "groups": actor.groups if actor else None, + } diff --git a/posthog/mcp/_context_parameters.py b/posthog/mcp/_context_parameters.py index 943d13764..f0a742c31 100644 --- a/posthog/mcp/_context_parameters.py +++ b/posthog/mcp/_context_parameters.py @@ -55,11 +55,7 @@ def add_context_parameter_to_schema( """ schema = input_schema - if ( - schema - and isinstance(schema.get("properties"), dict) - and "context" in schema["properties"] - ): + if schema_has_param(schema, "context"): log( f"WARN: Tool \"{tool_name}\" already has 'context' parameter. Skipping context injection." ) @@ -89,11 +85,15 @@ def add_context_parameter_to_schema( } if required: - required_list = schema.get("required") - if isinstance(required_list, list): - if "context" not in required_list: - required_list.append("context") - else: - schema["required"] = ["context"] + _require_context(schema) return schema + + +def _require_context(schema: Dict[str, Any]) -> None: + required_list = schema.get("required") + if isinstance(required_list, list): + if "context" not in required_list: + required_list.append("context") + else: + schema["required"] = ["context"] diff --git a/posthog/mcp/_conversation_id.py b/posthog/mcp/_conversation_id.py index d3c774516..9f6a91fe9 100644 --- a/posthog/mcp/_conversation_id.py +++ b/posthog/mcp/_conversation_id.py @@ -14,6 +14,7 @@ import re from typing import Any, Dict, Optional, Tuple +from ._context_parameters import schema_has_param from .constants import DEFAULT_CONVERSATION_ID_DESCRIPTION from ._ids import _uuid7 from .logger import log @@ -39,11 +40,7 @@ def add_conversation_id_to_schema( ``$ref``/``oneOf``/``allOf``/``anyOf``. """ schema = input_schema - if ( - schema - and isinstance(schema.get("properties"), dict) - and CONVERSATION_ID_PARAM_NAME in schema["properties"] - ): + if schema and schema_has_param(schema, CONVERSATION_ID_PARAM_NAME): if _is_our_declaration(schema["properties"][CONVERSATION_ID_PARAM_NAME]): return schema log( @@ -151,17 +148,26 @@ def inject_prompt_back(result: Any, conversation_id: str) -> Any: if isinstance(result, list): return [*result, block] - target = getattr(result, "root", result) - content = getattr(target, "content", None) - if not isinstance(content, list): - return result + return _inject_model_prompt_back(result, block) + + +def _copy_with_attr(value: Any, attr: str, updated: Any) -> Optional[Any]: try: - import mcp.types as mcp_types # noqa: PLC0415 + copied = copy.copy(value) + except Exception: # noqa: BLE001 - delivery must not break a tool call + return None + if copied is value: + return None + try: + setattr(copied, attr, updated) + except Exception: # noqa: BLE001 - read-only objects fail closed + return None + return copied - block = mcp_types.TextContent(type="text", text=block["text"]) - except ImportError: - pass +def _copy_prompt_back_result( + result: Any, target: Any, content: list, block: Any +) -> Any: copy_model = getattr(target, "model_copy", None) if callable(copy_model): try: @@ -185,15 +191,16 @@ def inject_prompt_back(result: Any, conversation_id: str) -> Any: return result if wrapped is None else wrapped -def _copy_with_attr(value: Any, attr: str, updated: Any) -> Optional[Any]: - try: - copied = copy.copy(value) - except Exception: # noqa: BLE001 - delivery must not break a tool call - return None - if copied is value: - return None +def _inject_model_prompt_back(result: Any, block: Any) -> Any: + target = getattr(result, "root", result) + content = getattr(target, "content", None) + if not isinstance(content, list): + return result try: - setattr(copied, attr, updated) - except Exception: # noqa: BLE001 - read-only objects fail closed - return None - return copied + import mcp.types as mcp_types # noqa: PLC0415 + + block = mcp_types.TextContent(type="text", text=block["text"]) + except ImportError: + pass + + return _copy_prompt_back_result(result, target, content, block) diff --git a/posthog/mcp/_instrument_lowlevel.py b/posthog/mcp/_instrument_lowlevel.py index ace769fd3..b8cf5527d 100644 --- a/posthog/mcp/_instrument_lowlevel.py +++ b/posthog/mcp/_instrument_lowlevel.py @@ -730,14 +730,7 @@ async def _listed_input_schema( # spend rate limits, and its registry can disagree with what that # middleware advertises, so the advertised schema is unknown. return None - candidates = [tool for tool in await list_tools() if tool.name == name] - if version is not None: - candidates = [ - tool - for tool in candidates - if str(getattr(tool, "version", "")) == version - ] - tool = candidates[-1] if candidates else None + tool = _last_listed_tool(await list_tools(), name, version) schema = getattr(tool, "parameters", None) except Exception as error: # noqa: BLE001 - analytics must not break dispatch log(f"PostHog MCP: could not resolve schema for tool {name!r} - {error}") @@ -771,13 +764,7 @@ def _schema_view(schema: Dict[str, Any], *, dereferenced: bool) -> Tuple[set, bo node.get(key) for node in nodes for key in ("oneOf", "allOf", "anyOf") ): return set(_INJECTED_KEYS), False - declared = { - key - for node in nodes - if isinstance(node.get("properties"), dict) - for key in node["properties"] - if key in _INJECTED_KEYS - } + declared = _declared_injected_keys(nodes) injectable = can_inject_model_parameter(nodes[-1]) and "llm_model" not in declared return declared, injectable @@ -903,10 +890,7 @@ def _reference_chain(schema: Dict[str, Any]) -> Optional[List[Dict[str, Any]]]: return nodes if not isinstance(ref, str) or not ref.startswith("#/"): return None - target: Any = schema - for part in ref[2:].split("/"): - key = part.replace("~1", "/").replace("~0", "~") # JSON Pointer escapes - target = target.get(key) if isinstance(target, dict) else None + target = _resolve_local_pointer(schema, ref) if not isinstance(target, dict) or any(target is node for node in nodes): return None nodes.append(target) @@ -952,3 +936,31 @@ def _mcp_session_id(server: Any) -> Optional[str]: except Exception: # noqa: BLE001 pass return None + + +def _resolve_local_pointer(schema: Dict[str, Any], ref: str) -> Any: + target: Any = schema + for part in ref[2:].split("/"): + key = part.replace("~1", "/").replace("~0", "~") # JSON Pointer escapes + target = target.get(key) if isinstance(target, dict) else None + return target + + +def _declared_injected_keys(nodes: List[Dict[str, Any]]) -> set: + declared = { + key + for node in nodes + if isinstance(node.get("properties"), dict) + for key in node["properties"] + if key in _INJECTED_KEYS + } + return declared + + +def _last_listed_tool(tools: list, name: str, version: Optional[str]) -> Any: + candidates = [tool for tool in tools if tool.name == name] + if version is not None: + candidates = [ + tool for tool in candidates if str(getattr(tool, "version", "")) == version + ] + return candidates[-1] if candidates else None diff --git a/posthog/mcp/_instrument_v2.py b/posthog/mcp/_instrument_v2.py index da85d2c06..46d21a5af 100644 --- a/posthog/mcp/_instrument_v2.py +++ b/posthog/mcp/_instrument_v2.py @@ -555,24 +555,7 @@ async def _standalone_injected_parameters( Listings from other requests can have different application-owned parameters. Without a schema, stripping could delete application arguments. """ - try: - from fastmcp.utilities.versions import VersionSpec, version_sort_key - - version_spec = VersionSpec(eq=version) if version else None - # Middleware can shadow registered tools, so resolve the effective listing. - candidates = [ - tool - for tool in await server.list_tools() - if tool.name == name - and (version_spec is None or version_spec.matches(tool.version)) - ] - tool = max(candidates, key=version_sort_key, default=None) - if tool is None: - tool = await server.get_tool(name, version=version_spec) - schema = getattr(tool, "parameters", None) - except Exception as error: # noqa: BLE001 - schema lookup must not prevent dispatch - log(f"PostHog MCP: could not resolve schema for tool {name!r} - {error}") - return None, None + schema = await _standalone_input_schema(server, name, version) if not isinstance(schema, dict): return None, None injected = set() @@ -879,3 +862,27 @@ def _name_owned_by_real_tool_v2(high_level: Any, name: str) -> Optional[bool]: except Exception as err: # noqa: BLE001 - analytics must not break the call warn_ownership_lookup_failed(name, err) return None + + +async def _standalone_input_schema( + server: Any, name: str, version: Optional[str] +) -> Any: + try: + from fastmcp.utilities.versions import VersionSpec, version_sort_key + + version_spec = VersionSpec(eq=version) if version else None + # Middleware can shadow registered tools, so resolve the effective listing. + candidates = [ + tool + for tool in await server.list_tools() + if tool.name == name + and (version_spec is None or version_spec.matches(tool.version)) + ] + tool = max(candidates, key=version_sort_key, default=None) + if tool is None: + tool = await server.get_tool(name, version=version_spec) + schema = getattr(tool, "parameters", None) + except Exception as error: # noqa: BLE001 - schema lookup must not prevent dispatch + log(f"PostHog MCP: could not resolve schema for tool {name!r} - {error}") + return None + return schema diff --git a/posthog/mcp/_instrumentation.py b/posthog/mcp/_instrumentation.py index dd5d51e7e..1a194f2f4 100644 --- a/posthog/mcp/_instrumentation.py +++ b/posthog/mcp/_instrumentation.py @@ -57,7 +57,12 @@ from .session import resolve_session_id, resolve_session_id_with_source from .session_token import SessionTokenPayload, decode_session_id from .tools import resolve_missing_capability_tool_name -from .types import CollectFeedbackOptions, FeedbackReport, ToolInputOptions +from .types import ( + CollectFeedbackOptions, + FeedbackReport, + InputAliasMap, + ToolInputOptions, +) # The virtual tools this SDK advertises into tools/list. Every piece of per-tool # policy -- enable switch, configured name, warning text, warn-once @@ -819,22 +824,10 @@ async def record_tool_call( event["llm_model"] = model event["llm_model_source"] = source - if result is not None: - event["response"] = _wrap_response(result) - if error is None and is_tool_result_error(result): - error = result - if error is not None: - event["is_error"] = True - event["error"] = capture_exception(error) - event["error_status"] = http_status(error) + _set_tool_outcome(event, result, error) props = await resolve_event_properties(data, request, extra) - input_aliases = None - if data.options.resolve_input_aliases is not None: - try: - input_aliases = data.options.resolve_input_aliases(name) - except Exception as err: # noqa: BLE001 - analytics callbacks are isolated - log(f"Warning: resolve_input_aliases failed for tool {name}: {err}") + input_aliases = _resolve_input_aliases(data, name) event["properties"] = { **(props or {}), **get_tool_input_properties( @@ -1039,18 +1032,7 @@ def resolve_virtual_tool_injection( listed = advertised_tool_names(tools) if not is_first_page: - for kind, name in enabled.items(): - # Only warn about a tool we actually shadowed. If this kind never - # made it onto the first page -- a real tool already held the name - # ("blocked"), or the other virtual tool won it ("duplicate") -- - # then nothing of ours is advertised under it and the host's tool - # runs untouched. Telling them otherwise sends them chasing a bug - # that isn't there. - if name in listed and not any( - (kind, name, variant) in data.warned_virtual_tool_collisions - for variant in ("blocked", "duplicate") - ): - _warn_virtual_tool_collision(data, kind, name, "shadowed") + _warn_shadowed_virtual_tools(data, enabled, listed) return {} injectable: Dict[str, str] = {} @@ -1221,11 +1203,7 @@ def mutate_tool_schema( schema, "conversation_id" ): schema = add_conversation_id_to_schema(schema, tool.name) - if schema is not original_schema: - try: - setattr(tool, schema_attribute, schema) - except Exception: # noqa: BLE001 - some schema attrs may be read-only - log(f"WARN: could not set {schema_attribute} on tool {tool.name}") + _write_tool_schema(tool, schema_attribute, original_schema, schema) if data.options.enable_conversation_id: data.tool_output_instructions[tool.name] = add_instructions_to_output_schema( tool @@ -1584,3 +1562,53 @@ async def record_resource_request( fire_and_forget(capture_event(data, event), data) except Exception as err: # noqa: BLE001 - isolate analytics from the request path log(f"record_resource_request failed (event dropped): {err}") + + +def _set_tool_outcome(event: Dict[str, Any], result: Any, error: Any) -> None: + if result is not None: + event["response"] = _wrap_response(result) + if error is None and is_tool_result_error(result): + error = result + if error is not None: + event["is_error"] = True + event["error"] = capture_exception(error) + event["error_status"] = http_status(error) + + +def _resolve_input_aliases( + data: MCPAnalyticsData, name: str +) -> Optional[InputAliasMap]: + input_aliases = None + if data.options.resolve_input_aliases is not None: + try: + input_aliases = data.options.resolve_input_aliases(name) + except Exception as err: # noqa: BLE001 - analytics callbacks are isolated + log(f"Warning: resolve_input_aliases failed for tool {name}: {err}") + return input_aliases + + +def _warn_shadowed_virtual_tools( + data: MCPAnalyticsData, enabled: Dict[str, str], listed: Set[str] +) -> None: + for kind, name in enabled.items(): + # Only warn about a tool we actually shadowed. If this kind never + # made it onto the first page -- a real tool already held the name + # ("blocked"), or the other virtual tool won it ("duplicate") -- + # then nothing of ours is advertised under it and the host's tool + # runs untouched. Telling them otherwise sends them chasing a bug + # that isn't there. + if name in listed and not any( + (kind, name, variant) in data.warned_virtual_tool_collisions + for variant in ("blocked", "duplicate") + ): + _warn_virtual_tool_collision(data, kind, name, "shadowed") + + +def _write_tool_schema( + tool: Any, schema_attribute: str, original_schema: Any, schema: Any +) -> None: + if schema is not original_schema: + try: + setattr(tool, schema_attribute, schema) + except Exception: # noqa: BLE001 - some schema attrs may be read-only + log(f"WARN: could not set {schema_attribute} on tool {tool.name}") diff --git a/posthog/mcp/_output_instructions.py b/posthog/mcp/_output_instructions.py index ee391f1e7..6841ef817 100644 --- a/posthog/mcp/_output_instructions.py +++ b/posthog/mcp/_output_instructions.py @@ -198,6 +198,28 @@ def mirror_instructions_into_structured_content( }, True return result, False + return _mirror_model_instructions(result, payload) + + +def _copy_with_attr(value: Any, attr: str, updated: Any) -> Optional[Any]: + """Return a shallow copy with one changed attribute, or ``None`` when the + object cannot be copied safely.""" + try: + copied = copy.copy(value) + except Exception: # noqa: BLE001 - analytics must not break tool results + return None + if copied is value: + return None + try: + setattr(copied, attr, updated) + except Exception: # noqa: BLE001 - read-only result objects fail closed + return None + return copied + + +def _mirror_model_instructions( + result: Any, payload: Dict[str, Any] +) -> Tuple[Any, bool]: # CallToolResult model (or the ServerResult wrapper around one). target = getattr(result, "root", result) attr, structured = _read_attr(target, _STRUCTURED_CONTENT_ATTRS) @@ -212,6 +234,12 @@ def mirror_instructions_into_structured_content( # result object, and pinning one conversation's handle onto it would serve # that handle to every later caller (and, through the handle, collapse # unrelated clients into one session). + return _copy_structured_result(result, target, attr, updated) + + +def _copy_structured_result( + result: Any, target: Any, attr: str, updated: Any +) -> Tuple[Any, bool]: copy_model = getattr(target, "model_copy", None) if callable(copy_model): try: @@ -234,19 +262,3 @@ def mirror_instructions_into_structured_content( if new_result is None: return result, False return new_result, True - - -def _copy_with_attr(value: Any, attr: str, updated: Any) -> Optional[Any]: - """Return a shallow copy with one changed attribute, or ``None`` when the - object cannot be copied safely.""" - try: - copied = copy.copy(value) - except Exception: # noqa: BLE001 - analytics must not break tool results - return None - if copied is value: - return None - try: - setattr(copied, attr, updated) - except Exception: # noqa: BLE001 - read-only result objects fail closed - return None - return copied diff --git a/posthog/mcp/_posthog_events.py b/posthog/mcp/_posthog_events.py index aeda2f86b..4f64a2de0 100644 --- a/posthog/mcp/_posthog_events.py +++ b/posthog/mcp/_posthog_events.py @@ -112,18 +112,7 @@ def _is_tool_call(event: Event) -> bool: def _add_common_properties(event: Event, properties: Dict[str, Any]) -> None: - if event.get("resource_name"): - is_unknown_tool = ( - event.get("event_type") == MCPAnalyticsEventType.MCP_UNKNOWN_TOOL - ) - if not is_unknown_tool: - properties[_P.RESOURCE_NAME] = event["resource_name"] - if is_unknown_tool or _is_tool_call(event): - properties[_P.TOOL_NAME] = event["resource_name"] - if event.get("tool_description") and _is_tool_call(event): - properties[_P.TOOL_DESCRIPTION] = event["tool_description"] - if event.get("tool_category") and _is_tool_call(event): - properties[_P.TOOL_CATEGORY] = event["tool_category"] + _add_resource_properties(event, properties) if ( event.get("listed_tool_names") and len(event["listed_tool_names"]) > 0 @@ -132,42 +121,29 @@ def _add_common_properties(event: Event, properties: Dict[str, Any]) -> None: properties[_P.LISTED_TOOL_NAMES] = event["listed_tool_names"] if event.get("duration") is not None: properties[_P.DURATION_MS] = event["duration"] - if event.get("server_name"): - properties[_P.SERVER_NAME] = event["server_name"] - if event.get("server_version"): - properties[_P.SERVER_VERSION] = event["server_version"] - if event.get("client_name"): - properties[_P.CLIENT_NAME] = event["client_name"] - if event.get("client_version"): - properties[_P.CLIENT_VERSION] = event["client_version"] - # HTTP transports only, and only for the request that carried the header — - # stdio and in-memory servers simply never set these. - if event.get("client_user_agent"): - properties[_P.CLIENT_USER_AGENT] = event["client_user_agent"] - if event.get("vendor_client"): - properties[_P.VENDOR_CLIENT] = event["vendor_client"] - if event.get("protocol_version"): - properties[_P.PROTOCOL_VERSION] = event["protocol_version"] - if event.get("user_intent"): - properties[_P.INTENT] = event["user_intent"] - if event.get("user_intent_source"): - properties[_P.INTENT_SOURCE] = event["user_intent_source"] - if event.get("llm_model"): - properties[_P.LLM_MODEL] = event["llm_model"] - if event.get("llm_model_source"): - properties[_P.LLM_MODEL_SOURCE] = event["llm_model_source"] + # HTTP header fields are set only by the request that carried them. + _add_truthy_properties( + event, + properties, + ( + ("server_name", _P.SERVER_NAME), + ("server_version", _P.SERVER_VERSION), + ("client_name", _P.CLIENT_NAME), + ("client_version", _P.CLIENT_VERSION), + ("client_user_agent", _P.CLIENT_USER_AGENT), + ("vendor_client", _P.VENDOR_CLIENT), + ("protocol_version", _P.PROTOCOL_VERSION), + ("user_intent", _P.INTENT), + ("user_intent_source", _P.INTENT_SOURCE), + ("llm_model", _P.LLM_MODEL), + ("llm_model_source", _P.LLM_MODEL_SOURCE), + ), + ) if event.get("is_error") is not None: properties[_P.IS_ERROR] = event["is_error"] if event.get("is_error"): _add_error_details(event, properties) - if event.get("parameters") is not None: - properties[_P.PARAMETERS] = event["parameters"] - if event.get("response") is not None: - properties[_P.RESPONSE] = event["response"] - identify_actor_data = event.get("identify_actor_data") - if identify_actor_data and len(identify_actor_data) > 0: - # Person properties from identify().properties go straight to $set. - properties["$set"] = {**identify_actor_data} + _add_payload_properties(event, properties) # The dispatch wrappers that say nothing the event does not already say: the @@ -290,16 +266,17 @@ def _build_exception_event(event: Event) -> PostHogCaptureEvent: properties[_P.TOOL_DESCRIPTION] = event["tool_description"] if event.get("tool_category") and _is_tool_call(event): properties[_P.TOOL_CATEGORY] = event["tool_category"] - if event.get("server_name"): - properties[_P.SERVER_NAME] = event["server_name"] - if event.get("server_version"): - properties[_P.SERVER_VERSION] = event["server_version"] - if event.get("client_name"): - properties[_P.CLIENT_NAME] = event["client_name"] - if event.get("client_version"): - properties[_P.CLIENT_VERSION] = event["client_version"] - if event.get("protocol_version"): - properties[_P.PROTOCOL_VERSION] = event["protocol_version"] + _add_truthy_properties( + event, + properties, + ( + ("server_name", _P.SERVER_NAME), + ("server_version", _P.SERVER_VERSION), + ("client_name", _P.CLIENT_NAME), + ("client_version", _P.CLIENT_VERSION), + ("protocol_version", _P.PROTOCOL_VERSION), + ), + ) _add_custom_properties(event, properties) _add_server_build(event, properties) @@ -310,3 +287,37 @@ def _build_exception_event(event: Event) -> PostHogCaptureEvent: "properties": properties, "timestamp": _get_timestamp(event), } + + +def _add_truthy_properties( + event: Event, properties: Dict[str, Any], fields: tuple[tuple[str, str], ...] +) -> None: + for field, property_name in fields: + if event.get(field): + properties[property_name] = event[field] + + +def _add_resource_properties(event: Event, properties: Dict[str, Any]) -> None: + if event.get("resource_name"): + is_unknown_tool = ( + event.get("event_type") == MCPAnalyticsEventType.MCP_UNKNOWN_TOOL + ) + if not is_unknown_tool: + properties[_P.RESOURCE_NAME] = event["resource_name"] + if is_unknown_tool or _is_tool_call(event): + properties[_P.TOOL_NAME] = event["resource_name"] + if event.get("tool_description") and _is_tool_call(event): + properties[_P.TOOL_DESCRIPTION] = event["tool_description"] + if event.get("tool_category") and _is_tool_call(event): + properties[_P.TOOL_CATEGORY] = event["tool_category"] + + +def _add_payload_properties(event: Event, properties: Dict[str, Any]) -> None: + if event.get("parameters") is not None: + properties[_P.PARAMETERS] = event["parameters"] + if event.get("response") is not None: + properties[_P.RESPONSE] = event["response"] + identify_actor_data = event.get("identify_actor_data") + if identify_actor_data and len(identify_actor_data) > 0: + # Person properties from identify().properties go straight to $set. + properties["$set"] = {**identify_actor_data} diff --git a/posthog/mcp/_sanitization.py b/posthog/mcp/_sanitization.py index 12b442245..145dfcec7 100644 --- a/posthog/mcp/_sanitization.py +++ b/posthog/mcp/_sanitization.py @@ -198,21 +198,9 @@ def _sanitize_single_url(value: str, *, nested: bool, in_prose: bool) -> str: try: url = urlsplit(url_text) query, sanitized_query = _sanitize_url_fields(url.query, nested=nested) - # A `?` inside a fragment splits it in two, and each half stands on its - # own: `#/callback?token=x` is text then fields, `#a=1?b=2` is fields - # twice. Shape cannot tell them apart — `#/token=x` looks like a route and - # is a field list — so each half is judged only on whether it holds a `=`. - head, separator, fragment_tail = url.fragment.partition("?") - sanitized_head, head_rewrote_last = _sanitize_fragment_part(head, nested=nested) - # A `?` can fall inside a credential (`#password=pre?fix`), and nothing - # here can tell that from a real boundary. When the head ends in a value - # just redacted, the tail may be the rest of it, so it goes too. - sanitized_tail, tail_rewrote_last = ( - (_REDACTED_VALUE, True) - if head_rewrote_last and fragment_tail - else _sanitize_fragment_part(fragment_tail, nested=nested) + fragment, head_rewrote_last, tail_rewrote_last = _sanitize_url_fragment( + url.fragment, nested=nested ) - fragment = sanitized_head + separator + sanitized_tail netloc = _redact_userinfo(url.netloc) if (netloc, sanitized_query, fragment) == ( url.netloc, @@ -982,3 +970,24 @@ def _build_captured_mcp_arguments( continue captured[key] = sanitize_captured_value(value) return captured + + +def _sanitize_url_fragment( + fragment_value: str, *, nested: bool +) -> tuple[str, bool, bool]: + # A `?` inside a fragment splits it in two, and each half stands on its + # own: `#/callback?token=x` is text then fields, `#a=1?b=2` is fields + # twice. Shape cannot tell them apart — `#/token=x` looks like a route and + # is a field list — so each half is judged only on whether it holds a `=`. + head, separator, fragment_tail = fragment_value.partition("?") + sanitized_head, head_rewrote_last = _sanitize_fragment_part(head, nested=nested) + # A `?` can fall inside a credential (`#password=pre?fix`), and nothing + # here can tell that from a real boundary. When the head ends in a value + # just redacted, the tail may be the rest of it, so it goes too. + sanitized_tail, tail_rewrote_last = ( + (_REDACTED_VALUE, True) + if head_rewrote_last and fragment_tail + else _sanitize_fragment_part(fragment_tail, nested=nested) + ) + fragment = sanitized_head + separator + sanitized_tail + return fragment, head_rewrote_last, tail_rewrote_last diff --git a/posthog/mcp/_tool_input.py b/posthog/mcp/_tool_input.py index 60135a6f0..006b876f7 100644 --- a/posthog/mcp/_tool_input.py +++ b/posthog/mcp/_tool_input.py @@ -34,10 +34,7 @@ def _root_reference_chain(schema: Dict[str, Any]) -> Optional[List[Dict[str, Any return nodes if not isinstance(ref, str) or not ref.startswith("#/"): return None - target: Any = schema - for part in ref[2:].split("/"): - key = part.replace("~1", "/").replace("~0", "~") - target = target.get(key) if isinstance(target, dict) else None + target = _resolve_local_pointer(schema, ref) if not isinstance(target, dict) or any(target is node for node in nodes): return None nodes.append(target) @@ -75,24 +72,12 @@ def _aliases_used( return [] used = [] for canonical, names in aliases.items(): - if ( - not isinstance(canonical, str) - or canonical in input_value - or len(canonical) > _MAX_KEY_LENGTH - or not can_record(canonical) - ): + if not _can_record_canonical(canonical, input_value, can_record): continue names_value: Any = names if not isinstance(names_value, (list, tuple)): continue - alias = next( - ( - name - for name in names_value - if isinstance(name, str) and name in input_value - ), - None, - ) + alias = _first_present_alias(names_value, input_value) if alias and len(alias) <= _MAX_KEY_LENGTH and can_record(alias): used.append(f"{alias}:{canonical}") return sorted(used)[:_MAX_INPUT_KEYS] @@ -114,44 +99,13 @@ def get_tool_input_properties( resolved = options or ToolInputOptions() properties = _declared_properties(input_schema) known = set(properties) | set(_alias_names(resolved.input_aliases)) - keys = [ - key - for key in input_value - if isinstance(key, str) and (key in known or key not in _ANALYTICS_KEYS) - ] - declared: List[str] = [] - undeclared: List[str] = [] - has_redacted = False - recording_decisions: Dict[tuple[str, bool], bool] = {} - - def can_record(key: str, is_declared: bool) -> bool: - cache_key = (key, is_declared) - if cache_key in recording_decisions: - return recording_decisions[cache_key] - record = is_declared - if resolved.should_record_input_key is not None: - try: - record = ( - resolved.should_record_input_key(key, {"declared": is_declared}) - is True - ) - except Exception: # noqa: BLE001 - analytics callbacks fail closed - record = False - recording_decisions[cache_key] = record - return record - - for key in keys: - is_declared = key in known - if len(key) <= _MAX_KEY_LENGTH and can_record(key, is_declared): - (declared if is_declared else undeclared).append(key) - else: - has_redacted = True - - visible = [*sorted(declared), *sorted(undeclared)][:_MAX_INPUT_KEYS] - if has_redacted and len(visible) < _MAX_INPUT_KEYS: - visible.append("[redacted]") + keys = _input_keys(input_value, known) + recorder = _InputKeyRecorder(resolved) + visible = _visible_input_keys(keys, known, recorder) aliases_used = _aliases_used( - resolved.input_aliases, input_value, lambda key: can_record(key, True) + resolved.input_aliases, + input_value, + lambda key: recorder.can_record(key, True), ) result: JsonRecord = { PostHogMCPAnalyticsProperty.INPUT_KEYS: visible, @@ -161,3 +115,77 @@ def can_record(key: str, is_declared: bool) -> bool: return result except Exception: # noqa: BLE001 - analytics must not change tool dispatch return {} + + +def _resolve_local_pointer(schema: Dict[str, Any], ref: str) -> Any: + target: Any = schema + for part in ref[2:].split("/"): + key = part.replace("~1", "/").replace("~0", "~") # JSON Pointer escapes + target = target.get(key) if isinstance(target, dict) else None + return target + + +def _first_present_alias(names: Any, input_value: Dict[str, Any]) -> Optional[str]: + return next( + (name for name in names if isinstance(name, str) and name in input_value), None + ) + + +def _can_record_canonical( + canonical: Any, input_value: Dict[str, Any], can_record: Callable[[str], bool] +) -> bool: + return ( + isinstance(canonical, str) + and canonical not in input_value + and len(canonical) <= _MAX_KEY_LENGTH + and can_record(canonical) + ) + + +def _visible_input_keys( + keys: List[str], known: set, recorder: _InputKeyRecorder +) -> List[str]: + declared: List[str] = [] + undeclared: List[str] = [] + has_redacted = False + for key in keys: + is_declared = key in known + if len(key) <= _MAX_KEY_LENGTH and recorder.can_record(key, is_declared): + (declared if is_declared else undeclared).append(key) + else: + has_redacted = True + + visible = [*sorted(declared), *sorted(undeclared)][:_MAX_INPUT_KEYS] + if has_redacted and len(visible) < _MAX_INPUT_KEYS: + visible.append("[redacted]") + return visible + + +def _input_keys(input_value: Dict[str, Any], known: set) -> List[str]: + return [ + key + for key in input_value + if isinstance(key, str) and (key in known or key not in _ANALYTICS_KEYS) + ] + + +class _InputKeyRecorder: + def __init__(self, options: ToolInputOptions) -> None: + self.options = options + self.decisions: Dict[tuple[str, bool], bool] = {} + + def can_record(self, key: str, is_declared: bool) -> bool: + cache_key = (key, is_declared) + if cache_key in self.decisions: + return self.decisions[cache_key] + record = is_declared + if self.options.should_record_input_key is not None: + try: + record = ( + self.options.should_record_input_key(key, {"declared": is_declared}) + is True + ) + except Exception: # noqa: BLE001 - analytics callbacks fail closed + record = False + self.decisions[cache_key] = record + return record diff --git a/posthog/mcp/_truncation.py b/posthog/mcp/_truncation.py index 382c64639..67fa0b939 100644 --- a/posthog/mcp/_truncation.py +++ b/posthog/mcp/_truncation.py @@ -78,12 +78,7 @@ def _visit( if isinstance(value, bool): # before int — bool is an int subclass return value if isinstance(value, (int, float)): - if isinstance(value, float): - if math.isnan(value): - return "[NaN]" - if math.isinf(value): - return "[Infinity]" if value > 0 else "[-Infinity]" - return value + return _normalize_number(value) if isinstance(value, str): return truncate_text(value, max_string_length) if isinstance(value, datetime): @@ -91,33 +86,9 @@ def _visit( if callable(value): return f"[Function: {getattr(value, '__name__', '') or ''}]" - if isinstance(value, (list, tuple)): - oid = id(value) - if oid in memo: - return "[Circular ~]" - if remaining_depth <= 0: - return "[Array]" - memo.add(oid) - result: Any = _visit_array( - list(value), remaining_depth - 1, max_breadth, max_string_length, memo - ) - memo.discard(oid) - return result - - if isinstance(value, dict): - oid = id(value) - if oid in memo: - return "[Circular ~]" - if remaining_depth <= 0: - return "[Object]" - memo.add(oid) - result = _visit_object( - value, remaining_depth - 1, max_breadth, max_string_length, memo - ) - memo.discard(oid) - return result - - return str(value) + return _visit_container( + value, remaining_depth, max_breadth, max_string_length, memo + ) def _visit_array( @@ -255,12 +226,7 @@ def _collect_string_paths( return if isinstance(obj, dict): for key, value in obj.items(): - if ( - not current_path - and key == "server_build" - and isinstance(value, str) - and len(value) <= MAX_SERVER_BUILD_LENGTH - ): + if _is_preserved_build(current_path, key, value): continue _collect_string_paths(value, current_path + [str(key)], results) @@ -373,3 +339,57 @@ def truncate_event(event: Dict[str, Any]) -> Dict[str, Any]: # Layer 3: size-targeted normalization return _truncate_to_size(result) + + +def _visit_container( + value: Any, + remaining_depth: int, + max_breadth: int, + max_string_length: int, + memo: set, +) -> Any: + if isinstance(value, (list, tuple)): + oid = id(value) + if oid in memo: + return "[Circular ~]" + if remaining_depth <= 0: + return "[Array]" + memo.add(oid) + result: Any = _visit_array( + list(value), remaining_depth - 1, max_breadth, max_string_length, memo + ) + memo.discard(oid) + return result + + if isinstance(value, dict): + oid = id(value) + if oid in memo: + return "[Circular ~]" + if remaining_depth <= 0: + return "[Object]" + memo.add(oid) + result = _visit_object( + value, remaining_depth - 1, max_breadth, max_string_length, memo + ) + memo.discard(oid) + return result + + return str(value) + + +def _normalize_number(value: Any) -> Any: + if isinstance(value, float): + if math.isnan(value): + return "[NaN]" + if math.isinf(value): + return "[Infinity]" if value > 0 else "[-Infinity]" + return value + + +def _is_preserved_build(current_path: List[str], key: Any, value: Any) -> bool: + return ( + not current_path + and key == "server_build" + and isinstance(value, str) + and len(value) <= MAX_SERVER_BUILD_LENGTH + ) diff --git a/posthog/mcp/asgi.py b/posthog/mcp/asgi.py index a66b41113..c450f026a 100644 --- a/posthog/mcp/asgi.py +++ b/posthog/mcp/asgi.py @@ -116,15 +116,7 @@ async def __call__(self, scope: Any, receive: Any, send: Any) -> None: if scope.get("type") != "http": await self.app(scope, receive, send) return - # Tell the in-process fallback that this request's handshake is captured - # here. Two stacked middlewares see the same request; the outer one owns it. - # The SSE transport stays unmarked: its session is in a query parameter, so - # its first request captures the handshake, in the session its calls use. - observer = None - if HANDSHAKE_OBSERVER_KEY not in scope and not _is_sse(scope): - observer = self._analytics() - if observer is not None: - scope[HANDSHAKE_OBSERVER_KEY] = observer + observer = self._handshake_observer(scope) try: incoming_header = read_mcp_session_header(_headers_dict(scope)) @@ -148,15 +140,7 @@ async def __call__(self, scope: Any, receive: Any, send: Any) -> None: # Guard the whole sniff+mint path: on any failure (a raising receive() or # adversarial body) the request passes through untouched, per the contract. - token = None - initialize = None - try: - body, receive = await _buffer_body(receive) - initialize = _parse_initialize(body) - if initialize is not None: - token = _mint_token(initialize) - except Exception as error: # noqa: BLE001 - log(f"PostHog MCP session middleware: mint failed - {error}") + initialize, token, receive = await _sniff_initialize(receive) if initialize is None: await self.app(scope, receive, send) @@ -176,6 +160,19 @@ async def __call__(self, scope: Any, receive: Any, send: Any) -> None: await self.app(scope, receive, send) + def _handshake_observer(self, scope: Any) -> Optional[MCPAnalyticsData]: + # Tell the in-process fallback that this request's handshake is captured + # here. Two stacked middlewares see the same request; the outer one owns it. + # The SSE transport stays unmarked: its session is in a query parameter, so + # its first request captures the handshake, in the session its calls use. + observer = None + if HANDSHAKE_OBSERVER_KEY not in scope and not _is_sse(scope): + observer = self._analytics() + if observer is not None: + scope[HANDSHAKE_OBSERVER_KEY] = observer + + return observer + def _is_sse(scope: Any) -> bool: """The deprecated SSE transport, which keys its session on ``?session_id=``.""" @@ -482,3 +479,17 @@ def factory(*args: Any, **kwargs: Any) -> Any: setattr(factory, _AUTOWIRED, True) return factory + + +async def _sniff_initialize(receive: Any) -> tuple[Any, Optional[str], Any]: + token = None + initialize = None + try: + body, receive = await _buffer_body(receive) + initialize = _parse_initialize(body) + if initialize is not None: + token = _mint_token(initialize) + except Exception as error: # noqa: BLE001 + log(f"PostHog MCP session middleware: mint failed - {error}") + + return initialize, token, receive diff --git a/posthog/mcp/feedback.py b/posthog/mcp/feedback.py index 5cb732b6c..080359db4 100644 --- a/posthog/mcp/feedback.py +++ b/posthog/mcp/feedback.py @@ -143,17 +143,7 @@ def get_feedback_tool_descriptor( extra_properties = options.extra_properties or {} extra_required = options.extra_required or [] - for key in extra_properties: - if key in _RESERVED_EXTRA_PROPERTY_KEYS: - raise ValueError( - f'collect_feedback extra_properties key "{key}" collides with a core or ' - "SDK-reserved send_feedback field. Rename it." - ) - for key in extra_required: - if key not in extra_properties: - raise ValueError( - f'collect_feedback extra_required key "{key}" is not declared in extra_properties.' - ) + _validate_feedback_extras(extra_properties, extra_required) # Deep copies: the host may reuse or mutate the fragments it handed us, and # schema injection mutates the advertised descriptor. @@ -182,18 +172,7 @@ def _matches_extra_schema(value: Any, schema: Dict[str, Any]) -> bool: ``enum`` — the same advisory-schema enforcement the core fields get, so ``extras`` only ever holds schema-conforming values and a misbehaving agent shows up as absence rather than as an unexpected shape in the host's handler.""" - if isinstance(value, list): - actual = "array" - elif value is None: - actual = "null" - elif isinstance(value, bool): - actual = "boolean" - elif isinstance(value, (int, float)): - actual = "number" - elif isinstance(value, str): - actual = "string" - else: - actual = "object" + actual = _json_type(value) declared = schema.get("type") if declared == "integer" and actual == "number": # A JSON Schema `integer` also accepts a whole-valued float (`3.0`), but @@ -219,12 +198,7 @@ def parse_feedback_report( ``type``/``enum`` are lifted into ``extras`` — mismatches and anything the agent invented reach the handler via ``raw`` only and are never captured.""" raw = args or {} - declared = (options.extra_properties if options is not None else None) or {} - extras = { - key: raw[key] - for key, schema in declared.items() - if raw.get(key) is not None and _matches_extra_schema(raw[key], schema) - } + extras = _parse_feedback_extras(raw, options) feedback_type = raw.get("feedback_type") sentiment = raw.get("sentiment") task_completed = raw.get("task_completed") @@ -309,10 +283,7 @@ def build_feedback_event_properties(report: FeedbackReport) -> JsonRecord: properties[PostHogMCPAnalyticsProperty.FEEDBACK_TASK_COMPLETED] = ( report.task_completed ) - for key, value in report.extras.items(): - captured = _capture_extra_value(value) - if captured is not None: - properties[f"$mcp_feedback_{key}"] = captured + _add_feedback_extras(report, properties) return properties @@ -354,3 +325,54 @@ async def handle_feedback( f"({type(error).__name__}); returning the default acknowledgement" ) return _SEND_FEEDBACK_RESULT_TEXT + + +def _validate_feedback_extras( + extra_properties: Dict[str, Any], extra_required: list[str] +) -> None: + for key in extra_properties: + if key in _RESERVED_EXTRA_PROPERTY_KEYS: + raise ValueError( + f'collect_feedback extra_properties key "{key}" collides with a core or ' + "SDK-reserved send_feedback field. Rename it." + ) + for key in extra_required: + if key not in extra_properties: + raise ValueError( + f'collect_feedback extra_required key "{key}" is not declared in extra_properties.' + ) + + +def _json_type(value: Any) -> str: + if isinstance(value, list): + actual = "array" + elif value is None: + actual = "null" + elif isinstance(value, bool): + actual = "boolean" + elif isinstance(value, (int, float)): + actual = "number" + elif isinstance(value, str): + actual = "string" + else: + actual = "object" + return actual + + +def _parse_feedback_extras( + raw: JsonRecord, options: Optional[CollectFeedbackOptions] +) -> JsonRecord: + declared = (options.extra_properties if options is not None else None) or {} + extras = { + key: raw[key] + for key, schema in declared.items() + if raw.get(key) is not None and _matches_extra_schema(raw[key], schema) + } + return extras + + +def _add_feedback_extras(report: FeedbackReport, properties: JsonRecord) -> None: + for key, value in report.extras.items(): + captured = _capture_extra_value(value) + if captured is not None: + properties[f"$mcp_feedback_{key}"] = captured diff --git a/posthog/mcp/posthog_mcp.py b/posthog/mcp/posthog_mcp.py index 0f039620c..f176e93de 100644 --- a/posthog/mcp/posthog_mcp.py +++ b/posthog/mcp/posthog_mcp.py @@ -470,40 +470,46 @@ def prepare_tool_list( # descriptor, which a host re-preparing an already-prepared list hands # straight back. Warning about that would be warning about ourselves. if report_missing: - name = self._missing_capability_tool_name - existing = _find_tool(prepared, name) - if existing is not None and not self._is_sdk_virtual_tool(existing): - self._warn_virtual_tool_collision( - VIRTUAL_TOOL_MISSING_CAPABILITY, - name, - 'PostHogMCP(missing_capability_tool_name="...")', - ) - elif existing is None: - prepared.append(build_report_missing_descriptor(name)) + self._append_missing_capability(prepared) if collect_feedback and self._collect_feedback is not None: - name = self._feedback_tool_name - existing = _find_tool(prepared, name) - # Both virtual tools under one name: missing-capability wins in - # `prepare_tool_call`, so advertising this one too would dead-letter - # the feedback path. Same precedence as `instrument()`. - duplicate = name == self._missing_capability_tool_name - if duplicate or ( - existing is not None and not self._is_sdk_virtual_tool(existing) - ): - self._warn_virtual_tool_collision( - VIRTUAL_TOOL_FEEDBACK, - name, - 'PostHogMCP(collect_feedback=CollectFeedbackOptions(tool_name="..."))', - variant="duplicate" if duplicate else "blocked", - ) - elif existing is None: - prepared.append(get_feedback_tool_descriptor(self._collect_feedback)) + self._append_feedback(prepared) # Read ownership before any analytics field lands on the schemas. conversation_ownership = _collect_conversation_ownership(prepared) prepared = self._inject_models(prepared) prepared = self._inject_conversation(prepared, conversation_ownership) return prepared + def _append_missing_capability(self, prepared: List[Any]) -> None: + name = self._missing_capability_tool_name + existing = _find_tool(prepared, name) + if existing is not None and not self._is_sdk_virtual_tool(existing): + self._warn_virtual_tool_collision( + VIRTUAL_TOOL_MISSING_CAPABILITY, + name, + 'PostHogMCP(missing_capability_tool_name="...")', + ) + elif existing is None: + prepared.append(build_report_missing_descriptor(name)) + + def _append_feedback(self, prepared: List[Any]) -> None: + name = self._feedback_tool_name + existing = _find_tool(prepared, name) + # Both virtual tools under one name: missing-capability wins in + # `prepare_tool_call`, so advertising this one too would dead-letter + # the feedback path. Same precedence as `instrument()`. + duplicate = name == self._missing_capability_tool_name + if duplicate or ( + existing is not None and not self._is_sdk_virtual_tool(existing) + ): + self._warn_virtual_tool_collision( + VIRTUAL_TOOL_FEEDBACK, + name, + 'PostHogMCP(collect_feedback=CollectFeedbackOptions(tool_name="..."))', + variant="duplicate" if duplicate else "blocked", + ) + elif existing is None: + prepared.append(get_feedback_tool_descriptor(self._collect_feedback)) + def _warn_virtual_tool_collision( self, kind: str, @@ -572,6 +578,63 @@ def prepare_tool_call( if isinstance(raw_context, str) and raw_context.strip() else None ) + prepared_args, llm_model, llm_model_source = self._prepare_model( + name, args, request_meta, original_tool + ) + + prepared_args, session_id, conversation_id, conversation_state = ( + self._prepare_conversation( + name, args, prepared_args, original_tool, session_id + ) + ) + # A supplied `original_tool` is a real application tool by this name (it + # comes from the host's own list, which never holds a virtual tool), so + # the real tool wins — the stateless twin of the ownership check + # instrument() runs. Without it the name match stands, and the + # documented remedy for a collision is renaming PostHog's tool. + # The name check against missing-capability keeps one precedence when + # both tools share a name: without it both flags are true, and a + # dispatcher testing `is_feedback` first misroutes every call. + is_feedback = self._is_feedback_call(name, original_tool) + # Same guard for the missing-capability tool. Unlike feedback it has no + # constructor enable switch on this path (the name is always populated), + # so `original_tool` is the only ownership signal available here. + is_missing_capability = ( + name == self._missing_capability_tool_name and original_tool is None + ) + return PreparedToolCall( + args=prepared_args, + intent=intent, + intent_source="context_parameter" if intent else None, + llm_model=llm_model, + llm_model_source=llm_model_source, + is_missing_capability=is_missing_capability, + is_feedback=is_feedback, + feedback_report=( + parse_feedback_report(args, self._collect_feedback) + if is_feedback + else None + ), + session_id=session_id, + conversation_id=conversation_id, + _conversation_state=conversation_state, + ) + + def _is_feedback_call(self, name: str, original_tool: Any) -> bool: + return ( + self._collect_feedback is not None + and name == self._feedback_tool_name + and name != self._missing_capability_tool_name + and original_tool is None + ) + + def _prepare_model( + self, + name: str, + args: Optional[JsonRecord], + request_meta: Optional[JsonRecord], + original_tool: Any, + ) -> Tuple[Optional[JsonRecord], Optional[str], Optional[MCPAnalyticsModelSource]]: analytics_owns_model = False llm_model: Optional[str] = None llm_model_source: Optional[MCPAnalyticsModelSource] = None @@ -589,6 +652,27 @@ def prepare_tool_call( if analytics_owns_model: prepared_args = _strip_args(prepared_args, "llm_model") + return prepared_args, llm_model, llm_model_source + + def _owns_conversation_parameter( + self, ownership: Optional[_ConversationOwnership] + ) -> bool: + return ( + self._enable_conversation_id + and ownership is not None + and ownership.conversation_id + ) + + def _prepare_conversation( + self, + name: str, + args: Optional[JsonRecord], + prepared_args: Optional[JsonRecord], + original_tool: Any, + session_id: Optional[str], + ) -> Tuple[ + Optional[JsonRecord], Optional[str], Optional[str], PreparedConversationState + ]: ownership = ( _conversation_ownership_of(original_tool) if original_tool is not None @@ -607,53 +691,21 @@ def prepare_tool_call( conversation_id = None if minted else resolved_conversation_id if conversation_id: session_id = derive_session_id_from_conversation(conversation_id) - if ( - self._enable_conversation_id - and ownership is not None - and ownership.conversation_id - ): + if self._owns_conversation_parameter(ownership): prepared_args = _strip_args(prepared_args, "conversation_id") - # A supplied `original_tool` is a real application tool by this name (it - # comes from the host's own list, which never holds a virtual tool), so - # the real tool wins — the stateless twin of the ownership check - # instrument() runs. Without it the name match stands, and the - # documented remedy for a collision is renaming PostHog's tool. - # The name check against missing-capability keeps one precedence when - # both tools share a name: without it both flags are true, and a - # dispatcher testing `is_feedback` first misroutes every call. - is_feedback = ( - self._collect_feedback is not None - and name == self._feedback_tool_name - and name != self._missing_capability_tool_name - and original_tool is None - ) - # Same guard for the missing-capability tool. Unlike feedback it has no - # constructor enable switch on this path (the name is always populated), - # so `original_tool` is the only ownership signal available here. - is_missing_capability = ( - name == self._missing_capability_tool_name and original_tool is None - ) - return PreparedToolCall( - args=prepared_args, - intent=intent, - intent_source="context_parameter" if intent else None, - llm_model=llm_model, - llm_model_source=llm_model_source, - is_missing_capability=is_missing_capability, - is_feedback=is_feedback, - feedback_report=( - parse_feedback_report(args, self._collect_feedback) - if is_feedback - else None - ), - session_id=session_id, - conversation_id=conversation_id, - _conversation_state=PreparedConversationState( - minted_conversation_id=minted_conversation_id, - output_instructions=self._enable_conversation_id - and ownership is not None - and ownership.output_instructions, - ), + state = self._prepared_conversation_state(ownership, minted_conversation_id) + return prepared_args, session_id, conversation_id, state + + def _prepared_conversation_state( + self, + ownership: Optional[_ConversationOwnership], + minted_conversation_id: Optional[str], + ) -> PreparedConversationState: + return PreparedConversationState( + minted_conversation_id=minted_conversation_id, + output_instructions=self._enable_conversation_id + and ownership is not None + and ownership.output_instructions, ) def prepare_tool_result( @@ -683,10 +735,7 @@ def prepare_tool_result( prepared, handle ) if minted_conversation_id: - injected = inject_prompt_back(prepared, handle) - if injected is not prepared: - delivered = True - prepared = injected + prepared, delivered = _deliver_minted_handle(prepared, handle, delivered) if delivered: conversation_id = handle session_id = derive_session_id_from_conversation(handle) @@ -982,3 +1031,12 @@ def _tool_schema(tool: Any) -> Optional[Dict[str, Any]]: if schema is None: schema = getattr(tool, "inputSchema", None) return schema if isinstance(schema, dict) else None + + +def _deliver_minted_handle( + prepared: Any, handle: str, delivered: bool +) -> Tuple[Any, bool]: + injected = inject_prompt_back(prepared, handle) + if injected is not prepared: + delivered = True + return injected, delivered diff --git a/posthog/mcp/session_token.py b/posthog/mcp/session_token.py index ac2b38593..a562b9b27 100644 --- a/posthog/mcp/session_token.py +++ b/posthog/mcp/session_token.py @@ -86,10 +86,31 @@ def decode_session_id(value: Any) -> Optional[SessionTokenPayload]: return None if not isinstance(parsed, dict): return None - sid = parsed.get("sid") - if not isinstance(sid, str) or not sid or len(sid) > _MAX_SESSION_ID_LENGTH: + return _decode_token_payload(parsed) + + +def read_mcp_session_header(headers: Any) -> Optional[str]: + """Read the ``mcp-session-id`` value off a headers mapping. + + Handles case-insensitive keys (transports lowercase them, but hand-built + mappings may not) and list-valued headers, and trims whitespace. + """ + if headers is None: return None - payload = SessionTokenPayload(session_id=sid) + value = _session_header_value(headers) + first = value[0] if isinstance(value, (list, tuple)) and value else value + if not isinstance(first, str): + return None + trimmed = first.strip() + return trimmed or None + + +def _base64url_to_bytes(value: str) -> bytes: + padding = "=" * (-len(value) % 4) + return base64.urlsafe_b64decode(value + padding) + + +def _decode_client_fields(parsed: dict, payload: SessionTokenPayload) -> None: # A bad cn/cv/pv just means no client info -- it does not reject the token. cn = parsed.get("cn") if isinstance(cn, str) and cn: @@ -100,17 +121,9 @@ def decode_session_id(value: Any) -> Optional[SessionTokenPayload]: pv = parsed.get("pv") if isinstance(pv, str) and pv: payload.protocol_version = pv[:_MAX_CLIENT_FIELD_LENGTH] - return payload - -def read_mcp_session_header(headers: Any) -> Optional[str]: - """Read the ``mcp-session-id`` value off a headers mapping. - Handles case-insensitive keys (transports lowercase them, but hand-built - mappings may not) and list-valued headers, and trims whitespace. - """ - if headers is None: - return None +def _session_header_value(headers: Any) -> Any: value: Any = None # Mapping-like: prefer a direct get, else scan case-insensitively. get = getattr(headers, "get", None) @@ -125,13 +138,13 @@ def read_mcp_session_header(headers: Any) -> Optional[str]: if isinstance(key, str) and key.lower() == MCP_SESSION_HEADER: value = candidate break - first = value[0] if isinstance(value, (list, tuple)) and value else value - if not isinstance(first, str): - return None - trimmed = first.strip() - return trimmed or None + return value -def _base64url_to_bytes(value: str) -> bytes: - padding = "=" * (-len(value) % 4) - return base64.urlsafe_b64decode(value + padding) +def _decode_token_payload(parsed: dict[str, Any]) -> Optional[SessionTokenPayload]: + sid = parsed.get("sid") + if not isinstance(sid, str) or not sid or len(sid) > _MAX_SESSION_ID_LENGTH: + return None + payload = SessionTokenPayload(session_id=sid) + _decode_client_fields(parsed, payload) + return payload diff --git a/posthog/metrics_capture.py b/posthog/metrics_capture.py index 3d8bc15d4..86dd5c5db 100644 --- a/posthog/metrics_capture.py +++ b/posthog/metrics_capture.py @@ -102,16 +102,7 @@ def _to_otlp_any_value(value: Any) -> dict: if isinstance(value, int): return {"intValue": value} if isinstance(value, float): - # proto3 JSON has no representation for non-finite floats; encode the proto3 - # literal strings (not Python's "inf"/"nan") so both SDKs emit identical bytes. - if not math.isfinite(value): - if math.isnan(value): - return {"stringValue": "NaN"} - return {"stringValue": "Infinity" if value > 0 else "-Infinity"} - # Integral floats encode as intValue, matching the JS Number.isInteger branch. - if value.is_integer(): - return {"intValue": int(value)} - return {"doubleValue": value} + return _float_otlp_value(value) if isinstance(value, str): return {"stringValue": value} if isinstance(value, (list, tuple)): @@ -343,18 +334,9 @@ def __init__(self, client, config: Optional[dict] = None): self._flush_interval: float = _validated_flush_interval( config.get("flush_interval", _DEFAULT_FLUSH_INTERVAL_SECONDS) ) - max_series = config.get("max_series_per_flush", _DEFAULT_MAX_SERIES_PER_FLUSH) - if ( - not isinstance(max_series, int) - or isinstance(max_series, bool) - or max_series <= 0 - ): - log.warning( - "Ignoring metrics max_series_per_flush %r: expected a positive integer", - max_series, - ) - max_series = _DEFAULT_MAX_SERIES_PER_FLUSH - self._max_series_per_flush: int = max_series + self._max_series_per_flush: int = _validated_max_series( + config.get("max_series_per_flush", _DEFAULT_MAX_SERIES_PER_FLUSH) + ) self._before_send: Optional[Callable] = _validated_before_send( config.get("before_send") ) @@ -450,17 +432,8 @@ def _capture( "attributes": attributes, } if self._before_send is not None: - try: - filtered = self._before_send(sample) - except Exception as e: - log.error("Error in metrics before_send: %s", e) - return - if not filtered: - return - if not isinstance(filtered, dict): - log.warning( - "Dropping metric: before_send must return the sample dict or a falsy value" - ) + filtered = _filter_metric_sample(self._before_send, sample) + if filtered is None: return sample_dict: dict[str, Any] = filtered # Defaults keep the static types closed; a hook that removed the field @@ -471,26 +444,7 @@ def _capture( unit = sample_dict.get("unit") attributes = sample_dict.get("attributes") - if metric_type not in _VALID_METRIC_TYPES: - log.warning( - "Dropping metric '%s': unknown metric type '%s'", name, metric_type - ) - return - - if not name or not isinstance(name, str): - log.warning("Dropping metric with empty name") - return - if ( - not isinstance(value, (int, float)) - or isinstance(value, bool) - or not math.isfinite(value) - ): - log.warning("Dropping metric '%s': value must be a finite number", name) - return - if metric_type == "count" and value < 0: - log.warning( - "Dropping count '%s': counters are monotonic, value must be >= 0", name - ) + if not _valid_metric_sample(metric_type, name, value): return if attributes: @@ -503,45 +457,53 @@ def _capture( with self._lock: self._reset_after_fork_locked() - state = self._series.get(key) + state = self._admit_series_locked(key, name, metric_type, unit, attributes) if state is None: - if len(self._series) >= self._max_series_per_flush: - if not self._series_cap_warned: - self._series_cap_warned = True - log.warning( - "Metric series cap reached (%s per flush window); dropping new series " - "until the next flush. Reduce attribute cardinality.", - self._max_series_per_flush, - ) - return - state = _SeriesState(name, metric_type, unit, attributes) - self._series[key] = state - - # Bookkeeping only for admitted samples, so name-cardinality misuse (IDs in - # metric names) can't grow this map past the series cap. - seen_type = self._type_by_name.get(name) - if seen_type is None: - self._type_by_name[name] = metric_type - elif seen_type != metric_type and name not in self._type_collision_warned: - self._type_collision_warned.add(name) - log.warning( - "Metric name '%s' is already used as a %s; recording it as a %s too will blend " - "both series in charts. Use a distinct name.", - name, - seen_type, - metric_type, - ) + return self._fold(state, float(value)) - if trace_context is not None: - state.exemplar = { - "trace_id": trace_context[0], - "span_id": trace_context[1], - "value": float(value), - "time_ms": int(time.time() * 1000), - } + _record_exemplar(state, trace_context, value) self._arm_flush_timer() + def _admit_series_locked( + self, + key: str, + name: str, + metric_type: str, + unit: Optional[str], + attributes: Optional[dict], + ) -> Optional[_SeriesState]: + state = self._series.get(key) + if state is None: + if len(self._series) >= self._max_series_per_flush: + if not self._series_cap_warned: + self._series_cap_warned = True + log.warning( + "Metric series cap reached (%s per flush window); dropping new series " + "until the next flush. Reduce attribute cardinality.", + self._max_series_per_flush, + ) + return None + state = _SeriesState(name, metric_type, unit, attributes) + self._series[key] = state + + # Bookkeeping only for admitted samples, so name-cardinality misuse (IDs in + # metric names) can't grow this map past the series cap. + seen_type = self._type_by_name.get(name) + if seen_type is None: + self._type_by_name[name] = metric_type + elif seen_type != metric_type and name not in self._type_collision_warned: + self._type_collision_warned.add(name) + log.warning( + "Metric name '%s' is already used as a %s; recording it as a %s too will blend " + "both series in charts. Use a distinct name.", + name, + seen_type, + metric_type, + ) + + return state + def _reinit_after_fork(self) -> None: # Runs in a forked child (via the client's os.register_at_fork hook) before # user code. The inherited locks may be held by parent threads that do not @@ -734,23 +696,7 @@ def _merge_window_back(self, window: dict) -> None: continue self._series[key] = old continue - current.window_start_ms = min(current.window_start_ms, old.window_start_ms) - # The live window's exemplar is newer; the old one only fills a gap. - if current.exemplar is None: - current.exemplar = old.exemplar - if current.type == "count": - current.total = (current.total or 0.0) + (old.total or 0.0) - elif current.type == "histogram" and old.hist: - if current.hist is None: - current.hist = old.hist - else: - current.hist["count"] += old.hist["count"] - current.hist["sum"] += old.hist["sum"] - current.hist["min"] = min(current.hist["min"], old.hist["min"]) - current.hist["max"] = max(current.hist["max"], old.hist["max"]) - for i, count in enumerate(old.hist["bucket_counts"]): - current.hist["bucket_counts"][i] += count - # Gauge: the live window's value is newer — keep it. + _merge_series_state(current, old) if dropped: log.warning( "Dropped %s unsent metric series while merging a failed flush back (series cap %s)", @@ -795,64 +741,172 @@ def _build_metrics(self, window: dict) -> list: metric_key = (state.type, state.name, state.unit or "") metric = by_metric.get(metric_key) if metric is None: - metric = {"name": state.name} - if state.unit: - metric["unit"] = state.unit - if state.type == "count": - metric["sum"] = { - "aggregationTemporality": _OTLP_TEMPORALITY_DELTA, - "isMonotonic": True, - "dataPoints": [], - } - elif state.type == "gauge": - metric["gauge"] = {"dataPoints": []} - else: - metric["histogram"] = { - "aggregationTemporality": _OTLP_TEMPORALITY_DELTA, - "dataPoints": [], - } + metric = _metric_descriptor(state) by_metric[metric_key] = metric - attributes = _to_otlp_key_value_list(state.attributes or {}) - start_nano = _ms_to_unix_nano(state.window_start_ms) - exemplars = _build_exemplars(state.exemplar) - - if state.type == "count": - metric["sum"]["dataPoints"].append( - { - "attributes": attributes, - "startTimeUnixNano": start_nano, - "timeUnixNano": now_nano, - "asDouble": state.total or 0.0, - **exemplars, - } - ) - elif state.type == "gauge": - metric["gauge"]["dataPoints"].append( - { - "attributes": attributes, - "timeUnixNano": now_nano, - "asDouble": state.last or 0.0, - **exemplars, - } - ) - elif state.hist is not None: - # Encoding pinned by the ingest's JSON deserializer: nano timestamps are decimal - # strings, but count/bucketCounts are plain JSON numbers — string-encoded u64s in - # those fields are silently dropped upstream (opentelemetry-rust#3328). - metric["histogram"]["dataPoints"].append( - { - "attributes": attributes, - "startTimeUnixNano": start_nano, - "timeUnixNano": now_nano, - "count": state.hist["count"], - "sum": state.hist["sum"], - "min": state.hist["min"], - "max": state.hist["max"], - "bucketCounts": state.hist["bucket_counts"], - "explicitBounds": DEFAULT_HISTOGRAM_BOUNDS, - **exemplars, - } - ) + _append_metric_point(metric, state, now_nano) return list(by_metric.values()) + + +def _float_otlp_value(value: float) -> dict: + # proto3 JSON has no representation for non-finite floats; encode the proto3 + # literal strings (not Python's "inf"/"nan") so both SDKs emit identical bytes. + if not math.isfinite(value): + if math.isnan(value): + return {"stringValue": "NaN"} + return {"stringValue": "Infinity" if value > 0 else "-Infinity"} + # Integral floats encode as intValue, matching the JS Number.isInteger branch. + if value.is_integer(): + return {"intValue": int(value)} + return {"doubleValue": value} + + +def _validated_max_series(max_series: Any) -> int: + if ( + not isinstance(max_series, int) + or isinstance(max_series, bool) + or max_series <= 0 + ): + log.warning( + "Ignoring metrics max_series_per_flush %r: expected a positive integer", + max_series, + ) + max_series = _DEFAULT_MAX_SERIES_PER_FLUSH + return max_series + + +def _valid_metric_sample(metric_type: str, name: str, value: float) -> bool: + if metric_type not in _VALID_METRIC_TYPES: + log.warning("Dropping metric '%s': unknown metric type '%s'", name, metric_type) + return False + + if not name or not isinstance(name, str): + log.warning("Dropping metric with empty name") + return False + if ( + not isinstance(value, (int, float)) + or isinstance(value, bool) + or not math.isfinite(value) + ): + log.warning("Dropping metric '%s': value must be a finite number", name) + return False + if metric_type == "count" and value < 0: + log.warning( + "Dropping count '%s': counters are monotonic, value must be >= 0", name + ) + return False + + return True + + +def _filter_metric_sample(before_send: Callable, sample: dict) -> Optional[dict]: + try: + filtered = before_send(sample) + except Exception as e: + log.error("Error in metrics before_send: %s", e) + return None + if not filtered: + return None + if not isinstance(filtered, dict): + log.warning( + "Dropping metric: before_send must return the sample dict or a falsy value" + ) + return None + return filtered + + +def _merge_series_state(current: _SeriesState, old: _SeriesState) -> None: + current.window_start_ms = min(current.window_start_ms, old.window_start_ms) + # The live window's exemplar is newer; the old one only fills a gap. + if current.exemplar is None: + current.exemplar = old.exemplar + if current.type == "count": + current.total = (current.total or 0.0) + (old.total or 0.0) + elif current.type == "histogram" and old.hist: + if current.hist is None: + current.hist = old.hist + else: + current.hist["count"] += old.hist["count"] + current.hist["sum"] += old.hist["sum"] + current.hist["min"] = min(current.hist["min"], old.hist["min"]) + current.hist["max"] = max(current.hist["max"], old.hist["max"]) + for i, count in enumerate(old.hist["bucket_counts"]): + current.hist["bucket_counts"][i] += count + # Gauge: the live window's value is newer — keep it. + + +def _metric_descriptor(state: _SeriesState) -> dict: + metric: dict = {"name": state.name} + if state.unit: + metric["unit"] = state.unit + if state.type == "count": + metric["sum"] = { + "aggregationTemporality": _OTLP_TEMPORALITY_DELTA, + "isMonotonic": True, + "dataPoints": [], + } + elif state.type == "gauge": + metric["gauge"] = {"dataPoints": []} + else: + metric["histogram"] = { + "aggregationTemporality": _OTLP_TEMPORALITY_DELTA, + "dataPoints": [], + } + return metric + + +def _record_exemplar( + state: _SeriesState, trace_context: Optional[tuple[str, str]], value: float +) -> None: + if trace_context is not None: + state.exemplar = { + "trace_id": trace_context[0], + "span_id": trace_context[1], + "value": float(value), + "time_ms": int(time.time() * 1000), + } + + +def _append_metric_point(metric: dict, state: _SeriesState, now_nano: str) -> None: + attributes = _to_otlp_key_value_list(state.attributes or {}) + start_nano = _ms_to_unix_nano(state.window_start_ms) + exemplars = _build_exemplars(state.exemplar) + + if state.type == "count": + metric["sum"]["dataPoints"].append( + { + "attributes": attributes, + "startTimeUnixNano": start_nano, + "timeUnixNano": now_nano, + "asDouble": state.total or 0.0, + **exemplars, + } + ) + elif state.type == "gauge": + metric["gauge"]["dataPoints"].append( + { + "attributes": attributes, + "timeUnixNano": now_nano, + "asDouble": state.last or 0.0, + **exemplars, + } + ) + elif state.hist is not None: + # Encoding pinned by the ingest's JSON deserializer: nano timestamps are decimal + # strings, but count/bucketCounts are plain JSON numbers — string-encoded u64s in + # those fields are silently dropped upstream (opentelemetry-rust#3328). + metric["histogram"]["dataPoints"].append( + { + "attributes": attributes, + "startTimeUnixNano": start_nano, + "timeUnixNano": now_nano, + "count": state.hist["count"], + "sum": state.hist["sum"], + "min": state.hist["min"], + "max": state.hist["max"], + "bucketCounts": state.hist["bucket_counts"], + "explicitBounds": DEFAULT_HISTOGRAM_BOUNDS, + **exemplars, + } + ) diff --git a/posthog/request.py b/posthog/request.py index 52854f922..e7f179374 100644 --- a/posthog/request.py +++ b/posthog/request.py @@ -296,24 +296,7 @@ def _process_response( ) raise QuotaLimitError(res.status_code, "Feature flags quota limited") return response - retry_after = None - retry_after_header = res.headers.get("Retry-After") - if retry_after_header: - try: - retry_after = float(retry_after_header) - except (ValueError, TypeError): - try: - from email.utils import parsedate_to_datetime - - retry_after = max( - 0.0, - ( - parsedate_to_datetime(retry_after_header) - - datetime.now(timezone.utc) - ).total_seconds(), - ) - except (ValueError, TypeError): - pass + retry_after = _response_retry_after(res) try: payload = res.json() @@ -550,3 +533,26 @@ def default(self, obj: Any): def encode(self, o: Any) -> str: return super().encode(_replace_non_finite_floats(o)) + + +def _response_retry_after(res: requests.Response) -> Optional[float]: + retry_after = None + retry_after_header = res.headers.get("Retry-After") + if retry_after_header: + try: + retry_after = float(retry_after_header) + except (ValueError, TypeError): + try: + from email.utils import parsedate_to_datetime + + retry_after = max( + 0.0, + ( + parsedate_to_datetime(retry_after_header) + - datetime.now(timezone.utc) + ).total_seconds(), + ) + except (ValueError, TypeError): + pass + + return retry_after diff --git a/posthog/test/ai/anthropic/test_anthropic_converter.py b/posthog/test/ai/anthropic/test_anthropic_converter.py index aef31a03a..9294c465d 100644 --- a/posthog/test/ai/anthropic/test_anthropic_converter.py +++ b/posthog/test/ai/anthropic/test_anthropic_converter.py @@ -213,3 +213,95 @@ def test_stream_message_delta_thinking_tokens_not_double_counted(): ) assert acc.usage_stats["output_tokens"] == 50 assert acc.usage_stats["reasoning_tokens"] == 30 + + +def test_stream_keeps_block_indexes_thinking_private_from_text_and_cumulative_usage(): + from types import SimpleNamespace as NS + + from posthog.ai.anthropic._anthropic_stream import _AnthropicStreamAccumulator + + accumulator = _AnthropicStreamAccumulator() + events = [ + NS( + type="message_start", + message=NS(usage=NS(input_tokens=10, cache_read_input_tokens=1)), + ), + NS( + type="content_block_start", + index=0, + content_block=NS(type="thinking", thinking="", signature=""), + ), + NS( + type="content_block_delta", + index=0, + delta=NS(type="thinking_delta", thinking="reason"), + ), + NS( + type="content_block_delta", + index=0, + delta=NS(type="signature_delta", signature="sig"), + ), + NS(type="content_block_stop", index=0), + NS( + type="content_block_start", + index=1, + content_block=NS(type="server_tool_use", id="server-1"), + ), + NS(type="content_block_stop", index=1), + NS( + type="content_block_start", + index=2, + content_block=NS(type="tool_use", id="call-2", name="lookup"), + ), + NS( + type="content_block_delta", + index=2, + delta=NS(type="input_json_delta", partial_json='{"q":'), + ), + NS( + type="content_block_delta", + index=2, + delta=NS(type="input_json_delta", partial_json='"term"}'), + ), + NS(type="content_block_stop", index=2), + NS(type="content_block_start", index=3, content_block=NS(type="text")), + NS( + type="content_block_delta", + index=3, + delta=NS(type="text_delta", text="answer"), + ), + NS(type="content_block_stop", index=3), + NS( + type="message_delta", + usage=NS(input_tokens=30, cache_read_input_tokens=4, output_tokens=5), + ), + NS( + type="message_delta", + usage=NS(input_tokens=28, output_tokens=8), + delta=NS(stop_reason="end_turn"), + ), + ] + for event in events: + accumulator.consume(event) + + assert accumulator.accumulated_content == "answer" + assert accumulator.stop_reason == "end_turn" + assert accumulator.usage_stats["input_tokens"] == 30 + assert accumulator.usage_stats["cache_read_input_tokens"] == 4 + assert accumulator.usage_stats["output_tokens"] == 8 + assert format_anthropic_streaming_output_complete( + accumulator.content_blocks, accumulator.accumulated_content + ) == [ + { + "role": "assistant", + "content": [ + {"type": "thinking", "thinking": "reason", "signature": "sig"}, + { + "type": "function", + "id": "call-2", + "function": {"name": "lookup", "arguments": {"q": "term"}}, + }, + {"type": "text", "text": "answer"}, + ], + } + ] diff --git a/posthog/test/ai/claude_agent_sdk/test_client.py b/posthog/test/ai/claude_agent_sdk/test_client.py new file mode 100644 index 000000000..acdd38ac3 --- /dev/null +++ b/posthog/test/ai/claude_agent_sdk/test_client.py @@ -0,0 +1,372 @@ +"""Stateful Claude client delivery, turn boundaries, and teardown contracts.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest + +pytest.importorskip("claude_agent_sdk") +from claude_agent_sdk.types import ( # noqa: E402 + AssistantMessage, + ClaudeAgentOptions, + ResultMessage, + StreamEvent, + TextBlock, + ToolResultBlock, + ToolUseBlock, + UserMessage, +) + +from posthog.ai.claude_agent_sdk import PostHogClaudeSDKClient # noqa: E402 +from posthog.ai.claude_agent_sdk.processor import ( # noqa: E402 + PostHogClaudeAgentProcessor, +) + + +def stream(kind, **data): + return StreamEvent(uuid="evt", session_id="session", event={"type": kind, **data}) + + +def result(**overrides): + return ResultMessage( + **{ + "subtype": "success", + "duration_ms": 2000, + "duration_api_ms": 1500, + "is_error": False, + "num_turns": 1, + "session_id": "session", + "usage": {"input_tokens": 10, "output_tokens": 0}, + "total_cost_usd": 0.01, + **overrides, + } + ) + + +@pytest.fixture +def sdk(monkeypatch): + client = SimpleNamespace( + connect=AsyncMock(), + query=AsyncMock(), + disconnect=AsyncMock(), + interrupt=AsyncMock(), + set_permission_mode=AsyncMock(), + set_model=AsyncMock(), + ) + constructor = MagicMock(return_value=client) + monkeypatch.setattr( + "posthog.ai.claude_agent_sdk.client.ClaudeSDKClient", constructor + ) + client.constructor = constructor + return client + + +def respond(sdk, messages): + async def receive(): + for message in messages: + yield message + + sdk.receive_response = receive + + +def analytics(): + return MagicMock(privacy_mode=False, enable_full_ai_capture=False) + + +def events(ph, name): + return [ + call.kwargs + for call in ph.capture.call_args_list + if call.kwargs["event"] == name + ] + + +@pytest.mark.asyncio +async def test_multiturn_stream_tool_parentage_input_promotion_and_final_trace(sdk): + ph = analytics() + tool = ToolUseBlock(id="tool-1", name="lookup", input={"query": "stock"}) + first = [ + stream( + "message_start", message={"model": "claude", "usage": {"input_tokens": 12}} + ), + AssistantMessage(model="claude", content=[TextBlock(text="checking"), tool]), + UserMessage( + content=[ + ToolResultBlock( + tool_use_id="tool-1", + content=[ + { + "type": "image", + "source": { + "type": "base64", + "media_type": "image/png", + "data": "A" * 400, + }, + } + ], + ), + TextBlock(text="tool done"), + ] + ), + # Empty/unrecognized content must not overwrite already queued tool results. + UserMessage(content=[]), + stream( + "message_delta", + usage={"output_tokens": 4}, + delta={"stop_reason": "tool_use"}, + ), + stream("message_stop"), + stream( + "message_start", message={"model": "claude", "usage": {"input_tokens": 20}} + ), + AssistantMessage(model="claude", content=[TextBlock(text="answer")]), + UserMessage(content="next input"), + stream("message_delta", usage={"output_tokens": 2}), + stream("message_stop"), + result(), + ] + async with PostHogClaudeSDKClient( + posthog_client=ph, + posthog_distinct_id="user", + posthog_trace_id="trace", + posthog_properties={"environment": "test"}, + posthog_groups={"team": "sdk"}, + ) as client: + await client.query("question", session_id="session") + respond(sdk, first) + assert [msg async for msg in client.receive_response()] == first + assert not events(ph, "$ai_trace") + generations = events(ph, "$ai_generation") + assert len(generations) == 2 + one, two = [event["properties"] for event in generations] + assert one["$ai_input"] == [{"role": "user", "content": "question"}] + assert one["$ai_output_choices"][0]["content"][0] == { + "type": "text", + "text": "checking", + } + assert one["$ai_input_tokens"] == 12 + assert one["$ai_output_tokens"] == 4 + assert one["$ai_stop_reason"] == "tool_use" + assert two["$ai_input"] == [ + { + "role": "user", + "content": [ + { + "type": "tool_result", + "tool_use_id": "tool-1", + "content": [ + { + "type": "image", + "source": { + "type": "base64", + "media_type": "image/png", + "data": "[base64 image redacted]", + }, + }, + ], + }, + {"type": "text", "text": "tool done"}, + ], + } + ] + span = events(ph, "$ai_span")[0]["properties"] + assert span["$ai_parent_id"] == one["$ai_span_id"] + assert span["$ai_input_state"] == {"query": "stock"} + assert span["$ai_span_name"] == "lookup" + + await client.query("follow up") + second = [ + stream("message_start", message={"model": "claude", "usage": {}}), + AssistantMessage(model="claude", content=[]), + stream("message_stop"), + result(), + ] + respond(sdk, second) + assert [msg async for msg in client.receive_response()] == second + third = events(ph, "$ai_generation")[2]["properties"] + assert third["$ai_span_name"] == "generation_3" + assert third["$ai_input"] == [{"role": "user", "content": "follow up"}] + assert "$ai_output_choices" not in third + assert "$ai_input_tokens" not in third + assert not events(ph, "$ai_trace") + traces = events(ph, "$ai_trace") + assert len(traces) == 1 + assert traces[0]["properties"]["$ai_trace_name"] == "claude_agent_sdk_session" + assert { + event["properties"]["$ai_trace_id"] for event in events(ph, "$ai_generation") + } == {"trace"} + for event in ph.capture.call_args_list: + assert event.kwargs["distinct_id"] == "user" + assert event.kwargs["groups"] == {"team": "sdk"} + assert event.kwargs["properties"]["environment"] == "test" + ph.flush.assert_called_once_with() + sdk.connect.assert_awaited_once_with(None) + assert sdk.query.await_args_list[0].args == ("question", "session") + sdk.disconnect.assert_awaited_once_with() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("private", [False, True]) +async def test_result_fallback_and_privacy_without_person_identity(sdk, private): + ph = analytics() + client = PostHogClaudeSDKClient( + posthog_client=ph, posthog_trace_id="trace", posthog_privacy_mode=private + ) + await client.query("secret") + messages = [ + AssistantMessage(model="claude", content=[TextBlock(text="response")]), + result(), + ] + respond(sdk, messages) + assert [msg async for msg in client.receive_response()] == messages + generation = events(ph, "$ai_generation")[0] + props = generation["properties"] + assert generation["distinct_id"] == "trace" + assert props["$process_person_profile"] is False + assert props["$ai_input"] == ( + None if private else [{"role": "user", "content": "secret"}] + ) + assert props["$ai_output_choices"] == ( + None + if private + else [{"role": "assistant", "content": [{"type": "text", "text": "response"}]}] + ) + assert props["$ai_input_tokens"] == 10 + assert props["$ai_output_tokens"] == 0 + assert props["$ai_latency"] == 1.5 + assert props["$ai_total_cost_usd"] == 0.01 + assert not events(ph, "$ai_trace") + await client.disconnect() + assert events(ph, "$ai_trace")[0]["properties"]["$process_person_profile"] is False + + +@pytest.mark.asyncio +@pytest.mark.parametrize("partial", [None, False, True]) +async def test_options_are_copied_and_delegation_preserves_arguments(sdk, partial): + options = ( + None + if partial is None + else ClaudeAgentOptions( + include_partial_messages=partial, system_prompt="system" + ) + ) + transport = object() + client = PostHogClaudeSDKClient(options, transport, posthog_client=analytics()) + actual, actual_transport = sdk.constructor.call_args.args + assert actual.include_partial_messages is True + assert actual_transport is transport + if options is not None: + assert options.include_partial_messages is partial + assert actual.system_prompt == "system" + assert (actual is options) is partial + await client.connect("initial") + await client.interrupt() + await client.set_permission_mode("acceptEdits") + await client.set_model("claude") + await client.set_model() + sdk.connect.assert_awaited_once_with("initial") + sdk.interrupt.assert_awaited_once_with() + sdk.set_permission_mode.assert_awaited_once_with("acceptEdits") + assert [call.args for call in sdk.set_model.await_args_list] == [ + ("claude",), + (None,), + ] + + +@pytest.mark.asyncio +async def test_instrumentation_failures_never_interrupt_delivery_or_disconnect(sdk): + ph = analytics() + ph.capture.side_effect = RuntimeError("capture failure") + ph.flush.side_effect = RuntimeError("flush failure") + client = PostHogClaudeSDKClient(posthog_client=ph) + await client.query("prompt") + messages = [stream("message_start", message=None), result()] + respond(sdk, messages) + assert [msg async for msg in client.receive_response()] == messages + await client.disconnect() + sdk.disconnect.assert_awaited_once_with() + + +@pytest.mark.asyncio +async def test_context_manager_propagates_application_exception_and_disconnects(sdk): + ph = analytics() + with pytest.raises(ValueError, match="application failure"): + async with PostHogClaudeSDKClient(posthog_client=ph): + raise ValueError("application failure") + sdk.disconnect.assert_awaited_once_with() + assert len(events(ph, "$ai_trace")) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("resolved", [None, "person", 123]) +async def test_processor_callable_identity_receives_result_only( + sdk, monkeypatch, resolved +): + ph = analytics() + resolve = MagicMock(return_value=resolved) + processor = PostHogClaudeAgentProcessor(client=ph, distinct_id=resolve) + message = result() + + async def query(**kwargs): + yield message + + monkeypatch.setattr("posthog.ai.claude_agent_sdk.processor.original_query", query) + assert [msg async for msg in processor.query(prompt="question")] == [message] + resolve.assert_called_once_with(message) + generation = events(ph, "$ai_generation")[0] + trace = events(ph, "$ai_trace")[0] + assert generation["distinct_id"] == generation["properties"]["$ai_trace_id"] + assert generation["properties"]["$process_person_profile"] is False + assert trace["distinct_id"] == ( + str(resolved) if resolved else trace["properties"]["$ai_trace_id"] + ) + assert ("$process_person_profile" in trace["properties"]) is (not bool(resolved)) + + +@pytest.mark.parametrize("resolved", [None, "person", 123, ""]) +def test_processor_identity_fallback_defers_callable_until_result(resolved): + """Generation events have no result; only the final trace may resolve a callable ID.""" + resolve = MagicMock(return_value=resolved) + processor = PostHogClaudeAgentProcessor(client=analytics(), distinct_id=resolve) + assert processor._resolve_distinct_id(None) is None + resolve.assert_not_called() + message = result() + assert processor._resolve_distinct_id(None, message) == ( + str(resolved) if resolved else None + ) + resolve.assert_called_once_with(message) + + +@pytest.mark.asyncio +async def test_processor_cancellation_propagates_without_synthetic_generation_or_trace( + monkeypatch, +): + import asyncio + + entered = asyncio.Event() + released = asyncio.Event() + finalized = asyncio.Event() + + async def query(**kwargs): + try: + yield stream("message_start", message={"model": "claude", "usage": {}}) + entered.set() + await released.wait() + finally: + finalized.set() + + monkeypatch.setattr("posthog.ai.claude_agent_sdk.processor.original_query", query) + ph = analytics() + processor = PostHogClaudeAgentProcessor(client=ph) + + async def consume(): + return [message async for message in processor.query(prompt="question")] + + task = asyncio.create_task(consume()) + await entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert finalized.is_set() + ph.capture.assert_not_called() + ph.flush.assert_not_called() diff --git a/posthog/test/ai/gemini/test_gemini_converter.py b/posthog/test/ai/gemini/test_gemini_converter.py index 4227b6d08..7614f7037 100644 --- a/posthog/test/ai/gemini/test_gemini_converter.py +++ b/posthog/test/ai/gemini/test_gemini_converter.py @@ -361,3 +361,64 @@ def test_input_tokens_without_tool_use(self): ) usage = extract_gemini_usage_from_response(resp) assert usage["input_tokens"] == 20 + + +@pytest.mark.parametrize( + "message, expected", + [ + ({"role": "model", "content": 42}, {"role": "model", "content": "42"}), + ({"content": None}, {"role": "user", "content": "None"}), + ({"content": ""}, {"role": "user", "content": ""}), + ( + {"role": "model", "content": [{"text": "answer"}]}, + {"role": "model", "content": [{"type": "text", "text": "answer"}]}, + ), + ( + {"role": "model", "parts": [], "content": "ignored"}, + {"role": "model", "content": []}, + ), + ( + {"text": "bare part"}, + {"role": "user", "content": [{"type": "text", "text": "bare part"}]}, + ), + ({"role": "model", "text": "answer"}, {"role": "model", "content": "answer"}), + ({"unknown": 1}, {"role": "user", "content": "{'unknown': 1}"}), + ( + {"parts": "not a list"}, + {"role": "user", "content": "{'parts': 'not a list'}"}, + ), + ], +) +def test_input_dictionary_field_precedence_and_content_coercion(message, expected): + assert format_gemini_input(message) == [expected] + + +@pytest.mark.parametrize( + "attributes, expected", + [ + ( + {"role": 7, "parts": ("first", {"text": "second"})}, + { + "role": "user", + "content": [ + {"type": "text", "text": "first"}, + {"type": "text", "text": "second"}, + ], + }, + ), + ( + {"role": None, "text": 0, "content": "ignored"}, + {"role": "user", "content": 0}, + ), + ( + {"role": "model", "content": [{"text": "answer"}]}, + {"role": "model", "content": [{"type": "text", "text": "answer"}]}, + ), + ({"role": "model", "content": 42}, {"role": "model", "content": "42"}), + ({"role": "model", "content": ""}, {"role": "model", "content": ""}), + ], +) +def test_input_object_field_precedence_and_role_validation(attributes, expected): + from types import SimpleNamespace + + assert format_gemini_input(SimpleNamespace(**attributes)) == [expected] diff --git a/posthog/test/ai/openai/test_openai_converter.py b/posthog/test/ai/openai/test_openai_converter.py index 2034f533f..155a03d73 100644 --- a/posthog/test/ai/openai/test_openai_converter.py +++ b/posthog/test/ai/openai/test_openai_converter.py @@ -420,3 +420,129 @@ def test_indexless_calls_keep_their_order_around_indexed_ones(): ("call_b", "b", "{}"), ("call_c", "c", "{}"), ] + + +@pytest.mark.parametrize( + "text, tool_calls, expected", + [ + ("", None, []), + ("hello", None, [{"type": "text", "text": "hello"}]), + ("", [{}], [{"type": "function", "id": None, "function": {}}]), + ( + "hello", + [{"id": "call-1", "function": {"name": "f", "arguments": "{}"}}], + [ + {"type": "text", "text": "hello"}, + { + "type": "function", + "id": "call-1", + "function": {"name": "f", "arguments": "{}"}, + }, + ], + ), + ], +) +def test_legacy_streaming_content_preserves_text_then_tools(text, tool_calls, expected): + from copy import deepcopy + + from posthog.ai.openai.openai_converter import format_openai_streaming_content + + original = deepcopy(tool_calls) + assert format_openai_streaming_content(text, tool_calls) == expected + assert tool_calls == original + + +def test_responses_content_preserves_empty_values_and_field_precedence(): + from posthog.ai.openai.openai_converter import format_openai_response + + response = types.SimpleNamespace( + output=[ + { + "type": "message", + "role": "developer", + "content": [ + {"type": "output_text", "text": ""}, + {"type": "refusal", "refusal": "", "text": "ignored"}, + types.SimpleNamespace(type="unknown", text="fallback"), + {"type": "input_image", "image_url": "https://image"}, + { + "type": "input_image", + "image_url": "ignored", + "text": "text wins", + }, + {"type": "unknown"}, + ], + }, + {"type": "message", "content": 0}, + {"type": "message", "content": None}, + ] + ) + assert format_openai_response(response) == [ + { + "role": "developer", + "content": [ + {"type": "text", "text": ""}, + {"type": "refusal", "refusal": ""}, + {"type": "text", "text": "fallback"}, + {"type": "image", "image": "https://image"}, + {"type": "text", "text": "text wins"}, + {"type": "text", "text": "0"}, + ], + } + ] + + +@pytest.mark.parametrize( + "item, expected", + [ + (42, {"role": "user", "content": "42"}), + (None, {"role": "user", "content": "None"}), + ("prompt", {"role": "user", "content": "prompt"}), + ( + {"type": "function_call_output", "output": "ok"}, + {"type": "function_call_output", "output": "ok"}, + ), + ({"type": "message", "role": "system"}, {"role": "system", "content": ""}), + ({"type": "message", "content": None}, {"role": "user", "content": None}), + ( + types.SimpleNamespace(role="assistant", content="typed"), + {"role": "user", "content": "namespace(role='assistant', content='typed')"}, + ), + ], +) +def test_responses_input_distinguishes_messages_from_typed_items(item, expected): + assert format_openai_input(input_data=[item]) == [expected] + + +def test_usage_chat_fields_override_responses_even_when_null_or_zero(): + from posthog.ai.openai.openai_converter import ( + extract_openai_usage_from_chunk, + extract_openai_usage_from_response, + ) + + usage = types.SimpleNamespace( + input_tokens=100, + output_tokens=50, + input_tokens_details=types.SimpleNamespace(cached_tokens=9), + output_tokens_details=types.SimpleNamespace(reasoning_tokens=7), + prompt_tokens=None, + completion_tokens=0, + prompt_tokens_details=types.SimpleNamespace(cached_tokens=None), + completion_tokens_details=types.SimpleNamespace(reasoning_tokens=0), + ) + response = types.SimpleNamespace(usage=usage) + non_streamed = extract_openai_usage_from_response(response) + assert set(non_streamed) == {"output_tokens", "raw_usage"} + assert non_streamed["output_tokens"] == 0 + assert non_streamed["raw_usage"]["prompt_tokens"] is None + + streamed = extract_openai_usage_from_chunk(response, "chat") + assert set(streamed) == { + "input_tokens", + "output_tokens", + "reasoning_tokens", + "raw_usage", + } + assert streamed["input_tokens"] is None + assert streamed["output_tokens"] == streamed["reasoning_tokens"] == 0 + assert streamed["raw_usage"] == non_streamed["raw_usage"] diff --git a/posthog/test/ai/openai_agents/test_processor.py b/posthog/test/ai/openai_agents/test_processor.py index 36e9a5803..13f0c6c7a 100644 --- a/posthog/test/ai/openai_agents/test_processor.py +++ b/posthog/test/ai/openai_agents/test_processor.py @@ -1222,3 +1222,70 @@ def test_ai_lane_client_routes_through_capture_ai(mock_client, mock_trace): mock_client.capture.assert_not_called() mock_client.capture_ai.assert_called_once() assert mock_client.capture_ai.call_args[1]["event"] == "$ai_trace" + + +@pytest.mark.parametrize("full_capture", [False, True]) +@pytest.mark.parametrize("privacy", [False, True]) +def test_transcription_privacy_wins_over_full_capture_without_mutating_config( + mock_client, mock_span, full_capture, privacy +): + mock_client.enable_full_ai_capture = full_capture + processor = PostHogTracingProcessor( + client=mock_client, distinct_id="audio-user", privacy_mode=privacy + ) + config = { + "prompt": "private prompt", + "instructions": "private instructions", + "language": "en", + } + data = TranscriptionSpanData( + input="AAAA", + input_format="pcm", + output="private transcript", + model_config=config, + ) + mock_span.span_data = data + processor.on_span_end(mock_span) + + capture = mock_client.capture_ai if full_capture else mock_client.capture + capture.assert_called_once() + props = capture.call_args.kwargs["properties"] + assert capture.call_args.kwargs["distinct_id"] == "audio-user" + assert props["$ai_input"] == ( + None if privacy else "AAAA" if full_capture else "[base64 audio redacted]" + ) + assert props["$ai_output_state"] == (None if privacy else "private transcript") + assert props["model_config"] == { + "prompt": None if privacy else "private prompt", + "instructions": None if privacy else "private instructions", + "language": "en", + } + assert ( + data.model_config + == config + == { + "prompt": "private prompt", + "instructions": "private instructions", + "language": "en", + } + ) + + +def test_span_error_category_keeps_precedence_and_privacy_summary( + mock_client, mock_span +): + processor = PostHogTracingProcessor(client=mock_client, privacy_mode=True) + mock_client.enable_full_ai_capture = False + mock_span.span_data = GenerationSpanData(model="gpt-4o", usage={"input_tokens": 0}) + mock_span.error = { + "type": "UserError", + "message": "private ModelBehaviorError and MaxTurnsExceeded", + } + processor.on_span_end(mock_span) + + props = mock_client.capture.call_args.kwargs["properties"] + assert props["$ai_error_type"] == "model_behavior_error" + assert props["$ai_error"] == "UserError" + assert props["$ai_input_tokens"] == props["$ai_total_tokens"] == 0 + assert "$ai_output_tokens" not in props + assert props["$process_person_profile"] is False diff --git a/posthog/test/ai/test_sanitization.py b/posthog/test/ai/test_sanitization.py index 34be067b4..9f40ed885 100644 --- a/posthog/test/ai/test_sanitization.py +++ b/posthog/test/ai/test_sanitization.py @@ -672,3 +672,32 @@ def test_sanitize_messages_importable_from_utils(): if __name__ == "__main__": unittest.main() + + +class TestMediaPlaceholderMimeHints(unittest.TestCase): + def test_media_kind_in_placeholders_preserves_mime_and_format_classification(self): + cases = { + "audio/wav": "audio", + "video/mp4": "video", + "application/pdf": "file", + "AUDIO": "audio", + "video": "video", + "image": "image", + "mp3": "audio", + "webm": "video", + "png": "image", + "pdf": "file", + } + for mime, kind in cases.items(): + with self.subTest(mime=mime): + value = {"inline_data": {"mime_type": mime, "data": LONG_RAW_BASE64}} + self.assertEqual( + redact_media(value), + { + "inline_data": { + "mime_type": mime, + "data": f"[base64 {kind} redacted]", + } + }, + ) + self.assertEqual(value["inline_data"]["data"], LONG_RAW_BASE64) diff --git a/posthog/test/ai/test_utils.py b/posthog/test/ai/test_utils.py new file mode 100644 index 000000000..49add2881 --- /dev/null +++ b/posthog/test/ai/test_utils.py @@ -0,0 +1,166 @@ +"""Usage conversion fallback order and streaming merge ownership contracts.""" + +from copy import deepcopy +from types import SimpleNamespace + +import pytest + +from posthog.ai.types import TokenUsage +from posthog.ai.utils import merge_usage_stats, serialize_raw_usage + + +class PydanticUsage: + def model_dump(self): + return {"input_tokens": 4} + + def to_dict(self): + raise AssertionError("model_dump must take precedence") + + +class ProtobufUsage: + def model_dump(self): + raise ValueError("unsupported model serialization") + + def to_dict(self): + return {"output_tokens": 7} + + +class AttributeUsage: + def __init__(self): + self.input_tokens = 9 + + def model_dump(self): + raise ValueError("failed") + + def to_dict(self): + raise ValueError("failed") + + +class StringUsage: + __slots__ = () + model_dump = None + to_dict = None + + def __str__(self): + return "provider usage" + + +class UnreadableUsage(StringUsage): + __slots__ = () + + def __str__(self): + raise ValueError("cannot stringify") + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + (None, None), + ({"input_tokens": 1}, {"input_tokens": 1}), + (PydanticUsage(), {"input_tokens": 4}), + (ProtobufUsage(), {"output_tokens": 7}), + (AttributeUsage(), {"input_tokens": 9}), + (SimpleNamespace(output_tokens=3), {"output_tokens": 3}), + (StringUsage(), {"_raw": "provider usage"}), + (UnreadableUsage(), None), + ], +) +def test_serialize_raw_usage_follows_fallback_order_without_raising(raw, expected): + assert serialize_raw_usage(raw) == expected + + +def test_serialize_raw_usage_preserves_already_serialized_mapping(): + raw = {"input_tokens": 0, "nested": {"details": 1}} + assert serialize_raw_usage(raw) is raw + + +def test_merge_usage_stats_incremental_keeps_max_search_and_merges_raw_shallowly(): + target = TokenUsage( + input_tokens=None, + output_tokens=3, + cache_read_input_tokens=2, + cache_creation_input_tokens=4, + reasoning_tokens=1, + web_search_count=5, + cache_reporting_exclusive=False, + raw_usage={"input_tokens": 12, "details": {"old": 1}}, + ) + source = TokenUsage( + input_tokens=10, + output_tokens=0, + cache_read_input_tokens=3, + cache_creation_input_tokens=6, + reasoning_tokens=2, + web_search_count=2, + cache_reporting_exclusive=True, + raw_usage={"output_tokens": 7, "details": {"new": 2}}, + ) + original_source = deepcopy(source) + previous_raw = target["raw_usage"] + merge_usage_stats(target, source) + assert target == { + "input_tokens": 10, + "output_tokens": 3, + "cache_read_input_tokens": 5, + "cache_creation_input_tokens": 10, + "reasoning_tokens": 3, + "web_search_count": 5, + "cache_reporting_exclusive": True, + "raw_usage": {"input_tokens": 12, "output_tokens": 7, "details": {"new": 2}}, + } + assert previous_raw == {"input_tokens": 12, "details": {"old": 1}} + assert source == original_source + assert target["raw_usage"] is not source["raw_usage"] + merge_usage_stats( + target, TokenUsage(input_tokens=None, output_tokens=None, raw_usage=None) + ) + assert target["input_tokens"] == 10 + assert target["output_tokens"] == 3 + assert target["raw_usage"] == { + "input_tokens": 12, + "output_tokens": 7, + "details": {"new": 2}, + } + + +def test_merge_usage_stats_cumulative_replaces_zero_and_false_but_not_none(): + target = TokenUsage( + input_tokens=10, + output_tokens=8, + cache_read_input_tokens=3, + cache_creation_input_tokens=6, + reasoning_tokens=4, + web_search_count=7, + cache_reporting_exclusive=True, + raw_usage={"previous": 1}, + ) + source = TokenUsage( + input_tokens=None, + output_tokens=0, + cache_read_input_tokens=0, + cache_creation_input_tokens=0, + reasoning_tokens=0, + web_search_count=0, + cache_reporting_exclusive=False, + raw_usage={"latest": 2}, + ) + merge_usage_stats(target, source, mode="cumulative") + assert target == { + "input_tokens": 10, + "output_tokens": 0, + "cache_read_input_tokens": 0, + "cache_creation_input_tokens": 0, + "reasoning_tokens": 0, + "web_search_count": 0, + "cache_reporting_exclusive": False, + "raw_usage": {"latest": 2}, + } + assert source["input_tokens"] is None + assert target["raw_usage"] is source["raw_usage"] + + +def test_merge_usage_stats_invalid_mode_does_not_mutate_target(): + target = TokenUsage(input_tokens=10) + with pytest.raises(ValueError, match="Invalid mode: unknown"): + merge_usage_stats(target, TokenUsage(input_tokens=4), mode="unknown") + assert target == {"input_tokens": 10} diff --git a/posthog/test/integrations/test_asgi_integration.py b/posthog/test/integrations/test_asgi_integration.py index 922f6fcde..480b098b6 100644 --- a/posthog/test/integrations/test_asgi_integration.py +++ b/posthog/test/integrations/test_asgi_integration.py @@ -439,15 +439,32 @@ async def app(received_scope, receive, send): @pytest.mark.asyncio -async def test_builds_url_from_server_when_host_header_is_absent(): +@pytest.mark.parametrize( + "scheme,server,expected_url", + [ + ("http", ("2001:db8::1", 8080), "http://[2001:db8::1]:8080/health"), + ("https", ("2001:db8::1", 443), "https://[2001:db8::1]/health"), + ("http", ("[2001:db8::1]", 80), "http://[2001:db8::1]/health"), + ("http", ("example.com", 80), "http://example.com/health"), + ("https", ("example.com", 443), "https://example.com/health"), + ("wss", ("example.com", 443), "wss://example.com:443/health"), + ("https", ("example.com", "443"), None), + ("https", (None, 443), None), + ("https", (" \r\n ", 443), None), + ("https", ("example.com",), None), + ("https", None, None), + ], +) +async def test_builds_url_from_server_when_host_header_is_absent( + scheme, server, expected_url +): observed = {} async def app(scope, receive, send): observed.update(contexts.get_tags()) - scope = http_scope( - headers=[], scheme="http", server=("2001:db8::1", 8080), path="/health" - ) + scope = http_scope(headers=[], scheme=scheme, server=server, path="/health") await PosthogASGIMiddleware(app)(scope, noop_receive, noop_send) - assert observed["$current_url"] == "http://[2001:db8::1]:8080/health" + assert observed.get("$current_url") == expected_url + assert observed["$request_path"] == "/health" diff --git a/posthog/test/mcp/test_asgi.py b/posthog/test/mcp/test_asgi.py new file mode 100644 index 000000000..395d826e8 --- /dev/null +++ b/posthog/test/mcp/test_asgi.py @@ -0,0 +1,28 @@ +"""Cancellation at the request-body boundary must not start the downstream app.""" + +import asyncio + +import pytest + +from posthog.mcp.asgi import PostHogMcpStatelessSessionMiddleware, get_mcp_session + + +async def test_cancellation_while_sniffing_initialize_propagates(): + calls = [] + scope = {"type": "http", "method": "POST", "headers": []} + + async def receive(): + raise asyncio.CancelledError() + + async def app(*args): + calls.append("app") + + async def send(message): + calls.append(message) + + middleware = PostHogMcpStatelessSessionMiddleware(app) + with pytest.raises(asyncio.CancelledError): + await middleware(scope, receive, send) + + assert calls == [] + assert get_mcp_session(scope) is None diff --git a/posthog/test/mcp/test_capture.py b/posthog/test/mcp/test_capture.py new file mode 100644 index 000000000..1190f9941 --- /dev/null +++ b/posthog/test/mcp/test_capture.py @@ -0,0 +1,69 @@ +"""Custom event handles must use the same privacy and identity pipeline as auto capture.""" + +import pytest +from mcp.server.lowlevel import Server + +from posthog.mcp import McpAnalytics, instrument +from posthog.mcp._internal import get_server_tracking_data +from posthog.mcp.types import UserIdentity +from posthog.test.mcp._helpers import FakeClient + + +async def test_custom_capture_is_awaited_and_preserves_session_identity(): + server = Server("custom-capture") + client = FakeClient() + handle = instrument(server, client) + data = get_server_tracking_data(server) + data.identified_sessions.set( + data.session_id, + UserIdentity( + distinct_id="user-7", properties={"plan": "pro"}, groups={"org": "acme"} + ), + ) + + await handle.capture("report_exported", {"format": "csv"}) + + assert len(client.events) == 1 + event = client.events[0] + assert event["event"] == "report_exported" + assert event["distinct_id"] == "user-7" + assert event["properties"]["$session_id"] == data.session_id + assert event["properties"]["$set"] == {"plan": "pro"} + assert event["properties"]["$groups"] == {"org": "acme"} + assert event["properties"]["format"] == "csv" + assert "$process_person_profile" not in event["properties"] + + +@pytest.mark.parametrize("name", [None, "", 3]) +async def test_custom_capture_rejects_invalid_event_names(name): + server = Server("custom-capture") + client = FakeClient() + handle = instrument(server, client) + + with pytest.raises(ValueError, match="requires an event name"): + await handle.capture(name) + + assert client.events == [] + + +async def test_custom_capture_after_tracking_removed_is_a_noop(): + server = Server("custom-capture") + client = FakeClient() + instrument(server, client) + # A handle without tracking state is inert, not a fallback to another server. + handle = McpAnalytics(Server("untracked")) + + await handle.capture("report_exported") + + assert client.events == [] + + +async def test_custom_capture_with_no_sink_is_a_noop(): + server = Server("custom-capture") + client = FakeClient() + handle = instrument(server, client) + get_server_tracking_data(server).sink = None + + await handle.capture("report_exported") + + assert client.events == [] diff --git a/posthog/test/mcp/test_instrument_lowlevel_ownership.py b/posthog/test/mcp/test_instrument_lowlevel_ownership.py new file mode 100644 index 000000000..e10eb00b1 --- /dev/null +++ b/posthog/test/mcp/test_instrument_lowlevel_ownership.py @@ -0,0 +1,70 @@ +"""Ownership inference stays safe when a host exposes only a function registry.""" + +from types import SimpleNamespace + +import pytest + +from posthog.mcp._instrument_lowlevel import ( + _standalone_ownership, + registered_tool_exists, +) +from posthog.mcp._internal import MCPAnalyticsData +from posthog.mcp.types import MCPAnalyticsOptions + + +def _application_arguments(context, conversation_id, llm_model): + pass + + +class _UninspectableFunction: + @property + def __signature__(self): + raise ValueError("signature unavailable") + + def __call__(self): + pass + + +@pytest.mark.parametrize( + ("tool", "expected_strip", "expected_model"), + [ + (None, {"context", "conversation_id"}, None), + (SimpleNamespace(), {"context", "conversation_id", "llm_model"}, True), + (SimpleNamespace(fn=_application_arguments), set(), False), + ( + SimpleNamespace(fn=_UninspectableFunction()), + {"context", "conversation_id", "llm_model"}, + True, + ), + ], +) +async def test_signature_only_registry_preserves_application_arguments( + tool, expected_strip, expected_model +): + async def get_tool(name): + assert name == "search" + return tool + + server = SimpleNamespace(get_tool=get_tool, middleware=[]) + data = MCPAnalyticsData(options=MCPAnalyticsOptions()) + + strip, model_owned, schema = await _standalone_ownership( + data, server, "search", None + ) + + assert strip == expected_strip + assert model_owned is expected_model + assert schema is None + + +async def test_registry_outage_is_not_evidence_of_an_unknown_tool(): + fastmcp = pytest.importorskip("fastmcp") + server = fastmcp.FastMCP("registry-outage") + + async def unavailable(name): + raise RuntimeError("registry temporarily unavailable") + + server.get_tool = unavailable + + assert await registered_tool_exists(server, "search") is None + assert await registered_tool_exists(None, "search") is None diff --git a/posthog/test/mcp/test_instrument_v2.py b/posthog/test/mcp/test_instrument_v2.py new file mode 100644 index 000000000..b559b07b6 --- /dev/null +++ b/posthog/test/mcp/test_instrument_v2.py @@ -0,0 +1,36 @@ +"""The v2 ownership lookup must not consume host request cancellation.""" + +import asyncio +import sys +from types import SimpleNamespace + +import pytest + +from posthog.mcp._instrument_v2 import _standalone_injected_parameters +from posthog.mcp._internal import MCPAnalyticsData +from posthog.mcp.types import MCPAnalyticsOptions + + +async def test_cancellation_during_standalone_schema_lookup_propagates(monkeypatch): + # Isolate cancellation from the optional, version-specific FastMCP import. + monkeypatch.setitem( + sys.modules, + "fastmcp.utilities.versions", + SimpleNamespace(VersionSpec=pytest.fail, version_sort_key=pytest.fail), + ) + calls = [] + + async def list_tools(): + calls.append("list") + raise asyncio.CancelledError() + + async def get_tool(*args, **kwargs): + calls.append("get") + + server = SimpleNamespace(list_tools=list_tools, get_tool=get_tool) + data = MCPAnalyticsData(options=MCPAnalyticsOptions()) + with pytest.raises(asyncio.CancelledError): + await _standalone_injected_parameters(server, data, "search", None) + + assert calls == ["list"] + assert data.tool_model_parameter_injected == {} diff --git a/posthog/test/mcp/test_model_parameters.py b/posthog/test/mcp/test_model_parameters.py index 1c2620f8c..d13e1b151 100644 --- a/posthog/test/mcp/test_model_parameters.py +++ b/posthog/test/mcp/test_model_parameters.py @@ -102,3 +102,27 @@ def test_request_meta_from_context_supports_pydantic_style_metadata(): assert request_meta_from_context(SimpleNamespace(meta=meta)) == { "x-codex-turn-metadata": {"model": "gpt-5.6-sol"} } + + +@pytest.mark.parametrize("method", ["model_dump", "dict"]) +@pytest.mark.parametrize("outcome", ["metadata", "non_object", "raises"]) +def test_request_metadata_serialization_is_best_effort(method, outcome): + metadata = {"x-codex-turn-metadata": {"model": "reported-model"}} + calls = [] + + def serialize(**kwargs): + calls.append(kwargs) + if outcome == "raises": + raise RuntimeError("metadata unavailable") + return metadata if outcome == "metadata" else ["not metadata"] + + context = SimpleNamespace(meta=SimpleNamespace(**{method: serialize})) + + assert request_meta_from_context(context) == ( + metadata if outcome == "metadata" else None + ) + assert calls == [ + {"mode": "python", "by_alias": True} + if method == "model_dump" + else {"by_alias": True} + ] diff --git a/posthog/test/mcp/test_posthog_mcp.py b/posthog/test/mcp/test_posthog_mcp.py index fb2e69961..76c724bb6 100644 --- a/posthog/test/mcp/test_posthog_mcp.py +++ b/posthog/test/mcp/test_posthog_mcp.py @@ -797,3 +797,69 @@ def test_capture_without_a_session_gets_a_fresh_one_per_call(): assert session.startswith("ses_") assert first["distinct_id"] == session assert second["properties"]["$session_id"] != session + + +class _UncopyableToolResult: + def __init__(self): + self.content = [] + self.structuredContent = {"rows": []} + + def __copy__(self): + return self + + +class _FailingModelCopyResult(_UncopyableToolResult): + def model_copy(self, **kwargs): + raise ValueError("result is read-only") + + +class _FailingResultWrapper: + def __init__(self, root): + self.root = root + + def model_copy(self, **kwargs): + raise ValueError("wrapper is read-only") + + +@pytest.mark.parametrize( + "make_result", + [ + _UncopyableToolResult, + _FailingModelCopyResult, + lambda: _FailingResultWrapper( + SimpleNamespace(content=[], structuredContent={"rows": []}) + ), + lambda: SimpleNamespace( + root=SimpleNamespace(content=[], structuredContent={"rows": []}) + ), + ], + ids=["uncopyable", "model-copy-fails", "rewrap-fails", "plain-wrapper"], +) +def test_prepare_tool_result_copy_failures_never_pin_a_shared_handle(make_result): + client, _ = make_client() + client.prepare_tool_list([_sql_tool()]) + call = client.prepare_tool_call("execute-sql", {}) + result = make_result() + target = getattr(result, "root", result) + + prepared = client.prepare_tool_result(result, call) + + assert target.content == [] + assert target.structuredContent == {"rows": []} + if isinstance(result, SimpleNamespace): + assert prepared.result is not result + assert prepared.result.root is not target + assert prepared.result.root.structuredContent[MCP_INSTRUCTIONS_KEY] == { + "conversation_id": prepared.conversation_id + } + assert ( + prepared.result.root.content[-1].text + == _handle_block(prepared.conversation_id)["text"] + ) + assert prepared.session_id == derive_session_id_from_conversation( + prepared.conversation_id + ) + else: + assert prepared.result is result + assert prepared.conversation_id is None + assert prepared.session_id is None diff --git a/posthog/test/test_async_client.py b/posthog/test/test_async_client.py index fcb6e2298..97ea959fe 100644 --- a/posthog/test/test_async_client.py +++ b/posthog/test/test_async_client.py @@ -3,6 +3,9 @@ import asyncio import contextvars import logging +from datetime import datetime, timezone +from pathlib import Path +from uuid import UUID import subprocess import sys import threading @@ -13,7 +16,9 @@ from posthog import AsyncClient, AsyncPosthog, CaptureCompression, CaptureMode from posthog.consumer import MAX_MSG_SIZE from posthog.contexts import ( + identify_context, new_context, + set_context_session, set_capture_exception_code_variables_context, set_code_variables_detect_secrets_context, set_code_variables_ignore_patterns_context, @@ -771,3 +776,245 @@ async def batch_post(*args, **kwargs): assert "items pending" in caplog.text allow_upload.set() await client.shutdown() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "method_name,method_kwargs,expected_id,expected_properties", + [ + ( + "group_identify", + { + "group_type": "company", + "group_key": "company-1", + "properties": {"plan": "pro", "nested": {"drop": None, "count": 0}}, + "distinct_id": "group-user", + }, + "group-user", + { + "$group_type": "company", + "$group_key": "company-1", + "$group_set": {"plan": "pro", "nested": {"drop": None, "count": 0}}, + }, + ), + ( + "alias", + {"previous_id": 123, "distinct_id": "alias-user"}, + "123", + {"distinct_id": "123", "alias": "alias-user"}, + ), + ], +) +async def test_identity_events_preserve_payload_session_and_normalized_envelope( + method_name, method_kwargs, expected_id, expected_properties +): + delivered = [] + + async def batch_post(*args, **kwargs): + delivered.extend(kwargs["batch"]) + + with mock.patch("posthog._async_consumer.async_batch_post", side_effect=batch_post): + async with AsyncPosthog("test-key", flush_interval=30) as client: + with new_context(fresh=True): + set_context_session("request-session") + event_uuid = getattr(client, method_name)( + **method_kwargs, + uuid="{4BF92F35-77B3-4DA6-A3CE-929D0E0E4736}", + timestamp="2025-01-02T03:04:05.123456+02:30", + disable_geoip=False, + ) + await client.flush(timeout_seconds=1) + + assert len(delivered) == 1 + event = delivered[0] + assert event_uuid == event["uuid"] == "4bf92f35-77b3-4da6-a3ce-929d0e0e4736" + assert event["timestamp"] == "2025-01-02T00:34:05.123456+00:00" + assert event["distinct_id"] == expected_id + assert { + key: event["properties"][key] for key in expected_properties + } == expected_properties + assert event["properties"]["$session_id"] == "request-session" + assert "$geoip_disable" not in event["properties"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "method_name,method_kwargs", + [ + ("group_identify", {"group_type": "", "group_key": "company-1"}), + ("group_identify", {"group_type": "company", "group_key": ""}), + ("alias", {"previous_id": "", "distinct_id": "user-1"}), + ("alias", {"previous_id": "anon-1", "distinct_id": None}), + ], +) +async def test_identity_events_reject_missing_required_ids(method_name, method_kwargs): + with ( + new_context(fresh=True), + mock.patch( + "posthog._async_consumer.async_batch_post", new=mock.AsyncMock() + ) as send, + ): + async with AsyncPosthog("test-key") as client: + assert getattr(client, method_name)(**method_kwargs) is None + await client.flush() + send.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_alias_uses_request_identity_when_no_explicit_distinct_id_is_supplied(): + delivered = [] + + async def batch_post(*args, **kwargs): + delivered.extend(kwargs["batch"]) + + with mock.patch("posthog._async_consumer.async_batch_post", side_effect=batch_post): + async with AsyncPosthog("test-key") as client: + with new_context(fresh=True): + identify_context("request-user") + assert client.alias("anon-1", None) is not None + await client.flush() + + assert delivered[0]["distinct_id"] == "anon-1" + assert delivered[0]["properties"]["alias"] == "request-user" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cancel_immediate", [False, True]) +async def test_concurrent_shutdown_closes_once_after_immediate_operation_finishes( + cancel_immediate, +): + started, release = asyncio.Event(), asyncio.Event() + http_client = mock.Mock(aclose=mock.AsyncMock()) + on_error = mock.AsyncMock() + + async def batch_post(*args, **kwargs): + started.set() + await release.wait() + + with ( + mock.patch("posthog.async_client._build_client", return_value=http_client), + mock.patch("posthog._async_consumer.async_batch_post", side_effect=batch_post), + ): + client = AsyncPosthog("test-key", on_error=on_error) + capture = asyncio.create_task(client.capture_immediate("in flight")) + await started.wait() + shutdowns = [asyncio.create_task(client.shutdown()) for _ in range(2)] + await asyncio.sleep(0) + assert client.capture("too late") is None + assert not any(task.done() for task in shutdowns) + http_client.aclose.assert_not_awaited() + if cancel_immediate: + capture.cancel() + with pytest.raises(asyncio.CancelledError): + await capture + else: + release.set() + assert await capture is not None + await asyncio.wait_for(asyncio.gather(*shutdowns), timeout=1) + + http_client.aclose.assert_awaited_once_with() + on_error.assert_not_awaited() + assert client._immediate_callers == {} + assert client._inflight_operations == set() + assert await client.capture_immediate("after shutdown") is None + + +@pytest.mark.asyncio +async def test_cancelled_shutdown_can_be_retried_without_cancelling_buffered_delivery(): + started, release = asyncio.Event(), asyncio.Event() + delivered = [] + + async def batch_post(*args, **kwargs): + started.set() + await release.wait() + delivered.extend(kwargs["batch"]) + + with mock.patch("posthog._async_consumer.async_batch_post", side_effect=batch_post): + client = AsyncPosthog("test-key", flush_at=1) + event_uuid = client.capture("buffered") + await started.wait() + shutdown = asyncio.create_task(client.shutdown()) + await asyncio.sleep(0) + shutdown.cancel() + with pytest.raises(asyncio.CancelledError): + await shutdown + assert client.capture("after cancelled shutdown") is None + release.set() + await asyncio.wait_for(client.shutdown(), timeout=1) + + assert [event["uuid"] for event in delivered] == [event_uuid] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("debug", [False, True]) +async def test_shutdown_attempts_remaining_cleanup_before_reporting_first_error(debug): + first_error = RuntimeError("flush failed") + http_client = mock.Mock( + aclose=mock.AsyncMock(side_effect=ValueError("close failed")) + ) + with ( + mock.patch("posthog.async_client._build_client", return_value=http_client), + mock.patch( + "posthog.async_client._async_flags", new=mock.AsyncMock(return_value={}) + ), + ): + client = AsyncPosthog("test-key", debug=debug, secret_key="secret-key") + await client.evaluate_flags("user-1") + emails = client.emails + with ( + mock.patch.object( + client, "flush", new=mock.AsyncMock(side_effect=first_error) + ), + mock.patch.object( + emails, + "aclose", + new=mock.AsyncMock(side_effect=OSError("email close failed")), + ) as close_email, + ): + if debug: + with pytest.raises(RuntimeError) as raised: + await client.shutdown() + assert raised.value is first_error + else: + await client.shutdown() + await client.shutdown() + + http_client.aclose.assert_awaited_once_with() + close_email.assert_awaited_once_with() + assert client._duplicate_client_registry_key is None + assert client._closed + assert client.capture("after shutdown") is None + + +@pytest.mark.asyncio +async def test_immediate_capture_replaces_invalid_uuid_and_timestamp_before_hook(): + observed = [] + + async def before_send(event): + observed.append(event.copy()) + return {**event, "uuid": "hook-cannot-replace-event-identity"} + + with mock.patch( + "posthog._async_consumer.async_batch_post", new=mock.AsyncMock() + ) as send: + client = AsyncPosthog("test-key", before_send=before_send) + before = datetime.now(timezone.utc) + event_uuid = await client.capture_immediate( + "event", uuid="invalid", timestamp="not-a-date" + ) + after = datetime.now(timezone.utc) + await client.shutdown() + + assert str(UUID(event_uuid)) == event_uuid + assert observed[0]["uuid"] == event_uuid + assert before <= datetime.fromisoformat(observed[0]["timestamp"]) <= after + assert send.await_args.kwargs["batch"][0]["uuid"] == event_uuid + + +@pytest.mark.asyncio +async def test_deprecated_secret_key_warning_points_to_constructor_caller(): + with pytest.warns(DeprecationWarning, match="personal_api_key") as warnings_seen: + client = AsyncPosthog("test-key", personal_api_key=" legacy-key ", send=False) + assert Path(warnings_seen[0].filename) == Path(__file__) + assert client.secret_key == client.personal_api_key == "legacy-key" + await client.shutdown() diff --git a/posthog/test/test_async_consumer.py b/posthog/test/test_async_consumer.py index 9bb3f682f..7ccae1efd 100644 --- a/posthog/test/test_async_consumer.py +++ b/posthog/test/test_async_consumer.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import contextvars import json from unittest import mock @@ -8,7 +9,7 @@ import pytest from freezegun import freeze_time -from posthog._async_consumer import _AsyncConsumer +from posthog._async_consumer import _AsyncConsumer, _QueuedEvent, _STOP from posthog.capture_compression import CaptureCompression from posthog.capture_mode import CaptureMode from posthog.request import APIError @@ -207,3 +208,113 @@ async def test_get_or_flush_preserves_results_and_cleans_up_waiters(queued, flus assert not (asyncio.all_tasks() - tasks_before) if queued: consumer.queue.task_done() + + +@pytest.mark.asyncio +async def test_run_drops_invalid_events_and_preserves_queued_context(monkeypatch): + marker = contextvars.ContextVar("queued_test_marker", default="outside") + consumer = make_consumer(retries=0) + monkeypatch.setattr("posthog._async_consumer.MAX_MSG_SIZE", 256) + + async def process(event): + if event["event"] == "broken": + raise ValueError("processing failed") + if event["event"] == "filtered": + return None + return {**event, "context": marker.get()} + + consumer.process_event = process + token = marker.set("queued") + try: + for event in [ + {"event": "broken"}, + {"event": "filtered"}, + {"event": "invalid-json", "properties": {("tuple",): True}}, + {"event": "too-large", "properties": {"large": "x" * 256}}, + {"event": "accepted"}, + ]: + consumer.queue.put_nowait(_QueuedEvent(event, contextvars.copy_context())) + finally: + marker.reset(token) + consumer.queue.put_nowait(_STOP) + + with mock.patch( + "posthog._async_consumer.async_batch_post", new=mock.AsyncMock() + ) as batch_post: + await consumer.run() + await asyncio.wait_for(consumer.queue.join(), 1) + + assert batch_post.await_count == 1 + assert batch_post.await_args.kwargs["batch"] == [ + {"event": "accepted", "context": "queued"} + ] + assert marker.get() == "outside" + + +@pytest.mark.asyncio +async def test_next_carries_oversized_batch_tail_without_reprocessing(monkeypatch): + consumer = make_consumer(retries=0) + events = [{"event": "first"}, {"event": "second"}] + monkeypatch.setattr( + "posthog._async_consumer.BATCH_SIZE_LIMIT", + sum(len(json.dumps(event).encode()) for event in events) - 1, + ) + for event in events: + consumer.queue.put_nowait(_QueuedEvent(event, contextvars.copy_context())) + consumer.queue.put_nowait(_STOP) + + first, stopped_first = await consumer.next() + second, stopped_second = await consumer.next() + + assert first == [events[0]] + assert second == [events[1]] + assert (stopped_first, stopped_second) == (False, True) + assert consumer.process_event.await_count == 2 + with mock.patch.object(consumer, "request", new=mock.AsyncMock()): + await consumer.upload(first) + await consumer.upload(second) + await asyncio.wait_for(consumer.queue.join(), 1) + + +@pytest.mark.asyncio +async def test_upload_acknowledges_failed_batch_even_when_on_error_raises(): + consumer = make_consumer(retries=0) + consumer.on_error = mock.AsyncMock(side_effect=RuntimeError("callback failed")) + event = {"event": "failed"} + consumer.queue.put_nowait(event) + consumer.queue.get_nowait() + error = APIError(400, "terminal") + + with mock.patch( + "posthog._async_consumer.async_batch_post", + new=mock.AsyncMock(side_effect=error), + ): + await consumer.upload([event]) + await asyncio.wait_for(consumer.queue.join(), 1) + + consumer.on_error.assert_awaited_once_with(error, [event]) + + +@pytest.mark.asyncio +async def test_next_propagates_cancellation_during_event_processing(): + consumer = make_consumer(retries=0) + started = asyncio.Event() + cancelled = asyncio.Event() + + async def process(event): + started.set() + try: + await asyncio.Event().wait() + finally: + cancelled.set() + + consumer.process_event = process + consumer.queue.put_nowait( + _QueuedEvent({"event": "blocked"}, contextvars.copy_context()) + ) + task = asyncio.create_task(consumer.next()) + await asyncio.wait_for(started.wait(), 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert cancelled.is_set() diff --git a/posthog/test/test_client_crap_flags.py b/posthog/test/test_client_crap_flags.py new file mode 100644 index 000000000..c6356c84c --- /dev/null +++ b/posthog/test/test_client_crap_flags.py @@ -0,0 +1,170 @@ +"""Client flag initialization and failure contracts protected during decomposition.""" + +import sys +from unittest import mock + +import pytest + +from posthog.client import Client +from posthog.request import APIError +from posthog.test.test_property_matching_version import definitions +from posthog.test.test_utils import FAKE_TEST_API_KEY, FakeRedis +from posthog.utils import FlagCache, RedisFlagCache + + +@pytest.fixture +def client(): + instance = Client( + FAKE_TEST_API_KEY, + secret_key="test-secret", + send=False, + enable_local_evaluation=False, + ) + instance.feature_flags = [] + yield instance + instance.shutdown() + + +@pytest.mark.parametrize( + "configured,expected,ttl", + [ + ("redis://", "redis://localhost:6379", 300), + ("redis://cache/2?ttl=17", "redis://cache:6379/2", 17), + ("redis://user@cache:6380/0", "redis://user:@cache:6380/0", 300), + ("redis://:secret@cache/0", "redis://:secret@cache:6379/0", 300), + ( + "rediss://user:secret@[::1]:6380/3?ttl=11", + "rediss://user:secret@[::1]:6380/3", + 11, + ), + ], +) +def test_redis_cache_initialization_preserves_url_and_ttl( + monkeypatch, configured, expected, ttl +): + redis_module = mock.Mock() + monkeypatch.setitem(sys.modules, "redis", redis_module) + instance = Client( + FAKE_TEST_API_KEY, + send=False, + enable_local_evaluation=False, + flag_fallback_cache_url=configured, + ) + try: + redis_module.from_url.assert_called_once_with(expected) + redis_module.from_url.return_value.ping.assert_called_once_with() + assert isinstance(instance.flag_cache, RedisFlagCache) + assert instance.flag_cache.default_ttl == ttl + finally: + instance.shutdown() + + +@pytest.mark.parametrize("failure", ["missing_dependency", "connection_failure"]) +def test_redis_cache_initialization_failure_disables_only_cache( + monkeypatch, caplog, failure +): + if failure == "missing_dependency": + monkeypatch.setitem(sys.modules, "redis", None) + expected_warning = "Redis not available" + else: + redis_module = mock.Mock() + redis_module.from_url.return_value.ping.side_effect = RuntimeError("offline") + monkeypatch.setitem(sys.modules, "redis", redis_module) + expected_warning = "Redis connection failed: offline" + instance = Client( + FAKE_TEST_API_KEY, + send=False, + enable_local_evaluation=False, + flag_fallback_cache_url="redis://cache/0", + ) + try: + assert instance.flag_cache is None + assert not instance.disabled + assert expected_warning in caplog.text + finally: + instance.shutdown() + + +@pytest.mark.parametrize("status", [401, 402]) +@pytest.mark.parametrize("debug", [False, True]) +def test_definition_error_invalidates_redis_snapshot_even_when_debug_raises( + client, status, debug +): + client.flag_cache = RedisFlagCache(FakeRedis()) + client._update_flag_state(definitions(2)) + fingerprint = client._flag_definition_fingerprint + previous_version = client.flag_definition_version + client.debug = debug + with ( + mock.patch("posthog.client.get", side_effect=APIError(status, "rejected")), + mock.patch.object(client.flag_cache, "_invalidate_snapshot") as invalidate, + ): + if debug: + with pytest.raises(APIError) as error: + client._load_feature_flags() + assert error.value.status == status + else: + client._load_feature_flags() + invalidate.assert_called_once_with(fingerprint) + assert client.feature_flags == [] + assert client._property_matching_version == 1 + assert client._flags_etag is None + assert client.flag_definition_version == previous_version + 1 + assert ( + client._flag_definition_published_generation + == client._flag_definition_fetch_generation + == client._flag_definition_cache_generation + ) + + +def test_remote_cache_write_failure_keeps_stale_value_and_received_metadata(client): + client.flag_cache = FlagCache() + initial = {"featureFlags": {"checkout": "control"}} + with mock.patch("posthog.client.flags", return_value=initial): + assert ( + client.get_feature_flag_result( + "checkout", "user", send_feature_flag_events=False + ).get_value() + == "control" + ) + + response = { + "requestId": "new-request", + "evaluatedAt": 123, + "flags": { + "checkout": { + "value": "test", + "reason": {"description": "New assignment"}, + "metadata": { + "id": 7, + "version": 2, + "config_version": 2, + "rule_type": "experiment", + "rule_id": "rule-id", + "variant_key": "test", + }, + } + }, + } + with ( + mock.patch("posthog.client.flags", return_value=response), + mock.patch.object( + client.flag_cache, + "_set_cached_remote_flag", + side_effect=RuntimeError("offline"), + ), + mock.patch.object(client, "capture") as capture, + ): + result = client.get_feature_flag_result("checkout", "user") + assert result.get_value() == "control" + capture.assert_called_once() + event = capture.call_args.kwargs + assert capture.call_args.args == ("$feature_flag_called",) + properties = event["properties"] + assert properties["$feature_flag_response"] == "control" + assert properties["$feature_flag_error"] == "unknown_error" + assert properties["$feature_flag_request_id"] == "new-request" + assert properties["$feature_flag_evaluated_at"] == 123 + assert properties["$feature_flag_id"] == 7 + assert properties["$feature_flag_reason"] == "New assignment" + assert "$feature_flag_rule_id" not in properties diff --git a/posthog/test/test_code_variables.py b/posthog/test/test_code_variables.py index 6263b4b8d..2efa0bbec 100644 --- a/posthog/test/test_code_variables.py +++ b/posthog/test/test_code_variables.py @@ -1400,3 +1400,74 @@ def trigger_error(): ) assert "code_variables" in output assert "n8fK2pQ9vX7mL4wR8tY3uZ6bC1dE5gH" in output # detection off -> retained + + +@pytest.mark.parametrize( + "base, value, expected", + [ + (str, "contains_password_here", REDACTED), + (int, 42, 42), + (float, 1.5, 1.5), + (float, float("inf"), "inf"), + ], +) +def test_scalar_subclasses_are_masked_before_object_attribute_traversal( + base, value, expected +): + class Scalar(base): + pass + + scalar = Scalar(value) + scalar.extra = {"password": "not part of the scalar wire representation"} + assert mask(scalar) == expected + assert encode(scalar) == expected + + +def test_oversized_namedtuple_is_replaced_without_reading_items(): + class Wide(collections.namedtuple("Wide", [f"field{n}" for n in range(51)])): + def __iter__(self): + raise AssertionError("oversized values must not be read") + + assert mask(Wide(*range(51))) == TOO_LONG + + +@pytest.mark.parametrize( + "value, expected", [(float("nan"), "nan"), (float("inf"), "inf")] +) +def test_disabled_masking_still_encodes_non_finite_numbers_as_strings(value, expected): + config = _MaskingConfig.build( + [], [], mask_url_credentials=False, detect_secrets=False + ) + assert _encode_variable(value, config, VariableSizeLimiter()) == expected + + +def test_numeric_variables_charge_the_shared_budget_without_string_truncation(): + limiter = VariableSizeLimiter(max_size=3) + assert encode(123, limiter=limiter) == 123 + assert limiter.get_remaining_space() == 0 + assert encode(1, limiter=limiter) is None + + +def test_encoding_failure_uses_masked_repr_and_charges_the_budget(): + # Reading this dict fails before it can be serialized structurally. Its repr holds + # a named secret, so the fallback must redact rather than expose that repr. + broken = _BrokenDict(password="hunter2") + limiter = VariableSizeLimiter(max_size=len(REDACTED)) + assert encode(broken, limiter=limiter) == REDACTED + assert limiter.get_remaining_space() == 0 + assert encode(broken, limiter=limiter) is None + + +def test_disabling_name_patterns_does_not_read_property_getters(): + class Opaque: + __slots__ = () + + @property + def password(self): + raise AssertionError("masking must not read getters") + + def __repr__(self): + return "" + + assert mask(Opaque(), patterns=[]) == "" + assert mask(Opaque())["password"] == REDACTED diff --git a/posthog/test/test_emails.py b/posthog/test/test_emails.py index 82b8a8dce..b2690cff0 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -949,6 +949,103 @@ def test_rejects_a_code_send_that_mixes_or_misses_fields(_name, overrides, error assert adapter.requests == [] +@pytest.mark.parametrize("factory", [Emails, AsyncEmails]) +@pytest.mark.parametrize( + "options, message", + [ + ({"timeout": True}, "timeout must be a finite positive number of seconds."), + ({"timeout": "3"}, "timeout must be a finite positive number of seconds."), + ( + {"timeout": float("inf")}, + "timeout must be a finite positive number of seconds.", + ), + ( + {"timeout": float("nan")}, + "timeout must be a finite positive number of seconds.", + ), + ({"timeout": 0}, "timeout must be a finite positive number of seconds."), + ({"max_retries": True}, "max_retries must be a nonnegative integer."), + ({"max_retries": None}, "max_retries must be a nonnegative integer."), + ({"max_retries": -1}, "max_retries must be a nonnegative integer."), + ( + {"migrated_from": "re send"}, + "migrated_from must be visible ASCII characters, such as 'resend'.", + ), + ], +) +def test_invalid_transport_options_are_rejected_at_construction( + factory, options, message +): + with pytest.raises(ValueError) as raised: + factory(SECRET_KEY, **options) + assert str(raised.value) == message + + +@pytest.mark.parametrize("warnings", [None, {}, "not a warning list"]) +def test_non_list_warnings_are_ignored(warnings): + emails, _ = emails_with([accepted(warnings=warnings, replayed=1)]) + result = send(emails) + assert result.warnings == () + assert result.replayed is False + + +def test_warning_parsing_keeps_order_fallback_fields_and_safe_defaults(caplog): + emails, _ = emails_with( + [ + accepted( + warnings=[ + None, + { + "code": "first", + "detail": "preferred", + "message": "ignored", + "fix": "update", + }, + {"code": "", "detail": 42, "message": "fallback", "fix": False}, + {}, + ] + ) + ] + ) + with caplog.at_level(logging.WARNING, logger="posthog"): + result = send(emails) + assert [(w.code, w.message, w.fix) for w in result.warnings] == [ + ("first", "preferred", "update"), + ("warning", "fallback", None), + ("warning", "", None), + ] + assert len(caplog.records) == 3 + assert all( + record.getMessage().endswith(message) + for record, message in zip( + caplog.records, + [ + "PostHog email warning first: preferred", + "PostHog email warning warning: fallback", + "PostHog email warning warning: ", + ], + ) + ) + + +def test_code_send_preserves_utf8_and_compact_json_bytes(): + emails, adapter = emails_with([accepted()]) + send_code(emails, subject="Bonjour é", html="

你好

") + assert adapter.requests[0].body == ( + '{"to":"user@example.com","template_key":"password-reset",' + '"subject":"Bonjour é","html":"

你好

"}' + ).encode("utf-8") + + +def test_code_send_validation_order_still_checks_recipient_before_template_and_content(): + emails, adapter = emails_with([]) + with pytest.raises(TypeError, match="to must be one email address as a string"): + send_code(emails, to=[], template_key="bad key", subject=123, html=123) + with pytest.raises(ValueError, match="template_key can only have letters"): + send_code(emails, template_key="bad key", subject=123, html=123) + assert adapter.requests == [] + + def test_a_refused_send_names_the_field_from_attr(): posthog = FakePostHog() posthog.send_fields = SEND_FIELDS - {"cc"} diff --git a/posthog/test/test_evaluate_flags.py b/posthog/test/test_evaluate_flags.py index dbe33583c..bb76ed85a 100644 --- a/posthog/test/test_evaluate_flags.py +++ b/posthog/test/test_evaluate_flags.py @@ -1207,6 +1207,96 @@ def test_unsupported_definition_logs_warning(self, _name, checkout): len(self._warnings(logs, "checkout", "unsupported_definition")), 1 ) + @parameterized.expand( + [ + ("non_object", []), + ("unknown_group_type", {"type": "XOR", "values": []}), + ("non_list_values", {"type": "AND", "values": {}}), + ("non_object_entry", {"type": "AND", "values": [42]}), + ( + "nested_unsupported_leaf", + { + "type": "OR", + "values": [ + { + "type": "AND", + "values": [ + {"key": "plan", "operator": "bogus", "value": "pro"} + ], + } + ], + }, + ), + ] + ) + @mock.patch("posthog.client.flags") + def test_malformed_dynamic_cohort_warns_and_remains_unresolved( + self, _name, cohort, patch_flags + ): + client = self._client() + definitions = self._definitions( + _flag_with("checkout", {"type": "cohort", "value": 42}) + ) + definitions["cohorts"] = {"42": cohort} + + with self.assertLogs("posthog", level=logging.WARNING) as logs: + self._refresh( + client, GetResponse(data=definitions, etag=None, not_modified=False) + ) + self.assertEqual( + len(self._warnings(logs, "checkout", "unsupported_definition")), 1 + ) + snapshot = client.evaluate_flags( + "user", person_properties={"plan": "pro"}, only_evaluate_locally=True + ) + self.assertEqual(snapshot.keys, []) + self.assertEqual( + dict(snapshot.unresolved_flags), + {"checkout": UnresolvedFlagReason.UNSUPPORTED_DEFINITION}, + ) + patch_flags.assert_not_called() + + @parameterized.expand( + [ + ("canonical_empty", {}), + ( + "nested_supported_group", + { + "type": "AND", + "values": [ + {}, + { + "type": "OR", + "values": [{"key": "plan", "value": "pro"}], + }, + ], + }, + ), + ] + ) + @mock.patch("posthog.client.flags") + def test_supported_dynamic_cohort_does_not_warn_or_fall_back( + self, _name, cohort, patch_flags + ): + client = self._client() + definitions = self._definitions( + _flag_with("checkout", {"type": "cohort", "value": 42}) + ) + definitions["cohorts"] = {"42": cohort} + + with self.assertNoLogs("posthog", level=logging.WARNING): + self._refresh( + client, GetResponse(data=definitions, etag=None, not_modified=False) + ) + snapshot = client.evaluate_flags( + "user", person_properties={"plan": "pro"}, only_evaluate_locally=True + ) + self.assertIs( + snapshot.get_flag("checkout", send_feature_flag_events=False), True + ) + self.assertEqual(dict(snapshot.unresolved_flags), {}) + patch_flags.assert_not_called() + def test_does_not_warn_for_flags_that_depend_on_the_call(self): client = self._client() diff --git a/posthog/test/test_exception_utils.py b/posthog/test/test_exception_utils.py index 007d575b4..e719c8c31 100644 --- a/posthog/test/test_exception_utils.py +++ b/posthog/test/test_exception_utils.py @@ -1,5 +1,10 @@ +import sys from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +import pytest + +from posthog import exception_utils from posthog.exception_utils import format_timestamp @@ -16,3 +21,262 @@ def test_format_timestamp_converts_aware_value_to_utc(): ) assert format_timestamp(value) == "2026-06-27T12:00:00.123456Z" + + +# Source context, traversal and frame classification are observable payload contracts. +def test_source_context_keeps_file_order_and_five_lines_on_each_side(tmp_path): + source = tmp_path / "application.py" + source.write_text("\n".join(f"line {n}" for n in range(13))) + + assert exception_utils.get_lines_from_file(str(source), 6) == ( + ["line 1", "line 2", "line 3", "line 4", "line 5"], + "line 6", + ["line 7", "line 8", "line 9", "line 10", "line 11"], + ) + + +def test_source_context_prefers_loader_over_file(tmp_path): + source = tmp_path / "application.py" + source.write_text("stale contents") + loader = SimpleNamespace(get_source=lambda module: "before\r\ncurrent\r\nafter") + + assert exception_utils.get_lines_from_file( + str(source), 1, loader=loader, module="app" + ) == ( + ["before"], + "current", + ["after"], + ) + + +@pytest.mark.parametrize("failure", [ImportError, OSError]) +def test_source_context_falls_back_when_loader_cannot_read_source(tmp_path, failure): + def unavailable(module): + raise failure("source unavailable") + + source = tmp_path / "application.py" + source.write_text("current\nafter\n") + assert exception_utils.get_lines_from_file( + str(source), 0, loader=SimpleNamespace(get_source=unavailable), module="app" + ) == ([], "current", ["after"]) + + +def test_source_context_handles_changed_files(tmp_path): + source = tmp_path / "application.py" + source.write_text("current\n") + assert exception_utils.get_lines_from_file(str(source), 99) == ([], None, []) + + +def test_source_context_does_not_replace_empty_loader_source_with_stale_file(tmp_path): + source = tmp_path / "application.py" + source.write_text("stale contents") + loader = SimpleNamespace(get_source=lambda module: "") + assert exception_utils.get_lines_from_file(str(source), 0, loader=loader) == ( + [], + None, + [], + ) + + +def test_source_context_handles_unreadable_file(monkeypatch): + def unavailable(filename): + raise OSError("source unavailable") + + monkeypatch.setattr(exception_utils.linecache, "getlines", unavailable) + assert exception_utils.get_lines_from_file("application.py", 0) == ([], None, []) + + +@pytest.mark.parametrize("relationship", ["cause", "context"]) +def test_walk_exception_chain_is_outermost_first_and_stops_at_cycles(relationship): + outer, inner = RuntimeError("outer"), ValueError("inner") + if relationship == "cause": + outer.__cause__ = inner + inner.__cause__ = outer + else: + outer.__context__ = inner + inner.__context__ = outer + + assert list(exception_utils.walk_exception_chain((type(outer), outer, None))) == [ + (RuntimeError, outer, None), + (ValueError, inner, None), + ] + + +def test_walk_exception_chain_stops_at_suppressed_context(): + outer = RuntimeError("outer") + outer.__context__ = ValueError("ignored") + outer.__suppress_context__ = True + assert list(exception_utils.walk_exception_chain((RuntimeError, outer, None))) == [ + (RuntimeError, outer, None) + ] + assert list(exception_utils.walk_exception_chain((None, None, None))) == [] + + +def test_event_frame_iteration_keeps_top_level_thread_and_exception_order(): + first, second, third = ( + {"function": "main"}, + {"function": "thread"}, + {"function": "fail"}, + ) + event = { + "stacktrace": {"frames": [first]}, + "threads": {"values": [{}, {"stacktrace": {"frames": [second]}}]}, + "exception": { + "values": [{"stacktrace": {}}, {}, {"stacktrace": {"frames": [third]}}] + }, + } + assert list(exception_utils.iter_event_frames(event)) == [first, second, third] + assert ( + list(exception_utils.iter_event_frames({"threads": {}, "exception": {}})) == [] + ) + + +@pytest.mark.parametrize( + "frame, expected", + [ + ({"in_app": False, "module": "app"}, False), + ({"module": "app.handlers"}, True), + ({"module": "app2.handlers"}, None), + ({"module": "vendor.plugin"}, False), + ({"abs_path": "/venv/site-packages/pkg.py"}, False), + ({"abs_path": "/venv/dist-packages/pkg.py"}, False), + ({"abs_path": "/project/app.py"}, True), + ({"abs_path": "/elsewhere/app.py"}, None), + ({}, None), + ], +) +def test_frame_classification_preserves_overrides_and_module_boundaries( + frame, expected +): + frames = [frame] + assert ( + exception_utils.set_in_app_in_frames( + frames, + in_app_exclude=["vendor", "app"], + in_app_include=["app"], + project_root="/project/", + ) + is frames + ) + assert frame.get("in_app") is expected + + +def test_frame_classification_accepts_missing_options_and_empty_frames(): + frame = {"module": "app", "abs_path": "/project/app.py"} + exception_utils.set_in_app_in_frames([frame], None, None) + assert "in_app" not in frame + assert exception_utils.set_in_app_in_frames([], None, None) is None + + +def test_exc_info_preserves_explicit_tuple(): + error = ValueError("reported") + assert exception_utils.exc_info_from_error((ValueError, error, None)) == ( + ValueError, + error, + None, + ) + + +def test_exc_info_preserves_active_traceback_when_synthesis_fails(monkeypatch): + def unavailable(error): + raise RuntimeError("cannot synthesize traceback") + + monkeypatch.setattr(exception_utils, "construct_artificial_traceback", unavailable) + error = ValueError("active") + try: + raise error + except ValueError: + expected = sys.exc_info() + assert exception_utils.exc_info_from_error(error) == expected + + +def test_exc_info_does_not_borrow_an_unrelated_active_exception(monkeypatch): + monkeypatch.setattr( + exception_utils, "construct_artificial_traceback", lambda error: None + ) + error = ValueError("reported") + try: + raise RuntimeError("unrelated") + except RuntimeError: + assert exception_utils.exc_info_from_error(error) == (ValueError, error, None) + assert exception_utils.exc_info_from_error(error) == (ValueError, error, None) + + +@pytest.mark.parametrize("invalid", [None, "error", (ValueError, ValueError("bad"))]) +def test_exc_info_rejects_non_exception_inputs(invalid): + with pytest.raises(ValueError, match="Expected Exception object"): + exception_utils.exc_info_from_error(invalid) + + +@pytest.mark.parametrize( + "mechanism, expected", + [ + ( + { + "type": "custom", + "handled": False, + "source": "cause", + "synthetic": False, + "extra": "kept", + }, + { + "type": "custom", + "handled": False, + "source": "cause", + "synthetic": False, + "extra": "kept", + }, + ), + ( + { + "type": "", + "handled": 1, + "source": False, + "synthetic": "yes", + "extra": "kept", + }, + {"synthetic": False, "extra": "kept"}, + ), + (None, {"synthetic": False}), + ], +) +def test_exception_serialization_validates_mechanism_fields_independently( + mechanism, expected +): + error = ValueError("reported") + result = exception_utils.single_exception_from_error_tuple( + ValueError, error, None, mechanism=mechanism + ) + assert result == { + "mechanism": expected, + "module": None, + "type": "ValueError", + "value": "reported", + } + + +def test_exception_tree_truncates_long_cyclic_cause_chain_in_outermost_first_order(): + errors = [ValueError(str(n)) for n in range(60)] + for outer, inner in zip(errors, errors[1:]): + outer.__cause__ = inner + errors[-1].__cause__ = errors[0] + result = exception_utils.exceptions_from_error_tuple((ValueError, errors[0], None)) + assert [entry["value"] for entry in result] == [str(n) for n in range(50)] + assert [entry["mechanism"]["exception_id"] for entry in result] == list(range(50)) + assert [entry["mechanism"]["parent_id"] for entry in result[1:]] == list(range(49)) + assert all(entry["mechanism"]["source"] == "cause" for entry in result[1:]) + + +def test_exception_tree_stops_at_a_cycle_before_the_entry_limit(): + outer, inner = ValueError("outer"), RuntimeError("inner") + outer.__context__ = inner + inner.__context__ = outer + result = exception_utils.exceptions_from_error_tuple((ValueError, outer, None)) + assert [entry["value"] for entry in result] == ["outer", "inner"] + assert result[1]["mechanism"] == { + "exception_id": 1, + "parent_id": 0, + "type": "chained", + "source": "context", + "synthetic": False, + } diff --git a/posthog/test/test_feature_flags.py b/posthog/test/test_feature_flags.py index a18592db4..a994adeb8 100644 --- a/posthog/test/test_feature_flags.py +++ b/posthog/test/test_feature_flags.py @@ -506,6 +506,9 @@ def test_early_exit_preserves_fallback_after_inconclusive_presence_condition( "rollout_percentage": 100, }, {"properties": [], "rollout_percentage": 0}, + # Early exit must stop before this conclusive match, + # preserving the earlier missing-context fallback. + {"properties": [], "rollout_percentage": 100}, ], }, } diff --git a/posthog/test/test_metrics.py b/posthog/test/test_metrics.py index e25bb34bf..7185e631b 100644 --- a/posthog/test/test_metrics.py +++ b/posthog/test/test_metrics.py @@ -868,3 +868,47 @@ def test_failed_flushes_back_off_exponentially_capped(self): c.metrics.count("m", 1) assert c.metrics._flush_timer.interval == 1.0 c.metrics.reset() + + +@pytest.mark.parametrize("metric_type", ["count", "gauge", "histogram"]) +@pytest.mark.parametrize("current_sampled", [False, True]) +def test_failed_flush_merges_values_recorded_during_send( + client, metric_type, current_sampled +): + record = getattr(client.metrics, metric_type) + with trace.use_span(otel_span(sampled=True)): + record("in-flight", 3) + session = mock_session(503) + + def fail_with_concurrent_sample(*args, **kwargs): + with trace.use_span(otel_span(sampled=current_sampled)): + record("in-flight", 4) + return mock.Mock(status_code=503) + + session.post.side_effect = fail_with_concurrent_sample + with mock.patch("posthog.metrics_capture._get_session", return_value=session): + client.metrics.flush() + + payload, _, _ = flush_and_capture(client) + (metric,) = metrics_from(payload) + if metric_type == "count": + assert metric["sum"]["dataPoints"][0]["asDouble"] == 7.0 + elif metric_type == "gauge": + assert metric["gauge"]["dataPoints"][0]["asDouble"] == 4.0 + else: + (point,) = metric["histogram"]["dataPoints"] + assert (point["count"], point["sum"], point["min"], point["max"]) == ( + 2, + 7.0, + 3.0, + 4.0, + ) + assert point["bucketCounts"] == [0, 2] + [0] * 14 + assert len(metrics_from(payload)) == 1 + (point,) = data_points_by_type(payload).values() + (exemplar,) = point["exemplars"] + assert (exemplar["traceId"], exemplar["spanId"], exemplar["asDouble"]) == ( + OTEL_TRACE_ID, + OTEL_SPAN_ID, + 4.0 if current_sampled else 3.0, + ) diff --git a/posthog/test/test_metrics_autocapture.py b/posthog/test/test_metrics_autocapture.py index 57221289d..ab77e2c66 100644 --- a/posthog/test/test_metrics_autocapture.py +++ b/posthog/test/test_metrics_autocapture.py @@ -443,6 +443,60 @@ def test_limits_http_attribute_sets(self, posthog_host, app_server, started): assert len(attributes) == 2 assert {"otel.metric.overflow": True} in attributes + def test_fork_reset_replaces_held_collection_locks_without_acquiring_them( + self, posthog_host, started + ): + # Exercise the reset callback in-process: child coverage is not recorded, + # and a held inherited lock must never be acquired by the reset itself. + handle = _start( + posthog_host, + started, + export_interval_seconds=3600, + areas={"runtime": True}, + ) + meter = handle._meter_provider.get_meter("fork-reset-test") + histogram = meter.create_histogram("fork.reset.duration") + histogram.record(1) + consumer = handle._meter_provider._measurement_consumer + owners = [(meter, "_instrument_registration_lock"), (consumer, "_lock")] + for storage in consumer._reader_storages.values(): + owners.append((storage, "_lock")) + for matches in storage._instrument_view_instrument_matches.values(): + for match in matches: + owners.append((match, "_lock")) + for aggregation in match._attributes_aggregation.values(): + owners.append((aggregation, "_lock")) + reservoir = getattr(aggregation, "_reservoir", None) + if getattr(reservoir, "_lock", None) is not None: + owners.append((reservoir, "_lock")) + owners.extend( + [(handle._reader, "_export_lock"), (metrics_autocapture, "_lock")] + ) + original_locks = [getattr(owner, name) for owner, name in owners] + runtime = next(i for i in handle._instrumentors if hasattr(i, "_proc")) + original_process = runtime._proc + handle._flush_requested = 8 + handle._flush_exported = 5 + + with ExitStack() as stack: + for lock in original_locks: + stack.enter_context(_held_by_another_thread(lock)) + metrics_autocapture._reinit_after_fork() + for (owner, name), original in zip(owners, original_locks): + replacement = getattr(owner, name) + assert replacement is not original + assert type(replacement) is type(original) + assert replacement.acquire(blocking=False) + replacement.release() + histogram.record(2) + handle.force_flush() + + assert runtime._proc is not original_process + assert runtime._proc.pid == os.getpid() + assert handle._flush_thread is None + assert handle._flush_requested == handle._flush_exported == 0 + assert _metrics_exports(posthog_host) + @pytest.mark.skipif(not hasattr(os, "fork"), reason="needs os.fork") @pytest.mark.filterwarnings("ignore:This process .* is multi-threaded") def test_keeps_working_in_a_forked_child(self, posthog_host, app_server, started): diff --git a/posthog/test/tracing/test_export.py b/posthog/test/tracing/test_export.py index 52cff1515..0b6851035 100644 --- a/posthog/test/tracing/test_export.py +++ b/posthog/test/tracing/test_export.py @@ -394,6 +394,55 @@ def test_never_returns_a_span_it_failed_to_encode(self): assert sender.payloads == [] assert queued(pipeline) == [] + def test_encoding_failure_keeps_the_retry_batch_separate_from_later_spans( + self, clock, caplog + ): + caplog.set_level("WARNING", logger="posthog") + sender = FakeSender(SendOutcome("retry-later"), SendOutcome("ok")) + pipeline, _, _ = make_traces(sender=sender, max_export_batch_size=4) + pipeline.start_span("bad").end() + pipeline.start_span("retry-me").end() + encode = export_module.build_otlp_span + + def encode_unless_bad(record): + if record.name == "bad": + raise RuntimeError("bad") + return encode(record) + + with mock.patch.object(export_module, "build_otlp_span", encode_unless_bad): + pipeline.flush() + pipeline.start_span("later").end() + clock["now"] += 100 + pipeline.flush() + + assert [[span["name"] for span in batch] for batch in sender.batches()] == [ + ["retry-me"], + ["retry-me"], + ["later"], + ] + assert sender.batches()[0] == sender.batches()[1] + assert queued(pipeline) == [] + warnings = [ + r.getMessage() for r in caplog.records if "Dropping" in r.getMessage() + ] + assert len(warnings) == 1 + assert "Dropping 1 span(s)" in warnings[0] + + def test_close_during_encoding_abandons_the_batch_without_sending(self): + pipeline, sender, _ = make_traces() + pipeline.start_span("closing").end() + pipeline.start_span("queued").end() + + def close_and_fail(record): + pipeline.close() + raise RuntimeError("encoder failed after shutdown") + + with mock.patch.object(export_module, "build_otlp_span", close_and_fail): + pipeline.flush() + + assert sender.payloads == [] + assert queued(pipeline) == [] + def test_counts_a_span_it_failed_to_encode_once(self, caplog): caplog.set_level("WARNING", logger="posthog") sender = FakeSender(SendOutcome("fatal")) diff --git a/posthog/tracing/_config.py b/posthog/tracing/_config.py index 579d9ff48..0951080d5 100644 --- a/posthog/tracing/_config.py +++ b/posthog/tracing/_config.py @@ -143,27 +143,31 @@ def _resolve_before_span_send(value: Any) -> Tuple[Callable, ...]: return tuple(supplied) -def resolve_traces_config( - config: Any, host_resource_attributes: Optional[Mapping[str, str]] = None -) -> ResolvedTracesConfig: - """Validate the ``traces`` option, falling back to documented defaults per key. - - Host resource attributes (``os.name``, ``os.version``) merge first so user - ``resource_attributes`` win; a string ``service.name`` / ``service.version`` - / ``deployment.environment`` there wins over the named fields. - """ +def _config_mapping(config: Any) -> Mapping: if not isinstance(config, Mapping): if config is not None: log.warning( "Ignoring traces config: expected a dict, got %s", type(config).__name__ ) config = {} - unknown = [key for key in config if key not in _KNOWN_KEYS] if unknown: log.warning( "Ignoring unknown traces option(s): %s", ", ".join(map(str, unknown)) ) + return config + + +def resolve_traces_config( + config: Any, host_resource_attributes: Optional[Mapping[str, str]] = None +) -> ResolvedTracesConfig: + """Validate the ``traces`` option, falling back to documented defaults per key. + + Host resource attributes (``os.name``, ``os.version``) merge first so user + ``resource_attributes`` win; a string ``service.name`` / ``service.version`` + / ``deployment.environment`` there wins over the named fields. + """ + config = _config_mapping(config) resource_attributes: Dict[str, Any] = dict(host_resource_attributes or {}) resource_attributes.update( diff --git a/posthog/tracing/_context.py b/posthog/tracing/_context.py index 25c5299da..24ea98a42 100644 --- a/posthog/tracing/_context.py +++ b/posthog/tracing/_context.py @@ -28,6 +28,18 @@ def _enrichment_is_enabled() -> bool: return bool((project_api_key or "").strip() or (api_key or "").strip()) +def _missing_context_attributes(attributes: Mapping) -> dict: + context = contexts._get_active_span_context() + extra = {} + session_id = context["session_id"] + distinct_id = context["distinct_id"] + if session_id and "sessionId" not in attributes: + extra["sessionId"] = session_id + if distinct_id and not any(key in attributes for key in _IDENTITY_ATTRIBUTES): + extra["posthogDistinctId"] = distinct_id + return extra + + def _enrich_span(span: object) -> None: try: if not _enrichment_is_enabled() or not getattr(span, "is_recording")(): @@ -35,14 +47,7 @@ def _enrich_span(span: object) -> None: attributes = getattr(span, "attributes", None) if not isinstance(attributes, Mapping): return - context = contexts._get_active_span_context() - extra = {} - session_id = context["session_id"] - distinct_id = context["distinct_id"] - if session_id and "sessionId" not in attributes: - extra["sessionId"] = session_id - if distinct_id and not any(key in attributes for key in _IDENTITY_ATTRIBUTES): - extra["posthogDistinctId"] = distinct_id + extra = _missing_context_attributes(attributes) if not extra: return # The SDK exposes no public capacity getter and evicts old attributes diff --git a/posthog/tracing/_export.py b/posthog/tracing/_export.py index e68385f78..a68c5716e 100644 --- a/posthog/tracing/_export.py +++ b/posthog/tracing/_export.py @@ -202,11 +202,7 @@ def _drain_within_budget(self, deadline: Optional[float], retry: bool) -> None: while True: removed, stop = self._drain(deadline) if not stop: - if ( - removed - and self._queue - and (deadline is None or time.monotonic() < deadline) - ): + if self._followup_due(removed, deadline): self._drain(deadline) return if deadline is None or not retry: @@ -218,6 +214,13 @@ def _drain_within_budget(self, deadline: Optional[float], retry: bool) -> None: if self._wait_for_retry(min(wait, remaining)): return + def _followup_due(self, removed: int, deadline: Optional[float]) -> bool: + return bool( + removed + and self._queue + and (deadline is None or time.monotonic() < deadline) + ) + def _retry_wait_locked(self) -> Optional[float]: """The backoff to wait out before retrying, or ``None`` when there is nothing to retry.""" with self._lock: @@ -281,6 +284,11 @@ def _drain(self, deadline: Optional[float]) -> Tuple[int, bool]: if self._is_closed() or self._discard_if_disabled_locked(): return 0, True remaining = len(self._queue) + return self._drain_batches(remaining, deadline) + + def _drain_batches( + self, remaining: int, deadline: Optional[float] + ) -> Tuple[int, bool]: removed = 0 sent_any = False # A batch the SDK measured as too large says nothing about the batches @@ -292,70 +300,88 @@ def _drain(self, deadline: Optional[float]) -> Tuple[int, bool]: return removed, True if not self._queue: break - # A retried batch cannot grow to take in spans behind it. - cap = ( - min(self._max_export_batch_size, self._head_batch_size) - if self._head_batch_failures - else self._max_export_batch_size - ) - if local_cap is not None: - cap = min(cap, local_cap) - size = max(1, min(cap, remaining, len(self._queue))) - batch = self._queue[:size] - # Read before the send. A send inside an open Retry-After - # window is caller-driven and exempt from the wait, and so from - # the charge. - chargeable = ( - time.monotonic() >= self._head_batch_chargeable_at - and not self._retry_after.is_open() - ) + batch, chargeable = self._batch_locked(remaining, local_cap) + size = len(batch) - spans, failed = self._encode(batch) - if failed: - # Out of the queue before the send is settled, so a failed - # send does not count them a second time. - with self._lock: - if self._is_closed(): - return removed, True - for index in reversed(failed): - del self._queue[index] - if not spans: - self._reset_head_batch_budget_locked() - size -= len(failed) - remaining -= len(failed) - removed += len(failed) - if not spans: - continue + spans, failed = self._encode_queued_batch(batch) + if spans is None: + return removed, True + size -= failed + remaining -= failed + removed += failed + if not spans: + continue # The first request is exempt, so a flush called with no budget left # (a serverless handler, say) still ships a batch. - if sent_any and deadline is not None and time.monotonic() >= deadline: + if _request_budget_spent(sent_any, deadline): return removed, True sent_any = True - try: - outcome = self._send( - self._client, build_traces_payload(spans, self._resource) - ) - except Exception: - log.debug("Span batch send failed", exc_info=True) - outcome = SendOutcome("retry-later") - - with self._lock: - if self._is_closed(): - return removed, True - taken, stop, note = self._apply_outcome_locked( - outcome, size, chargeable - ) - if note: - log.debug(note) - if outcome.measured_locally and not taken: - local_cap = max(1, size // 2) + outcome, taken, stop = self._send_and_settle(spans, size, chargeable) + local_cap = _local_batch_cap(outcome, taken, size, local_cap) remaining -= taken removed += taken if stop: return removed, True return removed, False + def _send_and_settle( + self, spans: List[dict], size: int, chargeable: bool + ) -> Tuple[SendOutcome, int, bool]: + try: + outcome = self._send( + self._client, build_traces_payload(spans, self._resource) + ) + except Exception: + log.debug("Span batch send failed", exc_info=True) + outcome = SendOutcome("retry-later") + + with self._lock: + if self._is_closed(): + return outcome, 0, True + taken, stop, note = self._apply_outcome_locked(outcome, size, chargeable) + if note: + log.debug(note) + return outcome, taken, stop + + def _encode_queued_batch( + self, batch: List[SpanRecord] + ) -> Tuple[Optional[List[dict]], int]: + spans, failed = self._encode(batch) + if failed: + # Out of the queue before the send is settled, so a failed + # send does not count them a second time. + with self._lock: + if self._is_closed(): + return None, 0 + for index in reversed(failed): + del self._queue[index] + if not spans: + self._reset_head_batch_budget_locked() + return spans, len(failed) + + def _batch_locked( + self, remaining: int, local_cap: Optional[int] + ) -> Tuple[List[SpanRecord], bool]: + # A retried batch cannot grow to take in spans behind it. + cap = ( + min(self._max_export_batch_size, self._head_batch_size) + if self._head_batch_failures + else self._max_export_batch_size + ) + if local_cap is not None: + cap = min(cap, local_cap) + size = max(1, min(cap, remaining, len(self._queue))) + batch = self._queue[:size] + # Read before the send. A send inside an open Retry-After + # window is caller-driven and exempt from the wait, and so from + # the charge. + chargeable = ( + time.monotonic() >= self._head_batch_chargeable_at + and not self._retry_after.is_open() + ) + return batch, chargeable + def _apply_outcome_locked( self, outcome: SendOutcome, size: int, chargeable: bool ) -> Tuple[int, bool, Optional[str]]: @@ -373,30 +399,7 @@ def _apply_outcome_locked( return size, False, None if outcome.kind == "too-large": - if size == 1: - del self._queue[:1] - self._end_failure_sequence_locked() - self._drops.record(1, "it is too large for the ingestion endpoint") - # The oversized span is gone; the batches after it are not suspect. - if self._batch_size_before_halving is not None: - self._max_export_batch_size = self._batch_size_before_halving - self._batch_size_before_halving = None - return 1, False, None - # Halve the refused batch, not the configured size: a shallow queue - # would otherwise resend the same body. - halved = max(1, size // 2) - if not outcome.measured_locally: - if self._batch_size_before_halving is None: - self._batch_size_before_halving = self._max_export_batch_size - self._max_export_batch_size = halved - self._reset_head_batch_budget_locked() - return ( - 0, - False, - "Span batch too large; retrying the same spans in batches of {}".format( - halved - ), - ) + return self._apply_too_large_locked(outcome, size) if outcome.kind == "retry-later": self._consecutive_failures += 1 @@ -428,6 +431,34 @@ def _apply_outcome_locked( self._drops.record(size, "the ingestion endpoint rejected the batch") return size, False, None + def _apply_too_large_locked( + self, outcome: SendOutcome, size: int + ) -> Tuple[int, bool, Optional[str]]: + if size == 1: + del self._queue[:1] + self._end_failure_sequence_locked() + self._drops.record(1, "it is too large for the ingestion endpoint") + # The oversized span is gone; the batches after it are not suspect. + if self._batch_size_before_halving is not None: + self._max_export_batch_size = self._batch_size_before_halving + self._batch_size_before_halving = None + return 1, False, None + # Halve the refused batch, not the configured size: a shallow queue + # would otherwise resend the same body. + halved = max(1, size // 2) + if not outcome.measured_locally: + if self._batch_size_before_halving is None: + self._batch_size_before_halving = self._max_export_batch_size + self._max_export_batch_size = halved + self._reset_head_batch_budget_locked() + return ( + 0, + False, + "Span batch too large; retrying the same spans in batches of {}".format( + halved + ), + ) + def _is_closed(self) -> bool: # A method, so the check after each send is not narrowed away. return self._closed @@ -534,3 +565,15 @@ def _clear_timer_locked(self) -> None: def _draw_jitter() -> float: return 1 - FLUSH_BACKOFF_JITTER + random.random() * FLUSH_BACKOFF_JITTER * 2 + + +def _request_budget_spent(sent_any: bool, deadline: Optional[float]) -> bool: + return sent_any and deadline is not None and time.monotonic() >= deadline + + +def _local_batch_cap( + outcome: SendOutcome, taken: int, size: int, current: Optional[int] +) -> Optional[int]: + if outcome.measured_locally and not taken: + return max(1, size // 2) + return current diff --git a/posthog/tracing/_limits.py b/posthog/tracing/_limits.py index faeb55428..ae6f06d59 100644 --- a/posthog/tracing/_limits.py +++ b/posthog/tracing/_limits.py @@ -55,19 +55,7 @@ def _truncate(value: Any, max_length: int, state: _WalkState, depth: int) -> Any return None is_container = isinstance(value, (Mapping, list, tuple, set, frozenset)) if not is_container: - # Leaves are charged too: a shared subtree is walked once per path. - if state.remaining_nodes <= 0: - return value - state.remaining_nodes -= 1 - if isinstance(value, str): - return truncate_string(value, max_length) - if isinstance(value, (bool, int, float, date)) or callable(value): - return value - # The encoder stringifies anything else, so bound that text. - try: - return truncate_string(str(value), max_length) - except Exception: - return UNSERIALIZABLE_VALUE + return _truncate_leaf(value, max_length, state) marker = id(value) if marker in state.ancestors: @@ -86,6 +74,22 @@ def _truncate(value: Any, max_length: int, state: _WalkState, depth: int) -> Any state.ancestors.discard(marker) +def _truncate_leaf(value: Any, max_length: int, state: _WalkState) -> Any: + # Leaves are charged too: a shared subtree is walked once per path. + if state.remaining_nodes <= 0: + return value + state.remaining_nodes -= 1 + if isinstance(value, str): + return truncate_string(value, max_length) + if isinstance(value, (bool, int, float, date)) or callable(value): + return value + # The encoder stringifies anything else, so bound that text. + try: + return truncate_string(str(value), max_length) + except Exception: + return UNSERIALIZABLE_VALUE + + def _truncate_mapping( value: Mapping, max_length: int, state: _WalkState, depth: int ) -> dict: @@ -188,6 +192,17 @@ def apply_span_limits( non_negative_count(record.dropped_attributes_count) + dropped_attributes ) + _apply_event_limits(record, max_events, max_attributes_per_event, max_length) + + if record.status is not None and record.status.message: + record.status = SpanStatus( + record.status.code, truncate_string(record.status.message, max_length) + ) + + +def _apply_event_limits( + record: SpanRecord, max_events: int, max_attributes_per_event: int, max_length: int +) -> None: kept_events: list = [] dropped_events = 0 for event in record.events: @@ -208,8 +223,3 @@ def apply_span_limits( record.dropped_events_count = ( non_negative_count(record.dropped_events_count) + dropped_events ) - - if record.status is not None and record.status.message: - record.status = SpanStatus( - record.status.code, truncate_string(record.status.message, max_length) - ) diff --git a/posthog/tracing/_otlp.py b/posthog/tracing/_otlp.py index d5e0745b3..aba6e3922 100644 --- a/posthog/tracing/_otlp.py +++ b/posthog/tracing/_otlp.py @@ -153,47 +153,59 @@ def _encode(value: Any, state: _EncodeState, depth: int) -> dict: if isinstance(value, bool): return {"boolValue": value} if isinstance(value, int): - if value > INT64_MAX or value < INT64_MIN: - log.debug( - "Attribute %s is outside the int64 range; encoding it as a string", - value, - ) - return {"stringValue": str(value)} - # int(): an IntEnum stringifies as its name. - return {"intValue": str(int(value))} + return _encode_int(value) if isinstance(value, float): - if not math.isfinite(value): - if math.isnan(value): - return {"stringValue": "NaN"} - return {"stringValue": "Infinity" if value > 0 else "-Infinity"} - return {"doubleValue": value} + return _encode_float(value) if isinstance(value, str): return {"stringValue": sanitize_string(value)} if isinstance(value, (datetime, date)): return {"stringValue": value.isoformat()} - if isinstance(value, Mapping) or isinstance(value, (list, tuple, set, frozenset)): - marker = id(value) - if marker in state.ancestors: - return {"stringValue": CIRCULAR_VALUE} - if depth >= MAX_VALUE_DEPTH: - return {"stringValue": TRUNCATED_VALUE} - state.ancestors.add(marker) - try: - if isinstance(value, Mapping): - return { - "kvlistValue": { - "values": _encode_key_value_list(value, state, depth + 1)[0] - } - } - return {"arrayValue": {"values": _encode_array(value, state, depth + 1)}} - finally: - # Siblings sharing one object are not a cycle. - state.ancestors.discard(marker) + if isinstance(value, (Mapping, list, tuple, set, frozenset)): + return _encode_container(value, state, depth) if callable(value): return {"stringValue": FUNCTION_VALUE} return {"stringValue": wire_string(value)} +def _encode_int(value: int) -> dict: + if value > INT64_MAX or value < INT64_MIN: + log.debug( + "Attribute %s is outside the int64 range; encoding it as a string", + value, + ) + return {"stringValue": str(value)} + # int(): an IntEnum stringifies as its name. + return {"intValue": str(int(value))} + + +def _encode_float(value: float) -> dict: + if not math.isfinite(value): + if math.isnan(value): + return {"stringValue": "NaN"} + return {"stringValue": "Infinity" if value > 0 else "-Infinity"} + return {"doubleValue": value} + + +def _encode_container(value: Any, state: _EncodeState, depth: int) -> dict: + marker = id(value) + if marker in state.ancestors: + return {"stringValue": CIRCULAR_VALUE} + if depth >= MAX_VALUE_DEPTH: + return {"stringValue": TRUNCATED_VALUE} + state.ancestors.add(marker) + try: + if isinstance(value, Mapping): + return { + "kvlistValue": { + "values": _encode_key_value_list(value, state, depth + 1)[0] + } + } + return {"arrayValue": {"values": _encode_array(value, state, depth + 1)}} + finally: + # Siblings sharing one object are not a cycle. + state.ancestors.discard(marker) + + def _encode_array(values: Any, state: _EncodeState, depth: int) -> list: result: list = [] count = 0 @@ -328,14 +340,21 @@ def build_otlp_span(record: SpanRecord) -> dict: dropped_events = non_negative_count(record.dropped_events_count) if dropped_events: span["droppedEventsCount"] = dropped_events - if record.status is not None and record.status.code in SPAN_STATUS_TO_OTLP: - status: dict = {"code": SPAN_STATUS_TO_OTLP[record.status.code]} - if record.status.message: - status["message"] = wire_string(record.status.message) + status = _to_otlp_status(record.status) + if status is not None: span["status"] = status return span +def _to_otlp_status(value: Optional[SpanStatus]) -> Optional[dict]: + if value is not None and value.code in SPAN_STATUS_TO_OTLP: + status: dict = {"code": SPAN_STATUS_TO_OTLP[value.code]} + if value.message: + status["message"] = wire_string(value.message) + return status + return None + + def build_traces_payload(spans: List[dict], resource: list) -> dict: """Wrap spans in the OTLP envelope: one resource, one scope, N spans per batch. diff --git a/posthog/tracing/_pipeline.py b/posthog/tracing/_pipeline.py index b09d25dff..1562773f7 100644 --- a/posthog/tracing/_pipeline.py +++ b/posthog/tracing/_pipeline.py @@ -140,10 +140,7 @@ def _start_span( if self._closed or getattr(self._client, "disabled", False): return inert_span(parent, tracestate, self._active_var) - parent = traceparent_header(parent) - if isinstance(parent, str) and not parent.strip(): - # `headers.get("traceparent", "")` with no header: the default applies. - parent = None + parent = _normalize_parent(parent) if parent is not None and not isinstance(parent, (str, RecordingSpan)): if isinstance(parent, Span): # A child of an inert handle is inert too, still forwarding any @@ -156,10 +153,26 @@ def _start_span( else: parent_context = self._resolve_parent(parent, tracestate) + span_id = self._reserve_span() + if span_id is None: + return inert_span(parent, tracestate, self._active_var) + + try: + return self._build_span( + span_id, name, kind, attributes, parent_context, start_time + ) + except Exception: + # The reservation would otherwise hold its slot until age eviction. + with self._lock: + self._live_spans.pop(span_id, None) + raise + + def _reserve_span(self) -> Optional[str]: + """Reserve a live-span slot, reporting evictions outside the lock.""" with self._lock: if self._is_closed(): # close() may have run since the check above. - return inert_span(parent, tracestate, self._active_var) + return None # Swept only at the bound, so a long span that does end is still # exported, while a process that leaked its way there recovers. aged = 0 @@ -181,17 +194,9 @@ def _start_span( "the live-span limit ({}) was reached; spans are being started " "and never ended".format(self._config.max_live_spans), ) - return inert_span(parent, tracestate, self._active_var) + return None - try: - return self._build_span( - span_id, name, kind, attributes, parent_context, start_time - ) - except Exception: - # The reservation would otherwise hold its slot until age eviction. - with self._lock: - self._live_spans.pop(span_id, None) - raise + return span_id def _build_span( self, @@ -215,7 +220,7 @@ def _build_span( start_ns=start_ns, backdated=start_ns != now_ns, on_end=self._on_span_end, - kind=kind if isinstance(kind, str) and kind else "internal", + kind=_recording_kind(kind), attributes=span_attributes, parent_span_id=parent_context.parent_span_id if parent_context else None, trace_state=parent_context.trace_state if parent_context else None, @@ -331,3 +336,15 @@ def _report_limit_drops(record: SpanRecord) -> None: record.dropped_events_count, event_attributes, ) + + +def _recording_kind(kind: Any) -> str: + return kind if isinstance(kind, str) and kind else "internal" + + +def _normalize_parent(parent: Any) -> Any: + parent = traceparent_header(parent) + if isinstance(parent, str) and not parent.strip(): + # `headers.get("traceparent", "")` with no header: the default applies. + return None + return parent diff --git a/posthog/tracing/_sanitize.py b/posthog/tracing/_sanitize.py index d87299da8..8f57770ff 100644 --- a/posthog/tracing/_sanitize.py +++ b/posthog/tracing/_sanitize.py @@ -62,16 +62,10 @@ def to_epoch_ns(value: Any) -> Optional[int]: """A ``datetime`` or epoch seconds as unix nanoseconds; ``None`` when unusable.""" if value is None or isinstance(value, bool): return None - ns: int + ns: Optional[int] if isinstance(value, datetime): - try: - if value.tzinfo is None: - value = value.astimezone() - delta = value - _EPOCH - ns = ( - delta.days * 86400 + delta.seconds - ) * 10**9 + delta.microseconds * 1000 - except Exception: + ns = _datetime_epoch_ns(value) + if ns is None: return None elif isinstance(value, int): ns = value * 10**9 @@ -82,11 +76,21 @@ def to_epoch_ns(value: Any) -> Optional[int]: ns = int(round(scaled)) else: return None - if ns < MIN_TIMESTAMP_NS or ns > MAX_TIMESTAMP_NS: + if not MIN_TIMESTAMP_NS <= ns <= MAX_TIMESTAMP_NS: return None return ns +def _datetime_epoch_ns(value: datetime) -> Optional[int]: + try: + if value.tzinfo is None: + value = value.astimezone() + delta = value - _EPOCH + return (delta.days * 86400 + delta.seconds) * 10**9 + delta.microseconds * 1000 + except Exception: + return None + + def resolve_start_ns(value: Any, now_ns: int) -> int: """A caller-supplied start time, or now; warns when the server will clamp it.""" supplied = to_epoch_ns(value) diff --git a/posthog/tracing/_span.py b/posthog/tracing/_span.py index f78ae464f..4dd0b3a1e 100644 --- a/posthog/tracing/_span.py +++ b/posthog/tracing/_span.py @@ -288,9 +288,7 @@ def _write_attribute(self, key: str, value: Any) -> None: return if value is None: # None removes the key, freeing its slot. - if key in self._attributes and key not in self._auto_keys: - self._user_attribute_count -= 1 - self._attributes.pop(key, None) + self._remove_attribute_locked(key) return # Checked before the value is walked, which is the costly part. if key not in self._auto_keys and key not in self._attributes: @@ -305,6 +303,11 @@ def _write_attribute(self, key: str, value: Any) -> None: if not self._ended: self._attributes[key] = bounded + def _remove_attribute_locked(self, key: str) -> None: + if key in self._attributes and key not in self._auto_keys: + self._user_attribute_count -= 1 + self._attributes.pop(key, None) + def set_attribute(self, key: str, value: Any) -> "Span": if self._mutable("set_attribute"): key_str = attribute_key(key) diff --git a/posthog/tracing/_traceparent.py b/posthog/tracing/_traceparent.py index 974527b74..e8ee9072e 100644 --- a/posthog/tracing/_traceparent.py +++ b/posthog/tracing/_traceparent.py @@ -50,6 +50,12 @@ def _header_text(value: object) -> Optional[str]: return value if isinstance(value, str) else None +def _valid_version_fields(version: str, trailing: Optional[str]) -> bool: + if version == "ff" or (version == "00" and trailing): + return False + return not (trailing and _NON_PRINTABLE_ASCII_RE.search(trailing)) + + def _match_traceparent(value: object) -> Optional[_TraceparentFields]: value = _header_text(value) if value is None: @@ -62,9 +68,7 @@ def _match_traceparent(value: object) -> Optional[_TraceparentFields]: if match is None: return None version, trace_id, span_id, flags, trailing = match.group(1, 2, 3, 4, 5) - if version == "ff" or (version == "00" and trailing): - return None - if trailing and _NON_PRINTABLE_ASCII_RE.search(trailing): + if not _valid_version_fields(version, trailing): return None if trace_id == INVALID_TRACE_ID or span_id == INVALID_SPAN_ID: return None diff --git a/posthog/tracing/_transport.py b/posthog/tracing/_transport.py index a261a0e41..9474ce693 100644 --- a/posthog/tracing/_transport.py +++ b/posthog/tracing/_transport.py @@ -66,23 +66,30 @@ def parse_retry_after(value: Any, now: Optional[datetime] = None) -> Optional[fl raw = value.strip() if re.match(r"^\d+\s*,", raw): raw = raw.split(",", 1)[0].strip() + seconds: Optional[float] if _DELTA_SECONDS_RE.match(raw): seconds = float(raw) elif _NUMERIC_RE.match(raw): return None else: - try: - when = parsedate_to_datetime(raw) - except (TypeError, ValueError, IndexError): + seconds = _retry_after_date_seconds(raw, now) + if seconds is None: return None - if when.tzinfo is None: - when = when.replace(tzinfo=timezone.utc) - seconds = (when - (now or datetime.now(timezone.utc))).total_seconds() if not math.isfinite(seconds) or seconds <= 0: return None return seconds +def _retry_after_date_seconds(raw: str, now: Optional[datetime]) -> Optional[float]: + try: + when = parsedate_to_datetime(raw) + except (TypeError, ValueError, IndexError): + return None + if when.tzinfo is None: + when = when.replace(tzinfo=timezone.utc) + return (when - (now or datetime.now(timezone.utc))).total_seconds() + + def send_traces_batch(client: Any, payload: dict) -> SendOutcome: """POST one OTLP batch with bearer auth and gzip, classifying the response. diff --git a/posthog/types.py b/posthog/types.py index 229b25a16..625b5dc5a 100644 --- a/posthog/types.py +++ b/posthog/types.py @@ -358,6 +358,24 @@ def _legacy_rendering(value: Any) -> tuple[bool, Optional[str], Optional[str]]: return True, None, json.dumps(value, separators=(",", ":"), ensure_ascii=False) +def _parse_typed_reason(value: Any) -> Optional[FlagReason]: + reason = None + raw_reason = _read_typed(value, "reason", dict) + if raw_reason is not None: + reason = FlagReason( + code=_read_typed(raw_reason.get("code"), "reason.code", str) or "", + condition_index=_read_int( + raw_reason.get("condition_index"), "reason.condition_index" + ), + description=_read_typed( + raw_reason.get("description"), "reason.description", str + ) + or "", + ) + + return reason + + def _parse_typed_record(cls: Type[_F], key: str, resp: Any) -> _F: """Parse a ``/flags?v=4`` record, which carries a typed ``value``. @@ -372,19 +390,7 @@ def _parse_typed_record(cls: Type[_F], key: str, resp: Any) -> _F: value = _read_value(resp.get("value")) failed = _read_typed(resp.get("failed"), "failed", bool) is True - reason = None - raw_reason = _read_typed(resp.get("reason"), "reason", dict) - if raw_reason is not None: - reason = FlagReason( - code=_read_typed(raw_reason.get("code"), "reason.code", str) or "", - condition_index=_read_int( - raw_reason.get("condition_index"), "reason.condition_index" - ), - description=_read_typed( - raw_reason.get("description"), "reason.description", str - ) - or "", - ) + reason = _parse_typed_reason(resp.get("reason")) if failed: # A failed record has no value, whatever it carries. diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index b9d617def..d0037bb5f 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -813,6 +813,7 @@ attribute posthog.capture_v1.CaptureV1Error.request_id = request_id attribute posthog.capture_v1.CaptureV1Error.retry_exhausted = retry_exhausted or [] attribute posthog.client.Client.api_key = (project_api_key or '').strip() attribute posthog.client.Client.app_host = app_host +attribute posthog.client.Client.before_send = before_send attribute posthog.client.Client.capture_compression = _resolve_capture_compression(capture_compression, gzip_fallback=gzip) attribute posthog.client.Client.capture_exception_code_variables = capture_exception_code_variables attribute posthog.client.Client.capture_mode = _resolve_capture_mode(capture_mode) From 3511570b4d19f84589b59dcd677df0c7b0d05cfe Mon Sep 17 00:00:00 2001 From: Manoel Aranda Neto <5731772+marandaneto@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:19:24 +0700 Subject: [PATCH 18/33] fix: treat failed feature flag records as unevaluated (#1238) * fix: treat failed feature flag records as unevaluated * test: expect no result for failed flag attribution * test: update released comparisons for failed flag records * fix: use qualified PyPI package in flag changeset * fix(flags): preserve unresolved reasons for failed fallback * fix(flags): clarify failed-record classification and regression coverage * fix(flags): preserve failed snapshot diagnostics * ci: upgrade SDK compliance harness to 1.31.1 --- .github/workflows/sdk-compliance.yml | 8 +- .sampo/changesets/fix-failed-flag-records.md | 5 + .../openfeature-failed-flag-defaults.md | 5 + posthog/client.py | 72 +++-- posthog/feature_flag_evaluations.py | 61 ++-- posthog/test/test_evaluate_flags.py | 80 ++++- posthog/test/test_experiment_exposure.py | 23 +- posthog/test/test_failed_flag_records.py | 287 ++++++++++++++++++ posthog/test/test_flags_released_behaviour.py | 42 ++- posthog/test/test_flags_v4_response.py | 11 +- posthog/types.py | 17 +- references/public_api_snapshot.txt | 1 + sdk_compliance_adapter/CONTRIBUTING.md | 4 +- sdk_compliance_adapter/docker-compose.yml | 2 +- 14 files changed, 544 insertions(+), 74 deletions(-) create mode 100644 .sampo/changesets/fix-failed-flag-records.md create mode 100644 .sampo/changesets/openfeature-failed-flag-defaults.md create mode 100644 posthog/test/test_failed_flag_records.py diff --git a/.github/workflows/sdk-compliance.yml b/.github/workflows/sdk-compliance.yml index 7e72514a8..ea14f9b5e 100644 --- a/.github/workflows/sdk-compliance.yml +++ b/.github/workflows/sdk-compliance.yml @@ -29,20 +29,20 @@ jobs: compliance: name: PostHog SDK compliance tests (capture v0) - uses: PostHog/posthog-sdk-test-harness/.github/workflows/test-sdk-action.yml@75fb00092c6045daef60c30acc10ac83afefbfe9 # 1.27.0 + uses: PostHog/posthog-sdk-test-harness/.github/workflows/test-sdk-action.yml@003d4162421193b458bbaa93fbb7bb0d0104bc3b # 1.31.1 with: adapter-dockerfile: "sdk_compliance_adapter/Dockerfile" adapter-context: "." - test-harness-version: "1.28.0" + test-harness-version: "1.31.1" continue-on-error: false report-name: "sdk-compliance-report-v0" compliance-v1: name: PostHog SDK compliance tests (capture v1) - uses: PostHog/posthog-sdk-test-harness/.github/workflows/test-sdk-action.yml@75fb00092c6045daef60c30acc10ac83afefbfe9 # 1.27.0 + uses: PostHog/posthog-sdk-test-harness/.github/workflows/test-sdk-action.yml@003d4162421193b458bbaa93fbb7bb0d0104bc3b # 1.31.1 with: adapter-dockerfile: "sdk_compliance_adapter/Dockerfile.v1" adapter-context: "." - test-harness-version: "1.28.0" + test-harness-version: "1.31.1" continue-on-error: false report-name: "sdk-compliance-report-v1" diff --git a/.sampo/changesets/fix-failed-flag-records.md b/.sampo/changesets/fix-failed-flag-records.md new file mode 100644 index 000000000..e52498056 --- /dev/null +++ b/.sampo/changesets/fix-failed-flag-records.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +Treat server-marked failed feature flag records as unevaluated: direct result, value, enabled and payload getters return None rather than a disabled False result or placeholder payload. Snapshot value and payload reads return None, enablement honors the caller's default, and failed keys are omitted from enumeration and capture enrichment. Bulk value and payload maps omit failed remote records while preserving successful locally computed values and payloads for those keys. Preserve selected or accessed failure diagnostics through snapshot filters and report local_evaluation_inconclusive alongside evaluation_failed after an unresolved failed fallback; healthy False and malformed-record compatibility are unchanged. diff --git a/.sampo/changesets/openfeature-failed-flag-defaults.md b/.sampo/changesets/openfeature-failed-flag-defaults.md new file mode 100644 index 000000000..f9f5535b8 --- /dev/null +++ b/.sampo/changesets/openfeature-failed-flag-defaults.md @@ -0,0 +1,5 @@ +--- +pypi/openfeature-provider-posthog: patch +--- + +Document failed-record default handling with the updated PostHog SDK: a server-marked failed flag supplies no result, so the provider's existing FlagNotFoundError mapping lets OpenFeature return the caller's default instead of treating the failed record as a healthy disabled flag. This behavior requires upgrading the installed posthog dependency; the provider's compatible dependency range is unchanged and this patch intent does not force that upgrade. diff --git a/posthog/client.py b/posthog/client.py index 73181a82c..f4b6591fc 100644 --- a/posthog/client.py +++ b/posthog/client.py @@ -666,18 +666,19 @@ def _capture_flag_events( Every read that sends flag events comes here, on both clients: the single-flag getters and the reads of an ``evaluate_flags()`` snapshot. Both events are built - from ``details``, the parsed ``/flags`` record that supplied the value, and the - call's ``properties``; the flag is never evaluated again. + from ``details``, the parsed ``/flags`` record supplying the value or failure + diagnostics, and the call's ``properties``; the flag is never evaluated again. ``$feature_flag_called`` is sent if the (distinct_id, flag, response, groups) tuple hasn't already been reported on this client. Group context is included so that group-scoped flags fire a separate event for each group a user is evaluated - under. A config version 2 record that supplied the reported value + under. A config version 2 record supplying the value or failed-record diagnostics (``value_from_details``) adds its attribution to the event and to that tuple, so equal-valued A/A arms, successive experiments of one flag, and holdouts are each reported. Its reason code replaces the human-readable ``$feature_flag_reason``. - A config version 1 event and tuple are unchanged, and so are those of a read - whose value the record did not supply. + A failed record keeps its config version and reason code, but no rule tuple or + experiment exposure. Config version 1 events and reads reporting a successful + caller override or stale cached value keep their existing attribution. ``has_experiment`` is the server-reported signal for whether the flag is linked to an experiment (``None`` when the server did not report it). When the @@ -710,9 +711,8 @@ def _capture_flag_events( groups_key = ( tuple(sorted((str(k), str(v)) for k, v in groups.items())) if groups else () ) - # Only a record that supplied the reported value attributes it. A caller's - # match_value and a stale cached value are reported as before, with no config - # version 2 properties, even when a config version 2 record came with them. + # A failed record still reports its config version and reason code. A successful + # caller override or stale cached value has no config version 2 attribution. attribution = _rule_attribution(details) if value_from_details else None # What both config version 2 events report about the read itself. Each event # pins it, so a super property cannot make the pair disagree. @@ -5030,10 +5030,10 @@ def _get_remote_flag_result( self.log.debug( f"Successfully computed flag remotely: #{key} -> #{read.result}" ) - # A payload lookup for a caller's match_value reports that value, not - # the record's. A failure above falls back to a stale cached value. - read.value_from_details = ( - read.details is not None and override_match_value is None + # A successful payload override reports the caller's value. A failed + # record keeps its config version and reason code, never the override. + read.value_from_details = read.details is not None and ( + override_match_value is None or read.details._server_marked_failed ) except QuotaLimitError as e: self.log.warning(f"[FEATURE FLAGS] Quota limit exceeded: {e}") @@ -5096,6 +5096,8 @@ def _remote_flag_result_error(errors_while_computing, flag_details): errors.append(FeatureFlagError.ERRORS_WHILE_COMPUTING) if flag_details is None: errors.append(FeatureFlagError.FLAG_MISSING) + elif flag_details._server_marked_failed: + errors.append(FeatureFlagError.EVALUATION_FAILED) return ",".join(errors) if errors else None def _capture_flag_read_result( @@ -5190,7 +5192,9 @@ def get_feature_flag_result( device_id: The device ID for this request. Returns: - Optional[FeatureFlagResult]: The feature flag result or None if disabled/not found. + Optional[FeatureFlagResult]: The evaluated result, including a healthy + disabled flag, or None when no result is available (for example, + a missing flag or a server-marked failure without a successful fallback). """ return self._get_feature_flag_result( key, @@ -5439,9 +5443,8 @@ def _capture_feature_flag_called( local_flag_id: Optional[int] = None, local_flag_version: Optional[int] = None, *, - # Keyword-only, and false by default: a caller that does not say the record - # supplied the value reports no config version 2 attribution and sends no - # $experiment_exposure. + # Opt in when the record supplies the value or failed-record diagnostics. + # Failed records keep config version and reason code, but send no exposure. value_from_details: bool = False, ): properties: dict[str, Any] = { @@ -5511,9 +5514,9 @@ def _capture_feature_flag_called_if_needed( Shared by the single-flag evaluation path and the reads of a ``FeatureFlagEvaluations`` snapshot, so every read reports and dedupes identically. ``details`` is the parsed ``/flags`` record of the read, or - ``None`` for a locally evaluated flag. ``value_from_details`` says whether that - record supplied the reported value; only then does the read report config - version 2 attribution or send an exposure. + ``None`` for a locally evaluated flag. ``value_from_details`` includes a + failed record supplying config-version and reason-code diagnostics despite + having no value. Only a successful experiment split sends an exposure. """ _capture_flag_events( self.capture, @@ -5725,7 +5728,32 @@ def get_all_flags_and_payloads( flag_keys_to_evaluate=flag_keys_to_evaluate, device_id=device_id, ) - response = to_flags_and_payloads(decide_response) + remote_response = to_flags_and_payloads(decide_response) + # A key the server marked failed keeps its locally computed value + # and payload. Successful remote records replace local results. + failed_keys = { + key + for key, detail in decide_response.get("flags", {}).items() + if detail._server_marked_failed + } + response = { + "featureFlags": { + **{ + k: v + for k, v in (response["featureFlags"] or {}).items() + if k in failed_keys + }, + **(remote_response["featureFlags"] or {}), + }, + "featureFlagPayloads": { + **{ + k: v + for k, v in (response["featureFlagPayloads"] or {}).items() + if k in failed_keys + }, + **(remote_response["featureFlagPayloads"] or {}), + }, + } except Exception as e: self.log.exception( f"[FEATURE FLAGS] Unable to get feature flags and payloads: {e}" @@ -5930,6 +5958,10 @@ def _evaluate_flags_with_context( key: reason for key, reason in unresolved.items() if key not in result.records + or ( + isinstance(record := result.records[key], _RemoteFlagRecord) + and record.details._server_marked_failed + ) }, ) diff --git a/posthog/feature_flag_evaluations.py b/posthog/feature_flag_evaluations.py index eb4600174..870680c6f 100644 --- a/posthog/feature_flag_evaluations.py +++ b/posthog/feature_flag_evaluations.py @@ -10,6 +10,7 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Union from .types import FeatureFlag as _FeatureFlag +from .types import FeatureFlagError as _FeatureFlagError from .types import FlagMetadata as _FlagMetadata from .types import FlagValue, UnresolvedFlagReason, _parse_flag_payload @@ -152,7 +153,13 @@ def __init__( """Internal — instances are created by the SDK via ``Client.evaluate_flags()``.""" self._host = host self._distinct_id = distinct_id - self._flags = flags + self._failed_flags = { + key: flag + for key, flag in flags.items() + if isinstance(flag, _RemoteFlagRecord) + and flag.details._server_marked_failed + } + self._flags = {k: v for k, v in flags.items() if k not in self._failed_flags} self._groups: Dict[str, Union[str, int]] = dict(groups or {}) self._disable_geoip = disable_geoip self._request_id = request_id @@ -181,9 +188,10 @@ def is_enabled( Args: key: The feature flag key. default_value: Returned when the flag has no value in this evaluation — - the key was not part of the evaluated set, or the evaluation itself - came back empty (failed ``/flags`` request, quota limit, or no - resolvable ``distinct_id``). Defaults to ``False``. + the key was not part of the evaluated set, the server marked its + record failed, or the evaluation itself came back empty (failed + ``/flags`` request, quota limit, or no resolvable ``distinct_id``). + Defaults to ``False``. send_feature_flag_events: Whether this read sends ``$feature_flag_called``. When ``False``, no event is sent and the dedupe cache is left alone, but the key still counts as accessed for :meth:`only_accessed`. @@ -202,7 +210,8 @@ def get_flag( Returns the variant string for multivariate flags, ``True`` for enabled flags without a variant, ``False`` for disabled flags, and ``None`` for flags that - were not returned by the evaluation. + were not returned or whose remote record was marked failed by the server. + An unreadable remote record retains its disabled (``False``) result. Pass ``send_feature_flag_events=False`` to skip the event for this read, as with :meth:`is_enabled`. @@ -229,13 +238,23 @@ def only_accessed(self) -> "FeatureFlagEvaluations": Order-dependent: if nothing has been accessed yet, the returned snapshot is empty. The method honors its name — pre-access if you want a populated result. + Accessed failures retain private diagnostics, not values or enrichment. """ filtered = {k: self._flags[k] for k in self._accessed if k in self._flags} + filtered.update( + { + k: self._failed_flags[k] + for k in self._accessed + if k in self._failed_flags + } + ) return self._clone_with(filtered) def only(self, keys: List[str]) -> "FeatureFlagEvaluations": """Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. + Selected failures retain private diagnostics but remain absent from values, + keys and enrichment; their existing missing-value warning is unchanged. """ filtered: Dict[str, _EvaluatedFlagRecord] = {} missing: List[str] = [] @@ -250,6 +269,9 @@ def only(self, keys: List[str]) -> "FeatureFlagEvaluations": "FeatureFlagEvaluations.only() was called with flag keys that are not in the " f"evaluation set and will be dropped: {', '.join(missing)}" ) + filtered.update( + {k: self._failed_flags[k] for k in keys if k in self._failed_flags} + ) return self._clone_with(filtered) @property @@ -265,8 +287,9 @@ def unresolved_flags(self) -> Mapping[str, UnresolvedFlagReason]: A flag is listed when it has a loaded local definition, was in the requested scope, was inconclusive locally, and no remote value filled the gap. Listed flags are not part of :attr:`keys`, and reading one reports the - ``local_evaluation_inconclusive`` error instead of ``flag_missing``. Reading - this mapping does not count as an access and does not fire any event. + ``local_evaluation_inconclusive`` error instead of ``flag_missing``. + A server-marked failed fallback additionally reports ``evaluation_failed``. + Reading this mapping does not count as an access and does not fire any event. Snapshots returned by :meth:`only` and :meth:`only_accessed`, and by ``AsyncClient.evaluate_flags()``, which evaluates only remotely, carry no entries. @@ -337,8 +360,8 @@ def _record_access(self, key: str, send_feature_flag_events: bool) -> None: if not self._distinct_id: return - flag = self._flags.get(key) - response = _flag_response(flag) + flag = self._flags.get(key) or self._failed_flags.get(key) + response = None if key in self._failed_flags else _flag_response(flag) properties = self._get_flag_called_properties(key, flag, response) self._host.capture_flag_called_event_if_needed( @@ -350,8 +373,8 @@ def _record_access(self, key: str, send_feature_flag_events: bool) -> None: properties=properties, has_experiment=flag.has_experiment if flag else None, minimal_flag_called_events=self._minimal_flag_called_events, - # The record that supplied the value. A remotely evaluated experiment - # split also sends $experiment_exposure, whatever this read returned. + # A failed record still supplies config-version and reason-code diagnostics. + # Only a successful experiment split also sends $experiment_exposure. details=flag.details if isinstance(flag, _RemoteFlagRecord) else None, value_from_details=True, ) @@ -381,19 +404,19 @@ def _get_flag_called_properties(self, key, flag, response) -> Dict[str, Any]: def _get_access_errors(self, key, flag) -> List[str]: # Build the comma-joined `$feature_flag_error` matching the single-flag path's # granularity: response-level errors (errors-while-computing, quota-limited) are - # combined with per-flag errors (flag-missing or local-evaluation-inconclusive) - # so consumers can filter by type. + # combined with per-flag errors. A failed remote fallback must not hide the + # original snapshot's local-inconclusive diagnostic. errors: List[str] = [] if self._errors_while_computing: errors.append("errors_while_computing_flags") if self._quota_limited: errors.append("quota_limited") - if flag is None: - errors.append( - "local_evaluation_inconclusive" - if key in self._unresolved_flags - else "flag_missing" - ) + if key in self._failed_flags: + errors.append(_FeatureFlagError.EVALUATION_FAILED) + if key in self._unresolved_flags: + errors.append(_FeatureFlagError.LOCAL_EVALUATION_INCONCLUSIVE) + elif flag is None: + errors.append("flag_missing") return errors diff --git a/posthog/test/test_evaluate_flags.py b/posthog/test/test_evaluate_flags.py index bb76ed85a..2546c08f9 100644 --- a/posthog/test/test_evaluate_flags.py +++ b/posthog/test/test_evaluate_flags.py @@ -885,19 +885,93 @@ def test_dependency_resolved_locally_picks_its_condition(self, patch_flags): self.assertEqual(flags.get_flag("target"), "a") patch_flags.assert_not_called() + @parameterized.expand([(True,), (False,)]) @mock.patch("posthog.client.flags") - def test_flag_resolved_by_remote_fallback_is_not_unresolved(self, patch_flags): + def test_flag_resolved_by_remote_fallback_is_not_unresolved( + self, enabled, patch_flags + ): patch_flags.return_value = { - "flags": {"checkout": {"enabled": True, "variant": None}} + "flags": {"checkout": {"enabled": enabled, "variant": None}} } flags = self.client.evaluate_flags("user-123") - self.assertIs(flags.get_flag("checkout"), True) + self.assertIs(flags.get_flag("checkout"), enabled) self.assertEqual(sorted(flags.keys), ["beta-ui", "checkout"]) self.assertEqual(dict(flags.unresolved_flags), {}) patch_flags.assert_called_once() + @mock.patch("posthog.client.flags") + def test_malformed_remote_fallback_is_not_unresolved(self, patch_flags): + patch_flags.return_value = { + "flags": { + "checkout": { + "enabled": True, + "metadata": {"version": True}, + } + } + } + + flags = self.client.evaluate_flags("user-123") + + self.assertIs(flags.get_flag("checkout", send_feature_flag_events=False), False) + self.assertEqual(sorted(flags.keys), ["beta-ui", "checkout"]) + self.assertEqual(dict(flags.unresolved_flags), {}) + patch_flags.assert_called_once() + + @parameterized.expand([(None,), (False,), (True,)]) + @mock.patch("posthog.client.flags") + @mock.patch.object(Client, "capture") + def test_failed_remote_fallback_preserves_unresolved_reason( + self, error_bit, patch_capture, patch_flags + ): + response = { + "flags": { + key: { + "enabled": False, + "failed": True, + "metadata": {"payload": '"placeholder"'}, + } + for key in ("checkout", "remote-only") + } + } + if error_bit is not None: + response["errorsWhileComputingFlags"] = error_bit + patch_flags.return_value = response + + flags = self.client.evaluate_flags("user-123") + + self.assertEqual( + dict(flags.unresolved_flags), + {"checkout": UnresolvedFlagReason.EXPERIENCE_CONTINUITY}, + ) + self.assertEqual(flags.keys, ["beta-ui"]) + self.assertIsNone(flags.get_flag("checkout", send_feature_flag_events=False)) + self.assertTrue( + flags.is_enabled("checkout", True, send_feature_flag_events=False) + ) + self.assertIsNone(flags.get_flag_payload("checkout")) + self.assertNotIn("$feature/checkout", flags._get_event_properties()) + self.assertEqual(dict(flags.only(["checkout"]).unresolved_flags), {}) + self.assertEqual(dict(flags.only_accessed().unresolved_flags), {}) + patch_capture.assert_not_called() + flags.is_enabled("checkout", True) + flags.get_flag("checkout") + flags.get_flag("remote-only") + properties = _flag_called_properties(patch_capture) + expected_errors = "evaluation_failed,local_evaluation_inconclusive" + remote_errors = "evaluation_failed" + if error_bit: + expected_errors = "errors_while_computing_flags," + expected_errors + remote_errors = "errors_while_computing_flags," + remote_errors + self.assertEqual(properties["checkout"]["$feature_flag_error"], expected_errors) + self.assertIsNone(properties["checkout"]["$feature_flag_response"]) + self.assertEqual( + properties["remote-only"]["$feature_flag_error"], remote_errors + ) + self.assertEqual(patch_capture.call_count, 2) + patch_flags.assert_called_once() + @parameterized.expand( [ ( diff --git a/posthog/test/test_experiment_exposure.py b/posthog/test/test_experiment_exposure.py index c12152833..062f90e46 100644 --- a/posthog/test/test_experiment_exposure.py +++ b/posthog/test/test_experiment_exposure.py @@ -517,18 +517,28 @@ def _attribution_response(source: str) -> Dict[str, Any]: "source, expected", ATTRIBUTION_CASES, ids=[c[0] for c in ATTRIBUTION_CASES] ) def test_flag_called_attribution_follows_the_record(source, expected, path): - events = _read_events(path, _attribution_response(source), key="garden-layout") + response = _attribution_response(source) + failed = response["flags"]["garden-layout"].get("failed") is True + events = _read_events(path, response, key="garden-layout") [called] = _named(events, FLAG_CALLED, "garden-layout") assert _attribution(called.properties) == expected - FLAG_CALLED_SCHEMA.validate(_projection(FLAG_CALLED_SCHEMA, called.properties)) + if failed: + # The vendored schema rejects the null $feature_flag_response a failed record reports. + assert called.properties["$feature_flag_response"] is None + assert set(called.properties["$feature_flag_error"].split(",")) == { + "evaluation_failed", + "errors_while_computing_flags", + } + else: + FLAG_CALLED_SCHEMA.validate(_projection(FLAG_CALLED_SCHEMA, called.properties)) exposures = _named(events, EXPOSURE, "garden-layout") assert len(exposures) == (1 if "$feature_flag_variant_key" in expected else 0) # A record whose reason names no rule, or that failed, reports no rule even when it -# carries one. Neither sends an exposure. The last element says whether the record is -# a valid server outcome, which the contract's event schema then accepts. +# carries one. Neither sends an exposure. The last element says whether a successful +# record is a valid server outcome, which the contract's event schema then accepts. STRAY_RULE_CASES = [ ("no_rule_match", {}, True), ("missing_group_key", {}, True), @@ -569,7 +579,10 @@ def test_rule_fields_are_sent_only_for_reasons_that_name_a_rule( "$feature_flag_reason_code": code, } assert _named(events, EXPOSURE) == [] - if valid_outcome: + if fields.get("failed") is True: + assert called.properties["$feature_flag_response"] is None + assert called.properties["$feature_flag_error"] == "evaluation_failed" + elif valid_outcome: FLAG_CALLED_SCHEMA.validate(_projection(FLAG_CALLED_SCHEMA, called.properties)) diff --git a/posthog/test/test_failed_flag_records.py b/posthog/test/test_failed_flag_records.py new file mode 100644 index 000000000..c6ec36582 --- /dev/null +++ b/posthog/test/test_failed_flag_records.py @@ -0,0 +1,287 @@ +"""Spec 211: server failed records supply diagnostics, not evaluated values.""" + +import copy +from unittest import mock + +import pytest + +from posthog import AsyncPosthog +from posthog.client import Client +from posthog.types import normalize_flags_response + + +@pytest.fixture +def client(): + client = Client("project-key", send=False) + yield client + client.shutdown() + + +def response(shape, error_bit, failed_value="remote"): + records = {} + for key, value, failed in [("failed", failed_value, True), ("off", False, False)]: + record = { + "key": key, + "failed": failed, + "reason": {"code": "dependency_error" if failed else "flag_disabled"}, + "metadata": {"id": 1, "version": 2, "payload": '{"copy":"remote"}'}, + } + if shape == "v4": + record["value"] = value + record["metadata"]["config_version"] = 2 + else: + record.update( + enabled=bool(value), variant=value if isinstance(value, str) else None + ) + records[key] = record + result = { + "flags": records, + "featureFlags": {"failed": "mirror"}, + "featureFlagPayloads": {"failed": '"mirror"'}, + } + if error_bit is not None: + result["errorsWhileComputingFlags"] = error_bit + return result + + +@pytest.mark.parametrize("shape", ["v2", "v4"]) +@pytest.mark.parametrize("error_bit", [None, False, True]) +@pytest.mark.parametrize("failed_value", [False, "remote"]) +@pytest.mark.parametrize("local_inconclusive", [False, True]) +def test_failed_direct_results_and_events( + client, shape, error_bit, failed_value, local_inconclusive +): + if local_inconclusive: + client.feature_flags = [ + { + "key": "failed", + "active": True, + "ensure_experience_continuity": True, + "filters": {"groups": []}, + } + ] + with ( + mock.patch( + "posthog.client.flags", + side_effect=lambda *args, **kwargs: copy.deepcopy( + response(shape, error_bit, failed_value) + ), + ), + mock.patch.object(client, "capture", return_value=(True, {})) as capture, + ): + assert ( + client.get_feature_flag_result( + "failed", "user", send_feature_flag_events=False + ) + is None + ) + capture.assert_not_called() + assert client.get_feature_flag_result("failed", "user") is None + assert client.get_feature_flag("failed", "user") is None + assert client.feature_enabled("failed", "user") is None + assert ( + client.get_feature_flag_payload( + "failed", "user", match_value=True, send_feature_flag_events=True + ) + is None + ) + assert capture.call_count == 1 + props = capture.call_args.kwargs["properties"] + assert props["$feature_flag_response"] is None + assert "evaluation_failed" in props["$feature_flag_error"].split(",") + assert "flag_missing" not in props["$feature_flag_error"] + assert ("errors_while_computing_flags" in props["$feature_flag_error"]) is bool( + error_bit + ) + if shape == "v4": + assert props["$feature_flag_config_version"] == 2 + assert props["$feature_flag_reason_code"] == "dependency_error" + assert "$feature_flag_payload" not in props + assert client.get_feature_flag_result("off", "user").enabled is False + assert "evaluation_failed" not in capture.call_args.kwargs["properties"].get( + "$feature_flag_error", "" + ) + combined = client.get_all_flags_and_payloads("user") + assert combined["featureFlags"] == {"off": False} + assert "failed" not in combined["featureFlagPayloads"] + + +@pytest.mark.parametrize("shape", ["v2", "v4"]) +@pytest.mark.parametrize("error_bit", [None, False, True]) +def test_failed_snapshot_defaults_diagnostics_and_enrichment(client, shape, error_bit): + with ( + mock.patch("posthog.client.flags", return_value=response(shape, error_bit)), + mock.patch.object(client, "capture", return_value=(True, {})) as capture, + ): + snapshot = client.evaluate_flags("user") + assert ( + snapshot.is_enabled("failed", True, send_feature_flag_events=False) is True + ) + capture.assert_not_called() + assert snapshot.get_flag("failed") is None + assert snapshot.get_flag_payload("failed") is None + props = capture.call_args.kwargs["properties"] + assert props["$feature_flag_response"] is None + assert "evaluation_failed" in props["$feature_flag_error"] + assert "flag_missing" not in props["$feature_flag_error"] + assert ("errors_while_computing_flags" in props["$feature_flag_error"]) is bool( + error_bit + ) + assert snapshot.is_enabled("off", True) is False + assert snapshot.keys == ["off"] + assert snapshot._get_event_properties() == {"$feature/off": False} + + +@pytest.mark.parametrize("shape", ["v2", "v4"]) +@pytest.mark.parametrize("error_bit", [None, False, True]) +@pytest.mark.parametrize("filter_method", ["only", "only_accessed"]) +def test_filtered_snapshot_preserves_selected_failure_diagnostics( + client, shape, error_bit, filter_method +): + raw = response(shape, error_bit) + raw["requestId"] = "evaluation-request" + raw["evaluatedAt"] = 12345 + raw["flags"]["failed"]["reason"]["description"] = "Evaluation failed" + raw["flags"]["failed"]["metadata"]["has_experiment"] = True + raw["flags"]["other-failed"] = copy.deepcopy(raw["flags"]["failed"]) + raw["flags"]["other-failed"]["key"] = "other-failed" + with ( + mock.patch("posthog.client.flags", return_value=raw) as remote, + mock.patch.object(client, "_enqueue", return_value=(True, {})) as enqueue, + mock.patch.object(client.log, "warning") as warning, + ): + snapshot = client.evaluate_flags("user", groups={"company": "acme"}) + assert snapshot.get_flag_payload("other-failed") is None + if filter_method == "only": + filtered = snapshot.only(["failed", "off", "missing"]) + warning.assert_called_once() + assert warning.call_args.args[0].endswith("failed, missing") + else: + assert snapshot.only_accessed().keys == [] + snapshot.get_flag("failed", send_feature_flag_events=False) + snapshot.is_enabled("off", send_feature_flag_events=False) + filtered = snapshot.only_accessed() + warning.assert_not_called() + enqueue.assert_not_called() + assert filtered.keys == ["off"] + assert dict(filtered.unresolved_flags) == {} + assert filtered.get_flag_payload("failed") is None + assert ( + filtered.is_enabled("failed", True, send_feature_flag_events=False) is True + ) + enqueue.assert_not_called() + + assert filtered.get_flag("failed") is None + assert filtered.is_enabled("failed") is False + assert enqueue.call_count == 1 + called = enqueue.call_args.args[0] + assert called["event"] == "$feature_flag_called" + props = called["properties"] + assert props["$feature_flag_response"] is None + assert props["$feature_flag_error"] == ( + "errors_while_computing_flags,evaluation_failed" + if error_bit + else "evaluation_failed" + ) + assert props["$feature_flag_id"] == 1 + assert props["$feature_flag_version"] == 2 + assert props["$feature_flag_request_id"] == "evaluation-request" + assert props["$feature_flag_evaluated_at"] == 12345 + assert props["$groups"] == {"company": "acme"} + assert "$feature_flag_payload" not in props + if shape == "v4": + assert props["$feature_flag_config_version"] == 2 + assert props["$feature_flag_reason_code"] == "dependency_error" + else: + assert props["$feature_flag_reason"] == "Evaluation failed" + + client.capture("filtered-snapshot", distinct_id="user", flags=filtered) + enriched = enqueue.call_args.args[0] + assert enriched["event"] == "filtered-snapshot" + assert enriched["properties"]["$feature/off"] is False + assert "$feature/failed" not in enriched["properties"] + assert "$feature/other-failed" not in enriched["properties"] + assert enqueue.call_count == 2 + + assert filtered.get_flag("other-failed") is None + missing = enqueue.call_args.args[0]["properties"] + assert missing["$feature_flag_error"] == ( + "errors_while_computing_flags,flag_missing" if error_bit else "flag_missing" + ) + assert "$feature_flag_id" not in missing + assert "$feature_flag_reason_code" not in missing + assert enqueue.call_count == 3 + remote.assert_called_once() + + +@pytest.mark.parametrize("shape", ["v2", "v4"]) +@pytest.mark.parametrize("error_bit", [None, False, True]) +def test_failed_fallback_preserves_only_successful_local_pairs( + client, shape, error_bit +): + local = { + "featureFlags": { + "on": True, + "off": False, + "variant": "blue", + "success": True, + "local-only": True, + "malformed": True, + }, + "featureFlagPayloads": { + k: '{"copy":"local"}' + for k in ["on", "off", "variant", "success", "local-only", "malformed"] + }, + } + remote = response(shape, error_bit) + for key in ["on", "off", "variant"]: + remote["flags"][key] = copy.deepcopy(remote["flags"]["failed"]) + remote["flags"][key]["key"] = key + remote["flags"]["malformed"] = copy.deepcopy(remote["flags"]["failed"]) + remote["flags"]["malformed"]["key"] = "malformed" + remote["flags"]["malformed"]["metadata"]["version"] = True + remote["flags"]["success"] = { + "key": "success", + "enabled": True, + "variant": "remote", + "metadata": {"payload": '{"copy":"success"}'}, + } + with ( + mock.patch.object( + client, + "_get_all_flags_and_payloads_locally", + return_value=(local, True, {}), + ), + mock.patch.object( + client, "_get_flags_decision", return_value=normalize_flags_response(remote) + ), + ): + result = client.get_all_flags_and_payloads("user") + assert result["featureFlags"] == { + "on": True, + "off": False, + "variant": "blue", + "success": "remote", + "malformed": False, + } + assert result["featureFlagPayloads"] == { + k: '{"copy":"success"}' if k == "success" else '{"copy":"local"}' + for k in ["on", "off", "variant", "success"] + } + + +async def test_failed_async_snapshot_honors_default(): + client = AsyncPosthog("project-key", send=False) + try: + with mock.patch( + "posthog.async_client._async_flags", + new=mock.AsyncMock(return_value=response("v4", False)), + ): + snapshot = await client.evaluate_flags("user") + assert ( + snapshot.is_enabled("failed", True, send_feature_flag_events=False) is True + ) + assert snapshot.get_flag("failed", send_feature_flag_events=False) is None + assert snapshot.keys == ["off"] + finally: + await client.shutdown() diff --git a/posthog/test/test_flags_released_behaviour.py b/posthog/test/test_flags_released_behaviour.py index 7f5dd12b9..d646e076e 100644 --- a/posthog/test/test_flags_released_behaviour.py +++ b/posthog/test/test_flags_released_behaviour.py @@ -38,9 +38,8 @@ def test_every_legacy_getter_and_event_matches_7_82_1(request, results): assert (sparse["id"], sparse["version"]) == (0, 0) sparse["id"] = sparse["version"] = None - # A failed record reads as disabled, so it has no payload, even when the record - # carries one. 7.82.1 returned that payload from the payload reads and sent it on - # the flag's $feature_flag_called events. + # An explicit failed record has no evaluated value or payload. 7.82.1 treated + # it as disabled, included it in bulk results, and returned its payload. failed = expected["get_flags_decision"]["flags"]["server-failed"]["metadata"] assert failed["payload"] == '{"columns": 2}' failed["payload"] = None @@ -48,7 +47,15 @@ def test_every_legacy_getter_and_event_matches_7_82_1(request, results): assert expected[f"{read}:server-failed"] == {"columns": 2} expected[f"{read}:server-failed"] = None assert expected["get_feature_flag_result:server-failed"][2] == {"columns": 2} - expected["get_feature_flag_result:server-failed"][2] = None + expected["get_feature_flag_result:server-failed"] = None + for read in ["get_feature_flag", "feature_enabled", "snapshot.get_flag"]: + assert expected[f"{read}:server-failed"] is False + expected[f"{read}:server-failed"] = None + for read in ["get_feature_variants", "get_all_flags"]: + assert expected[read].pop("server-failed") is False + for read in ["get_feature_flags_and_payloads", "get_all_flags_and_payloads"]: + assert expected[read]["featureFlags"].pop("server-failed") is False + expected["snapshot.keys"].remove("server-failed") failed_events = [ properties for _, properties in expected["events"] @@ -57,6 +64,13 @@ def test_every_legacy_getter_and_event_matches_7_82_1(request, results): assert failed_events for properties in failed_events: assert properties.pop("$feature_flag_payload") == {"columns": 2} + assert properties["$feature_flag_response"] is False + properties["$feature_flag_response"] = None + properties["$feature/server-failed"] = None + properties["$feature_flag_error"] = "evaluation_failed" + for name, properties in expected["events"]: + if name in ["snapshot-event", "fetched-event"]: + assert properties.pop("$feature/server-failed") is False if request.node.callspec.params["results"] == "v4": # A $feature_flag_called for a config version 2 record carries its config @@ -108,12 +122,16 @@ def test_fallback_cache_histories_match_7_82_1(results, name): # unknown_error, no request details, and the cached value. expected = copy.deepcopy(RELEASED["cache histories"][name]) if name == "good, server failed, timeout": - # A failed record has no payload, even when the record carries one, so - # neither its read nor the cached result read after the timeout returns - # one, and their events leave it out. 7.82.1 returned it from both. - for result in expected["results"][1:]: - assert result[2] == {"theme": "dark"} - result[2] = None - for _, properties in expected["events"][1:]: - assert properties.pop("$feature_flag_payload") == {"theme": "dark"} + # Explicit failure supplies no result and cannot poison the last good + # cache entry. The later timeout still returns that successful pair. + expected["results"][1] = None + expected["results"][2] = copy.deepcopy(expected["results"][0]) + failed = expected["events"][1][1] + assert failed.pop("$feature_flag_payload") == {"theme": "dark"} + failed["$feature_flag_response"] = None + failed["$feature/cached"] = None + failed["$feature_flag_error"] = "evaluation_failed" + timeout = expected["events"][2][1] + timeout["$feature_flag_response"] = "blue" + timeout["$feature/cached"] = "blue" assert results["cache histories"][name] == expected diff --git a/posthog/test/test_flags_v4_response.py b/posthog/test/test_flags_v4_response.py index 352c793aa..c730f54f5 100644 --- a/posthog/test/test_flags_v4_response.py +++ b/posthog/test/test_flags_v4_response.py @@ -211,8 +211,8 @@ def test_a_failed_record_never_renders_its_value(client): response["flags"]["garden-layout"]["value"] = "compact" snapshot = _evaluate(client, response) - assert snapshot.get_flag("garden-layout") is False - assert snapshot.is_enabled("garden-layout", True) is False + assert snapshot.get_flag("garden-layout") is None + assert snapshot.is_enabled("garden-layout", True) is True @pytest.mark.parametrize( @@ -764,7 +764,7 @@ def _failed_with_payload(shape: str) -> Dict[str, Any]: @pytest.mark.parametrize("shape", ["v4", "older"]) def test_a_failed_record_has_no_payload_on_any_read(shape, client): - # A failed flag reads as disabled, so a payload on it would surprise the caller. + # A failed flag has no evaluated result or payload. response = _failed_with_payload(shape) [flag] = normalize_flags_response(copy.deepcopy(response))["flags"].values() assert flag._failed is True @@ -772,7 +772,7 @@ def test_a_failed_record_has_no_payload_on_any_read(shape, client): with mock.patch("posthog.client.flags", return_value=copy.deepcopy(response)): result = client.get_feature_flag_result("garden-layout", DISTINCT_ID) - assert result is not None and result.payload is None + assert result is None assert client.get_feature_flag_payload("garden-layout", DISTINCT_ID) is None assert ( client.get_feature_flag_payload( @@ -951,7 +951,8 @@ def test_v1_flags_render_the_same_legacy_values_from_both_shapes(case): "flags": v4_flags, } expected = { - "featureFlags": v1_maps["featureFlags"], + # Flat legacy maps retain their interpretation, but detailed failures do not. + "featureFlags": {} if outcome["failed"] else v1_maps["featureFlags"], "featureFlagPayloads": { key: json.loads(value) for key, value in v1_maps["featureFlagPayloads"].items() diff --git a/posthog/types.py b/posthog/types.py index 625b5dc5a..9335274e5 100644 --- a/posthog/types.py +++ b/posthog/types.py @@ -275,6 +275,11 @@ class FeatureFlag: # server marks failed has ``_failed`` set and this ``None``. _malformed_field: ClassVar[Optional[str]] = None + @property + def _server_marked_failed(self) -> bool: + """Whether a readable record reports a server evaluation failure.""" + return self._failed and self._malformed_field is None + def __post_init__(self) -> None: object.__setattr__( self, @@ -640,12 +645,15 @@ def from_flag_details( details (Union[FeatureFlag, None]): The FeatureFlag object to convert. override_match_value (Optional[FlagValue]): If provided, this value will be used to populate the enabled and variant fields instead of the values from the FeatureFlag. + A server-marked failure returns None even when this override is provided. Returns: - FeatureFlagResult | None: A new FeatureFlagResult instance, or None if details is None. + FeatureFlagResult | None: A new result, or None when details is absent or + the server marked the record failed. Unreadable records are not + treated as server-marked failures. """ - if details is None: + if details is None or details._server_marked_failed: return None if override_match_value is not None: @@ -725,7 +733,7 @@ def to_values(response: FlagsResponse) -> Optional[dict[str, FlagValue]]: return { key: value.get_value() for key, value in flags.items() - if isinstance(value, FeatureFlag) + if isinstance(value, FeatureFlag) and not value._server_marked_failed } @@ -737,6 +745,7 @@ def to_payloads(response: FlagsResponse) -> Optional[dict[str, str]]: key: value.metadata.payload for key, value in response.get("flags", {}).items() if isinstance(value, FeatureFlag) + and not value._server_marked_failed and value.enabled and value.metadata.payload is not None } @@ -751,6 +760,7 @@ class FeatureFlagError: Error values: ERRORS_WHILE_COMPUTING: Server returned errorsWhileComputingFlags=true + EVALUATION_FAILED: Server marked the requested flag failed, with no evaluated value FLAG_MISSING: Requested flag not in API response LOCAL_EVALUATION_INCONCLUSIVE: Requested flag has a loaded definition but local evaluation was inconclusive and no remote value filled the gap @@ -764,6 +774,7 @@ class FeatureFlagError: """ ERRORS_WHILE_COMPUTING = "errors_while_computing_flags" + EVALUATION_FAILED = "evaluation_failed" FLAG_MISSING = "flag_missing" LOCAL_EVALUATION_INCONCLUSIVE = "local_evaluation_inconclusive" QUOTA_LIMITED = "quota_limited" diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index d0037bb5f..4b51f85aa 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -1216,6 +1216,7 @@ attribute posthog.types.FeatureFlag.reason: Optional[FlagReason] attribute posthog.types.FeatureFlag.variant: Optional[str] attribute posthog.types.FeatureFlagError.CONNECTION_ERROR = 'connection_error' attribute posthog.types.FeatureFlagError.ERRORS_WHILE_COMPUTING = 'errors_while_computing_flags' +attribute posthog.types.FeatureFlagError.EVALUATION_FAILED = 'evaluation_failed' attribute posthog.types.FeatureFlagError.FLAG_MISSING = 'flag_missing' attribute posthog.types.FeatureFlagError.LOCAL_EVALUATION_INCONCLUSIVE = 'local_evaluation_inconclusive' attribute posthog.types.FeatureFlagError.QUOTA_LIMITED = 'quota_limited' diff --git a/sdk_compliance_adapter/CONTRIBUTING.md b/sdk_compliance_adapter/CONTRIBUTING.md index 8514a342c..22b26b50a 100644 --- a/sdk_compliance_adapter/CONTRIBUTING.md +++ b/sdk_compliance_adapter/CONTRIBUTING.md @@ -4,7 +4,7 @@ This package contains the PostHog Python SDK compliance adapter used with the Po ## Running tests -Tests run automatically in CI via GitHub Actions against harness **1.1.1**, for both capture protocols. Both jobs opt into the local-evaluation suite and fail on compliance regressions. +Tests run automatically in CI via GitHub Actions against harness **1.31.1**, for both capture protocols. Both jobs opt into the local-evaluation suite and fail on compliance regressions. Run adapter protocol tests from the repository root in an activated virtual environment: @@ -44,7 +44,7 @@ docker run -d --name sdk-adapter --network test-network -p 8080:8080 posthog-pyt docker run --rm \ --name test-harness \ --network test-network \ - ghcr.io/posthog/sdk-test-harness:1.28.0 \ + ghcr.io/posthog/sdk-test-harness:1.31.1 \ run --adapter-url http://sdk-adapter:8080 --mock-url http://test-harness:8081 # Cleanup diff --git a/sdk_compliance_adapter/docker-compose.yml b/sdk_compliance_adapter/docker-compose.yml index dcbd677de..ead39d536 100644 --- a/sdk_compliance_adapter/docker-compose.yml +++ b/sdk_compliance_adapter/docker-compose.yml @@ -23,7 +23,7 @@ services: # Test harness test-harness: - image: ghcr.io/posthog/sdk-test-harness:1.28.0 + image: ghcr.io/posthog/sdk-test-harness:1.31.1 command: ["run", "--adapter-url", "http://sdk-adapter:8080", "--mock-url", "http://test-harness:8081"] networks: - test-network From cd87bcdea81ef17e37a6943a20b043324d32a5e4 Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:22:03 +0000 Subject: [PATCH 19/33] chore: Release v7.91.1 [skip ci] --- .sampo/changesets/fix-failed-flag-records.md | 5 ----- .sampo/changesets/openfeature-failed-flag-defaults.md | 5 ----- openfeature-provider/CHANGELOG.md | 7 +++++++ openfeature-provider/pyproject.toml | 2 +- posthog/CHANGELOG.md | 6 ++++++ posthog/version.py | 2 +- pyproject.toml | 2 +- uv.lock | 4 ++-- 8 files changed, 18 insertions(+), 15 deletions(-) delete mode 100644 .sampo/changesets/fix-failed-flag-records.md delete mode 100644 .sampo/changesets/openfeature-failed-flag-defaults.md diff --git a/.sampo/changesets/fix-failed-flag-records.md b/.sampo/changesets/fix-failed-flag-records.md deleted file mode 100644 index e52498056..000000000 --- a/.sampo/changesets/fix-failed-flag-records.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: patch ---- - -Treat server-marked failed feature flag records as unevaluated: direct result, value, enabled and payload getters return None rather than a disabled False result or placeholder payload. Snapshot value and payload reads return None, enablement honors the caller's default, and failed keys are omitted from enumeration and capture enrichment. Bulk value and payload maps omit failed remote records while preserving successful locally computed values and payloads for those keys. Preserve selected or accessed failure diagnostics through snapshot filters and report local_evaluation_inconclusive alongside evaluation_failed after an unresolved failed fallback; healthy False and malformed-record compatibility are unchanged. diff --git a/.sampo/changesets/openfeature-failed-flag-defaults.md b/.sampo/changesets/openfeature-failed-flag-defaults.md deleted file mode 100644 index f9f5535b8..000000000 --- a/.sampo/changesets/openfeature-failed-flag-defaults.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/openfeature-provider-posthog: patch ---- - -Document failed-record default handling with the updated PostHog SDK: a server-marked failed flag supplies no result, so the provider's existing FlagNotFoundError mapping lets OpenFeature return the caller's default instead of treating the failed record as a healthy disabled flag. This behavior requires upgrading the installed posthog dependency; the provider's compatible dependency range is unchanged and this patch intent does not force that upgrade. diff --git a/openfeature-provider/CHANGELOG.md b/openfeature-provider/CHANGELOG.md index a8ca504df..2ef947f89 100644 --- a/openfeature-provider/CHANGELOG.md +++ b/openfeature-provider/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to `openfeature-provider-posthog` are documented here. This file is maintained by [Sampo](https://github.com/bruits/sampo) from changesets in `.sampo/changesets/` that target `pypi/openfeature-provider-posthog`. +## 0.1.164 — 2026-11-13 + +### Patch changes + +- [3511570b](https://github.com/posthog/posthog-python/commit/3511570b4d19f84589b59dcd677df0c7b0d05cfe) Document failed-record default handling with the updated PostHog SDK: a server-marked failed flag supplies no result, so the provider's existing FlagNotFoundError mapping lets OpenFeature return the caller's default instead of treating the failed record as a healthy disabled flag. This behavior requires upgrading the installed posthog dependency; the provider's compatible dependency range is unchanged and this patch intent does not force that upgrade. — Thanks @marandaneto! +- Updated dependencies: posthog@7.91.1 + ## 0.1.163 — 2026-11-13 ### Patch changes diff --git a/openfeature-provider/pyproject.toml b/openfeature-provider/pyproject.toml index e04c875bd..3103bab30 100644 --- a/openfeature-provider/pyproject.toml +++ b/openfeature-provider/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "openfeature-provider-posthog" -version = "0.1.163" +version = "0.1.164" description = "Official PostHog provider for the OpenFeature Python SDK." readme = "README.md" authors = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/posthog/CHANGELOG.md b/posthog/CHANGELOG.md index 836b10382..8ea763fa4 100644 --- a/posthog/CHANGELOG.md +++ b/posthog/CHANGELOG.md @@ -1,5 +1,11 @@ # posthog +## 7.91.1 — 2026-11-13 + +### Patch changes + +- [3511570b](https://github.com/posthog/posthog-python/commit/3511570b4d19f84589b59dcd677df0c7b0d05cfe) Treat server-marked failed feature flag records as unevaluated: direct result, value, enabled and payload getters return None rather than a disabled False result or placeholder payload. Snapshot value and payload reads return None, enablement honors the caller's default, and failed keys are omitted from enumeration and capture enrichment. Bulk value and payload maps omit failed remote records while preserving successful locally computed values and payloads for those keys. Preserve selected or accessed failure diagnostics through snapshot filters and report local_evaluation_inconclusive alongside evaluation_failed after an unresolved failed fallback; healthy False and malformed-record compatibility are unchanged. — Thanks @marandaneto! + ## 7.91.0 — 2026-11-13 ### Minor changes diff --git a/posthog/version.py b/posthog/version.py index f0d60c57d..3705a8564 100644 --- a/posthog/version.py +++ b/posthog/version.py @@ -1 +1 @@ -VERSION = "7.91.0" +VERSION = "7.91.1" diff --git a/pyproject.toml b/pyproject.toml index 8e5d19720..6bfa4b536 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "posthog" -version = "7.91.0" +version = "7.91.1" description = "Integrate PostHog into any python application." authors = [{ name = "PostHog", email = "engineering@posthog.com" }] maintainers = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/uv.lock b/uv.lock index 051754280..495ba1611 100644 --- a/uv.lock +++ b/uv.lock @@ -2723,7 +2723,7 @@ wheels = [ [[package]] name = "openfeature-provider-posthog" -version = "0.1.163" +version = "0.1.164" source = { editable = "openfeature-provider" } dependencies = [ { name = "openfeature-sdk" }, @@ -3280,7 +3280,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.91.0" +version = "7.91.1" source = { editable = "." } dependencies = [ { name = "backoff" }, From 6d21c7b753fefc659d5c4f8c8f3d825b31d5208e Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:22:12 +0000 Subject: [PATCH 20/33] Update generated references --- references/posthog-python-7.md | 42 ++++++++------------------ references/posthog-python-reference.md | 42 ++++++++------------------ 2 files changed, 26 insertions(+), 58 deletions(-) diff --git a/references/posthog-python-7.md b/references/posthog-python-7.md index 4704eef67..736d03a5a 100644 --- a/references/posthog-python-7.md +++ b/references/posthog-python-7.md @@ -627,7 +627,7 @@ Name | Type | Description | Default Type | Description ---- | ----------- -`Optional[FeatureFlagResult]` | Optional[FeatureFlagResult]: The feature flag result or None if disabled/not found. +`Optional[FeatureFlagResult]` | Optional[FeatureFlagResult]: The evaluated result, including a healthy disabled flag, or None when no result is available (for example, a missing flag or a server-marked failure without a successful fallback). ## Get feature flags @@ -1310,11 +1310,8 @@ Name | Type | Description `capture_exceptions` | `Optional[bool]` | `capture_tracing_headers` | | `client` | | -`extra_properties` | | `extra_tags` | | Compatibility alias for `extra_properties`. `get_response` | | -`properties_map` | | -`request_filter` | | `sync_capable` | | `tag_map` | | Compatibility alias for `properties_map`. `trust_tracing_headers` | `bool` | Deprecated alias for `capture_tracing_headers`. @@ -1385,12 +1382,6 @@ capture_tracing_headers = _resolve_capture_tracing_headers(capture_tracing_heade client = cast('Optional[Client]', settings.POSTHOG_MW_CLIENT) ``` -#### `posthog.integrations.django.PosthogContextMiddleware.extra_properties` - -```python -extra_properties = cast('Callable[[HttpRequest], Dict[str, Any]]', extra_properties) if callable(extra_properties) else None -``` - #### `posthog.integrations.django.PosthogContextMiddleware.extra_tags` ```python @@ -1446,18 +1437,6 @@ the middleware stack, so the context manager in __call__/__acall__ never sees th Note: Django's process_exception is always synchronous, even for async views. -#### `posthog.integrations.django.PosthogContextMiddleware.properties_map` - -```python -properties_map = cast('Callable[[Dict[str, Any]], Dict[str, Any]]', properties_map) if callable(properties_map) else None -``` - -#### `posthog.integrations.django.PosthogContextMiddleware.request_filter` - -```python -request_filter = cast('Optional[Callable[[HttpRequest], bool]]', settings.POSTHOG_MW_REQUEST_FILTER) -``` - #### `posthog.integrations.django.PosthogContextMiddleware.sync_capable` ```python @@ -3036,7 +3015,7 @@ Name | Description `get_flag` | Return the flag value. Fires `$feature_flag_called` on first access. `get_flag_payload` | Return the payload associated with a flag. `is_enabled` | Return whether the flag is enabled. Fires `$feature_flag_called` on the first access per (distinct_id, flag, value) tuple, deduped via the SDK's cache. -`only` | Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. +`only` | Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. Selected failures retain private diagnostics but remain absent from values, keys and enrichment; their existing missing-value warning is unchanged. `only_accessed` | Return a filtered copy containing only flags accessed via `is_enabled` or `get_flag` before this call. **Attributes:** @@ -3058,7 +3037,8 @@ Return the flag value. Fires `$feature_flag_called` on first access. Returns the variant string for multivariate flags, `True` for enabled flags without a variant, `False` for disabled flags, and `None` for flags that -were not returned by the evaluation. +were not returned or whose remote record was marked failed by the server. +An unreadable remote record retains its disabled (`False`) result. Pass `send_feature_flag_events=False` to skip the event for this read, as with `is_enabled`. @@ -3087,7 +3067,7 @@ first access per (distinct_id, flag, value) tuple, deduped via the SDK's cache. Name | Type | Description | Default ---- | ---- | ----------- | ------- `key` | `str` | The feature flag key. | *required* -`default_value` | `bool` | Returned when the flag has no value in this evaluation — the key was not part of the evaluated set, or the evaluation itself came back empty (failed `/flags` request, quota limit, or no resolvable `distinct_id`). Defaults to `False`. | `False` +`default_value` | `bool` | Returned when the flag has no value in this evaluation — the key was not part of the evaluated set, the server marked its record failed, or the evaluation itself came back empty (failed `/flags` request, quota limit, or no resolvable `distinct_id`). Defaults to `False`. | `False` `send_feature_flag_events` | `bool` | Whether this read sends `$feature_flag_called`. When `False`, no event is sent and the dedupe cache is left alone, but the key still counts as accessed for `only_accessed`. | `True` A flag that has a value always wins over `default_value`, including a @@ -3109,6 +3089,8 @@ only(keys: List[str]) -> FeatureFlagEvaluations Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. +Selected failures retain private diagnostics but remain absent from values, +keys and enrichment; their existing missing-value warning is unchanged. #### `posthog.feature_flag_evaluations.FeatureFlagEvaluations.only_accessed` @@ -3121,6 +3103,7 @@ or `get_flag` before this call. Order-dependent: if nothing has been accessed yet, the returned snapshot is empty. The method honors its name — pre-access if you want a populated result. +Accessed failures retain private diagnostics, not values or enrichment. #### `posthog.feature_flag_evaluations.FeatureFlagEvaluations.unresolved_flags` @@ -3134,8 +3117,9 @@ left it without a value. A flag is listed when it has a loaded local definition, was in the requested scope, was inconclusive locally, and no remote value filled the gap. Listed flags are not part of `keys`, and reading one reports the -`local_evaluation_inconclusive` error instead of `flag_missing`. Reading -this mapping does not count as an access and does not fire any event. +`local_evaluation_inconclusive` error instead of `flag_missing`. +A server-marked failed fallback additionally reports `evaluation_failed`. +Reading this mapping does not count as an access and does not fire any event. Snapshots returned by `only` and `only_accessed`, and by `AsyncClient.evaluate_flags()`, which evaluates only remotely, carry no entries. @@ -3185,13 +3169,13 @@ Create a FeatureFlagResult from a FeatureFlag object. Name | Type | Description | Default ---- | ---- | ----------- | ------- `details` | `Union[FeatureFlag, None]` | The FeatureFlag object to convert. | *required* -`override_match_value` | `Optional[FlagValue]` | If provided, this value will be used to populate the enabled and variant fields instead of the values from the FeatureFlag. | `None` +`override_match_value` | `Optional[FlagValue]` | If provided, this value will be used to populate the enabled and variant fields instead of the values from the FeatureFlag. A server-marked failure returns None even when this override is provided. | `None` **Returns:** Type | Description ---- | ----------- -`FeatureFlagResult \| None` | FeatureFlagResult | None: A new FeatureFlagResult instance, or None if details is None. +`FeatureFlagResult \| None` | FeatureFlagResult | None: A new result, or None when details is absent or the server marked the record failed. Unreadable records are not treated as server-marked failures. #### `posthog.types.FeatureFlagResult.from_value_and_payload` diff --git a/references/posthog-python-reference.md b/references/posthog-python-reference.md index e40076965..3d3e31800 100644 --- a/references/posthog-python-reference.md +++ b/references/posthog-python-reference.md @@ -627,7 +627,7 @@ Name | Type | Description | Default Type | Description ---- | ----------- -`Optional[FeatureFlagResult]` | Optional[FeatureFlagResult]: The feature flag result or None if disabled/not found. +`Optional[FeatureFlagResult]` | Optional[FeatureFlagResult]: The evaluated result, including a healthy disabled flag, or None when no result is available (for example, a missing flag or a server-marked failure without a successful fallback). ## Get feature flags @@ -1310,11 +1310,8 @@ Name | Type | Description `capture_exceptions` | `Optional[bool]` | `capture_tracing_headers` | | `client` | | -`extra_properties` | | `extra_tags` | | Compatibility alias for `extra_properties`. `get_response` | | -`properties_map` | | -`request_filter` | | `sync_capable` | | `tag_map` | | Compatibility alias for `properties_map`. `trust_tracing_headers` | `bool` | Deprecated alias for `capture_tracing_headers`. @@ -1385,12 +1382,6 @@ capture_tracing_headers = _resolve_capture_tracing_headers(capture_tracing_heade client = cast('Optional[Client]', settings.POSTHOG_MW_CLIENT) ``` -#### `posthog.integrations.django.PosthogContextMiddleware.extra_properties` - -```python -extra_properties = cast('Callable[[HttpRequest], Dict[str, Any]]', extra_properties) if callable(extra_properties) else None -``` - #### `posthog.integrations.django.PosthogContextMiddleware.extra_tags` ```python @@ -1446,18 +1437,6 @@ the middleware stack, so the context manager in __call__/__acall__ never sees th Note: Django's process_exception is always synchronous, even for async views. -#### `posthog.integrations.django.PosthogContextMiddleware.properties_map` - -```python -properties_map = cast('Callable[[Dict[str, Any]], Dict[str, Any]]', properties_map) if callable(properties_map) else None -``` - -#### `posthog.integrations.django.PosthogContextMiddleware.request_filter` - -```python -request_filter = cast('Optional[Callable[[HttpRequest], bool]]', settings.POSTHOG_MW_REQUEST_FILTER) -``` - #### `posthog.integrations.django.PosthogContextMiddleware.sync_capable` ```python @@ -3036,7 +3015,7 @@ Name | Description `get_flag` | Return the flag value. Fires `$feature_flag_called` on first access. `get_flag_payload` | Return the payload associated with a flag. `is_enabled` | Return whether the flag is enabled. Fires `$feature_flag_called` on the first access per (distinct_id, flag, value) tuple, deduped via the SDK's cache. -`only` | Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. +`only` | Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. Selected failures retain private diagnostics but remain absent from values, keys and enrichment; their existing missing-value warning is unchanged. `only_accessed` | Return a filtered copy containing only flags accessed via `is_enabled` or `get_flag` before this call. **Attributes:** @@ -3058,7 +3037,8 @@ Return the flag value. Fires `$feature_flag_called` on first access. Returns the variant string for multivariate flags, `True` for enabled flags without a variant, `False` for disabled flags, and `None` for flags that -were not returned by the evaluation. +were not returned or whose remote record was marked failed by the server. +An unreadable remote record retains its disabled (`False`) result. Pass `send_feature_flag_events=False` to skip the event for this read, as with `is_enabled`. @@ -3087,7 +3067,7 @@ first access per (distinct_id, flag, value) tuple, deduped via the SDK's cache. Name | Type | Description | Default ---- | ---- | ----------- | ------- `key` | `str` | The feature flag key. | *required* -`default_value` | `bool` | Returned when the flag has no value in this evaluation — the key was not part of the evaluated set, or the evaluation itself came back empty (failed `/flags` request, quota limit, or no resolvable `distinct_id`). Defaults to `False`. | `False` +`default_value` | `bool` | Returned when the flag has no value in this evaluation — the key was not part of the evaluated set, the server marked its record failed, or the evaluation itself came back empty (failed `/flags` request, quota limit, or no resolvable `distinct_id`). Defaults to `False`. | `False` `send_feature_flag_events` | `bool` | Whether this read sends `$feature_flag_called`. When `False`, no event is sent and the dedupe cache is left alone, but the key still counts as accessed for `only_accessed`. | `True` A flag that has a value always wins over `default_value`, including a @@ -3109,6 +3089,8 @@ only(keys: List[str]) -> FeatureFlagEvaluations Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. +Selected failures retain private diagnostics but remain absent from values, +keys and enrichment; their existing missing-value warning is unchanged. #### `posthog.feature_flag_evaluations.FeatureFlagEvaluations.only_accessed` @@ -3121,6 +3103,7 @@ or `get_flag` before this call. Order-dependent: if nothing has been accessed yet, the returned snapshot is empty. The method honors its name — pre-access if you want a populated result. +Accessed failures retain private diagnostics, not values or enrichment. #### `posthog.feature_flag_evaluations.FeatureFlagEvaluations.unresolved_flags` @@ -3134,8 +3117,9 @@ left it without a value. A flag is listed when it has a loaded local definition, was in the requested scope, was inconclusive locally, and no remote value filled the gap. Listed flags are not part of `keys`, and reading one reports the -`local_evaluation_inconclusive` error instead of `flag_missing`. Reading -this mapping does not count as an access and does not fire any event. +`local_evaluation_inconclusive` error instead of `flag_missing`. +A server-marked failed fallback additionally reports `evaluation_failed`. +Reading this mapping does not count as an access and does not fire any event. Snapshots returned by `only` and `only_accessed`, and by `AsyncClient.evaluate_flags()`, which evaluates only remotely, carry no entries. @@ -3185,13 +3169,13 @@ Create a FeatureFlagResult from a FeatureFlag object. Name | Type | Description | Default ---- | ---- | ----------- | ------- `details` | `Union[FeatureFlag, None]` | The FeatureFlag object to convert. | *required* -`override_match_value` | `Optional[FlagValue]` | If provided, this value will be used to populate the enabled and variant fields instead of the values from the FeatureFlag. | `None` +`override_match_value` | `Optional[FlagValue]` | If provided, this value will be used to populate the enabled and variant fields instead of the values from the FeatureFlag. A server-marked failure returns None even when this override is provided. | `None` **Returns:** Type | Description ---- | ----------- -`FeatureFlagResult \| None` | FeatureFlagResult | None: A new FeatureFlagResult instance, or None if details is None. +`FeatureFlagResult \| None` | FeatureFlagResult | None: A new result, or None when details is absent or the server marked the record failed. Unreadable records are not treated as server-marked failures. #### `posthog.types.FeatureFlagResult.from_value_and_payload` From ec112a6201569e1cf5e9b8827a01793de523f643 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" <29069505+gewenyu99@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:10:00 -0500 Subject: [PATCH 21/33] docs: publish the posthog-python 8.x reference and migration guide pages (#1251) * docs: publish the posthog-python 8.x reference and migration guide pages Adds references/posthog-python-8.md and references/posthog-python-migration.md as the 8.0.0 release will write them, so the Strapi sync puts them on posthog.com before 8.0.0 ships. Both come from running bin/docs on docs/migration-guide-structure (#1245) with posthog/version.py at 8.0.0, the version the release sets before it generates. The generator on main writes only the 7.x page and the reference page, and skips the migration page without docs/migration-*.md, so neither file is rewritten before the release. Co-Authored-By: Claude Opus 5.5 * docs: regenerate the migration page from the guide's latest fix Co-Authored-By: Claude Opus 5.5 * docs: regenerate the migration page without the 404 hint and self-hosted lines Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- references/posthog-python-8.md | 274 ++++++++-- references/posthog-python-migration.md | 678 +++++++++++++++++-------- 2 files changed, 688 insertions(+), 264 deletions(-) diff --git a/references/posthog-python-8.md b/references/posthog-python-8.md index cdaf0c02e..7f7416cfa 100644 --- a/references/posthog-python-8.md +++ b/references/posthog-python-8.md @@ -1,5 +1,5 @@ --- -title: "PostHog Python SDK 8.x (experimental)" +title: "PostHog Python SDK 8.x" sidebar: Docs showTitle: true contentMaxWidthClass: max-w-full @@ -89,7 +89,7 @@ To send your first event, install the package, create a client, capture an event ### Install ```bash -pip install posthog +pip install "posthog>=8,<9" ``` ### Initialize @@ -120,12 +120,35 @@ posthog.shutdown() In an asyncio app, use `AsyncPosthog` as an async context manager instead. See [AsyncClient](#asyncclient). +### Use AsyncPosthog in FastAPI + +Keep one `AsyncPosthog` client for the lifetime of your app. A FastAPI lifespan handler does this. + +```python +from contextlib import asynccontextmanager + +from fastapi import FastAPI +from posthog import AsyncPosthog + +@asynccontextmanager +async def lifespan(app: FastAPI): + async with AsyncPosthog("", host="") as posthog: + app.state.posthog = posthog + yield + +app = FastAPI(lifespan=lifespan) +``` + +### The posthoganalytics package + +`posthoganalytics` is the same SDK under another module name. Use it when another module named `posthog` is on your import path. + ## Setup ### `Client(...)` ```python -Client(project_api_key: str, host=None, *, debug=False, max_queue_size=10000, send=True, on_error=None, flush_at=100, flush_interval=5.0, max_retries=3, sync_mode=False, timeout: float = 15, thread=1, poll_interval=30, personal_api_key=None, disabled=False, disable_geoip=True, is_server=True, historical_migration=False, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries=1, super_properties=None, super_options=None, enable_exception_autocapture=False, log_captured_exceptions=False, project_root=None, privacy_mode=False, before_send=None, flag_fallback_cache_url=None, enable_local_evaluation=True, flag_definition_cache_provider: Optional[FlagDefinitionCacheProvider] = None, capture_exception_code_variables=False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: list[str] | None = None, enable_exception_autocapture_rate_limiting=False, exception_autocapture_bucket_size=ExceptionCapture.DEFAULT_BUCKET_SIZE, exception_autocapture_refill_rate=ExceptionCapture.DEFAULT_REFILL_RATE, exception_autocapture_refill_interval_seconds=ExceptionCapture.DEFAULT_REFILL_INTERVAL_SECONDS, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = AI_MAX_MSG_SIZE, secret_key=None, metrics: Optional[dict] = None, enable_full_ai_capture=False, capture_trace_context=False, traces: Optional[dict] = None, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2) +Client(project_api_key: str, host=None, *, debug=False, max_queue_size=10000, send=True, on_error=None, flush_at=100, flush_interval=5.0, max_retries=3, sync_mode=False, timeout: float = 15, thread=1, poll_interval=30, personal_api_key=None, disabled=False, disable_geoip=True, is_server=True, historical_migration=False, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries=1, super_properties=None, super_options=None, enable_exception_autocapture=False, log_captured_exceptions=False, project_root=None, privacy_mode=False, before_send=None, flag_fallback_cache_url=None, enable_local_evaluation=True, flag_definition_cache_provider: Optional[FlagDefinitionCacheProvider] = None, capture_exception_code_variables=False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: list[str] | None = None, enable_exception_autocapture_rate_limiting=False, exception_autocapture_bucket_size=ExceptionCapture.DEFAULT_BUCKET_SIZE, exception_autocapture_refill_rate=ExceptionCapture.DEFAULT_REFILL_RATE, exception_autocapture_refill_interval_seconds=ExceptionCapture.DEFAULT_REFILL_INTERVAL_SECONDS, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = AI_MAX_MSG_SIZE, secret_key=None, metrics: Optional[dict] = None, enable_full_ai_capture=False, capture_trace_context=False, traces: Optional[dict] = None, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2, migrated_from: Optional[str] = None) ``` Initialize a new PostHog client instance. @@ -158,8 +181,9 @@ Name | Type | Description | Default `app_host` | `Optional[str]` | Your PostHog app host, such as `https://posthog.example.com`. `emails` sends there. Needed only when `host` is not PostHog Cloud, for example a reverse proxy, which must not receive the secret key. | `None` `email_request_timeout_seconds` | `float` | Timeout in seconds for each email send request. Defaults to 15. | `15` `email_request_max_retries` | `int` | Number of retries for an email send after a network error, a rate limit, or an unavailable service. Defaults to 2. Set to 0 when a job runner already retries the send. | `2` +`migrated_from` | `Optional[str]` | The email provider you moved from, such as `"resend"`. `emails` sends it with every request. | `None` `super_properties` | | Properties for every captured event. They fill only keys the event leaves unset, before `before_send` runs. `$set`, `$set_once`, `$groups` and `$group_set` fill one level deep. An event's own properties and context tags override them, and `before_send` can change or remove them. | `None` -`super_options` | | Capture options for every captured event, such as `{"cookieless_mode": True}`. They fill only options the event leaves unset, before `before_send` runs. An event's own `options` and context options override them, and `before_send` can change them. They also win over an event's legacy property for the same key, such as `$cookieless_mode`, so pass per-event overrides of that key as `options`. | `None` +`super_options` | | Capture options for every captured event, such as `{"cookieless_mode": True}`. They fill only options the event leaves unset, before `before_send` runs. An event's own `options` and context options override them, and `before_send` can change them. They never set `process_person_profile` on identify-style events, such as `$identify` or `$set`, whose distinct ID the SDK did not generate: those default it to `True`. | `None` `enable_exception_autocapture` | | Automatically capture uncaught exceptions. | `False` `log_captured_exceptions` | | Also log exceptions captured by error tracking. | `False` `project_root` | | Root path used to determine in-app stack frames for captured exceptions. Defaults to the current working directory. | `None` @@ -171,7 +195,7 @@ Name | Type | Description | Default `flag_definition_cache_provider` | `Optional[FlagDefinitionCacheProvider]` | Optional external cache provider for sharing feature flag definitions across workers. | `None` `capture_exception_code_variables` | | Capture local variable values on exception stack frames. | `False` `capture_trace_context` | | When OpenTelemetry is installed and a valid span is active at capture time, add its trace and span IDs as `$trace_id` and `$span_id` properties to events captured with `capture()` and `capture_ai()`, so they can be correlated with backend traces. They fill after context tags and `super_properties`, before `before_send`. A `$trace_id` or `$span_id` from the event, a context tag or `super_properties` stops the SDK adding either ID. Exception events (`capture_exception`) always attach these IDs regardless of this setting. Defaults to False. | `False` -`traces` | `Optional[dict]` | Config dict for distributed tracing: `service_name`, `service_version`, `environment`, `resource_attributes`, `flush_interval` (5 s), `max_queue_size` (2048), `max_export_batch_size` (512), `max_live_spans` (10000), `max_span_age` (3600 s), `max_attributes_per_span` (128), `max_events_per_span` (128), `max_attribute_value_length` (8192). `before_span_send` is a callable, or a list run in order, that receives each finished span as a dict (`trace_id`, `span_id` and `parent_span_id` are read-only) and returns it, edited, or `None` to drop it; a hook that raises drops the span. Tracing is off until this is provided. Spans export on a background timer even with `sync_mode`; serverless handlers should call `flush()` before returning. Defaults to None. | `None` +`traces` | `Optional[dict]` | Config dict for distributed tracing. Non-empty string values for `service.name`, `service.version` and `deployment.environment` in `resource_attributes` take precedence over `service_name`, `service_version` and `environment`, respectively. Options include `service_name`, `service_version`, `environment`, `resource_attributes`, `flush_interval` (5 s), `max_queue_size` (2048), `max_export_batch_size` (512), `max_live_spans` (10000), `max_span_age` (3600 s), `max_attributes_per_span` (128), `max_events_per_span` (128), `max_attribute_value_length` (8192). `before_span_send` is a callable, or a list run in order, that receives each finished span as a dict (`trace_id`, `span_id` and `parent_span_id` are read-only) and returns it, edited, or `None` to drop it; a hook that raises drops the span. The span dict has `name`, `kind`, `status`, `attributes`, `events`, `start_time_ns`, `end_time_ns`, `trace_id`, `span_id` and `parent_span_id`, and its attributes are plain Python values. The hook runs after `posthogDistinctId` and `sessionId` are attached, so it can scrub them. It must be a regular function. An `async` hook drops every span. In a list of hooks, the first one to return `None` stops the chain. An entry that isn't callable turns tracing off for the client. Past a per-span cap, the earliest attributes and events are kept and the span reports how many were dropped. `posthogDistinctId` and `sessionId` don't count toward the attribute cap and are never dropped. `max_attribute_value_length` also applies to strings nested in lists and dictionaries. All caps are applied again after `before_span_send`. Spans beyond `max_queue_size` are dropped. An invalid value falls back to its default with a warning. Tracing is off until this is provided. Spans export on a background timer even with `sync_mode`; serverless handlers should call `flush()` before returning. Defaults to None. | `None` `code_variables_mask_patterns` | | Variable-name patterns to mask when capturing code variables. | `None` `code_variables_ignore_patterns` | | Variable-name patterns to omit when capturing code variables. | `None` `code_variables_mask_url_credentials` | | Scrub credentials embedded in URLs/DSNs (e.g. `user:pass@host`) from captured code variables, regardless of the surrounding variable name. Defaults to True. | `None` @@ -181,7 +205,7 @@ Name | Type | Description | Default `exception_autocapture_bucket_size` | | Maximum burst of autocaptured exceptions allowed per exception type (token bucket size, clamped to 0-100). | `DEFAULT_BUCKET_SIZE` `exception_autocapture_refill_rate` | | Tokens restored per refill interval for each exception type's bucket. | `DEFAULT_REFILL_RATE` `exception_autocapture_refill_interval_seconds` | | Seconds between token refills for autocaptured exception rate limiting. | `DEFAULT_REFILL_INTERVAL_SECONDS` -`capture_compression` | `Optional[Union[CaptureCompression, str]]` | Request-body compression for `capture()` uploads. `CaptureCompression.GZIP` or `DEFLATE` (or the strings `"gzip"`/`"deflate"`). When omitted, the `POSTHOG_CAPTURE_COMPRESSION` env var is consulted, then no compression. | `None` +`capture_compression` | `Optional[Union[CaptureCompression, str]]` | Request-body compression for `capture()` uploads. `CaptureCompression.GZIP`, `DEFLATE` or `ZSTD` (or the strings `"gzip"`, `"deflate"` or `"zstd"`). `ZSTD` needs `pip install posthog[zstd]`. When omitted, the `POSTHOG_CAPTURE_COMPRESSION` env var is consulted, then no compression. | `None` `capture_ai_compression` | `Optional[Union[CaptureCompression, str]]` | Request-body compression for `capture_ai()` uploads, set independently of `capture_compression`. Defaults to no compression, and the env var does not apply. `CaptureCompression.ZSTD` suits large AI payloads. | `None` `capture_ai_max_queue_size` | `int` | Maximum number of AI events buffered before upload. Defaults to 1000, lower than `max_queue_size` because AI events are much larger. | `1000` `capture_ai_timeout` | `float` | Seconds allowed for one AI upload request. Defaults to 30, longer than `timeout` because AI batches are much larger. | `30` @@ -218,7 +242,7 @@ Name | Type | Description | Default `flags` | | A FeatureFlagEvaluations snapshot from evaluate_flags(). The exact values from the snapshot are attached with no extra /flags request. | `send_feature_flags` | | Deprecated. Prefer flags=... from evaluate_flags(). When truthy, evaluates flags during capture and attaches them to the event. | `disable_geoip` | | Whether to disable GeoIP for this event. It wins over a `$geoip_disable` in context tags or `super_properties`. A `$geoip_disable` property in this call's `properties` wins over it. | -`options` | | Capture options for this event, such as `{"process_person_profile": False}`. Sent as given, for PostHog to validate. They override context options and `super_options`, which fill in before `before_send` runs. An option set at any layer wins over its legacy `$` property, such as `$process_person_profile`, set at any layer. A `None` option counts as unset. | +`options` | | Capture options for this event, such as `{"process_person_profile": False}`. Sent as given, for PostHog to validate. They override context options and `super_options`, which fill in before `before_send` runs. An option overrides its legacy `$` property, such as `$process_person_profile`. A `None` option counts as unset. An identify-style event, such as `$identify` or `$set`, gets `process_person_profile: True` when this call leaves it unset, unless the SDK generated its distinct ID. | **Examples:** @@ -316,12 +340,17 @@ start_span(name: str, *, kind: Optional[str] = None, attributes: Optional[Mappin Start a span for distributed tracing. Alpha. +The span API is experimental and can change in a minor release. Spans +already sent are kept; the SDK API isn't frozen yet. + Returns a span handle. Use it as a context manager to make it the active span for the block and end it on exit (recording a raised exception on the way out); or call `end()` yourself for a span that cannot wrap a block. Spans started inside the block nest under it automatically. Always returns a usable handle, even when tracing is off, so calling -code never branches. +code never branches. At `max_live_spans` open spans, the SDK first +evicts spans open longer than `max_span_age` seconds, which are never +exported. If it is still at the limit, the returned span isn't recorded. **Parameters:** @@ -330,9 +359,9 @@ Name | Type | Description | Default `name` | `str` | A low-cardinality operation name, e.g. `GET /users/:id`. Variable values belong in attributes, not the name. | *required* `kind` | `Optional[str]` | `internal` (default), `server`, `client`, `producer` or `consumer`. | `None` `attributes` | `Optional[Mapping[str, Any]]` | Initial attributes. | `None` -`parent` | `Union[Span, str, None]` | A span handle, or an inbound W3C `traceparent` header value to continue a remote trace. Defaults to the active span. A forked child starts with no active span; pass the parent span to continue a trace across a fork. | `None` +`parent` | `Union[Span, str, None]` | A span handle, or an inbound W3C `traceparent` header value to continue a remote trace. Defaults to the active span. A forked child starts with no active span; pass the parent span to continue a trace across a fork. The active span is tracked with `contextvars`, so it carries across `await`. Threads don't reliably inherit it, so pass `parent=span` in a thread or a `ThreadPoolExecutor` task. A malformed `traceparent` starts a new trace and doesn't raise. A continued trace propagates the sampled flag it received. PostHog doesn't sample, so the span is exported whichever way the flag is set. | `None` `tracestate` | `Optional[str]` | The inbound `tracestate` header accompanying a `traceparent` string `parent`; preserved and propagated. | `None` -`start_time` | `Union[datetime, float, None]` | A `datetime` or epoch seconds, to backdate the span. | `None` +`start_time` | `Union[datetime, float, None]` | A `datetime` or epoch seconds, to backdate the span. PostHog clamps a start time more than 24 hours old to the receive time. | `None` **Examples:** @@ -385,7 +414,7 @@ Name | Type | Description | Default `timestamp` | `Optional[Union[datetime, str]]` | The timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. | `None` `uuid` | `Optional[str]` | A unique identifier for the event. If provided, it must be a valid UUID string or uuid.UUID instance; invalid values are ignored and replaced with a newly generated UUID. | `None` `disable_geoip` | `Optional[bool]` | Whether to disable GeoIP for this event. | `None` -`options` | `Optional[Dict[str, Any]]` | Capture options for this event, sent as given. | `None` +`options` | `Optional[Dict[str, Any]]` | Capture options for this event, sent as given. `process_person_profile` is `True` unless this call sets it. | `None` **Examples:** @@ -459,10 +488,10 @@ except Exception as e: emails: Emails ``` -Send transactional email from PostHog email templates, and read the -status of each email sent with `get`. +Send transactional email from PostHog email templates or from content +in your code, and read the status of each email sent with `get`. -Needs `secret_key`, a project secret API key with the `hog_flow:write` +Needs `secret_key`, a project secret API key with the `transactional_email:write` scope. Sends go to `app_host`, or to the PostHog Cloud app host of `host`. `email_request_timeout_seconds` and `email_request_max_retries` configure each send. A disabled or shut-down client sends nothing. See @@ -601,6 +630,9 @@ get_feature_flag_result(key: str, distinct_id: ID_TYPES, *, groups: Optional[Map Get a FeatureFlagResult object which contains the flag result and payload for a key by evaluating locally or remotely depending on whether local evaluation is enabled and the flag can be locally evaluated. This also captures the `$feature_flag_called` event unless `send_feature_flag_events` is `False`. +When the flag was evaluated remotely and its config version 2 record is a complete experiment +split (an experiment rule with a rule ID and a variant key), it also captures the +`$experiment_exposure` event, once per distinct ID, groups, flag, rule and variant. **Examples:** @@ -809,7 +841,7 @@ Name | Type | Description | Default `uuid` | `Optional[Union[str, UUID]]` | A unique identifier for the event. If provided, it must be a valid UUID string or uuid.UUID instance; invalid values are ignored and replaced with a newly generated UUID. | `None` `disable_geoip` | `Optional[bool]` | Whether to disable GeoIP for this event. | `None` `distinct_id` | `Optional[ID_TYPES]` | The distinct ID of the user performing the action. Falls back to the context distinct ID, then to `$_`. | `None` -`options` | `Optional[Dict[str, Any]]` | Capture options for this event, sent as given. | `None` +`options` | `Optional[Dict[str, Any]]` | Capture options for this event, sent as given. `process_person_profile` is `True` unless this call sets it. | `None` **Examples:** @@ -898,6 +930,8 @@ server receipt. Event draining has no timeout. Queued spans get one final flush with up to 30 seconds waiting for an in-flight flush, then a fresh 30-second drain budget; the last HTTP request is not cut short. Any spans it cannot send are discarded with a warning, as are spans still open. +A script that exits without calling `shutdown()` gets only a brief +best-effort span flush, so don't rely on it. Lifecycle cleanup is attempted once, and cleanup failures are logged without retry. When called directly from an SDK callback such as `on_error`, shutdown is deferred to avoid blocking the worker that @@ -1039,7 +1073,10 @@ Set a capture option for every event captured within the current context. Context options fill options an event leaves unset, before `before_send` runs, so the hook sees them. They override `super_options`. An event's own `options` override them, and -`before_send` can change them. +`before_send` can change them. They never set +`process_person_profile` on identify-style events, such as +`$identify` or `$set`, whose distinct ID the SDK did not generate: +those default it to `True`. **Parameters:** @@ -1615,6 +1652,12 @@ PosthogASGIMiddleware(app: _ASGIApp, client: Optional[Client] = None, capture_ex Add PostHog context and automatic exception capture to an ASGI app. +It creates a context for each HTTP or WebSocket request and captures +exceptions that escape the app. In FastAPI or Starlette, add it with +`app.add_middleware(PosthogASGIMiddleware, client=posthog)`. For Litestar, +another ASGI framework or a raw ASGI app, wrap the app with +`app = PosthogASGIMiddleware(app, client=posthog)`. + **Parameters:** Name | Type | Description | Default @@ -1698,7 +1741,7 @@ Name | Type | Description | Default `client` | `Optional[Client]` | Optional `Client` instance. When provided, all events and exceptions are captured through this client rather than the global `posthog` module. Don't skip this if using a custom flag definition cache provider, and pass the custom `Client` instance here initialized with the custom provider so fork safety for that provider is handled correctly. | `None` `capture_exceptions` | `bool` | Whether to capture task exceptions via `capture_exception` (default `True`). | `True` `capture_task_lifecycle_events` | `bool` | Whether to emit lifecycle events of the task such as "started", "success", "failure" etc. (default `True`). | `True` -`propagate_context` | `bool` | Whether to propagate PostHog context (distinct ID, session ID, tags) from the producer to the worker via task headers (default `True`). | `True` +`propagate_context` | `bool` | Whether to propagate PostHog context (distinct ID, session ID, tags, context options) from the producer to the worker via task headers (default `True`). | `True` `task_filter` | `Optional[Callable[[Optional[str], dict[str, Any]], bool]]` | Optional callback `(task_name, task_properties) -> bool` expected to return `False` if a given task should not be tracked. | `None` **Functions:** @@ -1823,6 +1866,9 @@ Enable TCP keepalive for SDK HTTP connections. This helps prevent idle pooled connections from being dropped by network infrastructure. Call during initialization, before making API requests. +Where the platform supports the corresponding socket options, it uses +a 60 second idle time, a 60 second probe interval and 3 probes before +timeout. Unsupported settings keep their system defaults. ### `posthog.request.disable_connection_reuse` @@ -1843,7 +1889,7 @@ Needs the `async` extra, `posthog[async]`. ### `AsyncClient(...)` ```python -AsyncClient(project_api_key: str, host: Optional[str] = None, *, debug: bool = False, max_queue_size: int = 10000, send: bool = True, on_error=None, flush_at: int = 100, flush_interval: float = 5.0, max_retries: int = 3, timeout: float = 15, thread: int = 1, disabled: bool = False, disable_geoip: bool = True, is_server: bool = True, historical_migration: bool = False, super_properties: Optional[dict[str, Any]] = None, super_options: Optional[dict[str, Any]] = None, before_send=None, log_captured_exceptions: bool = False, project_root: Optional[str] = None, capture_exception_code_variables: bool = False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: Optional[list[str]] = None, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = AI_MAX_MSG_SIZE, privacy_mode: bool = False, enable_full_ai_capture: bool = False, capture_trace_context: bool = False, secret_key: Optional[str] = None, personal_api_key: Optional[str] = None, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries: int = 1, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2) -> None +AsyncClient(project_api_key: str, host: Optional[str] = None, *, debug: bool = False, max_queue_size: int = 10000, send: bool = True, on_error=None, flush_at: int = 100, flush_interval: float = 5.0, max_retries: int = 3, timeout: float = 15, thread: int = 1, disabled: bool = False, disable_geoip: bool = True, is_server: bool = True, historical_migration: bool = False, super_properties: Optional[dict[str, Any]] = None, super_options: Optional[dict[str, Any]] = None, before_send=None, log_captured_exceptions: bool = False, project_root: Optional[str] = None, capture_exception_code_variables: bool = False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: Optional[list[str]] = None, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = AI_MAX_MSG_SIZE, privacy_mode: bool = False, enable_full_ai_capture: bool = False, capture_trace_context: bool = False, secret_key: Optional[str] = None, personal_api_key: Optional[str] = None, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries: int = 1, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2, migrated_from: Optional[str] = None) -> None ``` ### `AsyncClient.capture` @@ -1902,10 +1948,10 @@ unless the event, a context tag or `super_properties` sets either one. emails: AsyncEmails ``` -Send transactional email from PostHog email templates, and read the -status of each email sent with `get`. +Send transactional email from PostHog email templates or from content +in your code, and read the status of each email sent with `get`. -Needs `secret_key`, a project secret API key with the `hog_flow:write` +Needs `secret_key`, a project secret API key with the `transactional_email:write` scope, and `posthog[async]`. Sends go to `app_host`, or to the PostHog Cloud app host of `host`. `email_request_timeout_seconds` and `email_request_max_retries` configure each send. A disabled or shut-down @@ -2211,7 +2257,10 @@ Set a capture option for every event captured within the current context. Context options fill options an event leaves unset, before `before_send` runs, so the hook sees them. They override `super_options`. An event's -own `options` override them, and `before_send` can change them. +own `options` override them, and `before_send` can change them. They +never set `process_person_profile` on identify-style events, such as +`$identify` or `$set`, whose distinct ID the SDK did not generate: +those default it to `True`. **Parameters:** @@ -2421,7 +2470,7 @@ Name | Type | Description | Default `uuid` | `Optional[str]` | Optional UUID for the event | `None` `disable_geoip` | `Optional[bool]` | Whether to disable GeoIP lookup | `None` `distinct_id` | `Optional[ID_TYPES]` | Optional distinct ID of the user performing the action | `None` -`options` | `Optional[Dict[str, Any]]` | Optional capture options for the event, sent as given | `None` +`options` | `Optional[Dict[str, Any]]` | Optional capture options for the event, sent as given. `process_person_profile` is `True` unless this call sets it. | `None` **Examples:** @@ -2451,7 +2500,7 @@ Name | Type | Description | Default `timestamp` | `Optional[Union[datetime, str]]` | Optional timestamp for the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. | `None` `uuid` | `Optional[str]` | Optional UUID for the event | `None` `disable_geoip` | `Optional[bool]` | Whether to disable GeoIP lookup | `None` -`options` | `Optional[Dict[str, Any]]` | Optional capture options for the event, sent as given | `None` +`options` | `Optional[Dict[str, Any]]` | Optional capture options for the event, sent as given. `process_person_profile` is `True` unless this call sets it. | `None`
Details @@ -3048,7 +3097,7 @@ Name | Type | Description | Default `flags` | | A `FeatureFlagEvaluations` snapshot from `evaluate_flags()`. The exact flag values from the snapshot are attached to the event with no additional network call — prefer this over `send_feature_flags`. | `send_feature_flags` | | Deprecated — prefer `flags` with a `FeatureFlagEvaluations` snapshot. Whether to include currently active feature flags in the event properties. Can be a boolean or a SendFeatureFlagsOptions object. Defaults to False. Fires a hidden `/flags` request on capture and may return different values than the ones the code branched on. | `disable_geoip` | | Whether to disable GeoIP lookup for this event. Defaults to False. | -`options` | | Capture options for this event, such as `{"process_person_profile": False}`. Sent as given, for PostHog to validate. An option wins over its legacy `$` property, such as `$process_person_profile`. A value that is not a dict is logged and ignored. | +`options` | | Capture options for this event, such as `{"process_person_profile": False}`. Sent as given, for PostHog to validate. An option wins over its legacy `$` property, such as `$process_person_profile`. A value that is not a dict is logged and ignored. An identify-style event, such as `$identify` or `$set`, gets `process_person_profile: True` when this call leaves it unset, unless the SDK generated its distinct ID. | **Attributes:** @@ -3142,6 +3191,13 @@ To narrow the set of flags that get attached to a captured event, use the in-mem helpers `only` and `only_accessed`. To narrow the set of flags requested from the server in the first place, pass `flag_keys` to `Client.evaluate_flags`. +Reading a flag sends `$feature_flag_called`, deduplicated as `is_enabled` +describes. When the flag was evaluated remotely and its config version 2 record is +a complete experiment split (an experiment rule with a rule ID and a variant key), +the read also sends `$experiment_exposure`. The SDK sends one exposure per +distinct ID, groups, flag, rule and variant. `send_feature_flag_events=False` +suppresses both events. + **Functions:** Name | Description @@ -3590,7 +3646,7 @@ reason: UnresolvedFlagReason = UnresolvedFlagReason.UNSUPPORTED_DEFINITION ### `CaptureError` ```python -CaptureError(status: int | str, message: str, *, endpoint: str, retry_after: Optional[float] = None, request_id: Optional[str] = None, attempts: Optional[int] = None, retry_exhausted: Optional[list[str]] = None, drops: Optional[list[tuple[str, Optional[str]]]] = None, event_results: Optional[dict[str, CaptureEventResult]] = None) +CaptureError(status: int | str, message: str, *, endpoint: str, retry_after: Optional[float] = None, request_id: Optional[str] = None, attempts: Optional[int] = None, retry_exhausted: Optional[list[str]] = None, drops: Optional[Sequence[tuple[str, Optional[str]]]] = None, event_results: Optional[dict[str, CaptureEventResult]] = None) ``` Bases: `APIError` @@ -3606,6 +3662,9 @@ events were dropped or ran out of retries. response. Events missing from it never got a verdict, because every attempt that reached them failed as a whole request. +`drops` lists each event the server dropped on a 2xx response as a +`CaptureDroppedEvent`. + **Functions:** Name | Description @@ -3635,7 +3694,7 @@ attempts = attempts #### `posthog.capture_send.CaptureError.drops` ```python -drops = drops or [] +drops = [(CaptureDroppedEvent(*drop)) for drop in (drops or [])] ``` #### `posthog.capture_send.CaptureError.endpoint` @@ -3778,6 +3837,12 @@ may lose its cause). Returns the span, so calls chain. Inside `with span:` a raised `Exception` is recorded automatically, so this is for exceptions that are caught and handled. +The stack trace contains file paths from your server. Remove +`exception.stacktrace` in `before_span_send` to keep them in your +process. The `exception` event uses one of the span's event slots. A +span whose event slots are full keeps its `error` status and the +exception message, but loses the exception type and stack trace. + **Examples:** ```python @@ -3876,12 +3941,12 @@ span.update_name(f"{request.method} {route.pattern}") ### `Emails` ```python -Emails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, session: Optional[requests.Session] = None) -> None +Emails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, session: Optional[requests.Session] = None, migrated_from: Optional[str] = None) -> None ``` Bases: `_EmailsBase` -Sends transactional email from PostHog email templates. +Sends transactional email from PostHog email templates or from content in your code. `host` is your PostHog app host. PostHog Cloud ingestion hosts map to the app host, so `us.i.posthog.com` sends to `us.posthog.com`. Any other @@ -3891,7 +3956,8 @@ Each send retries network errors, rate limits and an unavailable service up to `max_retries` times, with the same idempotency key. Set `max_retries=0` when a job runner already retries the send. `timeout` is in seconds, per request. Pass `session` to send through your own -`requests.Session`, for example a test double. +`requests.Session`, for example a test double. `migrated_from`, such +as `"resend"`, tells PostHog which provider your sends came from. **Functions:** @@ -3899,7 +3965,7 @@ Name | Description ---- | ----------- `close` | Close the HTTP connections this client opened. A `session` you passed in stays open. `get` | Read what happened to an email that `send` queued. -`send` | Queue one email from a transactional email template. +`send` | Queue one email, from a template in PostHog or from content in your code. **Attributes:** @@ -3908,6 +3974,7 @@ Name | Type | Description `disabled` | | `host` | | `max_retries` | | +`migrated_from` | | `secret_key` | | `timeout` | | @@ -3973,6 +4040,12 @@ host = determine_app_host(host) max_retries = max_retries ``` +#### `posthog.emails.Emails.migrated_from` + +```python +migrated_from = migrated_from +``` + #### `posthog.emails.Emails.secret_key` ```python @@ -3982,21 +4055,26 @@ secret_key = secret_key.strip() if isinstance(secret_key, str) else None #### `posthog.emails.Emails.send` ```python -send(*, to: str, template_id: Union[str, UUID], template_data: Optional[Mapping[str, Any]] = None, distinct_id: Optional[str] = None, idempotency_key: Optional[str] = None, max_retries: Optional[int] = None) -> SendEmailResult +send(**kwargs: Any) -> SendEmailResult ``` -Queue one email from a transactional email template. +Queue one email, from a template in PostHog or from content in your code. + +Pass exactly one form. The template form names a template made in +PostHog with `template_id`. The code form names the email with +`template_key` and passes `subject` and `html`, `text` or both: +see `CodeEmailArgs`. **Parameters:** Name | Type | Description | Default ---- | ---- | ----------- | ------- -`to` | `str` | One recipient email address. | *required* -`template_id` | `Union[str, UUID]` | The UUID of a template made transactional in PostHog. | *required* -`template_data` | `Optional[Mapping[str, Any]]` | Values for the template's `{{ variables.* }}` placeholders. Values are encoded the way capture encodes properties. | `None` -`distinct_id` | `Optional[str]` | The recipient's distinct ID in your product. The email's events go to this person. Without it, they go to a person whose distinct ID is the email address. | `None` -`idempotency_key` | `Optional[str]` | 1 to 255 visible ASCII characters. A send with a key that PostHog has already accepted queues nothing and returns the first send's result. Without it, the client makes a key that covers its own retries. Pass a key derived from what the email is for, such as `welcome:user_123`, to cover retries outside this call, too. | `None` -`max_retries` | `Optional[int]` | Overrides the client's maximum number of retries for this send. `0` turns retries off. | `None` +`to` | | One recipient email address. | +`template_id` | | The UUID of a template made transactional in PostHog. | +`template_data` | | Values for the template's `{{ variables.* }}` placeholders. Values are encoded the way capture encodes properties. | +`distinct_id` | | The recipient's distinct ID in your product. The email's events go to this person. Without it, they go to a person whose distinct ID is the email address. | +`idempotency_key` | | 1 to 255 visible ASCII characters. A send with a key that PostHog has already accepted queues nothing and returns the first send's result. Without it, the client makes a key that covers its own retries. Pass a key derived from what the email is for, such as `welcome:user_123`, to cover retries outside this call, too. | +`max_retries` | | Overrides the client's maximum number of retries for this send. `0` turns retries off. | **Returns:** @@ -4021,6 +4099,13 @@ emails.send( distinct_id="user_123", idempotency_key="welcome:user_123", ) +emails.send( + to="user@example.com", + template_key="password-reset", + subject="Reset your password", + html=rendered_html, + distinct_id="user_123", +) ``` #### `posthog.emails.Emails.timeout` @@ -4160,7 +4245,7 @@ Name | Type | Description | Default `timestamp` | | When the properties were set (defaults to current time). UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC. | `uuid` | | Unique identifier for this operation. If not provided, one is generated. This UUID is returned, so you can correlate it with actions in your app. If provided, it must be a valid UUID string or uuid.UUID instance; invalid values are ignored and replaced with a newly generated UUID. | `disable_geoip` | | Whether to disable GeoIP lookup for this operation. Defaults to False. | -`options` | | Capture options for this event, sent as given. See `OptionalCaptureArgs`. | +`options` | | Capture options for this event, sent as given. See `OptionalCaptureArgs`. `process_person_profile` is `True` unless this call sets it. | **Attributes:** @@ -4208,3 +4293,112 @@ timestamp: NotRequired[Optional[Union[datetime, str]]] ```python uuid: NotRequired[Optional[Union[str, UUID]]] ``` + +### `CodeEmailArgs` + +Bases: `_RecipientArgs` + +A send of email content that your code rendered for one recipient, named by a key. + +The content goes out as is. To send a React email, render it to HTML in +your app first. + +An optional field passed as `None` counts as left out. + +**Parameters:** + +Name | Type | Description | Default +---- | ---- | ----------- | ------- +`to` | | One recipient email address. | +`template_key` | | Names the email, so its metrics, logs and status group under it. Letters, digits, `-` and `_`, at most 400. | +`subject` | | The subject line. | +`html` | | The HTML body. Give `html`, `text` or both. | +`text` | | The plain-text body. Without it, PostHog derives it from `html`. HTML with no text in it, such as a single image, goes out without a plain-text part. | +`from_` | | A verified sender, such as `"Acme "`. | +`reply_to` | | One address or a list of addresses. An empty list sends no reply-to. | +`capture_engagement` | | Capture the email's opens and clicks as events of the recipient. Defaults to `True`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. | +`distinct_id` | | The recipient's distinct ID in your product. | +`idempotency_key` | | 1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for another email, or for a `template_id` send, raises `idempotency_key_reused`. A retry with the same key returns the first send's result, also when its workflow was paused since. | +`max_retries` | | Overrides the client's maximum number of retries for this send. `0` turns retries off. | + +**Attributes:** + +Name | Type | Description +---- | ---- | ----------- +`capture_engagement` | `NotRequired[Optional[bool]]` | +`distinct_id` | `NotRequired[Optional[str]]` | +`from_` | `NotRequired[Optional[str]]` | +`html` | `NotRequired[Optional[str]]` | +`idempotency_key` | `NotRequired[Optional[str]]` | +`max_retries` | `NotRequired[Optional[int]]` | +`reply_to` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | +`subject` | `str` | +`template_key` | `str` | +`text` | `NotRequired[Optional[str]]` | +`to` | `str` | + +#### `posthog.emails.CodeEmailArgs.capture_engagement` + +```python +capture_engagement: NotRequired[Optional[bool]] +``` + +#### `posthog.emails.CodeEmailArgs.distinct_id` + +```python +distinct_id: NotRequired[Optional[str]] +``` + +#### `posthog.emails.CodeEmailArgs.from_` + +```python +from_: NotRequired[Optional[str]] +``` + +#### `posthog.emails.CodeEmailArgs.html` + +```python +html: NotRequired[Optional[str]] +``` + +#### `posthog.emails.CodeEmailArgs.idempotency_key` + +```python +idempotency_key: NotRequired[Optional[str]] +``` + +#### `posthog.emails.CodeEmailArgs.max_retries` + +```python +max_retries: NotRequired[Optional[int]] +``` + +#### `posthog.emails.CodeEmailArgs.reply_to` + +```python +reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] +``` + +#### `posthog.emails.CodeEmailArgs.subject` + +```python +subject: str +``` + +#### `posthog.emails.CodeEmailArgs.template_key` + +```python +template_key: str +``` + +#### `posthog.emails.CodeEmailArgs.text` + +```python +text: NotRequired[Optional[str]] +``` + +#### `posthog.emails.CodeEmailArgs.to` + +```python +to: str +``` diff --git a/references/posthog-python-migration.md b/references/posthog-python-migration.md index 1c6c18564..5059a5f2a 100644 --- a/references/posthog-python-migration.md +++ b/references/posthog-python-migration.md @@ -1,269 +1,499 @@ --- -title: PostHog Python SDK migration guides +title: "Migrate the Python SDK from 7.x.x to 8.0.0" sidebar: Docs showTitle: true --- -# Migrating from posthog 7.x to 8.0 +The Python SDK 8.x.x sends every event to the [capture v1](https://posthog.com/docs/api/capture-v1) endpoints, `/i/v1/analytics/events` and `/i/v1/ai/events`, and removes the legacy capture path. Most apps upgrade without code changes. -posthog 8.0 sends every event through capture v1 and removes the legacy capture path. -Most apps upgrade without code changes. -Read the checklist first, then the sections that apply to you. +Use the top right copy page button to work through this with your agents. + +You don't need to make every change on the day you upgrade your SDK. Required changes fall in these categories: -For the changes every capture v1 SDK shares, such as event options, limits and per-event results, see [Upgrading to capture v1 SDKs](https://posthog.com/docs/libraries/capture-v1). +- **Before you upgrade**: you should make these changes before you upgrade your SDK to 8.x.x. +- **During your upgrade**: These are changes that you need to make in the same PR that upgrades your SDK version. +- **Follow ups**: These are changes that can come in follow up PRs because 8.x.x has limited backward compatibility for methods that are to be deprecated. ## Checklist -You need to change code if your app does any of these: - -- passes `Client` or `AsyncPosthog` constructor arguments by position after `host` -- calls `posthog.request.post` or `posthog.request.flags` with positional arguments after `path` or `host` -- sets `$exception_level` or another reserved exception property in `capture_exception(properties=...)` -- sets `capture_mode`, `POSTHOG_CAPTURE_MODE` or `gzip` -- imports `CaptureMode`, `posthog.capture_mode`, `CaptureV1Error`, `posthog.capture_v1`, `request.batch_post`, `EVENTS_ENDPOINT` or `AI_EVENTS_ENDPOINT` -- sends events to a self-hosted PostHog that does not serve the capture v1 endpoints -- sends events through a proxy that redirects capture requests to another host -- reuses one event `uuid` for more than one event -- sets `$process_person_profile` to turn person processing on for events without a distinct ID -- passes strings such as `"true"` for `$cookieless_mode`, `$ignore_sent_at` or `$process_person_profile` -- expects `super_properties` to override properties passed to a single call, including `$set` and `$groups` -- sets `$is_server`, `$geoip_disable` or a system property such as `$os` and expects the SDK's value to win -- tests the AI integrations with a mock client and asserts on `capture` -- passes its own client object to the AI integrations -- sets `$lib` or `$lib_version`, or filters on `$lib = "posthog-python-mcp"` -- passes a personal API key (`phx_...`) as the project API key -- reads event content from the SDK's debug log -- calls `alias()` without a `distinct_id` and relies on the context distinct ID -- runs the Django, Flask or ASGI integration on 7.68 to 7.70 without tracing headers turned on (they are now read by default) - -## Endpoints +Read the checklist first, then the sections that apply to you. + +**Before you upgrade** + +- [ ] You send events through your own proxy → [Prepare your proxy](#prepare-your-proxy) +- [ ] A proxy redirects capture requests to another host → [Prepare your proxy](#prepare-your-proxy) +- [ ] You pass a personal API key (`phx_...`) as the project token → [Use a project token](#use-a-project-token) +- [ ] You use `openfeature-provider-posthog` below 0.2.0 → [Update OpenFeature](#update-openfeature) + +**During your upgrade** + +- [ ] You pass `Client` or `AsyncPosthog` constructor arguments by position after `host` → [Fix removed APIs](#fix-removed-apis) +- [ ] You call `posthog.request.post` or `posthog.request.flags` with positional arguments after `path` or `host` → [Fix removed APIs](#fix-removed-apis) +- [ ] You set `capture_mode`, `POSTHOG_CAPTURE_MODE`, or `gzip` → [Fix removed APIs](#fix-removed-apis) +- [ ] You import `CaptureMode`, `posthog.capture_mode`, `CaptureV1Error`, `posthog.capture_v1`, `request.batch_post`, `EVENTS_ENDPOINT`, or `AI_EVENTS_ENDPOINT` → [Fix removed APIs](#fix-removed-apis) +- [ ] Your `before_send` hook returns a new dict, in the client or in MCP → [Copy options in before_send](#copy-options-in-before_send) +- [ ] You test the AI integrations with a mock client and assert on `capture` → [Route AI events](#route-ai-events) +- [ ] You pass your own client object to the AI integrations → [Route AI events](#route-ai-events) +- [ ] You call `alias()` without a `distinct_id` and rely on the context distinct ID → [Fix identity calls](#fix-identity-calls) +- [ ] You turn person processing off with `super_options`, `super_properties`, a context option, or a context tag, and expect identify-style events, such as those from `alias`, `group_identify`, `set`, or `set_once`, to follow it → [Fix identity calls](#fix-identity-calls) +- [ ] You reuse one event `uuid` for more than one event → [Check event IDs](#check-event-ids) +- [ ] You expect `super_properties` to override a call's properties, including `$set` and `$groups` → [Check property precedence](#check-property-precedence) +- [ ] You set `$is_server`, `$geoip_disable`, or a system property such as `$os`, and expect the SDK's value to win → [Check property precedence](#check-property-precedence) +- [ ] You set `$lib` or `$lib_version` yourself → [Check SDK identity](#check-sdk-identity) +- [ ] An insight or dashboard filters on `$lib = posthog-python-mcp` → [Check SDK identity](#check-sdk-identity) +- [ ] You read event content from the SDK's debug log, or alert on SDK log lines → [Update error handling](#update-error-handling) +- [ ] You set `$exception_level` or another reserved exception property in `capture_exception(properties=...)` → [Check exceptions](#check-exceptions) +- [ ] You run the Django, Flask, or ASGI integration on 7.68.x to 7.70.x without tracing headers turned on → [Check tracing headers](#check-tracing-headers) + +**Follow ups** + +- [ ] You set legacy option properties like `$process_person_profile` → [Move to event options](#move-to-event-options) +- [ ] You capture `$ai_` events with `capture()` → [Send AI events with capture_ai](#send-ai-events-with-capture_ai) +- [ ] You use `trust_tracing_headers` or `_use_ai_lane`, set `posthog.capture_mode`, or pass a `gzip=` keyword to `request.post` → [Rename deprecated settings](#rename-deprecated-settings) + +## Before you upgrade + +### Prepare your proxy + +8.x.x sends events to these endpoints: | Method | Endpoint | | --- | --- | -| `capture`, `set`, `set_once`, `alias`, `group_identify`, `capture_exception` | `/i/v1/analytics/events` | +| `capture`, `set`, `set_once`, `alias`, `group_identify`, `capture_exception`, `AsyncPosthog.capture_immediate` | `/i/v1/analytics/events` | | `capture_ai`, `capture_ai_immediate`, and the AI wrapper integrations | `/i/v1/ai/events` | | OpenTelemetry (`posthog.ai.otel`) | `/i/v0/ai/otel`, unchanged | -If you send events to a self-hosted PostHog, check that it serves both endpoints before you upgrade. -An endpoint that is not served drops every event sent to it. - If you send events through your own reverse proxy, update it before you upgrade: -- Forward `/i/v1/analytics/events` and `/i/v1/ai/events` to PostHog. -- Pass `Authorization` (the project token, sent as `Bearer `), every `PostHog-*` header, `Content-Type`, `Content-Encoding` and `User-Agent` through unchanged. PostHog answers `401` without `Authorization` and `400` without the others, and the batch fails. -- Accept request bodies up to 20 MB. AI requests are often larger than 1 MB, the default limit in nginx and ingress-nginx. A `413` from the proxy fails the batch. +- **Forward both routes.** Forward `/i/v1/analytics/events` and `/i/v1/ai/events` to PostHog. +- **Pass the headers through unchanged.** Pass `Authorization`, every `PostHog-*` header, `Content-Type`, `Content-Encoding`, and `User-Agent`. `Authorization` holds the project token, sent as `Bearer `. PostHog answers `401` without `Authorization` and `400` without the others, and the batch fails. +- **Accept request bodies up to 20 MB.** AI requests are often larger than 1 MB, the default limit in nginx and ingress-nginx. A `413` from the proxy fails the batch. +- **Pass the capture response through.** Return PostHog's status code and response body unchanged. A proxy that answers the capture path with its own `200` fails the batch. PostHog's managed reverse proxy already does this. See the [proxy guides](https://posthog.com/docs/advanced/proxy). -The SDK follows a `307` or `308` redirect only to the origin of `host` (same scheme, host and port), at most 5 times. -Any other redirect fails the batch and reaches `on_error`. -In 7.x the sync client followed redirects to any origin. +The SDK follows a `307` or `308` redirect only to the origin of `host`, at most 5 times. The origin is the same scheme, host, and port. + +Any other redirect fails the batch and reaches `on_error`. In 7.x.x the sync client followed redirects to any origin. + If a proxy redirects capture requests to another host, point `host` at the final host. -## SDK identity +### Use a project token + +A personal API key (`phx_...`) passed as the project token disables the client and logs one error, as an empty key does. Capture rejects personal API keys, and the SDK no longer sends one with every request. + +### Update OpenFeature -PostHog sets `$lib` and `$lib_version` on every event from the `PostHog-Sdk-Info` request header, which is always `posthog-python/`. -The SDK removes `$lib` and `$lib_version` from the properties it sends. -A value you set in a call, in `super_properties` or in `before_send` does not reach PostHog. +`openfeature-provider-posthog` 0.2.0 works with `posthog` 7.x.x and 8.x.x. Older provider versions require `posthog` below 8.0.0, so upgrade the provider before or with `posthog`. -MCP instrumentation no longer relabels the client. -In 7.x, `posthog.mcp.instrument()` and `PostHogMCP` set the client's identity to `posthog-python-mcp`. -With the default client, or any client the app also used, every event and feature flag request from the app then reported `posthog-python-mcp`, not only the MCP events. -In 8.0, MCP events report `posthog-python` like all other events. -To find MCP traffic, filter on the `$mcp_*` events and properties instead of `$lib`. +## During your upgrade -## Removed options and APIs +### Fix removed APIs + +8.x.x removes these options and APIs: | Removed | Use instead | | --- | --- | -| `capture_mode`, `CaptureMode`, `POSTHOG_CAPTURE_MODE` | Nothing. Capture v1 is the only path. Setting `posthog.capture_mode` on the module has no effect. | -| `gzip=True` | `capture_compression=CaptureCompression.GZIP`. The default is no compression. `POSTHOG_CAPTURE_COMPRESSION` still works. | -| `CaptureV1Error` (`from posthog.capture_v1 import CaptureV1Error`) | `CaptureError` (`from posthog import CaptureError`). There is no alias. | +| `capture_mode`, `CaptureMode`, `POSTHOG_CAPTURE_MODE` | Nothing | +| `gzip=True` | `capture_compression` | +| `CaptureV1Error` | `CaptureError` | | `posthog.capture_v1` | `posthog.capture_event` and `posthog.capture_send` | -| `request.batch_post`, `async_batch_post`, `EVENTS_ENDPOINT`, `AI_EVENTS_ENDPOINT` | Nothing. Send events through a client. | -| The `gzip` parameter of `request.post` and `request.flags` | Nothing. The parameters after `path` in `post` and after `host` in `flags` are keyword-only, so a 7.x call that passes them by position raises `TypeError`. A `gzip=` keyword raises no error: it is sent as a field in the request body. | -| The `backoff` dependency | Add it to your own requirements if your code imports it. | +| `request.batch_post`, `async_batch_post`, `EVENTS_ENDPOINT`, `AI_EVENTS_ENDPOINT` | Send events through a client | +| The `gzip` parameter of `request.post` and `request.flags` | Nothing | +| The `backoff` dependency | Your own requirements, if your code imports it | + +Capture v1 is the only path. Setting `posthog.capture_mode` on the module has no effect. + +For gzip, set `capture_compression=CaptureCompression.GZIP`. `capture_compression` defaults to no compression. `POSTHOG_CAPTURE_COMPRESSION` still works. + +`capture_compression` and `capture_ai_compression` take `CaptureCompression.GZIP`, `DEFLATE`, or `ZSTD`. `ZSTD` needs the `zstandard` package, so install `posthog[zstd]`. Without it, the client raises `ValueError`. + +Replace `from posthog.capture_v1 import CaptureV1Error` with `from posthog import CaptureError`. There is no alias. + +The parameters after `path` in `request.post` and after `host` in `request.flags` are keyword-only, so a 7.x.x call that passes them by position raises `TypeError`. A `gzip=` keyword raises no error. It's sent as a field in the request body. The `posthoganalytics` package has the same changes. For example, import `CaptureError` from `posthoganalytics`. Constructor arguments after `host` are keyword-only: ```python -# 7.x +# 7.x.x Posthog("", "https://us.i.posthog.com", True) -# 8.0 +# 8.x.x Posthog("", host="https://us.i.posthog.com", debug=True) ``` -## Errors and `on_error` - -Capture v1 returns a result for every event, even when the request succeeds. -An event can be dropped inside a 2xx response, for example when it is over a product quota. -8.0 reports those events as failures. -When the whole request is over the billing limit, capture returns a `402` with no per-event results instead. - -- Every capture failure is a `CaptureError`, a subclass of `APIError`. It has these fields: - - `status`: the HTTP status, or `0` when the request never got a response. With `0`, `__cause__` holds the network error. In 7.x, `on_error` received the raw `requests` exception. - - `endpoint`, `request_id` and `attempts` - - `drops`: `(uuid, details)` pairs for the events capture dropped in a 2xx response - - `retry_exhausted`: the uuids still waiting for a retry after the last attempt - - `event_results`: a `CaptureEventResult(result, details)` for each uuid that got a result in a 2xx response, from `posthog.capture_send`. An event missing from it never got a result. - - `verdict_summary()`: counts such as `drop/llm_events_over_quota=1, retry/not_persisted=1` -- `on_error(error, batch)` receives every failure, including in `sync_mode` and from `AsyncPosthog.capture_immediate`. -- With `on_error` set, the SDK logs nothing for a failed batch. -- Without `on_error`, the SDK logs one line per failed batch, for example `2 event(s) not persisted by /i/v1/analytics/events: ...`. The line never contains event content or the server's response text. After a 2xx response it also counts the lost events by PostHog's reason, for example `drop/event_too_big=1`. -- The 7.x lines `error uploading: ...`, `async capture upload failed (...)` and `Immediate async capture failed (...)` are gone. In `sync_mode`, a failed request no longer logs the 7.x `Error in capture: ...` line, or the same line for another method. Update any log-based alerts that match these lines. -- In `sync_mode`, a failed `capture()` calls `on_error` and returns `None`. With `debug=True` it calls `on_error` and then re-raises the error. -- In `sync_mode`, a failed request is retried like a background batch, in the calling thread. With the default `max_retries` of 3, a call makes up to 4 attempts, and each attempt can take up to `timeout` (`capture_ai_timeout` for AI events). With the defaults, an analytics event whose requests keep timing out blocks the call for about a minute. 7.x made one attempt. -- If a capture inside `on_error` fails, the SDK logs the failure and does not call `on_error` again. -- The SDK retries `404`, `408`, `429`, `500`, `502`, `503` and `504` responses and network errors. Other error statuses fail the batch at once, including the other 5xx codes. 7.x retried `429` and every 5xx, but not `404`. Capture itself does not return `429`; a proxy in front of it can. A `404` that lasts through every attempt can mean the PostHog deployment has no capture v1 route, for example an older self-hosted install. -- Each attempt makes one connection try. 7.x also retried a failed connection up to twice inside each attempt, so a capture request could block for up to three times the `timeout` per attempt. -- Retries start at 100 ms and double each attempt, up to 30 seconds. Each wait varies randomly by up to 25%, so many clients do not retry at the same moment. A `Retry-After` header sets a minimum wait, up to 30 seconds. The `Consumer` default is 3 retries, down from 10. In 7.x the first retry waited up to 1 second. -- The SDK's own log lines no longer contain event content: the debug line for a queued event names the event and the lane, and the invalid timestamp warning no longer includes the value. When your `before_send` hook raises, the error line names the event and the exception type, not the exception message, which can hold the data the hook was removing. The traceback is logged at debug level. To inspect events, use `before_send`. -- A personal API key (`phx_...`) passed as the project API key disables the client and logs one error, as an empty key does. Capture rejects personal API keys, and the SDK no longer sends one with every request. - -## Invalid events - -Capture rejects a whole batch when one event cannot be parsed. -8.0 drops only the invalid event, so the rest of the batch is delivered. - -- An event whose name is missing, `None`, empty or not a string is dropped. The SDK logs one warning per reason per process. 7.x sent it. -- An event whose `before_send` hook sets `distinct_id` to `None` or a non-string is dropped, with one warning per reason per process. The SDK does not convert the hook's value or make up an ID. 7.x sent it, and capture would reject the whole batch. -- PostHog drops an event whose name is over 200 UTF-8 bytes (`event_name_too_long`), and `on_error` reports it. 7.x sent events to legacy capture, which had no event name limit. -- A `NaN` or infinite `float` value is sent as `null`, as in 7.75 and later, and the event is kept. Earlier 7.x versions sent invalid JSON, which made capture reject the whole batch. A `NaN` value in `$set` sets that person property to `null`. -- An event that cannot be serialized to JSON, for example one with a circular reference, is dropped and logged. As in 7.x, a circular reference logs `Error in capture: maximum recursion depth exceeded` with a long traceback. -- A property or option key that JSON cannot represent, such as a tuple, is dropped without a log, and the rest of the event is sent. 7.x dropped the event. `int`, finite `float`, `bool` and `None` keys are still converted to strings. A `NaN` or infinite `float` key still drops the event. - -## Event uuids - -- Each event needs its own uuid. Capture keeps the first event for each uuid in a request and drops the later copies. `on_error` reports each dropped copy in `CaptureError.drops` as `(uuid, "duplicate_event_uuid")`. 7.x sent every copy. Older PostHog versions reject the whole batch with a 400 `duplicate_event_uuid` instead. -- The SDK accepts a uuid with hyphens, 32 hex digits, `{...}` braces or a `urn:uuid:` prefix, in any case. It sends the lowercase hyphenated form and returns that form from `capture`. -- Any other value is replaced with a generated uuid, and the SDK logs one warning that names the rule, not the value. An empty string counts as unset, so the SDK generates a uuid without a warning. This applies to `AsyncPosthog` too. -- Generated uuids are UUIDv7. - -## Session and window IDs - -Capture v1 sends `$session_id` and `$window_id` as top-level event fields, not as properties. -The SDK moves them out of `properties` for you. - -- A string is sent as given, including `""`. -- `None` counts as unset and is removed. -- Any other value is removed and not sent, because capture would reject the whole batch. 7.x sent it as a property. The SDK logs a warning for each one, with the key and the value's type but not the value. - -## Identity and request context - -- An empty or whitespace-only `distinct_id` counts as missing, so the event gets a generated personless distinct ID. 7.x sent a whitespace-only ID, and capture dropped the event. -- Generated personless distinct IDs are UUIDv7. 7.x generated UUIDv4. -- `group_identify` uses the `distinct_id` you pass, then the context distinct ID, then `$_`. 7.x fell back to a random ID, which created a new person on every call. If `$_` is over 200 bytes, pass `distinct_id`: PostHog drops an event whose distinct ID is over 200 bytes. -- PostHog drops an event whose `distinct_id` is over 200 UTF-8 bytes (`distinct_id_too_large`), and `on_error` reports it. 7.x sent events to legacy capture, which shortened the ID to 200 characters and kept the event. -- `group_identify` no longer adds the context session ID. A session takes the person of its latest event, and this event's distinct ID is not the session's user. -- `alias()` needs an explicit `distinct_id`. It no longer falls back to the context distinct ID, which can come from a request header the client controls. Without one, the call is dropped with a warning. -- Context tags and context options now apply to `alias` and `group_identify`, below the call's own values, as they do for `capture`. -- Person processing turned off in the context, with `set_context_option("process_person_profile", False)` or a `$process_person_profile` tag, or in `super_options`, now applies to `$create_alias` and `$groupidentify` events too. A `$process_person_profile: False` in `super_properties` already did this in 7.x. PostHog drops these events when person processing is off, with an ingestion warning. Capture accepts them, so `on_error` does not report the drop. To keep them, turn person processing off per call instead. - -## Tracing headers - -The Django, Flask and ASGI integrations read the `X-PostHog-Distinct-Id` and `X-PostHog-Session-Id` headers by default, as in 7.71 and later. -The headers only fill a missing distinct ID or session ID, and any client can set them, so never use them for authentication. - -- To turn this off, set `POSTHOG_MW_CAPTURE_TRACING_HEADERS = False` in Django, or pass `capture_tracing_headers=False` to the Flask or ASGI integration. -- The 7.68 `trust_tracing_headers` and `POSTHOG_MW_TRUST_TRACING_HEADERS` names still work, but are deprecated. -- If you upgrade from 7.68, 7.69 or 7.70 and never turned these headers on, they are now read. - -## Exceptions - -- `capture_exception` takes a `level=` argument on `Client`, `AsyncPosthog` and the module. It sets `$exception_level`, for example `"warning"` or `"fatal"`. The default is `"error"`, and an unknown value counts as unset. -- `capture_exception` ignores reserved exception properties in `properties`, such as `$exception_list`, `$exception_level` and `$exception_source`. In 7.x they overrode the SDK's values, with a `DeprecationWarning`. Use `level=` instead of `$exception_level`. -- `AsyncPosthog.capture_exception` now sends `$exception_level`. -- `AsyncPosthog.capture_exception` now adds `$trace_id` and `$span_id` from the active OpenTelemetry span, like `Client.capture_exception`. In 7.x it added them only with `capture_trace_context=True`. - -## Event options - -Capture v1 sends processing options in an `options` object, next to `properties`. - -- `capture`, `capture_ai`, `set`, `set_once`, `alias`, `group_identify` and `capture_exception` take an `options` argument: - - ```python - posthog.capture("signed_up", distinct_id="user-1", options={"cookieless_mode": True}) - ``` - -- `super_options`, a new `Client`, `AsyncPosthog` and module setting, sets options on every event, like `super_properties`. -- `set_context_option(key, value)` sets an option for the current context, like `tag()`. `get_context_options()` returns the options of the current context. Both exist on `Client` and as module functions. `AsyncPosthog` has no context methods, like it has no `tag()`, so call the module functions. They apply to every client in the context. -- Context tags and options reach `capture`, `capture_ai`, `capture_exception`, `alias` and `group_identify`. Context options also reach `set` and `set_once`. `super_properties` and `super_options` reach every method. -- Options are sent as given. PostHog validates them. It drops an event with an option value it cannot read, such as a list for `cookieless_mode`, as `invalid_options`, and `on_error` reports it. -- An `options` value that is not a dict is logged as an error and ignored. The event is still sent. -- The legacy option properties, the `$`-prefixed properties legacy capture reads as settings, still work. They fill the matching option only when it is unset, and the SDK always removes them from `properties`. Their values are no longer converted, so pass `True` or `False`, not `"true"`. - - | Legacy option property | Option | - | --- | --- | - | `$cookieless_mode` | `cookieless_mode` | - | `$ignore_sent_at` | `disable_skew_correction` | - | `$product_tour_id` | `product_tour_id` | - | `$process_person_profile` | `process_person_profile` | - -- An option set at any layer wins over its legacy property set at any layer. For example, `super_options={"cookieless_mode": True}` wins over an event's `$cookieless_mode: False`. When you move a default to options, move the per-event overrides of that key to options too. -- A `None` option counts as unset, so a later step can fill it. - -Values apply in this order. Steps 2 to 4 fill only the options and properties that the steps before them left unset: - -1. the `options` and `properties` of the call, then the call's `disable_geoip` argument, which fills `$geoip_disable` -2. context options and tags -3. `super_options` and `super_properties` -4. values the SDK sets: `$is_server` from `is_server`, `$geoip_disable` from the client's `disable_geoip` setting, system properties such as `$os` and `$python_version`, the `$feature/` and `$active_feature_flags` properties from `flags` or `send_feature_flags`, `$trace_id` and `$span_id` from the active OpenTelemetry span (in `capture` and `capture_ai` only with `capture_trace_context=True`, and always in `capture_exception`), `options.process_person_profile = false` for events without a distinct ID, and `$release_id` from `POSTHOG_RELEASE_ID` -5. `before_send`, which sees the result of steps 1 to 4 and can change or remove any of it -6. legacy properties, which fill unset options and are then removed +### Copy options in before_send + +Review your `before_send` hooks for the new event shape. Capture v1 sends processing options in an `options` object, next to `properties`. + +To change an option, edit `options`. A hook that returns a new dict must copy `options`, or the event is sent without them. + +That includes the `process_person_profile = false` the SDK sets for an event without a distinct ID. Without it, PostHog would create a person for the event's generated ID. + +A hook that builds an identify-style event, or renames an event to one, must set the `process_person_profile` option itself (see [Fix identity calls](#fix-identity-calls)). + +A hook that spreads the event into the new dict keeps `options`: + +```python +def remove_email(event): + properties = {key: value for key, value in event["properties"].items() if key != "email"} + return {**event, "properties": properties} +``` + +The same applies to MCP's `before_send`. It gets each event's `options` in an `options` key of `PostHogCaptureEvent`. + +An MCP hook that returns a new dict must copy them, or the event is sent without the anonymous `process_person_profile: False`. + +### Route AI events -A property set to `None` counts as set, so no later step fills it. -`$set`, `$set_once`, `$groups` and `$group_set` fill one level deep. -When the call and a later step both set one of them to a dict, the later step adds only the keys the call left out. -For example, `super_properties={"$set": {"plan": "free", "source": "web"}}` and a call with `properties={"$set": {"plan": "pro"}}` send `{"plan": "pro", "source": "web"}`. +8.x.x routes AI events to their own endpoint: + +- **The endpoint.** `capture_ai` and the AI wrapper integrations send to `/i/v1/ai/events`. The AI endpoint accepts events up to 8 MiB. +- **Event names.** `capture_ai` sends any event name to the AI endpoint. PostHog drops an event whose name doesn't start with `$ai_` as `misrouted_event`, and `on_error` reports it. The SDK writes only a debug log. +- **Custom clients.** The AI integrations call your client's `capture_ai`, and never `capture`. A custom client object must implement `capture_ai` and accept its `options` keyword argument. +- **Clients without `capture_ai`.** The wrapper, callback handler, or tracing processor logs one error when you create it and captures no AI events. Provider calls still work. Before, such a client got `capture` calls. +- **Mock clients.** Tests that pass a `Mock` client to an AI integration must assert on `mock.capture_ai`, not `mock.capture`. +- **OpenTelemetry.** The OpenTelemetry integration (`PostHogSpanProcessor`, `PostHogTraceExporter`) is unchanged. It still exports spans over OTLP to `/i/v0/ai/otel`. +- **Content capture.** `enable_full_ai_capture` now controls only content: string truncation and media redaction. It no longer chooses the endpoint. +- **Fallback IDs.** When an AI integration or MCP falls back to a trace, run, or session ID, it turns person processing off with a per-event option. This is the only option the integrations set on their own. It wins over your `posthog_options`, `options`, `super_options`, and context options. `before_send` can still change it. +- **Empty distinct IDs.** An empty or whitespace-only distinct ID passed to an AI integration, such as `posthog_distinct_id=""`, counts as missing. The integration falls back the same way and turns person processing off. +- **Empty distinct IDs in 7.x.x.** An empty ID gave non-streaming wrapper calls a random personless ID. Streaming calls, embeddings, and LangChain used the trace or run ID with person processing on. OpenAI Agents already treated an empty ID as missing. Every integration sent a whitespace-only ID as given, with person processing on. +- **Async capture.** `AsyncPosthog` has `capture_ai` and `capture_ai_immediate`. It sends events with `requests` in a worker thread, and uses `httpx` only for feature flags and remote config. +- **Async content settings.** `AsyncPosthog` accepts `privacy_mode` and `enable_full_ai_capture`, with the same meaning as on `Client`. An AI integration given an `AsyncPosthog` client used to always truncate and redact media. + +`Client` and `AsyncPosthog` have new arguments for the AI lane: + +| Argument | Default | +| --- | --- | +| `capture_ai_compression` | No compression | +| `capture_ai_max_queue_size` | 1000 | +| `capture_ai_timeout` | 30 seconds | +| `capture_ai_max_event_bytes` | 8 MiB plus 64 KiB | + +`POSTHOG_CAPTURE_COMPRESSION` doesn't apply to `capture_ai_compression`. You can only lower `capture_ai_max_event_bytes`. + +The AI lane doesn't use `max_queue_size`, `timeout`, or `capture_compression`. An invalid `capture_ai_*` value raises `ValueError` when you create the client. + +The module-level client has no AI lane settings. To change them, create a `Client`. + +### Fix identity calls + +- **Empty IDs.** An empty or whitespace-only `distinct_id` counts as missing, so the event gets a generated personless distinct ID. 7.x.x sent a whitespace-only ID, and capture dropped the event. +- **Generated IDs.** Generated personless distinct IDs are UUIDv7. 7.x.x generated UUIDv4. +- **Group fallback.** `group_identify` uses the `distinct_id` you pass, then the context distinct ID, then `$_`. 7.x.x fell back to a random ID, which created a new person on every call. +- **Long group IDs.** If `$_` is over 200 bytes, pass `distinct_id`. PostHog drops an event whose distinct ID is over 200 bytes. +- **Long distinct IDs.** PostHog drops an event whose `distinct_id` is over 200 UTF-8 bytes (`distinct_id_too_large`), and `on_error` reports it. 7.x.x sent events to legacy capture, which shortened the ID to 200 characters and kept the event. +- **Group sessions.** `group_identify` no longer adds the context session ID. A session takes the person of its latest event, and this event's distinct ID isn't the session's user. +- **Alias.** `alias()` needs an explicit `distinct_id`. It no longer falls back to the context distinct ID, which can come from a request header the client controls. Without one, the SDK drops the call with a warning. +- **Context values.** Context tags and context options now apply to `alias` and `group_identify`, below the call's own values, as they do for `capture`. + +Identify-style events default to person processing on. These are `$identify`, `$create_alias`, `$merge_dangerously`, `$groupidentify`, `$set`, and `$set_once`, whether `alias`, `group_identify`, `set`, `set_once`, `capture`, or `capture_ai` sends them. + +The SDK sets `process_person_profile: True` on them unless the call sets the `process_person_profile` option, a `capture` or `capture_ai` call sets a `$process_person_profile` property, or the SDK generated the distinct ID. PostHog drops the `$create_alias` and `$groupidentify` events when person processing is off, with an ingestion warning, and ignores the person update of `$set` and `$set_once`. + +- **Call values.** The call's own value wins over context options and tags, `super_options`, and `super_properties`. So a `False` set there never reaches these events when the SDK didn't generate the distinct ID. In 7.x.x, `$process_person_profile: False` in `super_properties` reached them too. +- **Legacy property.** When a `capture` or `capture_ai` call sets only the `$process_person_profile` property, the SDK moves it into the option. The `properties` of `set`, `set_once`, and `group_identify` are person and group properties, so pass `process_person_profile` in the call's `options`. +- **`None` values.** A `None` option or property counts as unset here, so the event gets `True`. +- **Generated IDs.** An event whose distinct ID the SDK generated gets no default. Context options and `super_options` still fill it, then the personless `process_person_profile: False`. +- **`before_send`.** The hook sees the value and can change it. The SDK first removes any `$process_person_profile` property from these events, including one from a context tag or `super_properties`, so the hook sees only the option. +- **Built events.** A hook that builds an identify-style event, or renames an event to one, must set the option itself. + +To keep one of these events personless, set `process_person_profile: False` on the call or in `before_send`, or turn off person processing for the project in PostHog. + +### Check event IDs + +- **Duplicates.** Each event needs its own UUID. Capture keeps the first event for each UUID in a request and drops the later copies. `on_error` reports each dropped copy in `CaptureError.drops` as `(uuid, "duplicate_event_uuid")`. 7.x.x sent every copy. Older PostHog versions reject the whole batch with a 400 `duplicate_event_uuid` instead. +- **Accepted forms.** The SDK accepts a UUID with hyphens, 32 hex digits, `{...}` braces, or a `urn:uuid:` prefix, in any case. It sends the lowercase hyphenated form and returns that form from `capture`. +- **Other values.** The SDK replaces any other value with a generated UUID. It logs one warning that names the rule, not the value. An empty string counts as unset, so the SDK generates a UUID without a warning. This applies to `AsyncPosthog` too. +- **Generated UUIDs.** Generated UUIDs are UUIDv7. + +### Check property precedence + +An event's options and properties come from five steps, in this order. Steps 2 to 4 fill only the options and properties that the steps before them left unset: + +1. The `options` and `properties` of the call, then the call's `disable_geoip` argument, which fills `$geoip_disable`. An identify-style event also gets `process_person_profile: True` here when the call leaves it unset and the SDK didn't generate its distinct ID (see [Fix identity calls](#fix-identity-calls)). +2. Context options and tags. +3. `super_options` and `super_properties`. +4. Values the SDK sets: + - `$lib` and `$lib_version` as a pair (see [Check SDK identity](#check-sdk-identity)) + - `$is_server` from `is_server` + - `$geoip_disable` from the client's `disable_geoip` setting + - System properties such as `$os` and `$python_version` + - The `$feature/` and `$active_feature_flags` properties from `flags` or `send_feature_flags` + - `$trace_id` and `$span_id` from the active OpenTelemetry span (in `capture` and `capture_ai` only with `capture_trace_context=True`, and always in `capture_exception`) + - `options.process_person_profile = false` for events without a distinct ID + - `$release_id` from `POSTHOG_RELEASE_ID` +5. `before_send`, which sees the result of steps 1 to 4 and can change or remove any of it. + +A property set to `None` counts as set, so no later step fills it. A `None` option counts as unset, so a later step can fill it. + +`$lib` and `$lib_version` are the exception. They count as set only when they're non-empty strings (see [Check SDK identity](#check-sdk-identity)). + +`$set`, `$set_once`, `$groups`, and `$group_set` fill one level deep. When the call and a later step both set one of them to a dict, the later step adds only the keys the call left out. + +For example, `super_properties={"$set": {"plan": "free", "source": "web"}}` and a call with `properties={"$set": {"plan": "pro"}}` send `{"plan": "pro", "source": "web"}`. A `$set` in `super_properties` or a context tag sets those person properties on every event it reaches. These changes follow from this order: -- Properties passed to a call now override `super_properties`. `super_properties` can no longer change `$lib` or `$lib_version`. -- A `$is_server`, `$geoip_disable` or system property such as `$os` that you set in a call or a context tag now wins over the SDK's value. In 7.x the SDK overwrote it. `super_properties` win over the SDK's value too, so `super_properties={"$geoip_disable": False}` turns GeoIP lookup on for events, even with `disable_geoip=True`. -- Feature flag properties from `flags` or `send_feature_flags` still lose to the same key in the call's `properties`, a context tag or `super_properties`, as in 7.x. -- A `$trace_id` or `$span_id` in a context tag or `super_properties` now replaces the active OpenTelemetry span's IDs. In 7.x the span's IDs beat context tags. Setting either key in the call's `properties`, a context tag or `super_properties` stops the SDK adding both. In 7.x the SDK still added the other key. -- A `disable_geoip` argument to a call belongs to that event, so it wins over context tags and `super_properties`. A `$geoip_disable` in the call's own `properties` still wins over it. `disable_geoip=False` now sends `$geoip_disable: false`. In 7.x it sent no `$geoip_disable` property. -- The `groups` argument merges into a `$groups` property of the call, and wins key by key. In 7.x it replaced the property. MCP events merge their identity's groups into a custom `$groups` property the same way. -- A `$set`, `$set_once`, `$groups` or `$group_set` in `super_properties` no longer replaces the whole value of the call. The two merge, and the call wins key by key. -- An event without a distinct ID gets `options.process_person_profile = false`. A `$process_person_profile: true` property no longer turns person processing back on. Set the option instead. -- Review your `before_send` hooks for the new event shape. To change an option, edit `options`: a legacy property that `before_send` adds does not replace an option that is already set. A hook that returns a new dict must copy `options`, or the event is sent without them. That includes the `process_person_profile = false` the SDK sets for an event without a distinct ID, so PostHog would create a person for its generated ID. -- When the server enables minimal `$feature_flag_called` events, those events now keep `$window_id` and the legacy option properties, so their options still apply. - -## AI capture - -- `capture_ai` and the AI wrapper integrations send to `/i/v1/ai/events`. The AI endpoint accepts events up to 8 MiB. -- Send `$ai_` events with `capture_ai`. `capture()` sends every event to `/i/v1/analytics/events`, including `$ai_` events, which PostHog accepts there for now. -- `capture_ai` sends any event name to the AI endpoint. PostHog drops an event whose name does not start with `$ai_` as `misrouted_event`, and `on_error` reports it. The SDK writes only a debug log. -- The OpenTelemetry integration (`PostHogSpanProcessor`, `PostHogTraceExporter`) is unchanged: it still exports spans over OTLP to `/i/v0/ai/otel`. -- `enable_full_ai_capture` now controls only content: string truncation and media redaction. It no longer chooses the endpoint. `_use_ai_lane` and `_enable_multimodal_capture` still work as aliases. -- The AI integrations call your client's `capture_ai`, and never `capture`. A custom client object must implement `capture_ai` and accept its `options` keyword argument. If the client has no `capture_ai`, the wrapper, callback handler or tracing processor logs one error when you create it and captures no AI events; provider calls still work. Before, such a client got `capture` calls. -- Tests that pass a `Mock` client to an AI integration must assert on `mock.capture_ai`, not `mock.capture`. -- When an AI integration or MCP falls back to a trace, run or session ID, it turns person processing off with a per-event option. This is the only option the integrations pass. It wins over `super_options`, context options and a `$process_person_profile: true` property. `before_send` can still change it. -- An empty or whitespace-only distinct ID passed to an AI integration, such as `posthog_distinct_id=""`, counts as missing, so the integration falls back the same way and turns person processing off. In 7.x, an empty ID gave non-streaming wrapper calls a random personless ID. Streaming calls, embeddings and LangChain used the trace or run ID with person processing on. OpenAI Agents already treated an empty ID as missing. Every integration sent a whitespace-only ID as given, with person processing on. -- The AI integrations have no `options` argument. To set options on their events, use `set_context_option`, `super_options`, or a legacy property such as `$cookieless_mode` in `posthog_properties`. -- MCP's `PostHogCaptureEvent` has an `options` key. -- New `Client` and `AsyncPosthog` arguments for the AI lane: - - `capture_ai_compression`: default none. `POSTHOG_CAPTURE_COMPRESSION` does not apply to it. - - `capture_ai_max_queue_size`: default 1000 - - `capture_ai_timeout`: default 30 seconds - - `capture_ai_max_event_bytes`: default 8 MiB plus 64 KiB. You can only lower it. -- The AI lane does not use `max_queue_size`, `timeout` or `capture_compression`. An invalid `capture_ai_*` value raises `ValueError` when you create the client. -- The module-level client has no AI lane settings. To change them, create a `Client`. -- `AsyncPosthog` has `capture_ai` and `capture_ai_immediate`. -- `AsyncPosthog` sends events with `requests` in a worker thread. It uses `httpx` only for feature flags and remote config. -- `AsyncPosthog` accepts `privacy_mode` and `enable_full_ai_capture`, with the same meaning as on `Client`. An AI integration given an `AsyncPosthog` client used to always truncate and redact media. - -## Batching and size limits - -- An analytics event over 10 MiB is dropped and logged, because no capture request can carry it. 7.x dropped events over 900 KiB. Capture drops an event over its own per-event limit and reports it in `CaptureError.drops` as `event_too_big`. -- An AI event over `capture_ai_max_event_bytes` is dropped and logged. -- A batch stops before an event that would take it past 5 MiB. A larger event is sent alone. -- `flush()` and `shutdown()` drain the analytics and AI queues at the same time. - -## OpenFeature provider - -`openfeature-provider-posthog` 0.2.0 works with posthog 7.x and 8.x. -Older provider versions require posthog below 8.0, so upgrade the provider before or with posthog. +- **Call properties.** Properties passed to a call now override `super_properties`. +- **SDK values.** A `$is_server`, `$geoip_disable`, `$lib`, `$lib_version`, or system property such as `$os` that you set in a call or a context tag now wins over the SDK's value. In 7.x.x the SDK overwrote it. +- **SDK values and `super_properties`.** `super_properties` win over the SDK's value too. So `super_properties={"$geoip_disable": False}` turns GeoIP lookup on for events, even with `disable_geoip=True`. +- **Feature flag properties.** Feature flag properties from `flags` or `send_feature_flags` still lose to the same key in the call's `properties`, a context tag, or `super_properties`, as in 7.x.x. +- **Trace IDs.** A `$trace_id` or `$span_id` in a context tag or `super_properties` now replaces the active OpenTelemetry span's IDs. In 7.x.x the span's IDs beat context tags. +- **Trace ID pairs.** Setting either key in the call's `properties`, a context tag, or `super_properties` stops the SDK adding both. In 7.x.x the SDK still added the other key. +- **The `disable_geoip` argument.** A `disable_geoip` argument to a call belongs to that event, so it wins over context tags and `super_properties`. A `$geoip_disable` in the call's own `properties` still wins over it. +- **`disable_geoip=False`.** It now sends `$geoip_disable: false`. In 7.x.x it sent no `$geoip_disable` property. +- **The `groups` argument.** It merges into a `$groups` property of the call, and wins key by key. In 7.x.x it replaced the property. MCP events merge their identity's groups into a custom `$groups` property the same way. +- **Merged dicts.** A `$set`, `$set_once`, `$groups`, or `$group_set` in `super_properties` no longer replaces the whole value of the call. The two merge, and the call wins key by key. +- **Events without a distinct ID.** An event without a distinct ID gets `options.process_person_profile = false`. To turn person processing on for it, set the `process_person_profile` option. +- **Minimal flag events.** When the server enables minimal `$feature_flag_called` events, those events now keep `$window_id`. Their options still apply, because the trim removes only properties. + +### Check SDK identity + +By default every event carries `$lib: "posthog-python"` and the installed package version in `$lib_version`. PostHog stores the values the event is sent with. + +You can set them in a call's `properties`, a context tag, or `super_properties`. Like any other property, each one comes from the most specific place that sets it, so set both in the same place. + +`$lib` and `$lib_version` count as set only when they're non-empty strings. `before_send` sees both and can change or remove them. + +If you set `$lib` without `$lib_version`, the SDK adds its own version only when `$lib` is `posthog-python`. The SDK replaces a `$lib_version` that has no `$lib` with its own. + +| You set | 8.x.x sends | 7.x.x sent | +| --- | --- | --- | +| `$lib` or `$lib_version` in a call or a context tag | Your value | The SDK's value | +| `super_properties={"$lib": "my-lib"}` | No `$lib_version` | The SDK version | +| `super_properties={"$lib_version": "1.0"}` without a `$lib` | The SDK's `$lib` and version | `1.0` | + +If an event reaches PostHog without `$lib`, PostHog fills both from the SDK name and version your request sends. If `$lib` is that SDK name and `$lib_version` is missing, empty, or not a string, PostHog fills `$lib_version` the same way. + +MCP analytics events from `posthog.mcp.instrument()` or `PostHogMCP` report `posthog-python-mcp` and the installed package version. The integration sets both in each event's own properties, so neither a context tag nor `super_properties` replaces them, but `before_send` can. + +In 7.x.x the MCP integration relabeled the whole client, or the default client when `instrument()` got none. That covered the app's own events, the request headers, and feature flag requests. + +In 8.x.x those report `posthog-python`, so one client can serve both. + +Custom events from `PostHogMCP.capture()` now report `posthog-python`. In 7.x.x they reported `posthog-python-mcp`. + +Custom events from `McpAnalytics.capture()`, the handle `instrument()` returns, still report `posthog-python-mcp`. If an insight or dashboard filters on `$lib = posthog-python-mcp`, check that it still finds the events you expect. + +### Update error handling + +Capture v1 returns a result for every event, even when the request succeeds. An event can be dropped inside a 2xx response, for example when it's over a product quota. + +8.x.x reports those events as failures. When the whole request is over the billing limit, capture returns a `402` with no per-event results instead. + +Every capture failure is a `CaptureError`, a subclass of `APIError`. It has `endpoint`, `request_id`, and `attempts`, and these fields: + +| Field | Holds | +| --- | --- | +| `status` | The HTTP status, or `0` when the request never got a response | +| `drops` | A `CaptureDroppedEvent(uuid, details)` for each event capture dropped in a 2xx response | +| `retry_exhausted` | The UUIDs still waiting for a retry after the last attempt | +| `event_results` | A `CaptureEventResult(result, details)` for each UUID that got a result in a 2xx response | +| `verdict_summary()` | Counts such as `drop/llm_events_over_quota=1, retry/not_persisted=1` | + +When `status` is `0`, `__cause__` holds the network error. In 7.x.x, `on_error` received the raw `requests` exception. + +`CaptureDroppedEvent` and `CaptureEventResult` come from `posthog.capture_send`. A `CaptureDroppedEvent` is a tuple, so `for uuid, details in error.drops` also works. An event missing from `event_results` never got a result. + +`on_error` and the SDK's log lines change with it: + +- **Every failure.** `on_error(error, batch)` receives every failure, including in `sync_mode` and from `AsyncPosthog.capture_immediate`. +- **Logs with `on_error`.** With `on_error` set, the SDK logs nothing for a failed batch. +- **Logs without `on_error`.** The SDK logs one line per failed batch, for example `2 event(s) not persisted by /i/v1/analytics/events: ...`. The line never contains event content or the server's response text. After a 2xx response it also counts the lost events by PostHog's reason, for example `drop/event_too_big=1`. +- **Removed log lines.** The 7.x.x lines `error uploading: ...`, `async capture upload failed (...)`, and `Immediate async capture failed (...)` are gone. In `sync_mode`, a failed request no longer logs the 7.x.x `Error in capture: ...` line, or the same line for another method. Update any log-based alerts that match these lines. +- **Failures in `sync_mode`.** A failed `capture()` calls `on_error` and returns `None`. With `debug=True` it calls `on_error` and then re-raises the error. +- **Retries in `sync_mode`.** The SDK retries a failed request like a background batch, in the calling thread. With the default `max_retries` of 3, a call makes up to 4 attempts. Each attempt can take up to `timeout` (`capture_ai_timeout` for AI events). 7.x.x made one attempt. +- **Blocking in `sync_mode`.** With the defaults, an analytics event whose requests keep timing out blocks the call for about a minute. +- **Captures inside `on_error`.** If a capture inside `on_error` fails, the SDK logs the failure and doesn't call `on_error` again. +- **Event content.** The SDK's own log lines no longer contain event content. The debug line for a queued event names the event and the lane. The invalid timestamp warning no longer includes the value. To inspect events, use `before_send`. +- **Hook errors.** When your `before_send` hook raises, the error line names the event and the exception type, not the exception message. The message can hold the data the hook was removing. The SDK logs the traceback at debug level. + +Retries differ from 7.x.x in four ways: + +| Behavior | 7.x.x | 8.x.x | +| --- | --- | --- | +| Statuses retried | `429` and every 5xx, but not `404` | `404`, `408`, `429`, `500`, `502`, `503`, `504`, and network errors | +| Connection tries in each attempt | Up to three | One | +| First retry wait | Up to 1 second | 100 ms | +| `Consumer` default retries | 10 | 3 | + +In 8.x.x, any other error status fails the batch at once, including the other 5xx codes. In 7.x.x, a capture request could block for up to three times the `timeout` per attempt. + +In 8.x.x the wait doubles each attempt, up to 30 seconds. Each wait varies randomly by up to 25%, so many clients don't retry at the same moment. + +A `Retry-After` header sets a minimum wait, up to 30 seconds. + +Capture itself doesn't return `429`, but a proxy in front of it can. + +### Check dropped events + +Capture rejects a whole batch when one event can't be parsed. 8.x.x drops only the invalid event, so the rest of the batch is delivered. + +| Event | 8.x.x | 7.x.x | +| --- | --- | --- | +| The name is missing, `None`, empty, or not a string | Dropped, with a warning | Sent | +| A `before_send` hook sets `distinct_id` to `None` or a non-string | Dropped, with a warning | Sent, and capture rejected the whole batch | +| The name is over 200 UTF-8 bytes | Dropped by PostHog as `event_name_too_long` | Sent, with no name limit | +| A `NaN` or infinite `float` value | Sent as `null` | Sent as `null` from 7.75.0 | +| It can't be serialized to JSON, for example with a circular reference | Dropped and logged | Logged the same line | +| A property or option key JSON can't represent, such as a tuple | Key dropped without a log | Event dropped | +| A key is an `int`, finite `float`, `bool`, or `None` | Key converted to a string | Key converted to a string | +| A key is a `NaN` or infinite `float` | Event dropped | Event dropped | + +The SDK logs one warning per reason per process for a dropped name or `distinct_id`. It doesn't convert the hook's `distinct_id` or make up an ID. + +`on_error` reports an event that PostHog drops for its name. Before 7.75.0, a `NaN` or infinite `float` value made the JSON invalid, so capture rejected the whole batch. A `NaN` value in `$set` sets that person property to `null`. A circular reference logs `Error in capture: maximum recursion depth exceeded` with a long traceback. + +Capture v1 sends `$session_id` and `$window_id` as top-level event fields, not as properties. The SDK moves them out of `properties` for you, by the value's type: + +- **A string.** The SDK sends it as given, including `""`. +- **`None`.** It counts as unset, and the SDK removes it. +- **Any other value.** The SDK removes it and doesn't send it, because capture would reject the whole batch. 7.x.x sent it as a property. The SDK logs a warning for each one, with the key and the value's type but not the value. + +8.x.x applies these size and batch rules: + +- **Analytics events.** The SDK drops and logs an analytics event over 10 MiB, because no capture request can carry it. 7.x.x dropped events over 900 KiB. +- **Capture's own limit.** Capture drops an event over its own per-event limit and reports it in `CaptureError.drops` as `event_too_big`. +- **AI events.** The SDK drops and logs an AI event over `capture_ai_max_event_bytes`. +- **Batches.** A batch stops before an event that would take it past 5 MiB. A larger event is sent alone. +- **Queues.** `flush()` and `shutdown()` drain the analytics and AI queues at the same time. + +### Check exceptions + +- **The `level=` argument.** `capture_exception` takes a `level=` argument on `Client`, `AsyncPosthog`, and the module. It sets `$exception_level`, for example `"warning"` or `"fatal"`. The default is `"error"`, and an unknown value counts as unset. +- **Reserved properties.** `capture_exception` ignores reserved exception properties in `properties`, such as `$exception_list`, `$exception_level`, and `$exception_source`. In 7.x.x they overrode the SDK's values, with a `DeprecationWarning`. Use `level=` instead of `$exception_level`. +- **Async level.** `AsyncPosthog.capture_exception` now sends `$exception_level`. +- **Async trace IDs.** `AsyncPosthog.capture_exception` now adds `$trace_id` and `$span_id` from the active OpenTelemetry span, like `Client.capture_exception`. In 7.x.x it added them only with `capture_trace_context=True`. + +### Check tracing headers + +The Django, Flask, and ASGI integrations read the `X-PostHog-Distinct-Id` and `X-PostHog-Session-Id` headers by default, as in 7.71.0 and later. The headers only fill a missing distinct ID or session ID, and any client can set them, so never use them for authentication. + +- **Turn it off.** Set `POSTHOG_MW_CAPTURE_TRACING_HEADERS = False` in Django, or pass `capture_tracing_headers=False` to the Flask or ASGI integration. +- **Upgrades from 7.68.x, 7.69.x, or 7.70.x.** If you never turned these headers on, they're now read. + +## Follow ups + +### Move to event options + +Capture v1 sends processing options in an `options` object, next to `properties`. `capture`, `capture_ai`, `set`, `set_once`, `alias`, `group_identify`, and `capture_exception` take an `options` argument: + +```python +posthog.capture("signed_up", distinct_id="user-1", options={"cookieless_mode": True}) +``` + +The MCP capture methods take `event_options` instead (see [Add MCP event options](#add-mcp-event-options)). The AI integrations take `posthog_options` (see [Send AI events with capture_ai](#send-ai-events-with-capture_ai)). + +- **Every event.** `super_options`, a new `Client`, `AsyncPosthog`, and module setting, sets options on every event, like `super_properties`. +- **One context.** `set_context_option(key, value)` sets an option for the current context, like `tag()`. `get_context_options()` returns the options of the current context. Both exist on `Client` and as module functions. +- **Async contexts.** `AsyncPosthog` has no context methods, like it has no `tag()`, so call the module functions. They apply to every client in the context. +- **Celery workers.** The Celery integration propagates context options to workers, like tags. A propagated `process_person_profile: True` turns person processing on for worker events without a distinct ID. Each of those events creates a person. +- **Celery eager mode.** In eager mode (`task_always_eager`), Celery publishes nothing, so the distinct ID, tags, and options don't reach the task's events. To carry them, pass the task's PostHog headers with `task.apply(headers=...)` or `task.apply_async(headers=...)`. +- **Methods reached.** Context tags and options reach `capture`, `capture_ai`, `capture_exception`, `alias`, and `group_identify`. Context options also reach `set` and `set_once`. `super_properties` and `super_options` reach every method. +- **Validation.** Options are sent as given. PostHog validates them. It drops an event with an option value it can't read, such as a list for `cookieless_mode`, as `invalid_options`, and `on_error` reports it. +- **Values that aren't a dict.** The SDK logs an `options` value that isn't a dict as an error and ignores it. It still sends the event. +- **Boolean options.** Pass `True` or `False` for `cookieless_mode`, `disable_skew_correction`, and `process_person_profile`. PostHog also reads common forms such as `"false"`, `"off"`, or `0`. + +Each option replaces a legacy option property: + +| Option | Replaces | +| --- | --- | +| `cookieless_mode` | `$cookieless_mode` | +| `disable_skew_correction` | `$ignore_sent_at` | +| `product_tour_id` | `$product_tour_id` | +| `process_person_profile` | `$process_person_profile` | + +Legacy option properties still work, but an option overrides its legacy property. Use options. + +These four options are the full set. PostHog ignores any other key in `options`. + +Session and window IDs stay `$session_id` and `$window_id` properties (see [Check dropped events](#check-dropped-events)). + +### Send AI events with capture_ai + +Send `$ai_` events with `capture_ai`. `capture()` sends every event to `/i/v1/analytics/events`, including `$ai_` events. + +PostHog accepts them there for now, but this is temporary. + +The AI integrations take capture options: + +- **Wrapper methods.** Every wrapper method that takes `posthog_properties` also takes `posthog_options`, for the events of that call. This covers the sync and async OpenAI, Anthropic, and Gemini wrappers, and the Claude Agent SDK `query()` and `PostHogClaudeSDKClient`. The name keeps it apart from the Claude Agent SDK's own `options`. +- **Gemini clients.** The Gemini clients take `posthog_options` as a default for every call. A call's `posthog_options` win key by key. +- **Handlers and processors.** LangChain's `CallbackHandler` and `PostHogMiddleware` take `options=` for every event. So do OpenAI Agents' `instrument()` and `PostHogTracingProcessor`, and the Claude Agent SDK's `instrument()` and `PostHogClaudeAgentProcessor`. +- **Run metadata.** LangChain also reads `posthog_options` from run metadata, like `posthog_properties`. Like properties, the handler's or processor's options win over a run's or a query's. +- **Failed runs.** The `$exception` event LangChain captures for a failed run gets the same options. +- **Precedence.** These are the event's own options, so they win over context options and `super_options`, which still fill the keys they leave unset. `before_send` can still change them. +- **Values that aren't a dict.** The SDK logs a value that isn't a dict as a warning and ignores it. The provider call still runs, and the provider never receives `posthog_options`. + +Pass `posthog_options` to a wrapper call, or `options` to a handler: + +```python +from posthog.ai.langchain import CallbackHandler +from posthog.ai.openai import OpenAI + +client = OpenAI(posthog_client=posthog_client) +client.chat.completions.create( + model="gpt-5-mini", + messages=[{"role": "user", "content": "Hello"}], + posthog_distinct_id="user-1", + posthog_options={"cookieless_mode": True}, +) + +handler = CallbackHandler( + posthog_client, distinct_id="user-1", options={"cookieless_mode": True} +) +``` + +### Add MCP event options + +MCP events take options like other events, through an `event_options` argument and an `event_options` callback. + +- **The argument.** The `PostHogMCP` capture methods and `McpAnalytics.capture`, on the handle `instrument()` returns, take an `event_options` argument. The capture methods are `capture_tool_call`, `capture_initialize`, `capture_tools_list`, `capture_missing_capability`, and `capture_feedback`. +- **What the argument sets.** It sets options on that event. For a failed tool call, it also sets them on the `$exception` event. +- **The callback.** `MCPAnalyticsOptions(event_options=...)` sets options on every event `instrument()` captures automatically, including `$exception` events. It doesn't apply to `McpAnalytics.capture`. +- **The callback's shape.** Like `event_properties`, it's a function of `(request, extra)` that returns a dict or `None`, and it can be sync or async. +- **The core `capture`.** `PostHogMCP.capture()` is the core client's `capture`, so it takes `options`. The MCP capture methods take `event_options`. +- **Precedence.** The SDK passes these options as the event's own options, so they win over context options and `super_options`. +- **Events without an identity.** An event without an identity always sends `process_person_profile: False`, even when `event_options` sets it to `True`. Its distinct ID is the session ID, so person processing would create a person for each session. To process a person, identify the user with `identify` or pass `distinct_id`. +- **Values that aren't a dict.** The SDK logs an `event_options` value that isn't a dict and ignores it. It still sends the event. + +Set the callback in `instrument()`, or pass the argument to a capture method: + +```python +from posthog.mcp import MCPAnalyticsOptions, PostHogMCP, instrument + +instrument( + server, + posthog, + MCPAnalyticsOptions(event_options=lambda request, extra: {"cookieless_mode": True}), +) + +mcp_client = PostHogMCP("phc_...") +mcp_client.capture_tool_call( + "search_docs", + distinct_id="user-1", + event_options={"process_person_profile": False}, +) +``` + +`instrument()` captures `$mcp_tool_call` after the tool handler returns. A context you open inside the handler has ended by then, so options you set in it with `set_context_option` don't reach `$mcp_tool_call`. + +Events you capture inside that context still get them. To set options on `$mcp_tool_call`, use the `event_options` callback. + +### Rename deprecated settings + +These old names still work or have no effect in 8.x.x: + +| Old | New | +| --- | --- | +| `trust_tracing_headers`, `POSTHOG_MW_TRUST_TRACING_HEADERS` | `capture_tracing_headers`, `POSTHOG_MW_CAPTURE_TRACING_HEADERS` | +| `_use_ai_lane`, `_enable_multimodal_capture` | `enable_full_ai_capture` | +| `posthog.capture_mode` | Nothing | +| A `gzip=` keyword on `request.post` or `request.flags` | Nothing | + +The 7.68.x tracing header names still work, but are deprecated. `_use_ai_lane` and `_enable_multimodal_capture` still work as aliases. + +Setting `posthog.capture_mode` on the module has no effect. A `gzip=` keyword raises no error, and it's sent as a field in the request body. From f040c029b5b0224c0342b11672d5b28953e70e99 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:30:47 +0200 Subject: [PATCH 22/33] chore(deps): bump opentelemetry-api from 1.45.1 to 1.45.2 (#1254) Bumps [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python) from 1.45.1 to 1.45.2. - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) --- updated-dependencies: - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- uv.lock | 90 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/uv.lock b/uv.lock index 495ba1611..99774a420 100644 --- a/uv.lock +++ b/uv.lock @@ -2758,14 +2758,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -2831,7 +2831,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2839,14 +2839,14 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] name = "opentelemetry-instrumentation-aiohttp-client" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2855,28 +2855,28 @@ dependencies = [ { name = "opentelemetry-util-http" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/85/fe/634d77a0109df609eb290d172ab57e45fe35a1ef2c277f3e1908267acaa1/opentelemetry_instrumentation_aiohttp_client-0.66b1.tar.gz", hash = "sha256:6f853dadc53916fd6af41413bcb627b3e36c4a01b581e03b61b2f8eb6031d69f", size = 18849, upload-time = "2026-10-06T17:36:12.072Z" } +sdist = { url = "https://files.pythonhosted.org/packages/44/ac/a65ed79ca7139ad401619ca9d8cc242d0c0b97b338c27805de62cb803b46/opentelemetry_instrumentation_aiohttp_client-0.66b2.tar.gz", hash = "sha256:9b1b3ec682b7b1df3d3c8f7ad1745703be847391bb722c9bd39b661902c667a4", size = 18850, upload-time = "2026-10-29T17:38:13.034Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7b/30/dd352a722a4b928b22363df249b38b6d173173d36b2eab6d04770fd7d348/opentelemetry_instrumentation_aiohttp_client-0.66b1-py3-none-any.whl", hash = "sha256:bb3d412ae30e83e0692c8e9b600c5990bdab736c7c048847461b4567d504078d", size = 13610, upload-time = "2026-10-06T17:35:13.651Z" }, + { url = "https://files.pythonhosted.org/packages/19/b2/d37618e84d8340bdc7c780a0b9c6f4f1b12ba4c2298d8765217110fd5a40/opentelemetry_instrumentation_aiohttp_client-0.66b2-py3-none-any.whl", hash = "sha256:33c51743ca225c2405b81b40ac744697804aef44b530f64d1f524c9a9cd3dca2", size = 13610, upload-time = "2026-10-29T17:37:09.117Z" }, ] [[package]] name = "opentelemetry-instrumentation-celery" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-semantic-conventions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d5/66/c2bbfbb7c90850dc52dee5d4968ab45a986093d2b77a631ff17e4107eefc/opentelemetry_instrumentation_celery-0.66b1.tar.gz", hash = "sha256:3b6c5539c8d4a060edbc0eb1f334ef909d0f9a5ecb7af545bdd73644e6e2e814", size = 15947, upload-time = "2026-10-06T17:36:20.175Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/60/19a3a26da0ac391bb6f439c3a7226a5e8fc1fdc42daea0bd66b087fc940a/opentelemetry_instrumentation_celery-0.66b2.tar.gz", hash = "sha256:843645ecd28e85d16851eb6c24c082ee00c3102ba091752f095fc7628fcfb7bd", size = 15950, upload-time = "2026-10-29T17:38:22.322Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9e/73/b7597b2fede14cafe7122d1028bd6f648d9c1e049a61ab36481a4ed4f0df/opentelemetry_instrumentation_celery-0.66b1-py3-none-any.whl", hash = "sha256:145b5eece41331141edc8f454984238b05b107d7ead928b49e7a1916d5e48e99", size = 13480, upload-time = "2026-10-06T17:35:25.828Z" }, + { url = "https://files.pythonhosted.org/packages/39/a8/55e43dcc83750890f3ff1e5cdae1f104b99eb58df14b5ebc5b3168717d54/opentelemetry_instrumentation_celery-0.66b2-py3-none-any.whl", hash = "sha256:ebd105e957a92c1e002ced628f8948a19334296183f6d558eeab9fa406b84406", size = 13480, upload-time = "2026-10-29T17:37:22.172Z" }, ] [[package]] name = "opentelemetry-instrumentation-dbapi" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2884,14 +2884,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/23/b4/35c682a3a5762547cab6ac1d0f6e66a4e549cbbb852862903bb1523036fe/opentelemetry_instrumentation_dbapi-0.66b1.tar.gz", hash = "sha256:715be3080f644de2314d84388a73571acdbeca85bfbc7dc682f214c88cc18022", size = 19990, upload-time = "2026-10-06T17:36:22.281Z" } +sdist = { url = "https://files.pythonhosted.org/packages/25/c2/02589926023ad7d65a384577d64ed127e63fff9f41b4e47f6ce97e875572/opentelemetry_instrumentation_dbapi-0.66b2.tar.gz", hash = "sha256:7661bb9fde82e97788d5f9c7bd90b2fd26500b1264dbe74daf6359f33a2d9898", size = 19990, upload-time = "2026-10-29T17:38:24.374Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/77/89/7f2ccd50975b66b2977a31bb489a2f0205b7fd033fc99046dcfa001c4252/opentelemetry_instrumentation_dbapi-0.66b1-py3-none-any.whl", hash = "sha256:a38043a8a907a321ae6b838f778ad19c8e78c0bfc2f336d6d30c5fdce112e88d", size = 14706, upload-time = "2026-10-06T17:35:28.831Z" }, + { url = "https://files.pythonhosted.org/packages/7a/7b/f202758f25ab069f8e6eb7c4a7bb3fecb86bb8d9913185938f421af2cad6/opentelemetry_instrumentation_dbapi-0.66b2-py3-none-any.whl", hash = "sha256:911854dbe0d3cd26539a2287aab8f35c208197409c83a445981331b7d5388314", size = 14705, upload-time = "2026-10-29T17:37:25.592Z" }, ] [[package]] name = "opentelemetry-instrumentation-django" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2900,14 +2900,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e9/88/d0acbd7916aa3040a36486cedb60aa77c129c7029446fa6a00207345695c/opentelemetry_instrumentation_django-0.66b1.tar.gz", hash = "sha256:85b56193b6ce7b8db9c280c3ade4a4991601abc9ada4734c8911971423fd521f", size = 25233, upload-time = "2026-10-06T17:36:22.892Z" } +sdist = { url = "https://files.pythonhosted.org/packages/20/45/d88bf09705cffd4fc0cd7324be260de348a7c761d7ff75b1faa2f2e9e4ad/opentelemetry_instrumentation_django-0.66b2.tar.gz", hash = "sha256:af0cdcf33716184a02a44a8315d3bf74a860892710bee22e294f8298c316b17c", size = 25233, upload-time = "2026-10-29T17:38:25.138Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5b/c3/2739c248b60b2802b9e51d2a3373269f0ca3e16059ea4f1ca7370502118c/opentelemetry_instrumentation_django-0.66b1-py3-none-any.whl", hash = "sha256:23d1052940a025ae1dac70849b998cf9ba66731fa2b7e58254ab7dac5539a989", size = 18914, upload-time = "2026-10-06T17:35:30.052Z" }, + { url = "https://files.pythonhosted.org/packages/0c/36/c304aca6aa1f45e9f58d3b68e6431e4a076b9a51d0547b41e854e1cd767f/opentelemetry_instrumentation_django-0.66b2-py3-none-any.whl", hash = "sha256:a21f629959a90a62ca209cc5f40224128d7cbe7df9682f7febcb414de39d5978", size = 18913, upload-time = "2026-10-29T17:37:26.716Z" }, ] [[package]] name = "opentelemetry-instrumentation-flask" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2917,14 +2917,14 @@ dependencies = [ { name = "opentelemetry-util-http" }, { name = "packaging" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c0/fc/c1a692ceb7ed56818f2f4f88044b5a0895b6666da954dbd566fdf265195b/opentelemetry_instrumentation_flask-0.66b1.tar.gz", hash = "sha256:10f788aff95236f0dbaaa066687283bf6345bb3c77bbb437f0fb67cb6222d5eb", size = 23876, upload-time = "2026-10-06T17:36:25.763Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/4f/0b882c297856e7f074cbbf9bcf74a3a9cd171e320d02d41435b23b614c71/opentelemetry_instrumentation_flask-0.66b2.tar.gz", hash = "sha256:3983cbf4c67588f1ade7fd68458e3345e434a879bf3f51a7e2e9e7be903bfae6", size = 23875, upload-time = "2026-10-29T17:38:29.437Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/52/65/7aa45ca677c51afb185bcd5e7ed121c84b07b2c566a72948a9e56fd16ae7/opentelemetry_instrumentation_flask-0.66b1-py3-none-any.whl", hash = "sha256:2933e71b94cc9e8e943e648d872fd3dead9cdb61295dc6deffd5d6fa8f27a39b", size = 14961, upload-time = "2026-10-06T17:35:34.002Z" }, + { url = "https://files.pythonhosted.org/packages/eb/b8/c87f589a0cb85ae1a4c661196ed7f396e3e921eda30d3759f7f3116959f1/opentelemetry_instrumentation_flask-0.66b2-py3-none-any.whl", hash = "sha256:4e157d1375ba93c4f9b2f83f3a9b327d965141afda89b1e293668faa6ef08caa", size = 14961, upload-time = "2026-10-29T17:37:31.538Z" }, ] [[package]] name = "opentelemetry-instrumentation-httpx" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2933,14 +2933,14 @@ dependencies = [ { name = "opentelemetry-util-http" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/de/50/41544799b043d14fdfa6fe62fa2518eaba22793fce03e9abde930b92e671/opentelemetry_instrumentation_httpx-0.66b1.tar.gz", hash = "sha256:5865a72c68098c85955a271ab8744b480a36e3ee492d35b8cadb93c7c4dbb618", size = 26637, upload-time = "2026-10-06T17:36:27.265Z" } +sdist = { url = "https://files.pythonhosted.org/packages/41/43/3204ca7e7d91bd9e1b569a98a5f9252c98ae70ba3bb562d2770c34e21d49/opentelemetry_instrumentation_httpx-0.66b2.tar.gz", hash = "sha256:b4c81e4a6dc7b8d7cb2d3088eb8848f6db6bd4abdc443ac9586ec176f1460187", size = 26638, upload-time = "2026-10-29T17:38:31.46Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/4f/c6/e5682b1bfb320b32505e88255c34ae1e99fe9fb220cc465c244e91967eac/opentelemetry_instrumentation_httpx-0.66b1-py3-none-any.whl", hash = "sha256:0342a4002c6dbc6c4bf22cc7e698f50f5c8b77f63325c6f40c94ab87e016bf4d", size = 17723, upload-time = "2026-10-06T17:35:36.501Z" }, + { url = "https://files.pythonhosted.org/packages/53/40/37d6161dcd95285c9c3eb75e2dbeb1dbc6e868551532735374918a22e298/opentelemetry_instrumentation_httpx-0.66b2-py3-none-any.whl", hash = "sha256:93e2b6ab1a505d76ec3d98abcf7e8527d4712167d6c3b5ebbb9c68d9309d9ba5", size = 17723, upload-time = "2026-10-29T17:37:33.735Z" }, ] [[package]] name = "opentelemetry-instrumentation-requests" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2948,28 +2948,28 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/08/62/dcca0b7a2008675056040c61b70d37b5a24439613c7822068908ad3255ae/opentelemetry_instrumentation_requests-0.66b1.tar.gz", hash = "sha256:28578f72e68e3a5be3226c618ac9570ed360ef1dd22d5d6e0721c6905a4ccc67", size = 17985, upload-time = "2026-10-06T17:36:37.478Z" } +sdist = { url = "https://files.pythonhosted.org/packages/46/2e/cdd7a2ebbdb9d31879781842feb6a3515e4a1d4d87cd701556fc849ddd35/opentelemetry_instrumentation_requests-0.66b2.tar.gz", hash = "sha256:bcfbdc3ff3ec8524044908788f0e7f3c25e219053b496fd9926d75f8d7c7bc96", size = 17984, upload-time = "2026-10-29T17:38:43.998Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/88/01/98e9bb7fef12784cd19811e454cf25bce4d774fd3e46b3f5fd2bce237075/opentelemetry_instrumentation_requests-0.66b1-py3-none-any.whl", hash = "sha256:7ba17d984a2bd876b88bf0aafcca27b5e3ff4c1821e0fe07641e380a3cf3a3a2", size = 13320, upload-time = "2026-10-06T17:35:52.477Z" }, + { url = "https://files.pythonhosted.org/packages/b2/fc/d73ebbb46158722f63eb9e95a22a2aa03ec8cadd5ef9b91fda350ddd33ca/opentelemetry_instrumentation_requests-0.66b2-py3-none-any.whl", hash = "sha256:b0ba903a0bd7ebb234c8b32d3d957efc4061ba8571916558dc3f3dcdabb5e5e1", size = 13322, upload-time = "2026-10-29T17:37:51.421Z" }, ] [[package]] name = "opentelemetry-instrumentation-sqlite3" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-instrumentation" }, { name = "opentelemetry-instrumentation-dbapi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/25/54/742ab70c78a1589c29f5513fd5097845b2c2fda58390bbff0f6e1af2601a/opentelemetry_instrumentation_sqlite3-0.66b1.tar.gz", hash = "sha256:e5d672a347deac385a71fb52d556ea443e2f3cc51eac05cac8f0a739cac0bb38", size = 9019, upload-time = "2026-10-06T17:36:38.74Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ff/80/1e084a8367bffafda9ba610570f0c4321b7c1b4d493609ad98b8f91ac008/opentelemetry_instrumentation_sqlite3-0.66b2.tar.gz", hash = "sha256:d7c80d5a632e3de47e2c59405c600e837a94f8d79dfccce51f506d6612837986", size = 9021, upload-time = "2026-10-29T17:38:45.439Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3b/6a/c36552844c4e3545da7b2931213256c0717665c7d92246a4fe66e088fd9b/opentelemetry_instrumentation_sqlite3-0.66b1-py3-none-any.whl", hash = "sha256:f282b712f56186c36d592d4ab856d978bc7dd60f4b10500113da8c9eb45ff9bc", size = 8526, upload-time = "2026-10-06T17:35:54.362Z" }, + { url = "https://files.pythonhosted.org/packages/5d/da/01db3725f33898bfb67d5dbc60545c12d43e1da54d88cb4bceaf5cf9b020/opentelemetry_instrumentation_sqlite3-0.66b2-py3-none-any.whl", hash = "sha256:d730936e12907a619c7c165606d51c5e0e0f0977bb7c869af3251e999fb94e71", size = 8524, upload-time = "2026-10-29T17:37:53.68Z" }, ] [[package]] name = "opentelemetry-instrumentation-system-metrics" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2977,14 +2977,14 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "psutil" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d6/81/ab8cabaf45c5248fa88a0d0d3acea4483c105d76cd6c849654ebdab16f92/opentelemetry_instrumentation_system_metrics-0.66b1.tar.gz", hash = "sha256:b0fccbc1aecf35c182431a035ec4809b8f9607eec692243cf70f23b3bda51231", size = 17207, upload-time = "2026-10-06T17:36:40.518Z" } +sdist = { url = "https://files.pythonhosted.org/packages/83/1b/956ec5559dc90d64e4fb8d17c779b2a12e76d5c57e472af1ad428c7eabe0/opentelemetry_instrumentation_system_metrics-0.66b2.tar.gz", hash = "sha256:f6af8b1cf1b65cf4587c0f8d5e8e716d9eb9a053e29379481346b598c2c0af36", size = 17210, upload-time = "2026-10-29T17:38:47.492Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/fd/ea072c512d65ba4054b02c8b7080cf1b362761d4727ee6c1f36dce53328d/opentelemetry_instrumentation_system_metrics-0.66b1-py3-none-any.whl", hash = "sha256:0654b41eb6db3c2f9ad9979487afcc6f461e5b35df282f0a11d0f465e906d967", size = 13913, upload-time = "2026-10-06T17:35:57.01Z" }, + { url = "https://files.pythonhosted.org/packages/9b/7d/9cf3cdea542ac89342cd045a197d406261be7c946d63f6ad8eec758afb48/opentelemetry_instrumentation_system_metrics-0.66b2-py3-none-any.whl", hash = "sha256:da97942ec373e79e71ee6e72b0d78044ab87dd0c869429dfa8f825c7d8d51fe5", size = 13911, upload-time = "2026-10-29T17:37:56.626Z" }, ] [[package]] name = "opentelemetry-instrumentation-wsgi" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2992,9 +2992,9 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "opentelemetry-util-http" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/41/7a/a1ba86d95f849db8f41ffd03c7cb302559ef091d76cff78baddd4ad19205/opentelemetry_instrumentation_wsgi-0.66b1.tar.gz", hash = "sha256:ce803d8e828e75d7225c25a618b692cbd4687a11be64356308ed1feab0f70bab", size = 19527, upload-time = "2026-10-06T17:36:44.181Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a0/b3/b7727dad802bfe89734e7333fdad34d96a388cb323fda5fccb8ade46d6fc/opentelemetry_instrumentation_wsgi-0.66b2.tar.gz", hash = "sha256:631ab2d67968c0ed7d91153120ec0e5092c5a3e2b6093c80e7dea0219508453c", size = 19531, upload-time = "2026-10-29T17:38:52.64Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a5/4f/17f06b0dc7c542c482b1d3f7f1d0925046f7e156fb39c255634b3c4f526a/opentelemetry_instrumentation_wsgi-0.66b1-py3-none-any.whl", hash = "sha256:8c86390c32fe8d0924b3541f292122d3a2ba6c3accc2bcbcc73ae985ee8e799e", size = 13752, upload-time = "2026-10-06T17:36:03.166Z" }, + { url = "https://files.pythonhosted.org/packages/d7/98/7424f13fdc94efb5f51aa9d7f0889ff25157ea51d61adc09ce4d5e23417f/opentelemetry_instrumentation_wsgi-0.66b2-py3-none-any.whl", hash = "sha256:4b994e2463dec01b7c66e16d9ccbb5e7318b9f75514988a45c144d81ce3525e4", size = 13751, upload-time = "2026-10-29T17:38:03.15Z" }, ] [[package]] @@ -3011,38 +3011,38 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] name = "opentelemetry-util-http" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7c/b5/df4b61da899f6ebdffdbdf0c8b0f3189ee57151694ccd5b7d50ee2906241/opentelemetry_util_http-0.66b1.tar.gz", hash = "sha256:047dea1a628031f857a5a32261dc0e955bc162d39993ed1cffb8f2cff5ba8a62", size = 11586, upload-time = "2026-10-06T17:36:46.572Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/57/33566966a7bced4d02fbc672f92029184e4a743f5b531e44b4c0dc4c999b/opentelemetry_util_http-0.66b2.tar.gz", hash = "sha256:7ba066ea609202e474679ddf1d0f753a1e6619bd206b36afaecba4bbb86e25d0", size = 11587, upload-time = "2026-10-29T17:38:56.043Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/eb/9b/c77ecaea79ba0de1a11e7f06a7f5eea7043ec23f1860dcf5f03536698e4c/opentelemetry_util_http-0.66b1-py3-none-any.whl", hash = "sha256:8f443d7abcaf29c4a07b373bbd31b5b39132c0ed3c27d015a59dc0323d5b1c58", size = 8387, upload-time = "2026-10-06T17:36:06.984Z" }, + { url = "https://files.pythonhosted.org/packages/18/8d/39885564eefa43f6181acfa3d698af2f6b5fe3e64c86dce3f1b955f6397f/opentelemetry_util_http-0.66b2-py3-none-any.whl", hash = "sha256:c4bb5d6744e60353bcaa3e325bc529a1515346b51cb4d9c8e5b730579337e06d", size = 8383, upload-time = "2026-10-29T17:38:07.462Z" }, ] [[package]] From 7e7194ee0c065ac7074ab9b70cd5f9963e880e59 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:31:11 +0200 Subject: [PATCH 23/33] chore(deps): bump the uv group across 4 directories with 1 update (#1252) Bumps the uv group with 1 update in the /examples/example-ai-autogen directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-llamaindex directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-semantic-kernel directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-smolagents directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) --- updated-dependencies: - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- examples/example-ai-autogen/uv.lock | 44 ++++++++++++++------- examples/example-ai-llamaindex/uv.lock | 29 ++++++++------ examples/example-ai-semantic-kernel/uv.lock | 29 ++++++++------ examples/example-ai-smolagents/uv.lock | 44 ++++++++++++++------- 4 files changed, 92 insertions(+), 54 deletions(-) diff --git a/examples/example-ai-autogen/uv.lock b/examples/example-ai-autogen/uv.lock index 828f4ba21..acb2cec22 100644 --- a/examples/example-ai-autogen/uv.lock +++ b/examples/example-ai-autogen/uv.lock @@ -450,14 +450,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -523,7 +523,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -531,9 +531,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -564,29 +564,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -694,7 +694,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.76.0" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -727,6 +727,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -742,9 +745,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -772,7 +788,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-llamaindex/uv.lock b/examples/example-ai-llamaindex/uv.lock index 224e5a424..54209e48c 100644 --- a/examples/example-ai-llamaindex/uv.lock +++ b/examples/example-ai-llamaindex/uv.lock @@ -1558,14 +1558,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -1631,7 +1631,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1639,9 +1639,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -1674,29 +1674,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -1826,7 +1826,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.86.6" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -1859,6 +1859,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, diff --git a/examples/example-ai-semantic-kernel/uv.lock b/examples/example-ai-semantic-kernel/uv.lock index bed187c0a..2a83db2e2 100644 --- a/examples/example-ai-semantic-kernel/uv.lock +++ b/examples/example-ai-semantic-kernel/uv.lock @@ -1864,14 +1864,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -1937,7 +1937,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1945,9 +1945,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -1978,29 +1978,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -2032,7 +2032,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.86.6" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -2065,6 +2065,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, diff --git a/examples/example-ai-smolagents/uv.lock b/examples/example-ai-smolagents/uv.lock index fe6653891..2e8163b77 100644 --- a/examples/example-ai-smolagents/uv.lock +++ b/examples/example-ai-smolagents/uv.lock @@ -569,14 +569,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -642,7 +642,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -650,9 +650,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -683,29 +683,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -813,7 +813,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.76.0" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -846,6 +846,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -861,9 +864,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -891,7 +907,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] From 652b9792b76c8fb177c4e99c021ef9573a1f5366 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:04:19 +0200 Subject: [PATCH 24/33] chore(deps): bump the uv group across 26 directories with 1 update (#1255) Bumps the uv group with 1 update in the /examples/example-ai-anthropic directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-aws-bedrock directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-azure-openai directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-cerebras directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-cloudflare-ai-gateway directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-cohere directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-dedalus directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-deepseek directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-fireworks-ai directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-gemini directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-groq directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-helicone directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-hugging-face directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-instructor directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-langchain directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-langgraph directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-mirascope directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-mistral directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-ollama directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-openai directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-openrouter directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-perplexity directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-portkey directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-together-ai directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-vercel-ai-gateway directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Bumps the uv group with 1 update in the /examples/example-ai-xai directory: [opentelemetry-api](https://github.com/open-telemetry/opentelemetry-python). Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) Updates `opentelemetry-api` from 1.45.1 to 1.45.2 - [Release notes](https://github.com/open-telemetry/opentelemetry-python/releases) - [Changelog](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/open-telemetry/opentelemetry-python/compare/v1.45.1...v1.45.2) --- updated-dependencies: - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv - dependency-name: opentelemetry-api dependency-version: 1.45.2 dependency-type: indirect dependency-group: uv ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- examples/example-ai-anthropic/uv.lock | 50 +++++++++++------ examples/example-ai-aws-bedrock/uv.lock | 56 ++++++++++++------- examples/example-ai-azure-openai/uv.lock | 50 +++++++++++------ examples/example-ai-cerebras/uv.lock | 50 +++++++++++------ .../example-ai-cloudflare-ai-gateway/uv.lock | 50 +++++++++++------ examples/example-ai-cohere/uv.lock | 50 +++++++++++------ examples/example-ai-dedalus/uv.lock | 50 +++++++++++------ examples/example-ai-deepseek/uv.lock | 50 +++++++++++------ examples/example-ai-fireworks-ai/uv.lock | 50 +++++++++++------ examples/example-ai-gemini/uv.lock | 29 +++++----- examples/example-ai-groq/uv.lock | 50 +++++++++++------ examples/example-ai-helicone/uv.lock | 50 +++++++++++------ examples/example-ai-hugging-face/uv.lock | 50 +++++++++++------ examples/example-ai-instructor/uv.lock | 50 +++++++++++------ examples/example-ai-langchain/uv.lock | 29 +++++----- examples/example-ai-langgraph/uv.lock | 26 ++++----- examples/example-ai-mirascope/uv.lock | 50 +++++++++++------ examples/example-ai-mistral/uv.lock | 50 +++++++++++------ examples/example-ai-ollama/uv.lock | 50 +++++++++++------ examples/example-ai-openai/uv.lock | 50 +++++++++++------ examples/example-ai-openrouter/uv.lock | 50 +++++++++++------ examples/example-ai-perplexity/uv.lock | 50 +++++++++++------ examples/example-ai-portkey/uv.lock | 50 +++++++++++------ examples/example-ai-together-ai/uv.lock | 50 +++++++++++------ examples/example-ai-vercel-ai-gateway/uv.lock | 50 +++++++++++------ examples/example-ai-xai/uv.lock | 50 +++++++++++------ 26 files changed, 807 insertions(+), 433 deletions(-) diff --git a/examples/example-ai-anthropic/uv.lock b/examples/example-ai-anthropic/uv.lock index 7c08e365d..bbff0c1eb 100644 --- a/examples/example-ai-anthropic/uv.lock +++ b/examples/example-ai-anthropic/uv.lock @@ -62,11 +62,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -495,29 +495,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -544,7 +544,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -577,6 +577,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -592,9 +595,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -622,7 +638,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-aws-bedrock/uv.lock b/examples/example-ai-aws-bedrock/uv.lock index 3ab92317f..6faa29362 100644 --- a/examples/example-ai-aws-bedrock/uv.lock +++ b/examples/example-ai-aws-bedrock/uv.lock @@ -48,11 +48,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -220,14 +220,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -293,7 +293,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -301,14 +301,14 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] name = "opentelemetry-instrumentation-botocore" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -317,9 +317,9 @@ dependencies = [ { name = "opentelemetry-semantic-conventions" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/4d/f6/f648150c2bf30784b4ff448c15a6b5ad804ac41b91362ebe023ce14b88c3/opentelemetry_instrumentation_botocore-0.66b1.tar.gz", hash = "sha256:c601923e40aa008f4c0466b714c112fe47da07adb72ae6c69e2ac95992bcd66e", size = 129133, upload-time = "2026-10-06T17:36:18.898Z" } +sdist = { url = "https://files.pythonhosted.org/packages/8f/51/3ad86e9b2ec5cc6258cb366eb0f6f3db2e22d6c47207f206486a0026e291/opentelemetry_instrumentation_botocore-0.66b2.tar.gz", hash = "sha256:744959d5f6bae940d3d41e5f2663fad733b50dedf742bc55da9bbbcfb9773903", size = 129131, upload-time = "2026-10-29T17:38:20.605Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5d/6b/1f467c7e5725a8df6c2ed59446c5b9632bc480a525396a962ab67a4d7f28/opentelemetry_instrumentation_botocore-0.66b1-py3-none-any.whl", hash = "sha256:6352ceb4f204b13cd5b448f4df10de4a1a82f345fd0a81f8816a60e9ce3fdfc2", size = 36199, upload-time = "2026-10-06T17:35:23.976Z" }, + { url = "https://files.pythonhosted.org/packages/f4/69/9430cc905073241c6418f03c599d293c45b6a2d8cd3af0a88e2c2a465509/opentelemetry_instrumentation_botocore-0.66b2-py3-none-any.whl", hash = "sha256:a32d73c8c4bccbbeed56fe292077c8e4b474dca15955c1579905578609de0051", size = 36200, upload-time = "2026-10-29T17:37:19.889Z" }, ] [[package]] @@ -348,29 +348,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -384,7 +384,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -417,6 +417,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -432,9 +435,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -462,7 +478,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-azure-openai/uv.lock b/examples/example-ai-azure-openai/uv.lock index a5ef6855e..e4a05b596 100644 --- a/examples/example-ai-azure-openai/uv.lock +++ b/examples/example-ai-azure-openai/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-cerebras/uv.lock b/examples/example-ai-cerebras/uv.lock index c93a3adde..e5f3e4b16 100644 --- a/examples/example-ai-cerebras/uv.lock +++ b/examples/example-ai-cerebras/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-cloudflare-ai-gateway/uv.lock b/examples/example-ai-cloudflare-ai-gateway/uv.lock index b57760592..268ca2a68 100644 --- a/examples/example-ai-cloudflare-ai-gateway/uv.lock +++ b/examples/example-ai-cloudflare-ai-gateway/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-cohere/uv.lock b/examples/example-ai-cohere/uv.lock index 19e58c7b4..54c5e1a3e 100644 --- a/examples/example-ai-cohere/uv.lock +++ b/examples/example-ai-cohere/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-dedalus/uv.lock b/examples/example-ai-dedalus/uv.lock index 2dfb0a292..fe2ff5616 100644 --- a/examples/example-ai-dedalus/uv.lock +++ b/examples/example-ai-dedalus/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-deepseek/uv.lock b/examples/example-ai-deepseek/uv.lock index 7dd79a938..e2e6f1211 100644 --- a/examples/example-ai-deepseek/uv.lock +++ b/examples/example-ai-deepseek/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-fireworks-ai/uv.lock b/examples/example-ai-fireworks-ai/uv.lock index 2a573ab26..9dbab615d 100644 --- a/examples/example-ai-fireworks-ai/uv.lock +++ b/examples/example-ai-fireworks-ai/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-gemini/uv.lock b/examples/example-ai-gemini/uv.lock index e90030424..9249e320b 100644 --- a/examples/example-ai-gemini/uv.lock +++ b/examples/example-ai-gemini/uv.lock @@ -433,14 +433,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -506,7 +506,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -514,9 +514,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -548,29 +548,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -597,7 +597,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.86.6" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -630,6 +630,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, diff --git a/examples/example-ai-groq/uv.lock b/examples/example-ai-groq/uv.lock index 53278b351..83c428389 100644 --- a/examples/example-ai-groq/uv.lock +++ b/examples/example-ai-groq/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-helicone/uv.lock b/examples/example-ai-helicone/uv.lock index 803a8a6d8..4eb193207 100644 --- a/examples/example-ai-helicone/uv.lock +++ b/examples/example-ai-helicone/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-hugging-face/uv.lock b/examples/example-ai-hugging-face/uv.lock index b853347c5..4d12fd195 100644 --- a/examples/example-ai-hugging-face/uv.lock +++ b/examples/example-ai-hugging-face/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-instructor/uv.lock b/examples/example-ai-instructor/uv.lock index bde3f9560..76e7f727b 100644 --- a/examples/example-ai-instructor/uv.lock +++ b/examples/example-ai-instructor/uv.lock @@ -271,11 +271,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -1085,14 +1085,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -1158,7 +1158,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -1166,9 +1166,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -1199,29 +1199,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -1235,7 +1235,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -1268,6 +1268,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -1283,9 +1286,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -1313,7 +1329,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-langchain/uv.lock b/examples/example-ai-langchain/uv.lock index a6c8d1a9d..514b22982 100644 --- a/examples/example-ai-langchain/uv.lock +++ b/examples/example-ai-langchain/uv.lock @@ -547,14 +547,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -620,7 +620,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -628,9 +628,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -662,29 +662,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -848,7 +848,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.86.6" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -881,6 +881,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, diff --git a/examples/example-ai-langgraph/uv.lock b/examples/example-ai-langgraph/uv.lock index a717e0111..8f3ba55e1 100644 --- a/examples/example-ai-langgraph/uv.lock +++ b/examples/example-ai-langgraph/uv.lock @@ -533,14 +533,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -606,7 +606,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -614,9 +614,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -648,29 +648,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -834,7 +834,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.87.2" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, diff --git a/examples/example-ai-mirascope/uv.lock b/examples/example-ai-mirascope/uv.lock index 57bf711c8..323119d54 100644 --- a/examples/example-ai-mirascope/uv.lock +++ b/examples/example-ai-mirascope/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -407,14 +407,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -480,7 +480,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -488,9 +488,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -521,29 +521,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -557,7 +557,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -590,6 +590,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -605,9 +608,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -635,7 +651,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-mistral/uv.lock b/examples/example-ai-mistral/uv.lock index af7616869..62496182c 100644 --- a/examples/example-ai-mistral/uv.lock +++ b/examples/example-ai-mistral/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-ollama/uv.lock b/examples/example-ai-ollama/uv.lock index e55d5b5d2..bd7e55a77 100644 --- a/examples/example-ai-ollama/uv.lock +++ b/examples/example-ai-ollama/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-openai/uv.lock b/examples/example-ai-openai/uv.lock index b7cb99338..e4250456a 100644 --- a/examples/example-ai-openai/uv.lock +++ b/examples/example-ai-openai/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-openrouter/uv.lock b/examples/example-ai-openrouter/uv.lock index 7d07fff22..7b542f115 100644 --- a/examples/example-ai-openrouter/uv.lock +++ b/examples/example-ai-openrouter/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-perplexity/uv.lock b/examples/example-ai-perplexity/uv.lock index 5863f63b5..5acad848c 100644 --- a/examples/example-ai-perplexity/uv.lock +++ b/examples/example-ai-perplexity/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-portkey/uv.lock b/examples/example-ai-portkey/uv.lock index e609b0661..5c0400a7b 100644 --- a/examples/example-ai-portkey/uv.lock +++ b/examples/example-ai-portkey/uv.lock @@ -52,11 +52,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -391,14 +391,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -464,7 +464,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -472,9 +472,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -505,29 +505,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -562,7 +562,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -595,6 +595,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -610,9 +613,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -640,7 +656,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-together-ai/uv.lock b/examples/example-ai-together-ai/uv.lock index ab3afb7e5..fb0f32c57 100644 --- a/examples/example-ai-together-ai/uv.lock +++ b/examples/example-ai-together-ai/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-vercel-ai-gateway/uv.lock b/examples/example-ai-vercel-ai-gateway/uv.lock index 554ae8151..6a4705b41 100644 --- a/examples/example-ai-vercel-ai-gateway/uv.lock +++ b/examples/example-ai-vercel-ai-gateway/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] diff --git a/examples/example-ai-xai/uv.lock b/examples/example-ai-xai/uv.lock index 25459e607..a6713d1d3 100644 --- a/examples/example-ai-xai/uv.lock +++ b/examples/example-ai-xai/uv.lock @@ -43,11 +43,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.10.19" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -380,14 +380,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, ] [[package]] @@ -453,7 +453,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -461,9 +461,9 @@ dependencies = [ { name = "packaging" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a5/03/89e47ff8d52a4f83b343e6eb9ef1698ff45357216e5b6b2b21e0da5c5c7d/opentelemetry_instrumentation-0.66b1.tar.gz", hash = "sha256:e79a510f7d87c72d95e964ddb42193a0d9a75668c027d980eab032ea1322a5ce", size = 43308, upload-time = "2026-10-06T17:36:10.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/b2/d1413681ff43e13ac9860df27e1226d3199ab0b97b352ceea41abcc660a5/opentelemetry_instrumentation-0.66b1-py3-none-any.whl", hash = "sha256:4c4aa14dc9a24a02325a9d4c42c4d0208dbb1374c2b1b8fe6c9392d59f3e1008", size = 36904, upload-time = "2026-10-06T17:35:11.663Z" }, + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] [[package]] @@ -494,29 +494,29 @@ wheels = [ [[package]] name = "opentelemetry-sdk" -version = "1.45.1" +version = "1.45.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "opentelemetry-semantic-conventions" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/79/7392e21a1c8f0c61d90b223e31c7e48cb9d452e91a6b820ad24cca5f23c4/opentelemetry_sdk-1.45.1.tar.gz", hash = "sha256:63d24a6ca645019a631e6a51999c73e93adcac1196ca640b8ae78a7cc4762bf3", size = 218324, upload-time = "2026-10-06T17:33:13.26Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/95/3c/87c42b4bd6dd297536f04cd9383d212ac557ecd49f2cbdcd46da1c9ef5c8/opentelemetry_sdk-1.45.1-py3-none-any.whl", hash = "sha256:c604c11dc429810812348989115fa44bd558772a3d7442afc43d024f2c250ca4", size = 140063, upload-time = "2026-10-06T17:32:55.04Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, ] [[package]] name = "opentelemetry-semantic-conventions" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/46/e4/dbbfb2a010c4db2224a5114638acede6fe563d33cc20fb1752cebcbe6298/opentelemetry_semantic_conventions-0.66b1.tar.gz", hash = "sha256:497ca63bf383723411e8eaf60c8779e9877633c936bb641080adab59d0eb6ec8", size = 150250, upload-time = "2026-10-06T17:33:14.073Z" } +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] [[package]] @@ -530,7 +530,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.75.11" +version = "7.91.1" source = { directory = "../../" } dependencies = [ { name = "backoff" }, @@ -563,6 +563,9 @@ requires-dist = [ { name = "gevent", marker = "implementation_name == 'cpython' and extra == 'test'", specifier = ">=25.4.1" }, { name = "google-genai", marker = "extra == 'test'" }, { name = "griffe", marker = "extra == 'dev'" }, + { name = "griffe", marker = "extra == 'test'" }, + { name = "griffe2md", marker = "extra == 'dev'" }, + { name = "griffe2md", marker = "extra == 'test'" }, { name = "httpx", marker = "extra == 'async'", specifier = ">=0.27.0,<1.0" }, { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0" }, { name = "langchain", marker = "extra == 'langchain'", specifier = ">=1.3.9" }, @@ -578,9 +581,22 @@ requires-dist = [ { name = "mypy", marker = "extra == 'dev'" }, { name = "mypy-baseline", marker = "extra == 'dev'" }, { name = "openai-agents", marker = "extra == 'test'", specifier = ">=0.18" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'test'", specifier = ">=1.20.0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-aiohttp-client", marker = "extra == 'test'", specifier = ">=0.60b0" }, { name = "opentelemetry-instrumentation-celery", marker = "extra == 'test'", specifier = ">=0.41b0" }, + { name = "opentelemetry-instrumentation-django", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-flask", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-httpx", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-requests", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-sqlite3", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'metrics'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-system-metrics", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-instrumentation-wsgi", marker = "extra == 'test'", specifier = ">=0.60b0" }, + { name = "opentelemetry-sdk", marker = "extra == 'metrics'", specifier = ">=1.39.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.20.0" }, { name = "opentelemetry-sdk", marker = "extra == 'test'", specifier = ">=1.20.0" }, { name = "packaging", marker = "extra == 'dev'" }, @@ -608,7 +624,7 @@ requires-dist = [ { name = "zstandard", marker = "extra == 'test'", specifier = ">=0.23.0" }, { name = "zstandard", marker = "extra == 'zstd'", specifier = ">=0.23.0" }, ] -provides-extras = ["langchain", "async", "zstd", "otel", "dev", "test"] +provides-extras = ["langchain", "async", "zstd", "otel", "metrics", "dev", "test"] [package.metadata.requires-dev] dev = [{ name = "claude-agent-sdk", specifier = ">=0.1.50" }] From 84158304ab1a30f1868e5526560bb1b91fa1b1be Mon Sep 17 00:00:00 2001 From: alexcastgonz <82875882+pcbeingused333@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:23:41 -0400 Subject: [PATCH 25/33] fix(gemini): honor GEMINI_API_KEY environment variable (#1258) --- .../changesets/gemini-api-key-environment.md | 5 ++ posthog/ai/gemini/_shared.py | 8 ++- posthog/ai/gemini/gemini.py | 4 +- posthog/ai/gemini/gemini_async.py | 4 +- posthog/test/ai/gemini/test_gemini_parity.py | 50 +++++++++++++++++-- 5 files changed, 60 insertions(+), 11 deletions(-) create mode 100644 .sampo/changesets/gemini-api-key-environment.md diff --git a/.sampo/changesets/gemini-api-key-environment.md b/.sampo/changesets/gemini-api-key-environment.md new file mode 100644 index 000000000..c076fbc42 --- /dev/null +++ b/.sampo/changesets/gemini-api-key-environment.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +Honor `GEMINI_API_KEY` when initializing the synchronous and asynchronous Gemini clients, after `GOOGLE_API_KEY` and before the legacy `API_KEY` fallback. diff --git a/posthog/ai/gemini/_shared.py b/posthog/ai/gemini/_shared.py index cdff0fc30..367b7ba22 100644 --- a/posthog/ai/gemini/_shared.py +++ b/posthog/ai/gemini/_shared.py @@ -70,10 +70,14 @@ def _build_gemini_client_args( resolved_api_key = api_key if resolved_api_key is None: - resolved_api_key = os.environ.get("GOOGLE_API_KEY") or os.environ.get("API_KEY") + resolved_api_key = ( + os.environ.get("GOOGLE_API_KEY") + or os.environ.get("GEMINI_API_KEY") + or os.environ.get("API_KEY") + ) if resolved_api_key is None: raise ValueError( - "API key must be provided either as parameter or via GOOGLE_API_KEY/API_KEY environment variable" + "API key must be provided either as parameter or via GOOGLE_API_KEY/GEMINI_API_KEY/API_KEY environment variable" ) client_args["api_key"] = resolved_api_key diff --git a/posthog/ai/gemini/gemini.py b/posthog/ai/gemini/gemini.py index 42d5cb688..5c5c8fd60 100644 --- a/posthog/ai/gemini/gemini.py +++ b/posthog/ai/gemini/gemini.py @@ -81,7 +81,7 @@ def __init__( ): """ Args: - api_key: Google AI API key. If not provided, will use GOOGLE_API_KEY or API_KEY environment variable (not required for Vertex AI) + api_key: Google AI API key. If not provided, will use GOOGLE_API_KEY, GEMINI_API_KEY, or API_KEY environment variables in that order (not required for Vertex AI) vertexai: Whether to use Vertex AI authentication credentials: Vertex AI credentials object project: GCP project ID for Vertex AI @@ -160,7 +160,7 @@ def __init__( ): """ Args: - api_key: Google AI API key. If not provided, will use GOOGLE_API_KEY or API_KEY environment variable (not required for Vertex AI) + api_key: Google AI API key. If not provided, will use GOOGLE_API_KEY, GEMINI_API_KEY, or API_KEY environment variables in that order (not required for Vertex AI) vertexai: Whether to use Vertex AI authentication credentials: Vertex AI credentials object project: GCP project ID for Vertex AI diff --git a/posthog/ai/gemini/gemini_async.py b/posthog/ai/gemini/gemini_async.py index 3b0d45c69..7463318ab 100644 --- a/posthog/ai/gemini/gemini_async.py +++ b/posthog/ai/gemini/gemini_async.py @@ -76,7 +76,7 @@ def __init__( ): """ Args: - api_key: Google AI API key. If not provided, will use GOOGLE_API_KEY or API_KEY environment variable (not required for Vertex AI) + api_key: Google AI API key. If not provided, will use GOOGLE_API_KEY, GEMINI_API_KEY, or API_KEY environment variables in that order (not required for Vertex AI) vertexai: Whether to use Vertex AI authentication credentials: Vertex AI credentials object project: GCP project ID for Vertex AI @@ -144,7 +144,7 @@ def __init__( ): """ Args: - api_key: Google AI API key. If not provided, will use GOOGLE_API_KEY or API_KEY environment variable (not required for Vertex AI) + api_key: Google AI API key. If not provided, will use GOOGLE_API_KEY, GEMINI_API_KEY, or API_KEY environment variables in that order (not required for Vertex AI) vertexai: Whether to use Vertex AI authentication credentials: Vertex AI credentials object project: GCP project ID for Vertex AI diff --git a/posthog/test/ai/gemini/test_gemini_parity.py b/posthog/test/ai/gemini/test_gemini_parity.py index e4605e49c..9f7166f7e 100644 --- a/posthog/test/ai/gemini/test_gemini_parity.py +++ b/posthog/test/ai/gemini/test_gemini_parity.py @@ -11,16 +11,56 @@ @pytest.mark.parametrize("client_class", [Client, AsyncClient]) -def test_sync_and_async_clients_share_api_key_environment_precedence( +def test_clients_initialize_with_gemini_api_key_without_network( client_class, monkeypatch ): - monkeypatch.setenv("GOOGLE_API_KEY", "google-key") - monkeypatch.setenv("API_KEY", "legacy-key") + for name in ("GOOGLE_API_KEY", "API_KEY", "GOOGLE_GENAI_USE_VERTEXAI"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("GEMINI_API_KEY", "test-gemini-key") + + client = client_class(posthog_client=MagicMock()) + try: + assert client.models is not None + assert isinstance(client._provider_client, google_genai.Client) + finally: + client._provider_client.close() + + +@pytest.mark.parametrize("client_class", [Client, AsyncClient]) +@pytest.mark.parametrize( + "environment, explicit_key, expected_key", + [ + ({"GEMINI_API_KEY": "gemini-key"}, None, "gemini-key"), + ({"API_KEY": "legacy-key"}, None, "legacy-key"), + ( + {"GEMINI_API_KEY": "gemini-key", "API_KEY": "legacy-key"}, + None, + "gemini-key", + ), + ( + { + "GOOGLE_API_KEY": "google-key", + "GEMINI_API_KEY": "gemini-key", + "API_KEY": "legacy-key", + }, + None, + "google-key", + ), + ({"GEMINI_API_KEY": "gemini-key"}, "explicit-key", "explicit-key"), + ], +) +def test_sync_and_async_clients_share_api_key_environment_precedence( + client_class, monkeypatch, environment, explicit_key, expected_key +): + for name in ("GOOGLE_API_KEY", "GEMINI_API_KEY", "API_KEY"): + monkeypatch.delenv(name, raising=False) + for name, value in environment.items(): + monkeypatch.setenv(name, value) with patch.object(google_genai, "Client") as provider_client: - client_class(posthog_client=MagicMock()) + client_class(api_key=explicit_key, posthog_client=MagicMock()) - provider_client.assert_called_once_with(api_key="google-key") + provider_client.assert_called_once_with(api_key=expected_key) @pytest.mark.parametrize("client_class", [Client, AsyncClient]) From 534051451fd5d242a50974577bcd4f2c00ca5f74 Mon Sep 17 00:00:00 2001 From: Aditya Gupta <84338325+MaiAditya@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:55:01 +0530 Subject: [PATCH 26/33] fix(ai): give Claude Agent SDK generations their tool results and every output block (#1256) The Claude Code CLI sends each content block of a response as its own AssistantMessage, and each tool result as its own UserMessage after the generation's message_stop. The processor and PostHogClaudeSDKClient replaced the pending output on every AssistantMessage and promoted queued input at message_stop, so a generation kept only its last output block and the generation after a tool call had no $ai_input. Append output blocks per generation, append tool results to the queued input, and promote queued input when the next main-agent generation starts. A generation with nothing queued still has no input, as before. A request that is restarted before its message_stop drops its partial output. Without stream events, the result fallback reports every block of the final assistant turn. Messages a subagent sends (parent_tool_use_id set) stay out of the main generations' content. --- .../claude-agent-sdk-tool-results.md | 5 + posthog/ai/claude_agent_sdk/client.py | 32 ++- posthog/ai/claude_agent_sdk/formatting.py | 38 ++- posthog/ai/claude_agent_sdk/processor.py | 66 +++-- .../test/ai/claude_agent_sdk/test_client.py | 225 ++++++++++++++++++ 5 files changed, 341 insertions(+), 25 deletions(-) create mode 100644 .sampo/changesets/claude-agent-sdk-tool-results.md diff --git a/.sampo/changesets/claude-agent-sdk-tool-results.md b/.sampo/changesets/claude-agent-sdk-tool-results.md new file mode 100644 index 000000000..c09442ff8 --- /dev/null +++ b/.sampo/changesets/claude-agent-sdk-tool-results.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +Claude Agent SDK: give each generation the tool results it was called with, and keep every text and tool-use block of a response in its `$ai_output_choices`. diff --git a/posthog/ai/claude_agent_sdk/client.py b/posthog/ai/claude_agent_sdk/client.py index 5d3d3d458..df1491b0f 100644 --- a/posthog/ai/claude_agent_sdk/client.py +++ b/posthog/ai/claude_agent_sdk/client.py @@ -24,13 +24,17 @@ ) from .formatting import ( + _append_assistant_output, _format_user_input, - format_assistant_blocks, + format_assistant_blocks as format_assistant_blocks, format_tool_result_content as format_tool_result_content, ) from posthog.ai.claude_agent_sdk.processor import ( PostHogClaudeAgentProcessor, _GenerationTracker, + _from_subagent, + _promote_input, + _starts_generation, ) from posthog.client import Client @@ -130,6 +134,8 @@ async def query(self, prompt: str, session_id: str = "default") -> None: """ # Track the prompt as input for the next generation self._current_input = [{"role": "user", "content": prompt}] + self._next_input = None + self._pending_output = [] await self._client.query(prompt, session_id) async def receive_response(self): @@ -143,6 +149,14 @@ async def receive_response(self): def _process_message(self, message: Any) -> None: if isinstance(message, StreamEvent): + if _starts_generation(message): + if self._tracker.current_span_id is not None: + # The previous request never finished (it was retried), + # so its partial output is dropped. + self._pending_output = [] + self._current_input, self._next_input = _promote_input( + self._current_input, self._next_input + ) self._tracker.process_stream_event(message) if self._tracker.has_completed_generation(): @@ -160,14 +174,17 @@ def _process_message(self, message: Any) -> None: self._privacy, self._groups, ) - self._current_input = self._next_input - self._next_input = None + self._current_input = None self._pending_output = [] elif isinstance(message, AssistantMessage): self._process_assistant_message(message) - elif isinstance(message, UserMessage): + elif isinstance(message, UserMessage) and not _from_subagent(message): + if not self._tracker.had_any_stream_events: + # Without stream events, a tool result ends the assistant turn; + # the result fallback reports the final turn only. + self._pending_output = [] self._next_input = _format_user_input( message.content, self._processor._client, self._next_input ) @@ -203,9 +220,10 @@ def _process_assistant_message(self, message: "AssistantMessage") -> None: self._privacy, self._groups, ) - output_content = format_assistant_blocks(message.content) - if output_content: - self._pending_output = [{"role": "assistant", "content": output_content}] + if not _from_subagent(message): + self._pending_output = _append_assistant_output( + self._pending_output, message.content + ) async def disconnect(self) -> None: """ diff --git a/posthog/ai/claude_agent_sdk/formatting.py b/posthog/ai/claude_agent_sdk/formatting.py index a99c8cbd3..bf8cbcbc6 100644 --- a/posthog/ai/claude_agent_sdk/formatting.py +++ b/posthog/ai/claude_agent_sdk/formatting.py @@ -55,11 +55,45 @@ def format_assistant_blocks(blocks: Any) -> List[Dict[str, Any]]: return out +def _append_assistant_output( + pending: List[Dict[str, Any]], blocks: Any +) -> List[Dict[str, Any]]: + """Add one AssistantMessage's blocks to the output of the current generation. + + The CLI sends each content block of a response as its own AssistantMessage. + """ + output_content = format_assistant_blocks(blocks) + if not output_content: + return pending + previous = pending[0]["content"] if pending else [] + return [{"role": "assistant", "content": previous + output_content}] + + +def _append_user_input( + previous: Optional[List[Dict[str, Any]]], content: Any +) -> List[Dict[str, Any]]: + queued = previous or [] + last = queued[-1] if queued else None + if ( + isinstance(content, list) + and last is not None + and last.get("role") == "user" + and isinstance(last.get("content"), list) + ): + return queued[:-1] + [{"role": "user", "content": last["content"] + content}] + return queued + [{"role": "user", "content": content}] + + def _format_user_input( content: Any, client: Any, previous: Optional[List[Dict[str, Any]]] ) -> Optional[List[Dict[str, Any]]]: + """Queue a UserMessage as input for the next generation. + + The CLI sends each tool result as its own UserMessage, so results are + appended to what is already queued instead of replacing it. + """ if isinstance(content, str): - return [{"role": "user", "content": content}] + return _append_user_input(previous, content) if isinstance(content, list): formatted: List[Dict[str, Any]] = [] for block in content: @@ -74,5 +108,5 @@ def _format_user_input( elif hasattr(block, "text"): formatted.append({"type": "text", "text": block.text}) if formatted: - return [{"role": "user", "content": formatted}] + return _append_user_input(previous, formatted) return previous diff --git a/posthog/ai/claude_agent_sdk/processor.py b/posthog/ai/claude_agent_sdk/processor.py index 022ad8cc5..0f86feeb0 100644 --- a/posthog/ai/claude_agent_sdk/processor.py +++ b/posthog/ai/claude_agent_sdk/processor.py @@ -26,8 +26,9 @@ from posthog import setup from .formatting import ( + _append_assistant_output, _format_user_input, - format_assistant_blocks, + format_assistant_blocks as format_assistant_blocks, format_tool_result_content as format_tool_result_content, ) from posthog.ai.media import ensure_serializable as _ensure_serializable @@ -307,12 +308,14 @@ async def _instrument_query( # Two-slot input tracking: # - current_input: input for the generation currently in progress - # - next_input: tool results that arrive mid-turn, queued for the next generation + # - next_input: tool results queued for the next generation # - # Message ordering from the SDK is: - # message_start → content_blocks → AssistantMessage → UserMessage(tool result) → message_stop - # So UserMessage arrives *before* message_stop. When message_stop fires we emit - # with current_input, then promote next_input → current_input for the next turn. + # The CLI sends each content block as its own AssistantMessage before + # message_stop, and each tool result as its own UserMessage after it. + # Queued input is promoted when the next generation starts, so it + # does not matter which side of message_stop the tool results land on. + # Input is used by one generation only: a generation with nothing + # queued has no input. next_input: Optional[List[Dict[str, Any]]] = None # Accumulate assistant output per generation @@ -325,6 +328,14 @@ async def _instrument_query( # never interrupt the underlying Claude Agent SDK query. try: if isinstance(message, StreamEvent): + if _starts_generation(message): + if tracker.current_span_id is not None: + # The previous request never finished (it was + # retried), so its partial output is dropped. + pending_output = [] + current_input, next_input = _promote_input( + current_input, next_input + ) tracker.process_stream_event(message) # Emit $ai_generation when a turn completes @@ -343,9 +354,7 @@ async def _instrument_query( privacy, groups, ) - # Promote: tool results from this turn become input for next turn - current_input = next_input - next_input = None + current_input = None pending_output = [] elif isinstance(message, AssistantMessage): @@ -361,9 +370,13 @@ async def _instrument_query( pending_output, ) - elif isinstance(message, UserMessage): - # UserMessages carry tool results. They arrive *before* message_stop - # for the current turn, so queue them as input for the *next* generation. + elif isinstance(message, UserMessage) and not _from_subagent(message): + # UserMessages carry tool results; queue them as input for the + # *next* generation. + if not tracker.had_any_stream_events: + # Without stream events, a tool result ends the assistant + # turn; the result fallback reports the final turn only. + pending_output = [] next_input = _format_user_input( message.content, self._client, next_input ) @@ -455,10 +468,10 @@ def _process_assistant_message( privacy, groups, ) - output_content = format_assistant_blocks(message.content) - if output_content: - pending_output = [{"role": "assistant", "content": output_content}] - return pending_output + if _from_subagent(message): + # A subagent's own API calls are not this query's generations. + return pending_output + return _append_assistant_output(pending_output, message.content) def _emit_generation( self, @@ -678,6 +691,27 @@ def _resolve_distinct_id( return self._get_distinct_id(result) +def _from_subagent(message: Any) -> bool: + return getattr(message, "parent_tool_use_id", None) is not None + + +def _starts_generation(message: "StreamEvent") -> bool: + """Whether a main-agent API call is starting (subagent calls are skipped).""" + return ( + not _from_subagent(message) + and isinstance(message.event, dict) + and message.event.get("type") == "message_start" + ) + + +def _promote_input( + current_input: Optional[List[Dict[str, Any]]], + next_input: Optional[List[Dict[str, Any]]], +) -> tuple[Optional[List[Dict[str, Any]]], None]: + """Make queued input the input of the generation that is starting.""" + return (current_input if next_input is None else next_input), None + + def _query_inputs( prompt: Any, options: ClaudeAgentOptions ) -> tuple[List[Dict[str, Any]], Optional[List[Dict[str, Any]]]]: diff --git a/posthog/test/ai/claude_agent_sdk/test_client.py b/posthog/test/ai/claude_agent_sdk/test_client.py index acdd38ac3..6ceb3452a 100644 --- a/posthog/test/ai/claude_agent_sdk/test_client.py +++ b/posthog/test/ai/claude_agent_sdk/test_client.py @@ -1,5 +1,6 @@ """Stateful Claude client delivery, turn boundaries, and teardown contracts.""" +from dataclasses import replace from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock @@ -370,3 +371,227 @@ async def consume(): assert finalized.is_set() ph.capture.assert_not_called() ph.flush.assert_not_called() + + +def cli_tool_turn(): + """Message order the Claude Code CLI (2.1.212) emits for a turn with two tool calls. + + Each content block arrives as its own AssistantMessage, and each tool result + arrives as its own UserMessage after the generation's message_stop. + """ + return [ + stream( + "message_start", message={"model": "claude", "usage": {"input_tokens": 12}} + ), + AssistantMessage(model="claude", content=[TextBlock(text="Reading.")]), + AssistantMessage( + model="claude", + content=[ToolUseBlock(id="tool-1", name="Read", input={"path": "a"})], + ), + AssistantMessage( + model="claude", + content=[ToolUseBlock(id="tool-2", name="Read", input={"path": "b"})], + ), + stream("message_delta", usage={"output_tokens": 4}), + stream("message_stop"), + UserMessage(content=[ToolResultBlock(tool_use_id="tool-2", content="b text")]), + UserMessage(content=[ToolResultBlock(tool_use_id="tool-1", content="a text")]), + stream( + "message_start", message={"model": "claude", "usage": {"input_tokens": 20}} + ), + AssistantMessage(model="claude", content=[TextBlock(text="Done.")]), + stream("message_delta", usage={"output_tokens": 2}), + stream("message_stop"), + result(), + ] + + +async def run_turn(sdk, monkeypatch, use_client, messages): + ph = analytics() + if use_client: + client = PostHogClaudeSDKClient(posthog_client=ph) + await client.query("question") + respond(sdk, messages) + assert [msg async for msg in client.receive_response()] == messages + else: + + async def query(**kwargs): + for message in messages: + yield message + + monkeypatch.setattr( + "posthog.ai.claude_agent_sdk.processor.original_query", query + ) + processor = PostHogClaudeAgentProcessor(client=ph) + assert [msg async for msg in processor.query(prompt="question")] == messages + return [event["properties"] for event in events(ph, "$ai_generation")] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_client", [False, True]) +async def test_cli_order_keeps_every_output_block_in_its_generation( + sdk, monkeypatch, use_client +): + one, two = await run_turn(sdk, monkeypatch, use_client, cli_tool_turn()) + assert one["$ai_output_choices"] == [ + { + "role": "assistant", + "content": [ + {"type": "text", "text": "Reading."}, + { + "type": "function", + "function": {"name": "Read", "arguments": {"path": "a"}}, + }, + { + "type": "function", + "function": {"name": "Read", "arguments": {"path": "b"}}, + }, + ], + } + ] + assert two["$ai_output_choices"] == [ + {"role": "assistant", "content": [{"type": "text", "text": "Done."}]} + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_client", [False, True]) +async def test_cli_order_gives_tool_results_to_the_next_generation( + sdk, monkeypatch, use_client +): + one, two = await run_turn(sdk, monkeypatch, use_client, cli_tool_turn()) + assert one["$ai_input"] == [{"role": "user", "content": "question"}] + assert two["$ai_input"] == [ + { + "role": "user", + "content": [ + {"type": "tool_result", "tool_use_id": "tool-2", "content": "b text"}, + {"type": "tool_result", "tool_use_id": "tool-1", "content": "a text"}, + ], + } + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_client", [False, True]) +async def test_subagent_messages_stay_out_of_main_generation_content( + sdk, monkeypatch, use_client +): + turn = cli_tool_turn() + # The CLI forwards a subagent's messages with parent_tool_use_id set while + # the tool that started it runs, between the two main generations. + turn[7:7] = [ + AssistantMessage( + model="claude", + content=[TextBlock(text="subagent says")], + parent_tool_use_id="tool-1", + ), + UserMessage( + content=[ToolResultBlock(tool_use_id="sub-tool", content="sub result")], + parent_tool_use_id="tool-1", + ), + ] + one, two = await run_turn(sdk, monkeypatch, use_client, turn) + assert [b["tool_use_id"] for b in two["$ai_input"][0]["content"]] == [ + "tool-2", + "tool-1", + ] + assert two["$ai_output_choices"] == [ + {"role": "assistant", "content": [{"type": "text", "text": "Done."}]} + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_client", [False, True]) +async def test_subagent_stream_events_do_not_take_queued_tool_results( + sdk, monkeypatch, use_client +): + turn = cli_tool_turn() + # The subagent started by tool-1 makes its own API call after tool-2's + # result is queued and before tool-1's result arrives. + turn[7:7] = [ + replace(stream(kind), parent_tool_use_id="tool-1") + for kind in ("message_start", "message_stop") + ] + generations = await run_turn(sdk, monkeypatch, use_client, turn) + assert [b["tool_use_id"] for b in generations[-1]["$ai_input"][0]["content"]] == [ + "tool-2", + "tool-1", + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_client", [False, True]) +async def test_retried_request_reports_only_the_finished_attempt( + sdk, monkeypatch, use_client +): + messages = [ + stream("message_start", message={"model": "claude", "usage": {}}), + AssistantMessage(model="claude", content=[TextBlock(text="partial")]), + stream("message_start", message={"model": "claude", "usage": {}}), + AssistantMessage(model="claude", content=[TextBlock(text="full")]), + stream("message_stop"), + result(), + ] + (generation,) = await run_turn(sdk, monkeypatch, use_client, messages) + assert generation["$ai_input"] == [{"role": "user", "content": "question"}] + assert generation["$ai_output_choices"] == [ + {"role": "assistant", "content": [{"type": "text", "text": "full"}]} + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_client", [False, True]) +async def test_generation_without_queued_input_has_no_input( + sdk, monkeypatch, use_client +): + messages = [ + stream("message_start", message={"model": "claude", "usage": {}}), + AssistantMessage(model="claude", content=[TextBlock(text="one")]), + stream("message_stop"), + stream("message_start", message={"model": "claude", "usage": {}}), + AssistantMessage(model="claude", content=[TextBlock(text="two")]), + stream("message_stop"), + result(), + ] + one, two = await run_turn(sdk, monkeypatch, use_client, messages) + assert one["$ai_input"] == [{"role": "user", "content": "question"}] + assert "$ai_input" not in two + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_client", [False, True]) +async def test_result_fallback_reports_every_block_of_the_final_turn_only( + sdk, monkeypatch, use_client +): + turn = [m for m in cli_tool_turn() if not isinstance(m, StreamEvent)] + turn[-1:-1] = [AssistantMessage(model="claude", content=[TextBlock(text="Bye.")])] + (generation,) = await run_turn(sdk, monkeypatch, use_client, turn) + assert generation["$ai_input"] == [{"role": "user", "content": "question"}] + assert generation["$ai_output_choices"] == [ + { + "role": "assistant", + "content": [ + {"type": "text", "text": "Done."}, + {"type": "text", "text": "Bye."}, + ], + } + ] + + +@pytest.mark.asyncio +async def test_result_fallback_does_not_carry_output_into_the_next_query(sdk): + ph = analytics() + client = PostHogClaudeSDKClient(posthog_client=ph) + for prompt in ("first", "second"): + await client.query(prompt) + messages = [ + AssistantMessage(model="claude", content=[TextBlock(text=prompt)]), + result(), + ] + respond(sdk, messages) + assert [msg async for msg in client.receive_response()] == messages + second = events(ph, "$ai_generation")[1]["properties"] + assert second["$ai_output_choices"] == [ + {"role": "assistant", "content": [{"type": "text", "text": "second"}]} + ] From 92fae510c34dd1d1514b9b3b78791c159ab4dc1a Mon Sep 17 00:00:00 2001 From: Jae Birdsall Date: Mon, 16 Nov 2026 04:25:42 -0500 Subject: [PATCH 27/33] fix(ai): record an Anthropic stream error event's status, not 200 (#1253) fix(ai): record the status of an Anthropic stream error event instead of 200 Anthropic sends errors that happen after a stream starts, such as overloaded_error, as an SSE error event, and the anthropic SDK raises them with the stream response's 200 status. Map the error type to its documented HTTP status (0 when unknown) so these failures are not recorded as a 200. --- .../anthropic-stream-error-event-status.md | 5 +++ posthog/ai/langchain/callbacks.py | 3 ++ posthog/ai/utils.py | 35 ++++++++++++++++++- posthog/test/ai/test_http_status.py | 33 +++++++++++++++++ 4 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 .sampo/changesets/anthropic-stream-error-event-status.md diff --git a/.sampo/changesets/anthropic-stream-error-event-status.md b/.sampo/changesets/anthropic-stream-error-event-status.md new file mode 100644 index 000000000..d55761ea8 --- /dev/null +++ b/.sampo/changesets/anthropic-stream-error-event-status.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +An Anthropic error that arrives as an `error` event inside a stream, such as `overloaded_error`, is no longer recorded with `$ai_http_status: 200`. The anthropic SDK raises it with the stream's 200 status, so `$ai_http_status` now comes from the error type (529 for `overloaded_error`, 429 for `rate_limit_error`), or is 0 for an unknown type. This applies to the LangChain callback handler and to every capture that reads the status through `_get_http_status`. diff --git a/posthog/ai/langchain/callbacks.py b/posthog/ai/langchain/callbacks.py index 0589f472c..27b2eb6aa 100644 --- a/posthog/ai/langchain/callbacks.py +++ b/posthog/ai/langchain/callbacks.py @@ -47,6 +47,7 @@ from posthog.ai.utils import ( _capture_ai_event, _extract_cache_creation_ttl_breakdown, + _stream_error_event_status, finalize_ai_content, _format_ai_error, get_model_params, @@ -1046,6 +1047,8 @@ def _get_http_status(error: BaseException) -> int: for attribute in ("status_code", "code"): value = getattr(error, attribute, None) if isinstance(value, int) and not isinstance(value, bool): + if attribute == "status_code": + return _stream_error_event_status(error, value) return value return 0 diff --git a/posthog/ai/utils.py b/posthog/ai/utils.py index dfc4c8c90..17dc0500d 100644 --- a/posthog/ai/utils.py +++ b/posthog/ai/utils.py @@ -436,6 +436,39 @@ def _merge_openai_system_prompt( return messages +# https://docs.anthropic.com/en/api/errors +_ANTHROPIC_ERROR_TYPE_STATUS = { + "invalid_request_error": 400, + "authentication_error": 401, + "billing_error": 402, + "permission_error": 403, + "not_found_error": 404, + "request_too_large": 413, + "rate_limit_error": 429, + "api_error": 500, + "timeout_error": 504, + "overloaded_error": 529, +} + + +def _stream_error_event_status(exc: BaseException, status: int) -> int: + """Status of an error that arrived as an `error` event inside a stream. + + Anthropic sends errors that happen after a stream starts (such as + overloaded_error) as an SSE `error` event, and its SDK raises them with the + stream's own 200 status. Use the status that the error type stands for, or + 0 when it is unknown, so the event is not recorded as a 200. + """ + if status < 400: + body = getattr(exc, "body", None) + error = body.get("error") if isinstance(body, dict) else None + error_type = error.get("type") if isinstance(error, dict) else None + if isinstance(error_type, str): + return _ANTHROPIC_ERROR_TYPE_STATUS.get(error_type, 0) + return 0 + return status + + def _get_http_status(exc: BaseException) -> int: """HTTP status of an SDK exception, 0 when it has none. @@ -444,7 +477,7 @@ def _get_http_status(exc: BaseException) -> int: """ status = getattr(exc, "status_code", None) if isinstance(status, int): - return status + return _stream_error_event_status(exc, status) code = getattr(exc, "code", None) if isinstance(code, int) and not isinstance(code, bool) and 100 <= code <= 599: return code diff --git a/posthog/test/ai/test_http_status.py b/posthog/test/ai/test_http_status.py index 1f79fa276..8f464079a 100644 --- a/posthog/test/ai/test_http_status.py +++ b/posthog/test/ai/test_http_status.py @@ -122,3 +122,36 @@ def boom(**kwargs): ) assert mock_client.capture.call_args[1]["properties"]["$ai_http_status"] == 503 + + +def _anthropic_stream_error_event(error_type): + """The error the anthropic SDK raises for an SSE `error` event: it carries + the status of the stream response, which is 200.""" + import anthropic + from unittest.mock import MagicMock + + response = MagicMock(status_code=200, headers={}) + body = {"type": "error", "error": {"type": error_type, "message": "x"}} + return anthropic.Anthropic(api_key="k")._make_status_error( + str(body), body=body, response=response + ) + + +@pytest.mark.parametrize( + "error_type, status", + [("overloaded_error", 529), ("rate_limit_error", 429), ("api_error", 500)], +) +def test_anthropic_stream_error_event_status(error_type, status): + from posthog.ai.langchain.callbacks import ( + _get_http_status as _langchain_http_status, + ) + + error = _anthropic_stream_error_event(error_type) + assert error.status_code == 200 + assert _get_http_status(error) == status + assert _langchain_http_status(error) == status + + +def test_anthropic_stream_error_event_of_unknown_type_is_not_a_200(): + error = _anthropic_stream_error_event("some_new_error") + assert _get_http_status(error) == 0 From ade1ff990b3f334a41e284ca32e3241499019d80 Mon Sep 17 00:00:00 2001 From: alexcastgonz <82875882+pcbeingused333@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:27:28 -0400 Subject: [PATCH 28/33] fix(ai): capture initial request errors in Anthropic messages.stream() (#1249) messages.stream() wrapped the manager's request without a try/except, so a failed initial request (401, connection error) raised without any $ai_generation error event, unlike create(stream=True). Capture the error in both sync and async clients and re-raise. --- .../anthropic-stream-request-error.md | 5 +++ posthog/ai/anthropic/anthropic.py | 23 ++++++++++- posthog/ai/anthropic/anthropic_async.py | 23 ++++++++++- posthog/test/ai/anthropic/test_anthropic.py | 41 +++++++++++++++++++ 4 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 .sampo/changesets/anthropic-stream-request-error.md diff --git a/.sampo/changesets/anthropic-stream-request-error.md b/.sampo/changesets/anthropic-stream-request-error.md new file mode 100644 index 000000000..89d40b741 --- /dev/null +++ b/.sampo/changesets/anthropic-stream-request-error.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +`posthog.ai.anthropic`: `messages.stream()` (sync and async) now captures an `$ai_generation` event with `$ai_is_error` when the initial request fails, for example with a 401 or a connection error. Before, only `messages.create(stream=True)` captured that failure, so errors raised on entering the `stream()` context manager were never reported. diff --git a/posthog/ai/anthropic/anthropic.py b/posthog/ai/anthropic/anthropic.py index ef4c4dacb..957cdd380 100644 --- a/posthog/ai/anthropic/anthropic.py +++ b/posthog/ai/anthropic/anthropic.py @@ -140,7 +140,28 @@ def stream( def tracked_request(): start_time = time.time() - response = request() + try: + response = request() + except Exception as exc: + accumulator = _AnthropicStreamAccumulator() + try: + self._capture_streaming_event( + posthog_distinct_id, + posthog_trace_id, + posthog_properties, + posthog_privacy_mode, + posthog_groups, + kwargs, + accumulator.usage_stats, + time.time() - start_time, + accumulator.content_blocks, + accumulator.accumulated_content, + error=exc, + ) + except Exception: + # Telemetry must never replace the provider's own error. + _log.warning("[PostHog] Failed to capture streaming connect error") + raise return self._track_streaming_response( response, posthog_distinct_id, diff --git a/posthog/ai/anthropic/anthropic_async.py b/posthog/ai/anthropic/anthropic_async.py index 80014ce91..baf13c821 100644 --- a/posthog/ai/anthropic/anthropic_async.py +++ b/posthog/ai/anthropic/anthropic_async.py @@ -141,7 +141,28 @@ def stream( async def tracked_request(): start_time = time.time() - response = await request + try: + response = await request + except Exception as exc: + accumulator = _AnthropicStreamAccumulator() + try: + await self._capture_streaming_event( + posthog_distinct_id, + posthog_trace_id, + posthog_properties, + posthog_privacy_mode, + posthog_groups, + kwargs, + accumulator.usage_stats, + time.time() - start_time, + accumulator.content_blocks, + accumulator.accumulated_content, + error=exc, + ) + except Exception: + # Telemetry must never replace the provider's own error. + _log.warning("[PostHog] Failed to capture streaming connect error") + raise return self._track_streaming_response( response, posthog_distinct_id, diff --git a/posthog/test/ai/anthropic/test_anthropic.py b/posthog/test/ai/anthropic/test_anthropic.py index d14847a94..22e8d1767 100644 --- a/posthog/test/ai/anthropic/test_anthropic.py +++ b/posthog/test/ai/anthropic/test_anthropic.py @@ -2274,6 +2274,26 @@ def test_messages_stream_preserves_native_manager_helpers_close_and_tracking( assert "posthog_distinct_id" not in client.post.call_args.kwargs +def test_messages_stream_captures_initial_request_error(mock_client): + client = Anthropic(api_key="test-key", posthog_client=mock_client) + client.post = Mock(side_effect=RuntimeError("401 unauthorized")) + + manager = client.messages.stream( + model="claude-haiku-4-5", + messages=[{"role": "user", "content": "Foo"}], + max_tokens=1, + posthog_distinct_id="test-user", + ) + with pytest.raises(RuntimeError, match="401 unauthorized"): + with manager: + pass + + assert mock_client.capture.call_count == 1 + props = mock_client.capture.call_args.kwargs["properties"] + assert props["$ai_is_error"] is True + assert props["$ai_error"] == "401 unauthorized" + + def test_messages_stream_tolerates_provider_manager_internals_changing(mock_client): manager = object() client = Anthropic(api_key="test-key", posthog_client=mock_client) @@ -2316,6 +2336,27 @@ async def test_async_messages_stream_preserves_provider_contract_and_manager( assert "posthog_distinct_id" not in client.post.call_args.kwargs +@pytest.mark.asyncio +async def test_async_messages_stream_captures_initial_request_error(mock_client): + client = AsyncAnthropic(api_key="test-key", posthog_client=mock_client) + client.post = AsyncMock(side_effect=RuntimeError("401 unauthorized")) + + manager = client.messages.stream( + model="claude-haiku-4-5", + messages=[{"role": "user", "content": "Foo"}], + max_tokens=1, + posthog_distinct_id="test-user", + ) + with pytest.raises(RuntimeError, match="401 unauthorized"): + async with manager: + pass + + assert mock_client.capture.call_count == 1 + props = mock_client.capture.call_args.kwargs["properties"] + assert props["$ai_is_error"] is True + assert props["$ai_error"] == "401 unauthorized" + + def test_async_messages_stream_tolerates_provider_manager_internals_changing( mock_client, ): From eef61f61b8530d8520bf09efaa95a3a9ac8a7c20 Mon Sep 17 00:00:00 2001 From: "releaser-posthog-python[bot]" <262414804+releaser-posthog-python[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:09:52 +0000 Subject: [PATCH 29/33] chore: Release v7.91.2 [skip ci] --- .sampo/changesets/anthropic-stream-error-event-status.md | 5 ----- .sampo/changesets/anthropic-stream-request-error.md | 5 ----- .sampo/changesets/claude-agent-sdk-tool-results.md | 5 ----- .sampo/changesets/gemini-api-key-environment.md | 5 ----- openfeature-provider/CHANGELOG.md | 6 ++++++ openfeature-provider/pyproject.toml | 2 +- posthog/CHANGELOG.md | 9 +++++++++ posthog/version.py | 2 +- pyproject.toml | 2 +- uv.lock | 4 ++-- 10 files changed, 20 insertions(+), 25 deletions(-) delete mode 100644 .sampo/changesets/anthropic-stream-error-event-status.md delete mode 100644 .sampo/changesets/anthropic-stream-request-error.md delete mode 100644 .sampo/changesets/claude-agent-sdk-tool-results.md delete mode 100644 .sampo/changesets/gemini-api-key-environment.md diff --git a/.sampo/changesets/anthropic-stream-error-event-status.md b/.sampo/changesets/anthropic-stream-error-event-status.md deleted file mode 100644 index d55761ea8..000000000 --- a/.sampo/changesets/anthropic-stream-error-event-status.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: patch ---- - -An Anthropic error that arrives as an `error` event inside a stream, such as `overloaded_error`, is no longer recorded with `$ai_http_status: 200`. The anthropic SDK raises it with the stream's 200 status, so `$ai_http_status` now comes from the error type (529 for `overloaded_error`, 429 for `rate_limit_error`), or is 0 for an unknown type. This applies to the LangChain callback handler and to every capture that reads the status through `_get_http_status`. diff --git a/.sampo/changesets/anthropic-stream-request-error.md b/.sampo/changesets/anthropic-stream-request-error.md deleted file mode 100644 index 89d40b741..000000000 --- a/.sampo/changesets/anthropic-stream-request-error.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: patch ---- - -`posthog.ai.anthropic`: `messages.stream()` (sync and async) now captures an `$ai_generation` event with `$ai_is_error` when the initial request fails, for example with a 401 or a connection error. Before, only `messages.create(stream=True)` captured that failure, so errors raised on entering the `stream()` context manager were never reported. diff --git a/.sampo/changesets/claude-agent-sdk-tool-results.md b/.sampo/changesets/claude-agent-sdk-tool-results.md deleted file mode 100644 index c09442ff8..000000000 --- a/.sampo/changesets/claude-agent-sdk-tool-results.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: patch ---- - -Claude Agent SDK: give each generation the tool results it was called with, and keep every text and tool-use block of a response in its `$ai_output_choices`. diff --git a/.sampo/changesets/gemini-api-key-environment.md b/.sampo/changesets/gemini-api-key-environment.md deleted file mode 100644 index c076fbc42..000000000 --- a/.sampo/changesets/gemini-api-key-environment.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -pypi/posthog: patch ---- - -Honor `GEMINI_API_KEY` when initializing the synchronous and asynchronous Gemini clients, after `GOOGLE_API_KEY` and before the legacy `API_KEY` fallback. diff --git a/openfeature-provider/CHANGELOG.md b/openfeature-provider/CHANGELOG.md index 2ef947f89..dd1423d8f 100644 --- a/openfeature-provider/CHANGELOG.md +++ b/openfeature-provider/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to `openfeature-provider-posthog` are documented here. This file is maintained by [Sampo](https://github.com/bruits/sampo) from changesets in `.sampo/changesets/` that target `pypi/openfeature-provider-posthog`. +## 0.1.165 — 2026-11-16 + +### Patch changes + +- Updated dependencies: posthog@7.91.2 + ## 0.1.164 — 2026-11-13 ### Patch changes diff --git a/openfeature-provider/pyproject.toml b/openfeature-provider/pyproject.toml index 3103bab30..02e1dcadb 100644 --- a/openfeature-provider/pyproject.toml +++ b/openfeature-provider/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "openfeature-provider-posthog" -version = "0.1.164" +version = "0.1.165" description = "Official PostHog provider for the OpenFeature Python SDK." readme = "README.md" authors = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/posthog/CHANGELOG.md b/posthog/CHANGELOG.md index 8ea763fa4..9d9cd52c4 100644 --- a/posthog/CHANGELOG.md +++ b/posthog/CHANGELOG.md @@ -1,5 +1,14 @@ # posthog +## 7.91.2 — 2026-11-16 + +### Patch changes + +- [84158304](https://github.com/posthog/posthog-python/commit/84158304ab1a30f1868e5526560bb1b91fa1b1be) Honor `GEMINI_API_KEY` when initializing the synchronous and asynchronous Gemini clients, after `GOOGLE_API_KEY` and before the legacy `API_KEY` fallback. — Thanks @pcbeingused333! +- [ade1ff99](https://github.com/posthog/posthog-python/commit/ade1ff990b3f334a41e284ca32e3241499019d80) `posthog.ai.anthropic`: `messages.stream()` (sync and async) now captures an `$ai_generation` event with `$ai_is_error` when the initial request fails, for example with a 401 or a connection error. Before, only `messages.create(stream=True)` captured that failure, so errors raised on entering the `stream()` context manager were never reported. — Thanks @pcbeingused333! +- [92fae510](https://github.com/posthog/posthog-python/commit/92fae510c34dd1d1514b9b3b78791c159ab4dc1a) An Anthropic error that arrives as an `error` event inside a stream, such as `overloaded_error`, is no longer recorded with `$ai_http_status: 200`. The anthropic SDK raises it with the stream's 200 status, so `$ai_http_status` now comes from the error type (529 for `overloaded_error`, 429 for `rate_limit_error`), or is 0 for an unknown type. This applies to the LangChain callback handler and to every capture that reads the status through `_get_http_status`. — Thanks @jaeminbird! +- [53405145](https://github.com/posthog/posthog-python/commit/534051451fd5d242a50974577bcd4f2c00ca5f74) Claude Agent SDK: give each generation the tool results it was called with, and keep every text and tool-use block of a response in its `$ai_output_choices`. — Thanks @MaiAditya for your first contribution 🎉! + ## 7.91.1 — 2026-11-13 ### Patch changes diff --git a/posthog/version.py b/posthog/version.py index 3705a8564..d29da7e01 100644 --- a/posthog/version.py +++ b/posthog/version.py @@ -1 +1 @@ -VERSION = "7.91.1" +VERSION = "7.91.2" diff --git a/pyproject.toml b/pyproject.toml index 6bfa4b536..99b3f6286 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "posthog" -version = "7.91.1" +version = "7.91.2" description = "Integrate PostHog into any python application." authors = [{ name = "PostHog", email = "engineering@posthog.com" }] maintainers = [{ name = "PostHog", email = "engineering@posthog.com" }] diff --git a/uv.lock b/uv.lock index 99774a420..890d6b8a2 100644 --- a/uv.lock +++ b/uv.lock @@ -2723,7 +2723,7 @@ wheels = [ [[package]] name = "openfeature-provider-posthog" -version = "0.1.164" +version = "0.1.165" source = { editable = "openfeature-provider" } dependencies = [ { name = "openfeature-sdk" }, @@ -3280,7 +3280,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.91.1" +version = "7.91.2" source = { editable = "." } dependencies = [ { name = "backoff" }, From ca1ac3a4277a873edc039e3b28b64058763bfee3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:04:50 -0500 Subject: [PATCH 30/33] chore(deps): bump the github-actions group with 5 updates (#1259) Bumps the github-actions group with 5 updates: | Package | From | To | | --- | --- | --- | | [actions/setup-python](https://github.com/actions/setup-python) | `7.0.0` | `7.1.0` | | [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) | `10.3.0` | `10.3.3` | | [github/codeql-action/init](https://github.com/github/codeql-action) | `4.39.2` | `4.39.3` | | [github/codeql-action/analyze](https://github.com/github/codeql-action) | `4.39.2` | `4.39.3` | | [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) | `8.1.1` | `8.1.2` | Updates `actions/setup-python` from 7.0.0 to 7.1.0 - [Release notes](https://github.com/actions/setup-python/releases) - [Commits](https://github.com/actions/setup-python/compare/v7...6d4fd22b20465ccc0f7354476588e8df7c9ca0e0) Updates `astral-sh/setup-uv` from 10.3.0 to 10.3.3 - [Release notes](https://github.com/astral-sh/setup-uv/releases) - [Commits](https://github.com/astral-sh/setup-uv/compare/v10.3.0...68559e99cc807c1eb7e9238fd43a15bba460eec2) Updates `github/codeql-action/init` from 4.39.2 to 4.39.3 - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/1fc58d04a4d4374f921bdac573c3811c240f9c26...33d7b85da1a04171e211befe2c739303b9a4c066) Updates `github/codeql-action/analyze` from 4.39.2 to 4.39.3 - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/1fc58d04a4d4374f921bdac573c3811c240f9c26...33d7b85da1a04171e211befe2c739303b9a4c066) Updates `peter-evans/create-pull-request` from 8.1.1 to 8.1.2 - [Release notes](https://github.com/peter-evans/create-pull-request/releases) - [Commits](https://github.com/peter-evans/create-pull-request/compare/5f6978faf089d4d20b00c7766989d076bb2fc7f1...15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8) --- updated-dependencies: - dependency-name: actions/setup-python dependency-version: 7.1.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions - dependency-name: astral-sh/setup-uv dependency-version: 10.3.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions - dependency-name: github/codeql-action/init dependency-version: 4.39.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions - dependency-name: github/codeql-action/analyze dependency-version: 4.39.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions - dependency-name: peter-evans/create-pull-request dependency-version: 8.1.2 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/codeql.yml | 4 ++-- .github/workflows/generate-references.yml | 4 ++-- .github/workflows/posthog-upgrade.yml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index b15388d96..f8d92b062 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -30,7 +30,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Initialize CodeQL - uses: github/codeql-action/init@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} @@ -40,6 +40,6 @@ jobs: trap-caching: false - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 with: category: '/language:${{matrix.language}}' diff --git a/.github/workflows/generate-references.yml b/.github/workflows/generate-references.yml index 708e21322..14ef22d50 100644 --- a/.github/workflows/generate-references.yml +++ b/.github/workflows/generate-references.yml @@ -35,12 +35,12 @@ jobs: persist-credentials: false - name: Set up Python - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: 3.11 - name: Install uv - uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0 + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: version: "0.13.4" enable-cache: true diff --git a/.github/workflows/posthog-upgrade.yml b/.github/workflows/posthog-upgrade.yml index 55fc6718f..6435e643a 100644 --- a/.github/workflows/posthog-upgrade.yml +++ b/.github/workflows/posthog-upgrade.yml @@ -197,7 +197,7 @@ jobs: - name: Create main repo pull request if: steps.generate-pr-details.outputs.skip == 'false' id: main-repo-pr - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 env: HUSKY: "0" with: From 83eee808669a4e95dd1b4a0e0dc64a3039c53130 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:07:26 -0500 Subject: [PATCH 31/33] chore(deps): bump the ai-providers group with 9 updates (#1260) Bumps the ai-providers group with 9 updates: | Package | From | To | | --- | --- | --- | | [langchain](https://github.com/langchain-ai/langchain) | `1.4.7` | `1.4.9` | | [anthropic](https://github.com/anthropics/anthropic-sdk-python) | `1.13.0` | `2.6.0` | | [langgraph](https://github.com/langchain-ai/langgraph) | `1.2.16` | `1.2.20` | | [langchain-core](https://github.com/langchain-ai/langchain) | `1.6.13` | `1.7.6` | | [langchain-openai](https://github.com/langchain-ai/langchain) | `1.7.2` | `1.7.4` | | [langchain-anthropic](https://github.com/langchain-ai/langchain) | `1.7.6` | `1.7.10` | | [google-genai](https://github.com/googleapis/python-genai) | `2.32.0` | `2.33.0` | | [langchain-protocol](https://github.com/langchain-ai/agent-protocol) | `0.0.20` | `0.0.21` | | [openai](https://github.com/openai/openai-python) | `2.54.0` | `3.46.0` | Updates `langchain` from 1.4.7 to 1.4.9 - [Release notes](https://github.com/langchain-ai/langchain/releases) - [Commits](https://github.com/langchain-ai/langchain/compare/langchain==1.4.7...langchain==1.4.9) Updates `anthropic` from 1.13.0 to 2.6.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-python/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-python/compare/v1.13.0...v2.6.0) Updates `langgraph` from 1.2.16 to 1.2.20 - [Release notes](https://github.com/langchain-ai/langgraph/releases) - [Commits](https://github.com/langchain-ai/langgraph/compare/1.2.16...1.2.20) Updates `langchain-core` from 1.6.13 to 1.7.6 - [Release notes](https://github.com/langchain-ai/langchain/releases) - [Commits](https://github.com/langchain-ai/langchain/compare/langchain-core==1.6.13...langchain-core==1.7.6) Updates `langchain-openai` from 1.7.2 to 1.7.4 - [Release notes](https://github.com/langchain-ai/langchain/releases) - [Commits](https://github.com/langchain-ai/langchain/compare/langchain-openai==1.7.2...langchain-openai==1.7.4) Updates `langchain-anthropic` from 1.7.6 to 1.7.10 - [Release notes](https://github.com/langchain-ai/langchain/releases) - [Commits](https://github.com/langchain-ai/langchain/compare/langchain-anthropic==1.7.6...langchain-anthropic==1.7.10) Updates `google-genai` from 2.32.0 to 2.33.0 - [Release notes](https://github.com/googleapis/python-genai/releases) - [Changelog](https://github.com/googleapis/python-genai/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/python-genai/compare/v2.32.0...v2.33.0) Updates `langchain-protocol` from 0.0.20 to 0.0.21 - [Release notes](https://github.com/langchain-ai/agent-protocol/releases) - [Commits](https://github.com/langchain-ai/agent-protocol/compare/langchain-protocol==0.0.20...langchain-protocol==0.0.21) Updates `openai` from 2.54.0 to 3.46.0 - [Release notes](https://github.com/openai/openai-python/releases) - [Changelog](https://github.com/openai/openai-python/blob/main/CHANGELOG.md) - [Commits](https://github.com/openai/openai-python/compare/v2.54.0...v3.46.0) --- updated-dependencies: - dependency-name: langchain dependency-version: 1.4.9 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: ai-providers - dependency-name: anthropic dependency-version: 2.6.0 dependency-type: direct:production update-type: version-update:semver-major dependency-group: ai-providers - dependency-name: langgraph dependency-version: 1.2.20 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: ai-providers - dependency-name: langchain-core dependency-version: 1.7.6 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: ai-providers - dependency-name: langchain-openai dependency-version: 1.7.4 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: ai-providers - dependency-name: langchain-anthropic dependency-version: 1.7.10 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: ai-providers - dependency-name: google-genai dependency-version: 2.33.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: ai-providers - dependency-name: langchain-protocol dependency-version: 0.0.21 dependency-type: indirect update-type: version-update:semver-patch dependency-group: ai-providers - dependency-name: openai dependency-version: 3.46.0 dependency-type: indirect update-type: version-update:semver-major dependency-group: ai-providers ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- uv.lock | 400 ++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 286 insertions(+), 114 deletions(-) diff --git a/uv.lock b/uv.lock index 890d6b8a2..e6ced52b1 100644 --- a/uv.lock +++ b/uv.lock @@ -292,20 +292,22 @@ wheels = [ [[package]] name = "anthropic" -version = "1.13.0" +version = "2.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, { name = "docstring-parser" }, { name = "httpx2" }, - { name = "jiter" }, + { name = "jiter", version = "0.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jiter", version = "0.19.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "opentelemetry-api" }, { name = "pydantic" }, { name = "sniffio" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0b/ed/e76e50601b7c476bcb9a2a7a4c4dab6f1a9b2c03e3922de8b3ec599ccbc5/anthropic-1.13.0.tar.gz", hash = "sha256:ad11d9bb9adafdfea26113943bcde9973e2a439ebeeda6c89ff3e3d85bb2f5c1", size = 1567362, upload-time = "2026-10-09T15:29:08.803Z" } +sdist = { url = "https://files.pythonhosted.org/packages/4a/a8/0e50326e4c408f4b4ee3aae4c3bbd60012570b88bc5887effc8542509068/anthropic-2.6.0.tar.gz", hash = "sha256:a38d8698258a4cb33a9bc9d2f0ced1d96b71010870e5ed703807d21021a0da24", size = 1958763, upload-time = "2026-11-05T18:59:09.557Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ad/9a/a835340c91bc9a233bd54c05fc438fe07cbef71ca667f24f3892a268ae20/anthropic-1.13.0-py3-none-any.whl", hash = "sha256:157bd74dbf6a595cf9e5fcac557c791fd297924dc48261f57470c2ed6f4e6671", size = 1958595, upload-time = "2026-10-09T15:29:10.689Z" }, + { url = "https://files.pythonhosted.org/packages/38/0b/705a05ab68558914e725cf1143d7e409fa3bb596c35bca1eceab42402abe/anthropic-2.6.0-py3-none-any.whl", hash = "sha256:4325cdf9346fa29183674b6ee6289ebad5b2b0a935758f7350fa504032da1d9b", size = 2445307, upload-time = "2026-11-05T18:59:11.474Z" }, ] [[package]] @@ -1298,7 +1300,7 @@ requests = [ [[package]] name = "google-genai" -version = "2.32.0" +version = "2.33.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, @@ -1312,9 +1314,9 @@ dependencies = [ { name = "typing-extensions" }, { name = "websockets" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d3/f9/89c95879bd58f176f82415c1a63a9dce528ea2b7a83a155412db5b1c783b/google_genai-2.32.0.tar.gz", hash = "sha256:9e8fb72f0a878291bc20b941d5d535e249f5729290565b7d49406827a0c30152", size = 750015, upload-time = "2026-10-21T00:38:45.526Z" } +sdist = { url = "https://files.pythonhosted.org/packages/83/a4/b83b378b4a2fbbfb300c3fde0ff9f443f049c33e2accedf06bc0ad9bf393/google_genai-2.33.0.tar.gz", hash = "sha256:fced7f746da45264b34bcf6044a6fcdb91ebad1825e95c324ee48addb6e557ae", size = 758627, upload-time = "2026-10-23T00:06:28.332Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/97/70/964baf520f36019ad4e4ce316e6dc943189f3b398654ff8277dadb764f6d/google_genai-2.32.0-py3-none-any.whl", hash = "sha256:cf71a629df18510cd837cacb4843b38a2db6834c69eb93963a0d8ee4d657b725", size = 1213907, upload-time = "2026-10-21T00:38:43.471Z" }, + { url = "https://files.pythonhosted.org/packages/ba/3b/9ae8e16c5b2177bfdec1c64769a93eea9093de684e0bbb95c10c77645fef/google_genai-2.33.0-py3-none-any.whl", hash = "sha256:f3f8ab696b35caf95c222e05268740c1ccd6934257890506be73b126150d3b14", size = 1222487, upload-time = "2026-10-23T00:06:26.528Z" }, ] [[package]] @@ -1659,74 +1661,251 @@ wheels = [ [[package]] name = "jiter" -version = "0.10.0" +version = "0.18.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ee/9d/ae7ddb4b8ab3fb1b51faf4deb36cb48a4fbbd7cb36bad6a5fca4741306f7/jiter-0.10.0.tar.gz", hash = "sha256:07a7142c38aacc85194391108dc91b5b57093c978a9932bd86a36862759d9500", size = 162759, upload-time = "2025-05-18T19:04:59.73Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/be/7e/4011b5c77bec97cb2b572f566220364e3e21b51c48c5bd9c4a9c26b41b67/jiter-0.10.0-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:cd2fb72b02478f06a900a5782de2ef47e0396b3e1f7d5aba30daeb1fce66f303", size = 317215, upload-time = "2025-05-18T19:03:04.303Z" }, - { url = "https://files.pythonhosted.org/packages/8a/4f/144c1b57c39692efc7ea7d8e247acf28e47d0912800b34d0ad815f6b2824/jiter-0.10.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:32bb468e3af278f095d3fa5b90314728a6916d89ba3d0ffb726dd9bf7367285e", size = 322814, upload-time = "2025-05-18T19:03:06.433Z" }, - { url = "https://files.pythonhosted.org/packages/63/1f/db977336d332a9406c0b1f0b82be6f71f72526a806cbb2281baf201d38e3/jiter-0.10.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa8b3e0068c26ddedc7abc6fac37da2d0af16b921e288a5a613f4b86f050354f", size = 345237, upload-time = "2025-05-18T19:03:07.833Z" }, - { url = "https://files.pythonhosted.org/packages/d7/1c/aa30a4a775e8a672ad7f21532bdbfb269f0706b39c6ff14e1f86bdd9e5ff/jiter-0.10.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:286299b74cc49e25cd42eea19b72aa82c515d2f2ee12d11392c56d8701f52224", size = 370999, upload-time = "2025-05-18T19:03:09.338Z" }, - { url = "https://files.pythonhosted.org/packages/35/df/f8257abc4207830cb18880781b5f5b716bad5b2a22fb4330cfd357407c5b/jiter-0.10.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6ed5649ceeaeffc28d87fb012d25a4cd356dcd53eff5acff1f0466b831dda2a7", size = 491109, upload-time = "2025-05-18T19:03:11.13Z" }, - { url = "https://files.pythonhosted.org/packages/06/76/9e1516fd7b4278aa13a2cc7f159e56befbea9aa65c71586305e7afa8b0b3/jiter-0.10.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b2ab0051160cb758a70716448908ef14ad476c3774bd03ddce075f3c1f90a3d6", size = 388608, upload-time = "2025-05-18T19:03:12.911Z" }, - { url = "https://files.pythonhosted.org/packages/6d/64/67750672b4354ca20ca18d3d1ccf2c62a072e8a2d452ac3cf8ced73571ef/jiter-0.10.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:03997d2f37f6b67d2f5c475da4412be584e1cec273c1cfc03d642c46db43f8cf", size = 352454, upload-time = "2025-05-18T19:03:14.741Z" }, - { url = "https://files.pythonhosted.org/packages/96/4d/5c4e36d48f169a54b53a305114be3efa2bbffd33b648cd1478a688f639c1/jiter-0.10.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c404a99352d839fed80d6afd6c1d66071f3bacaaa5c4268983fc10f769112e90", size = 391833, upload-time = "2025-05-18T19:03:16.426Z" }, - { url = "https://files.pythonhosted.org/packages/0b/de/ce4a6166a78810bd83763d2fa13f85f73cbd3743a325469a4a9289af6dae/jiter-0.10.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:66e989410b6666d3ddb27a74c7e50d0829704ede652fd4c858e91f8d64b403d0", size = 523646, upload-time = "2025-05-18T19:03:17.704Z" }, - { url = "https://files.pythonhosted.org/packages/a2/a6/3bc9acce53466972964cf4ad85efecb94f9244539ab6da1107f7aed82934/jiter-0.10.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b532d3af9ef4f6374609a3bcb5e05a1951d3bf6190dc6b176fdb277c9bbf15ee", size = 514735, upload-time = "2025-05-18T19:03:19.44Z" }, - { url = "https://files.pythonhosted.org/packages/b4/d8/243c2ab8426a2a4dea85ba2a2ba43df379ccece2145320dfd4799b9633c5/jiter-0.10.0-cp310-cp310-win32.whl", hash = "sha256:da9be20b333970e28b72edc4dff63d4fec3398e05770fb3205f7fb460eb48dd4", size = 210747, upload-time = "2025-05-18T19:03:21.184Z" }, - { url = "https://files.pythonhosted.org/packages/37/7a/8021bd615ef7788b98fc76ff533eaac846322c170e93cbffa01979197a45/jiter-0.10.0-cp310-cp310-win_amd64.whl", hash = "sha256:f59e533afed0c5b0ac3eba20d2548c4a550336d8282ee69eb07b37ea526ee4e5", size = 207484, upload-time = "2025-05-18T19:03:23.046Z" }, - { url = "https://files.pythonhosted.org/packages/1b/dd/6cefc6bd68b1c3c979cecfa7029ab582b57690a31cd2f346c4d0ce7951b6/jiter-0.10.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:3bebe0c558e19902c96e99217e0b8e8b17d570906e72ed8a87170bc290b1e978", size = 317473, upload-time = "2025-05-18T19:03:25.942Z" }, - { url = "https://files.pythonhosted.org/packages/be/cf/fc33f5159ce132be1d8dd57251a1ec7a631c7df4bd11e1cd198308c6ae32/jiter-0.10.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:558cc7e44fd8e507a236bee6a02fa17199ba752874400a0ca6cd6e2196cdb7dc", size = 321971, upload-time = "2025-05-18T19:03:27.255Z" }, - { url = "https://files.pythonhosted.org/packages/68/a4/da3f150cf1d51f6c472616fb7650429c7ce053e0c962b41b68557fdf6379/jiter-0.10.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4d613e4b379a07d7c8453c5712ce7014e86c6ac93d990a0b8e7377e18505e98d", size = 345574, upload-time = "2025-05-18T19:03:28.63Z" }, - { url = "https://files.pythonhosted.org/packages/84/34/6e8d412e60ff06b186040e77da5f83bc158e9735759fcae65b37d681f28b/jiter-0.10.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f62cf8ba0618eda841b9bf61797f21c5ebd15a7a1e19daab76e4e4b498d515b2", size = 371028, upload-time = "2025-05-18T19:03:30.292Z" }, - { url = "https://files.pythonhosted.org/packages/fb/d9/9ee86173aae4576c35a2f50ae930d2ccb4c4c236f6cb9353267aa1d626b7/jiter-0.10.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:919d139cdfa8ae8945112398511cb7fca58a77382617d279556b344867a37e61", size = 491083, upload-time = "2025-05-18T19:03:31.654Z" }, - { url = "https://files.pythonhosted.org/packages/d9/2c/f955de55e74771493ac9e188b0f731524c6a995dffdcb8c255b89c6fb74b/jiter-0.10.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:13ddbc6ae311175a3b03bd8994881bc4635c923754932918e18da841632349db", size = 388821, upload-time = "2025-05-18T19:03:33.184Z" }, - { url = "https://files.pythonhosted.org/packages/81/5a/0e73541b6edd3f4aada586c24e50626c7815c561a7ba337d6a7eb0a915b4/jiter-0.10.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4c440ea003ad10927a30521a9062ce10b5479592e8a70da27f21eeb457b4a9c5", size = 352174, upload-time = "2025-05-18T19:03:34.965Z" }, - { url = "https://files.pythonhosted.org/packages/1c/c0/61eeec33b8c75b31cae42be14d44f9e6fe3ac15a4e58010256ac3abf3638/jiter-0.10.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:dc347c87944983481e138dea467c0551080c86b9d21de6ea9306efb12ca8f606", size = 391869, upload-time = "2025-05-18T19:03:36.436Z" }, - { url = "https://files.pythonhosted.org/packages/41/22/5beb5ee4ad4ef7d86f5ea5b4509f680a20706c4a7659e74344777efb7739/jiter-0.10.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:13252b58c1f4d8c5b63ab103c03d909e8e1e7842d302473f482915d95fefd605", size = 523741, upload-time = "2025-05-18T19:03:38.168Z" }, - { url = "https://files.pythonhosted.org/packages/ea/10/768e8818538e5817c637b0df52e54366ec4cebc3346108a4457ea7a98f32/jiter-0.10.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:7d1bbf3c465de4a24ab12fb7766a0003f6f9bce48b8b6a886158c4d569452dc5", size = 514527, upload-time = "2025-05-18T19:03:39.577Z" }, - { url = "https://files.pythonhosted.org/packages/73/6d/29b7c2dc76ce93cbedabfd842fc9096d01a0550c52692dfc33d3cc889815/jiter-0.10.0-cp311-cp311-win32.whl", hash = "sha256:db16e4848b7e826edca4ccdd5b145939758dadf0dc06e7007ad0e9cfb5928ae7", size = 210765, upload-time = "2025-05-18T19:03:41.271Z" }, - { url = "https://files.pythonhosted.org/packages/c2/c9/d394706deb4c660137caf13e33d05a031d734eb99c051142e039d8ceb794/jiter-0.10.0-cp311-cp311-win_amd64.whl", hash = "sha256:9c9c1d5f10e18909e993f9641f12fe1c77b3e9b533ee94ffa970acc14ded3812", size = 209234, upload-time = "2025-05-18T19:03:42.918Z" }, - { url = "https://files.pythonhosted.org/packages/6d/b5/348b3313c58f5fbfb2194eb4d07e46a35748ba6e5b3b3046143f3040bafa/jiter-0.10.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:1e274728e4a5345a6dde2d343c8da018b9d4bd4350f5a472fa91f66fda44911b", size = 312262, upload-time = "2025-05-18T19:03:44.637Z" }, - { url = "https://files.pythonhosted.org/packages/9c/4a/6a2397096162b21645162825f058d1709a02965606e537e3304b02742e9b/jiter-0.10.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7202ae396446c988cb2a5feb33a543ab2165b786ac97f53b59aafb803fef0744", size = 320124, upload-time = "2025-05-18T19:03:46.341Z" }, - { url = "https://files.pythonhosted.org/packages/2a/85/1ce02cade7516b726dd88f59a4ee46914bf79d1676d1228ef2002ed2f1c9/jiter-0.10.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:23ba7722d6748b6920ed02a8f1726fb4b33e0fd2f3f621816a8b486c66410ab2", size = 345330, upload-time = "2025-05-18T19:03:47.596Z" }, - { url = "https://files.pythonhosted.org/packages/75/d0/bb6b4f209a77190ce10ea8d7e50bf3725fc16d3372d0a9f11985a2b23eff/jiter-0.10.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:371eab43c0a288537d30e1f0b193bc4eca90439fc08a022dd83e5e07500ed026", size = 369670, upload-time = "2025-05-18T19:03:49.334Z" }, - { url = "https://files.pythonhosted.org/packages/a0/f5/a61787da9b8847a601e6827fbc42ecb12be2c925ced3252c8ffcb56afcaf/jiter-0.10.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6c675736059020365cebc845a820214765162728b51ab1e03a1b7b3abb70f74c", size = 489057, upload-time = "2025-05-18T19:03:50.66Z" }, - { url = "https://files.pythonhosted.org/packages/12/e4/6f906272810a7b21406c760a53aadbe52e99ee070fc5c0cb191e316de30b/jiter-0.10.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0c5867d40ab716e4684858e4887489685968a47e3ba222e44cde6e4a2154f959", size = 389372, upload-time = "2025-05-18T19:03:51.98Z" }, - { url = "https://files.pythonhosted.org/packages/e2/ba/77013b0b8ba904bf3762f11e0129b8928bff7f978a81838dfcc958ad5728/jiter-0.10.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:395bb9a26111b60141757d874d27fdea01b17e8fac958b91c20128ba8f4acc8a", size = 352038, upload-time = "2025-05-18T19:03:53.703Z" }, - { url = "https://files.pythonhosted.org/packages/67/27/c62568e3ccb03368dbcc44a1ef3a423cb86778a4389e995125d3d1aaa0a4/jiter-0.10.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6842184aed5cdb07e0c7e20e5bdcfafe33515ee1741a6835353bb45fe5d1bd95", size = 391538, upload-time = "2025-05-18T19:03:55.046Z" }, - { url = "https://files.pythonhosted.org/packages/c0/72/0d6b7e31fc17a8fdce76164884edef0698ba556b8eb0af9546ae1a06b91d/jiter-0.10.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:62755d1bcea9876770d4df713d82606c8c1a3dca88ff39046b85a048566d56ea", size = 523557, upload-time = "2025-05-18T19:03:56.386Z" }, - { url = "https://files.pythonhosted.org/packages/2f/09/bc1661fbbcbeb6244bd2904ff3a06f340aa77a2b94e5a7373fd165960ea3/jiter-0.10.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:533efbce2cacec78d5ba73a41756beff8431dfa1694b6346ce7af3a12c42202b", size = 514202, upload-time = "2025-05-18T19:03:57.675Z" }, - { url = "https://files.pythonhosted.org/packages/1b/84/5a5d5400e9d4d54b8004c9673bbe4403928a00d28529ff35b19e9d176b19/jiter-0.10.0-cp312-cp312-win32.whl", hash = "sha256:8be921f0cadd245e981b964dfbcd6fd4bc4e254cdc069490416dd7a2632ecc01", size = 211781, upload-time = "2025-05-18T19:03:59.025Z" }, - { url = "https://files.pythonhosted.org/packages/9b/52/7ec47455e26f2d6e5f2ea4951a0652c06e5b995c291f723973ae9e724a65/jiter-0.10.0-cp312-cp312-win_amd64.whl", hash = "sha256:a7c7d785ae9dda68c2678532a5a1581347e9c15362ae9f6e68f3fdbfb64f2e49", size = 206176, upload-time = "2025-05-18T19:04:00.305Z" }, - { url = "https://files.pythonhosted.org/packages/2e/b0/279597e7a270e8d22623fea6c5d4eeac328e7d95c236ed51a2b884c54f70/jiter-0.10.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:e0588107ec8e11b6f5ef0e0d656fb2803ac6cf94a96b2b9fc675c0e3ab5e8644", size = 311617, upload-time = "2025-05-18T19:04:02.078Z" }, - { url = "https://files.pythonhosted.org/packages/91/e3/0916334936f356d605f54cc164af4060e3e7094364add445a3bc79335d46/jiter-0.10.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cafc4628b616dc32530c20ee53d71589816cf385dd9449633e910d596b1f5c8a", size = 318947, upload-time = "2025-05-18T19:04:03.347Z" }, - { url = "https://files.pythonhosted.org/packages/6a/8e/fd94e8c02d0e94539b7d669a7ebbd2776e51f329bb2c84d4385e8063a2ad/jiter-0.10.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:520ef6d981172693786a49ff5b09eda72a42e539f14788124a07530f785c3ad6", size = 344618, upload-time = "2025-05-18T19:04:04.709Z" }, - { url = "https://files.pythonhosted.org/packages/6f/b0/f9f0a2ec42c6e9c2e61c327824687f1e2415b767e1089c1d9135f43816bd/jiter-0.10.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:554dedfd05937f8fc45d17ebdf298fe7e0c77458232bcb73d9fbbf4c6455f5b3", size = 368829, upload-time = "2025-05-18T19:04:06.912Z" }, - { url = "https://files.pythonhosted.org/packages/e8/57/5bbcd5331910595ad53b9fd0c610392ac68692176f05ae48d6ce5c852967/jiter-0.10.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5bc299da7789deacf95f64052d97f75c16d4fc8c4c214a22bf8d859a4288a1c2", size = 491034, upload-time = "2025-05-18T19:04:08.222Z" }, - { url = "https://files.pythonhosted.org/packages/9b/be/c393df00e6e6e9e623a73551774449f2f23b6ec6a502a3297aeeece2c65a/jiter-0.10.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5161e201172de298a8a1baad95eb85db4fb90e902353b1f6a41d64ea64644e25", size = 388529, upload-time = "2025-05-18T19:04:09.566Z" }, - { url = "https://files.pythonhosted.org/packages/42/3e/df2235c54d365434c7f150b986a6e35f41ebdc2f95acea3036d99613025d/jiter-0.10.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2e2227db6ba93cb3e2bf67c87e594adde0609f146344e8207e8730364db27041", size = 350671, upload-time = "2025-05-18T19:04:10.98Z" }, - { url = "https://files.pythonhosted.org/packages/c6/77/71b0b24cbcc28f55ab4dbfe029f9a5b73aeadaba677843fc6dc9ed2b1d0a/jiter-0.10.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:15acb267ea5e2c64515574b06a8bf393fbfee6a50eb1673614aa45f4613c0cca", size = 390864, upload-time = "2025-05-18T19:04:12.722Z" }, - { url = "https://files.pythonhosted.org/packages/6a/d3/ef774b6969b9b6178e1d1e7a89a3bd37d241f3d3ec5f8deb37bbd203714a/jiter-0.10.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:901b92f2e2947dc6dfcb52fd624453862e16665ea909a08398dde19c0731b7f4", size = 522989, upload-time = "2025-05-18T19:04:14.261Z" }, - { url = "https://files.pythonhosted.org/packages/0c/41/9becdb1d8dd5d854142f45a9d71949ed7e87a8e312b0bede2de849388cb9/jiter-0.10.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:d0cb9a125d5a3ec971a094a845eadde2db0de85b33c9f13eb94a0c63d463879e", size = 513495, upload-time = "2025-05-18T19:04:15.603Z" }, - { url = "https://files.pythonhosted.org/packages/9c/36/3468e5a18238bdedae7c4d19461265b5e9b8e288d3f86cd89d00cbb48686/jiter-0.10.0-cp313-cp313-win32.whl", hash = "sha256:48a403277ad1ee208fb930bdf91745e4d2d6e47253eedc96e2559d1e6527006d", size = 211289, upload-time = "2025-05-18T19:04:17.541Z" }, - { url = "https://files.pythonhosted.org/packages/7e/07/1c96b623128bcb913706e294adb5f768fb7baf8db5e1338ce7b4ee8c78ef/jiter-0.10.0-cp313-cp313-win_amd64.whl", hash = "sha256:75f9eb72ecb640619c29bf714e78c9c46c9c4eaafd644bf78577ede459f330d4", size = 205074, upload-time = "2025-05-18T19:04:19.21Z" }, - { url = "https://files.pythonhosted.org/packages/54/46/caa2c1342655f57d8f0f2519774c6d67132205909c65e9aa8255e1d7b4f4/jiter-0.10.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:28ed2a4c05a1f32ef0e1d24c2611330219fed727dae01789f4a335617634b1ca", size = 318225, upload-time = "2025-05-18T19:04:20.583Z" }, - { url = "https://files.pythonhosted.org/packages/43/84/c7d44c75767e18946219ba2d703a5a32ab37b0bc21886a97bc6062e4da42/jiter-0.10.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:14a4c418b1ec86a195f1ca69da8b23e8926c752b685af665ce30777233dfe070", size = 350235, upload-time = "2025-05-18T19:04:22.363Z" }, - { url = "https://files.pythonhosted.org/packages/01/16/f5a0135ccd968b480daad0e6ab34b0c7c5ba3bc447e5088152696140dcb3/jiter-0.10.0-cp313-cp313t-win_amd64.whl", hash = "sha256:d7bfed2fe1fe0e4dda6ef682cee888ba444b21e7a6553e03252e4feb6cf0adca", size = 207278, upload-time = "2025-05-18T19:04:23.627Z" }, - { url = "https://files.pythonhosted.org/packages/1c/9b/1d646da42c3de6c2188fdaa15bce8ecb22b635904fc68be025e21249ba44/jiter-0.10.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:5e9251a5e83fab8d87799d3e1a46cb4b7f2919b895c6f4483629ed2446f66522", size = 310866, upload-time = "2025-05-18T19:04:24.891Z" }, - { url = "https://files.pythonhosted.org/packages/ad/0e/26538b158e8a7c7987e94e7aeb2999e2e82b1f9d2e1f6e9874ddf71ebda0/jiter-0.10.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:023aa0204126fe5b87ccbcd75c8a0d0261b9abdbbf46d55e7ae9f8e22424eeb8", size = 318772, upload-time = "2025-05-18T19:04:26.161Z" }, - { url = "https://files.pythonhosted.org/packages/7b/fb/d302893151caa1c2636d6574d213e4b34e31fd077af6050a9c5cbb42f6fb/jiter-0.10.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c189c4f1779c05f75fc17c0c1267594ed918996a231593a21a5ca5438445216", size = 344534, upload-time = "2025-05-18T19:04:27.495Z" }, - { url = "https://files.pythonhosted.org/packages/01/d8/5780b64a149d74e347c5128d82176eb1e3241b1391ac07935693466d6219/jiter-0.10.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:15720084d90d1098ca0229352607cd68256c76991f6b374af96f36920eae13c4", size = 369087, upload-time = "2025-05-18T19:04:28.896Z" }, - { url = "https://files.pythonhosted.org/packages/e8/5b/f235a1437445160e777544f3ade57544daf96ba7e96c1a5b24a6f7ac7004/jiter-0.10.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e4f2fb68e5f1cfee30e2b2a09549a00683e0fde4c6a2ab88c94072fc33cb7426", size = 490694, upload-time = "2025-05-18T19:04:30.183Z" }, - { url = "https://files.pythonhosted.org/packages/85/a9/9c3d4617caa2ff89cf61b41e83820c27ebb3f7b5fae8a72901e8cd6ff9be/jiter-0.10.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ce541693355fc6da424c08b7edf39a2895f58d6ea17d92cc2b168d20907dee12", size = 388992, upload-time = "2025-05-18T19:04:32.028Z" }, - { url = "https://files.pythonhosted.org/packages/68/b1/344fd14049ba5c94526540af7eb661871f9c54d5f5601ff41a959b9a0bbd/jiter-0.10.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31c50c40272e189d50006ad5c73883caabb73d4e9748a688b216e85a9a9ca3b9", size = 351723, upload-time = "2025-05-18T19:04:33.467Z" }, - { url = "https://files.pythonhosted.org/packages/41/89/4c0e345041186f82a31aee7b9d4219a910df672b9fef26f129f0cda07a29/jiter-0.10.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fa3402a2ff9815960e0372a47b75c76979d74402448509ccd49a275fa983ef8a", size = 392215, upload-time = "2025-05-18T19:04:34.827Z" }, - { url = "https://files.pythonhosted.org/packages/55/58/ee607863e18d3f895feb802154a2177d7e823a7103f000df182e0f718b38/jiter-0.10.0-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:1956f934dca32d7bb647ea21d06d93ca40868b505c228556d3373cbd255ce853", size = 522762, upload-time = "2025-05-18T19:04:36.19Z" }, - { url = "https://files.pythonhosted.org/packages/15/d0/9123fb41825490d16929e73c212de9a42913d68324a8ce3c8476cae7ac9d/jiter-0.10.0-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:fcedb049bdfc555e261d6f65a6abe1d5ad68825b7202ccb9692636c70fcced86", size = 513427, upload-time = "2025-05-18T19:04:37.544Z" }, - { url = "https://files.pythonhosted.org/packages/d8/b3/2bd02071c5a2430d0b70403a34411fc519c2f227da7b03da9ba6a956f931/jiter-0.10.0-cp314-cp314-win32.whl", hash = "sha256:ac509f7eccca54b2a29daeb516fb95b6f0bd0d0d8084efaf8ed5dfc7b9f0b357", size = 210127, upload-time = "2025-05-18T19:04:38.837Z" }, - { url = "https://files.pythonhosted.org/packages/03/0c/5fe86614ea050c3ecd728ab4035534387cd41e7c1855ef6c031f1ca93e3f/jiter-0.10.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5ed975b83a2b8639356151cef5c0d597c68376fc4922b45d0eb384ac058cfa00", size = 318527, upload-time = "2025-05-18T19:04:40.612Z" }, - { url = "https://files.pythonhosted.org/packages/b3/4a/4175a563579e884192ba6e81725fc0448b042024419be8d83aa8a80a3f44/jiter-0.10.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3aa96f2abba33dc77f79b4cf791840230375f9534e5fac927ccceb58c5e604a5", size = 354213, upload-time = "2025-05-18T19:04:41.894Z" }, +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/63/5b/f68319f4fe624311a744a33d10fdbcac4c971991e348223cba60d31780b2/jiter-0.18.0.tar.gz", hash = "sha256:a0ca63fd9450a212e4e658d4cfe0ab4977c4f9b0003c68828b843c65e27662ff", size = 234470, upload-time = "2026-10-23T13:51:13.103Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/cd/659a700d5a8524960711a8b4fa5143b32c1deeb76b4503e648f48c9d8a99/jiter-0.18.0-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:74b8d31a39b9d22293c75bfdf0e6ab54d9dc16d32b540b2cb8f7c162961769ee", size = 289675, upload-time = "2026-10-23T13:48:38.07Z" }, + { url = "https://files.pythonhosted.org/packages/03/1a/1a0c57e6eacb7497abe18d83434360373793c824a97973212c7a99390b19/jiter-0.18.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:77d61c53ab1732e84ad20f77c44bfc761183ef323eef84a59ffdd9201bd51386", size = 318743, upload-time = "2026-10-23T13:48:39.53Z" }, + { url = "https://files.pythonhosted.org/packages/7a/72/b965c0df9bf6f9cb834ebd181f1f7ec7f376cb3e589c6169c596b6e5d6e6/jiter-0.18.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6ea6d553fe513447a7a8ef6175aeacecd9a6dbb7f68f9215c751389c58e1288c", size = 339163, upload-time = "2026-10-23T13:48:40.84Z" }, + { url = "https://files.pythonhosted.org/packages/88/33/bfdf32c15b55fba17d6af25f8878c9a23b15e000877af802808a0fb2b00c/jiter-0.18.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7779088592f8994e021cd79b9b334f41363cfa10a654af9bd5dd82b99c80497f", size = 323880, upload-time = "2026-10-23T13:48:42.141Z" }, + { url = "https://files.pythonhosted.org/packages/b7/72/882cba4fd704137f71fa99686e9492eda6a462523b417ce05c601c3378cd/jiter-0.18.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:879cf95bb0266643c1e8214be0862f2dd7186c9bb2e279f63d7b5fe099cb9a4b", size = 336028, upload-time = "2026-10-23T13:48:43.452Z" }, + { url = "https://files.pythonhosted.org/packages/85/f8/119ed3573d65d8a84b38864a2dcb10b9c5ce05316e06576e66fa55ec9e75/jiter-0.18.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1b291352b1f7dcf095b2a9d540777d59588c81685cc23f7c53f4356e07385e62", size = 349753, upload-time = "2026-10-23T13:48:44.672Z" }, + { url = "https://files.pythonhosted.org/packages/21/d4/88f08cf7189c3070a029a7ab3f22334f138c8664d731f574f6034928bed6/jiter-0.18.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a4ff2d7905b0f3f5c54b29626c7747cd4af3fcddfdedf0cce75fbd06b66e4d40", size = 337248, upload-time = "2026-10-23T13:48:45.968Z" }, + { url = "https://files.pythonhosted.org/packages/2a/f3/22782c5d97bb8947e3a27957e53d90bf4c031c4f9274dc85099c8beba6ef/jiter-0.18.0-cp310-cp310-manylinux_2_31_riscv64.whl", hash = "sha256:4d5ce30facd564d97aceb49013a02661daef1cf9c34ce322c1afbb841f1e5984", size = 316496, upload-time = "2026-10-23T13:48:47.615Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a2/cf0e87e7fe7345aa78e6a85b94f0e4d91e57d2ae233f11b6a15931ca1edb/jiter-0.18.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:131446a60b54ff9d4db62633a74189056387f6b2ad4e5171d3e7ed7977e31eb4", size = 334004, upload-time = "2026-10-23T13:48:49.058Z" }, + { url = "https://files.pythonhosted.org/packages/76/64/461748f1d0e7554f814f1467b57ce45bd92ef1922f1457fd6aa19413d717/jiter-0.18.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:389f5379f7cc5b09f6586db99bf91c5d828fac88f1a52fdeb4fc3b040c1dacc9", size = 481838, upload-time = "2026-10-23T13:48:50.288Z" }, + { url = "https://files.pythonhosted.org/packages/0f/b1/65940d140ff84426c0bd495e2b07c81ec61873264fcf302af7d12d6ec1de/jiter-0.18.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:db7804a8d3a433a3c5e08cd658ea69a6ee9a2ee43b756dd20048dae5a3d7ac67", size = 516434, upload-time = "2026-10-23T13:48:52.064Z" }, + { url = "https://files.pythonhosted.org/packages/fc/3e/1e4a62c1f8261f074069323f957b2a8b7fb62cd1c2962164bcf6f3de0b47/jiter-0.18.0-cp310-cp310-win32.whl", hash = "sha256:5c2a5dac57aec416140812f6d3824cdaf1da8a4f8f009ece64e50f507b6a709a", size = 187926, upload-time = "2026-10-23T13:48:53.314Z" }, + { url = "https://files.pythonhosted.org/packages/08/bb/ba0f2ff7a98030228eebc897928c6a5cb63be2f46bb64df805c8371fc408/jiter-0.18.0-cp310-cp310-win_amd64.whl", hash = "sha256:a447ed784b8013b518e0b1effe05424d5dfaa6974fed69aebdd4c1349d82fc54", size = 225049, upload-time = "2026-10-23T13:48:54.496Z" }, + { url = "https://files.pythonhosted.org/packages/5d/d1/014e38e099c9600dfd026962b454833538b82d9364ff9ed7414b5e5aa6e5/jiter-0.18.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:97cdff6fffc79d915e3d2691110e014f3f43c7529a73c0bfe8de63530b6efbd9", size = 289390, upload-time = "2026-10-23T13:48:55.902Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3f/f5b9d63db432b4938c972f04a6e541232af85169140c061b227f6690f9fd/jiter-0.18.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c938de3832ca88ca879bbf0c24673cbe0176b502eec8d2364f35c9edb9bdf890", size = 319955, upload-time = "2026-10-23T13:48:57.407Z" }, + { url = "https://files.pythonhosted.org/packages/d0/e1/ebf515f2cbbdabc8393783b7048c1aac9d9d171bf7d9dab26ca10a9fe9f8/jiter-0.18.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a41d8ef9f757fd5c11ce2fa56c9c4d008d857e97b6d0edfccbaacbd50830a75", size = 337385, upload-time = "2026-10-23T13:48:58.629Z" }, + { url = "https://files.pythonhosted.org/packages/18/c6/c55d469b5a346070dbfb842316cea8e73a8ba1a96dd65c60b16ec36cda38/jiter-0.18.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:b2cad787346aa8f458ed6d5ecbbe3b6dd13d6d40fdbaa44980c9e29a8b536048", size = 323553, upload-time = "2026-10-23T13:49:00.002Z" }, + { url = "https://files.pythonhosted.org/packages/9a/80/5f31105f07b9de70dade7aa074cccdf18f3e5df3632377ad05ecfd58cfa6/jiter-0.18.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3027e8ec2c86106bfd4b125af27aa6dd5eed2ab63427c35138e039931a98ba7c", size = 335724, upload-time = "2026-10-23T13:49:01.281Z" }, + { url = "https://files.pythonhosted.org/packages/39/99/ef5380973360aa6d7e4a33e60b1ab5e9c88fd7fc25671c683383522532be/jiter-0.18.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2485807c282b6df64d9135551c2d8e9ac2b098b4c85157979fc7ca8bd884a3b4", size = 349366, upload-time = "2026-10-23T13:49:02.476Z" }, + { url = "https://files.pythonhosted.org/packages/85/93/f133c7b38cc1bc7516929e9d82a28caa6a4403b4d4c5c9c1d39170128dee/jiter-0.18.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:55f808bce951fae459fc916359cc54097d386bef3e72265ddf02b39ba3275118", size = 337085, upload-time = "2026-10-23T13:49:03.72Z" }, + { url = "https://files.pythonhosted.org/packages/a0/1c/19a54abb30b83bccef20b24be95c637d634033208ba7252e2989f38e8657/jiter-0.18.0-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:4656c4b24fd711d6caa61cb2fe895dcc55d0d6944828df23f2fb05504435204b", size = 316184, upload-time = "2026-10-23T13:49:05.102Z" }, + { url = "https://files.pythonhosted.org/packages/76/b4/011a8a05b5548a02166621183fdd64473d6f6d0cd394758e26eba4831327/jiter-0.18.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5893dc87a2a5297e271dfc5f8f710c3e61ebeb64c137a0b4b786d5bcd11c8fb7", size = 333660, upload-time = "2026-10-23T13:49:06.345Z" }, + { url = "https://files.pythonhosted.org/packages/30/6b/9fedf0a78535bca9d8136756dae50e58229c16b4d9cf8c78e101b5b606fe/jiter-0.18.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:867a217d4a1857fba97c4cc5dc82a38ea257beee8c2a753b3d9b9310c01d12c0", size = 481791, upload-time = "2026-10-23T13:49:07.709Z" }, + { url = "https://files.pythonhosted.org/packages/91/64/e096051c182695ebb55011977016ec9c6af0e4135468653b1193a2d3f4eb/jiter-0.18.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:1df7b0ce46d869c49c77670ba31db737d96fd1bd4ae44d790d33bb731962c994", size = 516155, upload-time = "2026-10-23T13:49:09.086Z" }, + { url = "https://files.pythonhosted.org/packages/f7/9b/c36f7de00722441c7de54760200209e65445e7ea659d68c8f1c8be40df6a/jiter-0.18.0-cp311-cp311-win32.whl", hash = "sha256:b8b97658b0914e90a352a9a1d515e597bcc89c88514fe4bcb4e37fa2a2fbaa29", size = 187739, upload-time = "2026-10-23T13:49:10.365Z" }, + { url = "https://files.pythonhosted.org/packages/4d/3e/f17099d841ccb1603d1223941b845bf38503f540aa6be8e9d50c8488f98f/jiter-0.18.0-cp311-cp311-win_amd64.whl", hash = "sha256:8ad1a36e3d5ebbff515b85468d8e279b336eaa326953b1b36fa21d5e2b8e8f9d", size = 219536, upload-time = "2026-10-23T13:49:11.611Z" }, + { url = "https://files.pythonhosted.org/packages/58/35/c807b0274be3179bf971d56152a9fc9ac216b3afd169b6100a7fb9351892/jiter-0.18.0-cp311-cp311-win_arm64.whl", hash = "sha256:908f310576554379becf2e8c7730a8962693ebfba9395a54ef3c05c57b1cd9d8", size = 185718, upload-time = "2026-10-23T13:49:12.834Z" }, + { url = "https://files.pythonhosted.org/packages/45/0e/075bfa4fa46820da9ac8cf8a67c435b0586012279fba15deccde0e73b9ce/jiter-0.18.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:77a01cdf4381a1becbe5b827f682006f47b712581667451c5b1eb259b9ae7041", size = 290095, upload-time = "2026-10-23T13:49:14.118Z" }, + { url = "https://files.pythonhosted.org/packages/2e/e2/f4000a4d9c519ca019bf0e2922cc0c6b6db347be6303161382eda7635be7/jiter-0.18.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7b41cd64ee6b54db94bea6274e6e37002ed526aa06c114a8be6f36ffe21c184e", size = 316319, upload-time = "2026-10-23T13:49:15.263Z" }, + { url = "https://files.pythonhosted.org/packages/51/93/9aaef4d18d19446fd044b9cff0323b1b45b5526f077f1a80418567a6eef8/jiter-0.18.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d7424194e68ef44e94290961f59319850d7ce11a329a3957f91709c15ded6618", size = 335631, upload-time = "2026-10-23T13:49:16.551Z" }, + { url = "https://files.pythonhosted.org/packages/fd/9e/d2dc5e8179e248df7ef1c7c8822554f4c7f694a33be30790bb523f1e657a/jiter-0.18.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:04a484fce032a8b2c21dec0410a805d7b16573eb34297156a3b4d242c507d2b4", size = 322596, upload-time = "2026-10-23T13:49:17.875Z" }, + { url = "https://files.pythonhosted.org/packages/22/ca/28bfd20743be0b2b37c1ddfe069a637d5180e535f1c8faad555cf7ac0b98/jiter-0.18.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:860ac97858116bda0ac02ef5f50c541fc1a84ad7b9368cac68d4de5697a9012d", size = 333858, upload-time = "2026-10-23T13:49:19.343Z" }, + { url = "https://files.pythonhosted.org/packages/69/89/e42f7dba54dcf7787aa4be3e22cdcb1f14d9635b6527949652ab490d6f8e/jiter-0.18.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:39ef656cf371971486ec545ca0ae2da8d037d5479bc906121e3e46de86ee73c4", size = 348656, upload-time = "2026-10-23T13:49:20.796Z" }, + { url = "https://files.pythonhosted.org/packages/74/6a/b13407f609ddaf9a1f0cdf1336326dc5c8c7fc56943e8450a04a542f5edf/jiter-0.18.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b3c741e6b778c951a6861964ee475118812a33208426c54fb92bf4e318bda834", size = 336286, upload-time = "2026-10-23T13:49:22.152Z" }, + { url = "https://files.pythonhosted.org/packages/b2/7e/b560f97495a485a569e7fa338a13587328854f6a40cd2e93602c327ca4a6/jiter-0.18.0-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:1277ac083a58d2f49a24ff9a28fd9876a6443a1992d4467a1db80fb45e354b18", size = 314415, upload-time = "2026-10-23T13:49:23.645Z" }, + { url = "https://files.pythonhosted.org/packages/8b/97/457b6ec16f1f3f25ec760f23728f43a2b20ddf934fcd8f02c81a2183597e/jiter-0.18.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ccf224d2e706be81d464b59c2bc3f98ba65d12c092c1789e625127e64488944e", size = 332078, upload-time = "2026-10-23T13:49:24.917Z" }, + { url = "https://files.pythonhosted.org/packages/0e/d9/6f616071650f7bb8fcbce674d4dde7e59cfbd8a4d30f5c71c03630425d6e/jiter-0.18.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:5c7fc8e5357d1ad082bb177be71e398fcd3d458726439255ca5cb0d706060269", size = 480354, upload-time = "2026-10-23T13:49:26.221Z" }, + { url = "https://files.pythonhosted.org/packages/42/72/52a3630c8213cdc8093cc86dc6ad50f2bc89ccfa97ef272205d38a24e16d/jiter-0.18.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:a6bba0404b46157a651d1fe512cf2c59c8e42836a9284c35cdff35310758ba4f", size = 515322, upload-time = "2026-10-23T13:49:27.652Z" }, + { url = "https://files.pythonhosted.org/packages/31/54/987cfee52bdf8a286e9c1c58192a9bb64f8773a6be36e4ec46959f67fb7e/jiter-0.18.0-cp312-cp312-win32.whl", hash = "sha256:07ae058bc052ead609b49bbae78c01bf4dee8f5f9d21705cbae9bfe59b33efc9", size = 185341, upload-time = "2026-10-23T13:49:29.147Z" }, + { url = "https://files.pythonhosted.org/packages/c5/c9/b1279eecf68e5f62c918af3f7f856a071ae7db0c90b8fd2235b1b6020c8c/jiter-0.18.0-cp312-cp312-win_amd64.whl", hash = "sha256:79d1fe529bd7065c6f3f50279a08c2ab82eaa0631a6f5dfafa9c65105eeaaafa", size = 225889, upload-time = "2026-10-23T13:49:30.306Z" }, + { url = "https://files.pythonhosted.org/packages/e0/14/715f84be58a7fc97779aa40c37164acfa25ccb2cee89bfb69358e7071ff3/jiter-0.18.0-cp312-cp312-win_arm64.whl", hash = "sha256:1f8b3b3d8761dee3cddcb5d3e99eaccc0155bbefc345affcdedcc758a4933a1f", size = 181852, upload-time = "2026-10-23T13:49:31.811Z" }, + { url = "https://files.pythonhosted.org/packages/50/94/aa275cdb099fd84e402977f8fc8628e2cee2f7c8eafe1d1d5c5e722f5ee5/jiter-0.18.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:1517648b5f6268513dea206241a99d9991d6ffcbdbc406848e77a7f02ed3ccf1", size = 289648, upload-time = "2026-10-23T13:49:33.059Z" }, + { url = "https://files.pythonhosted.org/packages/8d/30/3eaf67279c6183393d3608b6713c93668ae82ea59f0589ea59d8176d8741/jiter-0.18.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7161217e2190b9b2c8c79b81699be29d67010f6f77e09a53a3b62261792d5489", size = 315919, upload-time = "2026-10-23T13:49:34.457Z" }, + { url = "https://files.pythonhosted.org/packages/f8/2b/d18adcfec3516b97b24c0d5cd1b0ced22cada8ea9806f21bece75af49ffe/jiter-0.18.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9623fc90f1a4754452a525383ce70476476c16556098944709b8cdbd9ad905f0", size = 335231, upload-time = "2026-10-23T13:49:35.776Z" }, + { url = "https://files.pythonhosted.org/packages/41/e8/42cff1077883ea5311621dc9384a1ede4799bc3c01411798ac75f7a71f15/jiter-0.18.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f9083a7c2a4ee6358bc0401c46b4d5090f208f6fadfb6275c7b5fe3217e13506", size = 321590, upload-time = "2026-10-23T13:49:36.997Z" }, + { url = "https://files.pythonhosted.org/packages/1d/4d/2fbedfce563223d4783a872cead5f5bb74d2d1e418f963410ca28e4b7394/jiter-0.18.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4632f5172800da4cd42fd53f4553c772acd08f1c33dd7ac135e29d735080fa0d", size = 332960, upload-time = "2026-10-23T13:49:38.615Z" }, + { url = "https://files.pythonhosted.org/packages/04/a0/b082b2d8bd3bef9a888cc0a0f060a24644f24b5195f2e8227a40507e6b71/jiter-0.18.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c00b1f8fc1dd06c610305be36778b38148ed1e9a532bdd81189c3c0d9905c888", size = 348149, upload-time = "2026-10-23T13:49:39.826Z" }, + { url = "https://files.pythonhosted.org/packages/64/11/babc8d3c004bb2f11b7e3adfe27a5bc7c1e13cdfc6360d424c57355c55ff/jiter-0.18.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6e3350b7431f7b8315b925d9ca0f29a44e8fb6ed45c1fe552392cb6297966bb9", size = 335978, upload-time = "2026-10-23T13:49:41.165Z" }, + { url = "https://files.pythonhosted.org/packages/3b/21/c50bf83c39d60f0df896ebcb025b316b670a703397d08bea2c69b9615101/jiter-0.18.0-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:3b49071fb7917cdbc6d80c81a491c6ad146c1a8fd6cb3076cd3c1bfeb6e266f6", size = 313767, upload-time = "2026-10-23T13:49:42.538Z" }, + { url = "https://files.pythonhosted.org/packages/af/19/3f66480d5bfd3f49571a073eefac4d890dd590a8eb3c78b15e0293909cc6/jiter-0.18.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:04e210f5ddcccdbde484821040216a112381e6484abc549c20c38e9698ab07ca", size = 331070, upload-time = "2026-10-23T13:49:43.782Z" }, + { url = "https://files.pythonhosted.org/packages/5a/3d/b5662c84b14475c8b018ed1ca2ea44069194b7d97a03bac81ae6b46f6b9f/jiter-0.18.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:5b339f6ae14fe7be92f391cc65cc5c80ff76e8da76d63b18fc14664f09b7cece", size = 479939, upload-time = "2026-10-23T13:49:45.033Z" }, + { url = "https://files.pythonhosted.org/packages/80/b8/081c0414379ee2564aa7808f78e963538a2c4aed2f8d31775e2423e1cdbf/jiter-0.18.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:5cb43336244e063f9cc11e44730e4b92dea70c6eb9b649d268c5ebebc4bc7685", size = 514734, upload-time = "2026-10-23T13:49:46.236Z" }, + { url = "https://files.pythonhosted.org/packages/0f/1c/6f7bf98786851ae424a1d88562586302536cc137848fd12d2add3960fab3/jiter-0.18.0-cp313-cp313-win32.whl", hash = "sha256:9656d0e9001f69c4af6523874ff445ab4e5db7b835f59733cc5ff51e73a9aa57", size = 184699, upload-time = "2026-10-23T13:49:47.398Z" }, + { url = "https://files.pythonhosted.org/packages/38/53/5803216c024a241a0bf41ed2668713d7228f92c5593e40d5e873e3b20e0b/jiter-0.18.0-cp313-cp313-win_amd64.whl", hash = "sha256:8f26198220165eb9627847401fff4d0ca8bebf3ef840a88c6312918d2291c33a", size = 222493, upload-time = "2026-10-23T13:49:48.533Z" }, + { url = "https://files.pythonhosted.org/packages/fe/8e/484919ccb041c9a1e84059be02bd37ff086b8b084e21630e0958d3ae41a3/jiter-0.18.0-cp313-cp313-win_arm64.whl", hash = "sha256:bef1fe687dc6af17bef9f644a95d465f15f0efa20b743c858e0b6a14e2c0c73e", size = 181250, upload-time = "2026-10-23T13:49:49.777Z" }, + { url = "https://files.pythonhosted.org/packages/74/0e/45a502771d73d4a939132d8bf85d7b049c7ca06a07f84b414b525c3dc084/jiter-0.18.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:248e939f67a9f8030e2624260a9f417decfe275af37aa96728d256468a9c4086", size = 291757, upload-time = "2026-10-23T13:49:50.95Z" }, + { url = "https://files.pythonhosted.org/packages/21/f6/d9cfa2bf2a969fb8e002fb8d8a6cd98d49a6248cb7e4ffe2247766af13fb/jiter-0.18.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0390fa550fcafbf69fb97ccb287bd71192f90410a1c7dd600ca4000aa9aabcf2", size = 318585, upload-time = "2026-10-23T13:49:52.407Z" }, + { url = "https://files.pythonhosted.org/packages/46/38/ea1dae56f123e3a864188cbbc577314293c0dcc019a880fa9c0a8097934a/jiter-0.18.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d8013186f2b9a8c27ededa601050392527aa9d27ffd35d49aae424fbd2062f38", size = 338099, upload-time = "2026-10-23T13:49:53.658Z" }, + { url = "https://files.pythonhosted.org/packages/1f/d9/fcc5c53a32f98d52f4fd46fda62b69f5c7c2c975a582c0e18501250a4f78/jiter-0.18.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bd4316df8e2074fcf5173f6001f1fc9596e7c1e8c4bf499b02f9ebe92babdfb1", size = 324016, upload-time = "2026-10-23T13:49:54.999Z" }, + { url = "https://files.pythonhosted.org/packages/d4/63/c24cd08907f08e6a3ba3173616ad268a3d32dd81c63ba34b991d08577d28/jiter-0.18.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a9e474da7a9f65d3b460cca93cc8a0f4ec0220d1fa41f1f7a3709195ead60056", size = 335904, upload-time = "2026-10-23T13:49:56.214Z" }, + { url = "https://files.pythonhosted.org/packages/0b/78/19ca1c8fe87bd3c8540b91504ff2dd52c9c538233044c4cf787fc1fab39b/jiter-0.18.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d55acd326db8ecfc94f21951abd20902c7939d35925444e48d94527e287bead7", size = 350523, upload-time = "2026-10-23T13:49:57.552Z" }, + { url = "https://files.pythonhosted.org/packages/c3/27/84be9cc1c2b781d2da7c694fd7608311af3aaab91f20eb00d4999285b351/jiter-0.18.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a01642d403b8925f2b1e1bb51b4ba49ece8a2bdc9b9560fc8ed0b1f2b35b567a", size = 338324, upload-time = "2026-10-23T13:49:58.842Z" }, + { url = "https://files.pythonhosted.org/packages/9a/ac/7b3bfb49b19e42ebc2ae56ec307c372602dd1e17892f7e051c9bf97cd7e6/jiter-0.18.0-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:89ba6b674d4bd7290f9943bbeba0e1bf35955bbb1e07e41ba94691648cf133d5", size = 316484, upload-time = "2026-10-23T13:50:00.257Z" }, + { url = "https://files.pythonhosted.org/packages/f9/6a/e37f50885aa4daa1dfe413784692ead6b48a1d9e857cd394a61bf345189c/jiter-0.18.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:feadebdfee32c61e91066433f4aa74c891752e26e43032c1feef08dda6d9b6ed", size = 334225, upload-time = "2026-10-23T13:50:01.542Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f8/1026bc92f0fd443a1137993d1448a7d7c4b7a34bec2722a1533302ebc4b4/jiter-0.18.0-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:dd7e57efd54a3580620f635c48a3226f910e23649b7eb83ffbc6f0f3386293b8", size = 482157, upload-time = "2026-10-23T13:50:02.849Z" }, + { url = "https://files.pythonhosted.org/packages/1b/2d/61f3c35736873c34eeee3d0008067febd88ded8e8cf6f9a0ab090348a787/jiter-0.18.0-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:ea69e23481497c2143775a98d273ccc43de5c92a6387df18c903d2d37bc2b181", size = 516956, upload-time = "2026-10-23T13:50:04.19Z" }, + { url = "https://files.pythonhosted.org/packages/6b/bf/9d14be58e76324f4927c7f8e5dbe2f9fd04faaec884a6465173f8142eac1/jiter-0.18.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:d9b61af76a3cd90ad9656a331737d97dab8c05facb2d04cb41fb16c9adadc966", size = 112087, upload-time = "2026-10-23T13:50:05.423Z" }, + { url = "https://files.pythonhosted.org/packages/c6/7d/cff751c560d514da283bae595fe154714f285ec5ac15e2b16e9e0c0c8948/jiter-0.18.0-cp314-cp314-win32.whl", hash = "sha256:fe42726d7fe171cd8fc1966d4457a6aae03bd408d519d2cc5e7726805460b51e", size = 186562, upload-time = "2026-10-23T13:50:06.81Z" }, + { url = "https://files.pythonhosted.org/packages/04/70/4e7f51e517be4146400fd1ce642d535380a38c7db5ab475d38bbcd16a82d/jiter-0.18.0-cp314-cp314-win_amd64.whl", hash = "sha256:f1e738b851019d6bb6ff4a42c6319bdede967dec958ef3ec6feb7ab9d12408f7", size = 225448, upload-time = "2026-10-23T13:50:08.302Z" }, + { url = "https://files.pythonhosted.org/packages/78/43/02bfb85f63e04c87c406731197e41f2e6b415035e41497428e0422fb326e/jiter-0.18.0-cp314-cp314-win_arm64.whl", hash = "sha256:80a961b1c5c7786bc03b332deb7f7ebe818b7baa6e26685e2bf480548ca128b4", size = 182907, upload-time = "2026-10-23T13:50:09.795Z" }, + { url = "https://files.pythonhosted.org/packages/9c/66/5cbde35cbb14c8339af39c9bc61cbda08b212116f96603d23b7c9cc84a4d/jiter-0.18.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:b066f37dd9ec19fc7931d79dee38f56b6f849217bbe824a7dad4518ef96ee515", size = 318962, upload-time = "2026-10-23T13:50:10.91Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d1/dccc47ed6070d3b25622823048a80a49fe87ccd737e5d66b802ca20e4fde/jiter-0.18.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ccdc09887b04f50f1761eedcfd19da882d9d834096bc1215049af637023f7db7", size = 336718, upload-time = "2026-10-23T13:50:12.149Z" }, + { url = "https://files.pythonhosted.org/packages/de/a5/8d4ec06d7a0f2bccbde8508ed847ccd323a9dd1fbab5900cda3fc5bd71f8/jiter-0.18.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6133abcd0f332964fbb8145adb1ce775cd0312c9eaf6e4bf26b7a5c9b6f7cca7", size = 322945, upload-time = "2026-10-23T13:50:13.591Z" }, + { url = "https://files.pythonhosted.org/packages/7f/50/49d06214b30c685d64ffdd40fdb50a98b6ccff4b012fc9ed491d44de9ef1/jiter-0.18.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ca381b4a466023d1fdd04c889c759b46f7d9654f622b28bb01e65abf31d07bba", size = 335325, upload-time = "2026-10-23T13:50:14.807Z" }, + { url = "https://files.pythonhosted.org/packages/f4/9a/4ecb866a7a01a4e76d9ffbde3fac2cd66ad978c8c797953d44f91fbf2040/jiter-0.18.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b961fedf589ffa182fe302fc4371acf4606d3ed4a6a48a151fbfd724d811f5a", size = 350578, upload-time = "2026-10-23T13:50:16.125Z" }, + { url = "https://files.pythonhosted.org/packages/16/7e/c8b5ecb6af4c9454376263f167f3f8bb5dec41b10fac4f48ea4557b9f115/jiter-0.18.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3b77eabfbae1ac47872be0076899e66340bbef39b862971c3d6c9a4b7c91fd10", size = 338791, upload-time = "2026-10-23T13:50:17.703Z" }, + { url = "https://files.pythonhosted.org/packages/8a/04/45ba31ce79022706323fd2291f87d956fd51fdfcba2ba8924b3de62f0ce2/jiter-0.18.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:92a16933d0fa852133500837d33cd6a4f75e4414d77389c58269e12bafc2ee02", size = 316169, upload-time = "2026-10-23T13:50:18.915Z" }, + { url = "https://files.pythonhosted.org/packages/62/c1/fd36126144f4c32d1b76939278e9d3b7b798075c0478b641d6066621bafd/jiter-0.18.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2f7ba518893a4ccef5afb38e41bc3e126bf652354417ec4e75e5a5b000fb1ef6", size = 334754, upload-time = "2026-10-23T13:50:20.169Z" }, + { url = "https://files.pythonhosted.org/packages/cc/e2/30a5ac1a3ee9e01bda75a4fcb55bbeddcf8875f8ce7e680b787c177f14b5/jiter-0.18.0-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:04d67a44b040a6662a35edc9869030f7aa566bf5baaf3549c99d847aa44213e2", size = 481094, upload-time = "2026-10-23T13:50:21.481Z" }, + { url = "https://files.pythonhosted.org/packages/33/de/5e736a36eff6933da012dc440540f79e3ccfc06e27f557638280657df023/jiter-0.18.0-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:e4d4819398d5330636bc0b91ccc0048dba782076fb99257038257ba6f121c840", size = 515524, upload-time = "2026-10-23T13:50:22.872Z" }, + { url = "https://files.pythonhosted.org/packages/0a/ea/1e8bc5b0c920a13e5b698106dbb2d2da5c5e3474668746246f649abb6d5f/jiter-0.18.0-cp314-cp314t-win32.whl", hash = "sha256:c435e795a7ea4b372166a058a5b49a25caeb9c94e469a1414868b14c83ee5c41", size = 185058, upload-time = "2026-10-23T13:50:24.098Z" }, + { url = "https://files.pythonhosted.org/packages/1e/0f/a742b397699c3af52dd95443332164884fe6204e5faa5321b7c073beab0f/jiter-0.18.0-cp314-cp314t-win_amd64.whl", hash = "sha256:5a3d5397da7ae46c7a9601ef02d2c9ec47a6c3abe15e1ea940eaf93e675ee20e", size = 225598, upload-time = "2026-10-23T13:50:25.44Z" }, + { url = "https://files.pythonhosted.org/packages/b3/b7/08ae26347dca48d5cadca33be2f2f5b6b1ae790b322109083d6f95959feb/jiter-0.18.0-cp314-cp314t-win_arm64.whl", hash = "sha256:4b81b474e4a8ec745ab20a6762275a360e1147cb70cf08872ec14e1aa5debc37", size = 183052, upload-time = "2026-10-23T13:50:26.675Z" }, + { url = "https://files.pythonhosted.org/packages/c2/d6/0d2a8a9747ad918141827fabdc05abc3bf73986f7f36647fb8c19708e21e/jiter-0.18.0-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:30f8ae18425e0247ffff4e4a5753ec1952e1b81ed4e7949b84e5ecfaf8315833", size = 291908, upload-time = "2026-10-23T13:50:27.94Z" }, + { url = "https://files.pythonhosted.org/packages/54/b4/19c582727e22681c6069db037c3b3e354c6fbdce7fbc5290a7bc7bc5884f/jiter-0.18.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:93150a3bb0317d8f5a94d4c3ea68db1cb434b94ac819e08c443cea97b7645f2f", size = 316544, upload-time = "2026-10-23T13:50:29.167Z" }, + { url = "https://files.pythonhosted.org/packages/c3/62/5d34e93dc5d1e707788a378335efc876cdc731ceb2111b0a9d7c6f9fdada/jiter-0.18.0-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c9c8a61d6227cdcb0a67c678f30a020837c9f3dd7e0b3f916781defa157e4eb9", size = 338101, upload-time = "2026-10-23T13:50:30.457Z" }, + { url = "https://files.pythonhosted.org/packages/75/e2/0b16a6ca5479cd9efa3c59497cd42f1979a539b6c664a5b9c87e3632f176/jiter-0.18.0-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:285cc15ff9ffcd4ce7f0b9ce02fcbc65e22fcf7dfbda1a3d71ccac8d7b73f8a1", size = 324213, upload-time = "2026-10-23T13:50:31.695Z" }, + { url = "https://files.pythonhosted.org/packages/85/9d/620a97457a0210092bf9faa1eb30f5da094fab2de07a9478af7c254e22fd/jiter-0.18.0-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c8f69ef2e28f8c1759bc1522385ab3e4ade0b1056053cecf67449a947c4525a8", size = 335777, upload-time = "2026-10-23T13:50:32.984Z" }, + { url = "https://files.pythonhosted.org/packages/76/08/a3514df093824f10a61dc1d0bbc22285ed779ba42f15d727499a8c877e16/jiter-0.18.0-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:eec2da60423287bd60377b0fad1723560dcc51cfb2b99615be8431ad425c4438", size = 350490, upload-time = "2026-10-23T13:50:34.421Z" }, + { url = "https://files.pythonhosted.org/packages/cd/60/8f8b51bae62259b429e83d0adff69d93e39e4fadbc4bd1856dc2a0950639/jiter-0.18.0-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5db2cdae6a2f01e8f52ab2154886dcf5bb1844b4f31245440bf623ec91b65b08", size = 338591, upload-time = "2026-10-23T13:50:35.759Z" }, + { url = "https://files.pythonhosted.org/packages/2e/ed/5307f0eb051d987510fdd1020c904927c0b364a4937d372817bdefaced31/jiter-0.18.0-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:029da1f29852beac2f9001f20209b73b29b4d7bdc748c7f8028895769e2cc0d8", size = 316623, upload-time = "2026-10-23T13:50:37.316Z" }, + { url = "https://files.pythonhosted.org/packages/f9/0e/4bdc945ffbf77c60f07c726fbeb45508018322df9d9942d262256397062e/jiter-0.18.0-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:67c6662b1b7e5728a507db06ad1b8a7ff8ade04c2a74f092d467209ef744d3a4", size = 334720, upload-time = "2026-10-23T13:50:38.507Z" }, + { url = "https://files.pythonhosted.org/packages/4b/33/fb3e8f9354e7edab05f3752383eac58ce6e785f2f1626b697dd5dd0a86e4/jiter-0.18.0-cp315-cp315-musllinux_1_1_aarch64.whl", hash = "sha256:4db12daef4a231df528a16f70d5ff7f5e3be21f70e8ad904e4c61442366e8a10", size = 482130, upload-time = "2026-10-23T13:50:40.023Z" }, + { url = "https://files.pythonhosted.org/packages/2e/3d/3aef2be95155bbacadd8691208b6f0f7371cc0cefe80241a1245e38e308d/jiter-0.18.0-cp315-cp315-musllinux_1_1_x86_64.whl", hash = "sha256:4654ea93f525ea96adf289afcf1ead32d773b8325ec326862b4f81f5f4570835", size = 516986, upload-time = "2026-10-23T13:50:41.279Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f6/2aa54fd5da3d0a93de2655e2525426263168454259ba3f2fb70d1b36fbc9/jiter-0.18.0-cp315-cp315-win32.whl", hash = "sha256:f035d01b450ac4e141502f1ce142462cee638198ff5a0237c80e6683798b3b87", size = 186645, upload-time = "2026-10-23T13:50:42.526Z" }, + { url = "https://files.pythonhosted.org/packages/b5/77/5b54ca8c292b83991cafbac6b022f515e46f1ae77dd5f4a97cc33644b235/jiter-0.18.0-cp315-cp315-win_amd64.whl", hash = "sha256:4a18ef4fe95685b000d95eca797cc683e0c178a4b364f2e39f6c79ab107a26e6", size = 225087, upload-time = "2026-10-23T13:50:43.779Z" }, + { url = "https://files.pythonhosted.org/packages/9f/f3/53b7f39b83c757380ab57d9bc3f934431d6b6751f007e8122f7f63c10c2c/jiter-0.18.0-cp315-cp315-win_arm64.whl", hash = "sha256:c73922e4ff4b1ad2929cd795c98223c6688a43c5fd42e9deb8955e4d43b00abb", size = 183120, upload-time = "2026-10-23T13:50:44.985Z" }, + { url = "https://files.pythonhosted.org/packages/77/f8/3a3ef55c528722f3b4be0e7b9686a37ddbe86ed96510bc1c2a63dab7f14b/jiter-0.18.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:0ccf55f6fcdcee82fe40ae617e9d64b8e5f433fa6cb5bf7d2969e584e6df0e5d", size = 317996, upload-time = "2026-10-23T13:50:46.266Z" }, + { url = "https://files.pythonhosted.org/packages/e1/15/b06c1c17bed30b5c5dabb40f80a56a3b71b89c16ae86552307f7ccedc93a/jiter-0.18.0-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:163a55e77f8e92d739b1f4ef212f1d445ddc58ecdf0da1feca44ef424b5331f8", size = 336638, upload-time = "2026-10-23T13:50:47.444Z" }, + { url = "https://files.pythonhosted.org/packages/87/79/b7bcd3e8c850326a323d18a5607334ea40659e22a4fc321e315d1d230007/jiter-0.18.0-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:9de6c9133be12a51ea2d8c270f39a04ed45ee369802bb6270649b952e6cec256", size = 323116, upload-time = "2026-10-23T13:50:48.715Z" }, + { url = "https://files.pythonhosted.org/packages/5e/99/4c53c9d46462cd0691c3c188f89612e63a424d19f5befd1b0631f8f90638/jiter-0.18.0-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2ea4f2ed18eba7454182d4ff727444788ae51ad11bf5a25ad892f5f0ad3e754b", size = 335162, upload-time = "2026-10-23T13:50:49.987Z" }, + { url = "https://files.pythonhosted.org/packages/6f/ab/ef873065a3a1c442a4e62558b77bfa338066317dbafdfdc991121201f5ad/jiter-0.18.0-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:626d5c9fb8b57babc6ce9d03224846ecb094e1d22ff5bff6080398e7f8aee162", size = 350560, upload-time = "2026-10-23T13:50:51.478Z" }, + { url = "https://files.pythonhosted.org/packages/19/7e/48e78558d7cb3d289211da0397b7ed31cfe3efc98dd85f2324abd574c07c/jiter-0.18.0-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b3c3318cc6ef857b6554b43479c30e8249fc143189d500d4137cde9c58412e6d", size = 337848, upload-time = "2026-10-23T13:50:52.961Z" }, + { url = "https://files.pythonhosted.org/packages/2c/35/b0a093e72def7caec970dd8536c3d42af3add3aedfb3c06ac0588effde26/jiter-0.18.0-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:9a70f25f6de76a01e309e109c9bcf2143c5c126b3488dd17a25c7aa404b28f16", size = 315870, upload-time = "2026-10-23T13:50:54.152Z" }, + { url = "https://files.pythonhosted.org/packages/48/a4/fd7ca4d1ce8b876be7a260f5e31615854aed5b041553a63e85c4a265cb63/jiter-0.18.0-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:22d8dd757e603224e46786d63cb7d7bfbddc8f579a02e7b082840468d18c06f3", size = 335253, upload-time = "2026-10-23T13:50:55.427Z" }, + { url = "https://files.pythonhosted.org/packages/f5/71/ccd7154afecd4687b22a8195d5dc6460f89f6e17537ec78edb58a2faac34/jiter-0.18.0-cp315-cp315t-musllinux_1_1_aarch64.whl", hash = "sha256:552a8714f26ddcb43115c82da6d045b3b9f2fa5997d8b21b2f8ec3721503bebb", size = 480775, upload-time = "2026-10-23T13:50:56.91Z" }, + { url = "https://files.pythonhosted.org/packages/c8/b9/bad5391d7fb734cd6ebc383c8603bc324518bf4ce865f5d813908ae42596/jiter-0.18.0-cp315-cp315t-musllinux_1_1_x86_64.whl", hash = "sha256:8060a206e290410d3bfc3bd91715f3ec90a499246f8335d48927e0b3b6a6ccc5", size = 515619, upload-time = "2026-10-23T13:50:58.231Z" }, + { url = "https://files.pythonhosted.org/packages/c8/5c/9596452ad56340e6ed395c5fe27ab102bb2aa0c4b59de2e6a8b3dc3b03a7/jiter-0.18.0-cp315-cp315t-win32.whl", hash = "sha256:91d463858f11ee76ce8e39f391bbcbf1d4c3cc4703a1496fed3a5666dcd5e01d", size = 185204, upload-time = "2026-10-23T13:50:59.456Z" }, + { url = "https://files.pythonhosted.org/packages/08/c8/62c798e2a1a6f827eac1d45232c93b1b0e387a22d559c8483dc7302d5fd5/jiter-0.18.0-cp315-cp315t-win_amd64.whl", hash = "sha256:6ee49daab0b826279c152ad8d61171ea17f4197f91a5e14251d0d5d4adf51059", size = 224948, upload-time = "2026-10-23T13:51:00.624Z" }, + { url = "https://files.pythonhosted.org/packages/64/42/cdfa494914b6d512431e795d8d6226b84b77b733bb8b5eccafd5a1a86dad/jiter-0.18.0-cp315-cp315t-win_arm64.whl", hash = "sha256:bec676a0dc24d4dabd4bdfb3d1f1bf80d4d3dd892fc5c5b3f8f953e2459dbfce", size = 183182, upload-time = "2026-10-23T13:51:01.797Z" }, + { url = "https://files.pythonhosted.org/packages/a9/3d/00a3ba5345740032df65ef415e5c367a89b0e40e9f6e509e5ade36e2f569/jiter-0.18.0-graalpy311-graalpy242_311_native-macosx_10_12_x86_64.whl", hash = "sha256:04aa358fd3217dedd673e9331febe8cccfa4a00382e5372b39efcafe7447ff63", size = 287708, upload-time = "2026-10-23T13:51:03.106Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f5/7337804b47b10e74a1edce33d54437a44adaddb98a4f12a9a87482c28748/jiter-0.18.0-graalpy311-graalpy242_311_native-macosx_11_0_arm64.whl", hash = "sha256:f5e5d58f589412c7774b3a2c4878b8ee54f9804840075822ad2bd2356a5080fd", size = 281345, upload-time = "2026-10-23T13:51:04.331Z" }, + { url = "https://files.pythonhosted.org/packages/1f/b1/1edcf5c674ddc61c0838315d6b7cf279d06c32550ecc40fc2d2f85a8a02d/jiter-0.18.0-graalpy311-graalpy242_311_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:df6d792b41ad90783cf9c3c8f66b02f06025250533b92997913ec600bcb0d075", size = 301499, upload-time = "2026-10-23T13:51:05.587Z" }, + { url = "https://files.pythonhosted.org/packages/e5/a7/949b75f8716f27d69a13eebf2ef5cdf5563ea401648cb330a086f232100b/jiter-0.18.0-graalpy311-graalpy242_311_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f39e7316ee0f16a1e74f23010a058e2bd59481992c7adec0470db4ea57a38e5", size = 302596, upload-time = "2026-10-23T13:51:06.852Z" }, + { url = "https://files.pythonhosted.org/packages/a0/c2/49ee8f4743c27e61c52b4746ba636b43bedda97131a14043dc6f5ce5bb9d/jiter-0.18.0-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:118c1fd995f349f1cad0557f31d6860f336b4aeef7f002dedbc068027f68e2c3", size = 287302, upload-time = "2026-10-23T13:51:08.073Z" }, + { url = "https://files.pythonhosted.org/packages/60/72/394036294ac3226216f73bfa4b14df920eb5baf7fb80fa7e0a0d7ef442a6/jiter-0.18.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:44d0d719cd7845e66b01a0cf346ec9882073e710a05e89a5b6d87be47a9dc69c", size = 277797, upload-time = "2026-10-23T13:51:09.324Z" }, + { url = "https://files.pythonhosted.org/packages/ce/80/f0dadedaa9a109f31e8978c7db355593916968d5956f382188a3f8c0888c/jiter-0.18.0-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4d1d2dc4d930ebc225f488b6b3790acebb2e51b3a165a4a42cc1d05bb927f83e", size = 300192, upload-time = "2026-10-23T13:51:10.551Z" }, + { url = "https://files.pythonhosted.org/packages/93/51/e57dbc6c264ec6557a677189755fe4525d83439237418e3ae59771ac1cde/jiter-0.18.0-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ebb0c346b6c5d9c033fe9e9b6ed6a1ff6dac0288fe681c3434dde6eb9c264fa1", size = 301141, upload-time = "2026-10-23T13:51:11.882Z" }, +] + +[[package]] +name = "jiter" +version = "0.19.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'win32'", + "python_full_version == '3.12.*'", + "python_full_version == '3.11.*'", +] +sdist = { url = "https://files.pythonhosted.org/packages/67/de/8dfd06a2153d8ab6a83a8ca8f8ae3ff860ce2fe324ee6a5d05294b621c2a/jiter-0.19.0.tar.gz", hash = "sha256:ba3064f8be276d7cfb83c2fb85c858be533da2c2f80f9b048c3781b45a57a195", size = 665248, upload-time = "2026-11-06T15:03:33.462Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/25/c5/3f98ccee535b6481fc401c594d23e07ca400d940ea8f9100a06262e07d66/jiter-0.19.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:9e1773b9a58b76c6c5398557f9beeddc64fdbb31ba66ef940280a6d603e0b989", size = 289386, upload-time = "2026-11-06T15:01:03.741Z" }, + { url = "https://files.pythonhosted.org/packages/91/60/2e8cd6da62ef71153a7b430c3b98259802af75546ea35e5f34653c672d68/jiter-0.19.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:af3ee9471733f88d1f13061fc58e4731a6b0141bf47e08c39a95a9bb391c3955", size = 318196, upload-time = "2026-11-06T15:01:05.532Z" }, + { url = "https://files.pythonhosted.org/packages/1d/27/4605012ffeafdc3d7733694d2d5083796381770973fe41b7371dc6544e16/jiter-0.19.0-cp311-cp311-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:fac2b90ad1709af1a4a5419e2031ff7d950810a584343c747a8087f842a4278e", size = 333702, upload-time = "2026-11-06T15:01:06.957Z" }, + { url = "https://files.pythonhosted.org/packages/80/2b/ca43d02e3ca5a3d8659d2d00f4c1a58408a05bf9db07a817f551ce7c365c/jiter-0.19.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:da606acf39d7d2f2a56bfbb48a0b36f25da1d22d801cd0c9aecfce2f791e3239", size = 337353, upload-time = "2026-11-06T15:01:08.311Z" }, + { url = "https://files.pythonhosted.org/packages/b2/9c/b9725a39cec632737a82521a6320aea46b8dde418ecc1fc2c86ea0a415d8/jiter-0.19.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:d60d0621f0d6f330a1fd92067340a8eb4262651a07b2dfd92a87e6527d05c933", size = 323554, upload-time = "2026-11-06T15:01:09.893Z" }, + { url = "https://files.pythonhosted.org/packages/1b/33/f72b9252b63c3a56920cbf44360722ef4a40f3e74830ede6ec9c02a26254/jiter-0.19.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fdc0a6ddcc9228a0955b350509041c9321af91e928c918402d0212d5fd315355", size = 335673, upload-time = "2026-11-06T15:01:11.135Z" }, + { url = "https://files.pythonhosted.org/packages/ef/f9/a422ccb7f89adc6238a860bea22816fae1d903a48289dccff44a1399b49b/jiter-0.19.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:e0238393882c0737846239bf4a553140e27d6b6781e87f570e7c3d671c916bab", size = 349297, upload-time = "2026-11-06T15:01:12.461Z" }, + { url = "https://files.pythonhosted.org/packages/43/06/37a1051b8fe6189c9cc87d4483fc3b30841b9678cba95caddcadc77d6ead/jiter-0.19.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cc4a2b70ecd4f102583344c1f8cc5dc11618665b1889286bb3b4279c19b337dd", size = 337119, upload-time = "2026-11-06T15:01:13.961Z" }, + { url = "https://files.pythonhosted.org/packages/20/a9/6de8dab28150e381b7733a27adaae42bc22af52b79a198c09ad9f046c85c/jiter-0.19.0-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:23a9cd6d7779b0022b9446d7f8b19ba81bf9631d494ca371d810d3925e10fc45", size = 316181, upload-time = "2026-11-06T15:01:15.339Z" }, + { url = "https://files.pythonhosted.org/packages/ee/df/78e3721c6c452a7209764d2d9760746bdbe69de7c8b93797a149c5cd80f8/jiter-0.19.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:2777713f5c0b49fe909ee0a68320bce095cdcdb9b7611d347d49394f24afabc0", size = 481784, upload-time = "2026-11-06T15:01:17.188Z" }, + { url = "https://files.pythonhosted.org/packages/52/af/6101a311e708c24587c44ab0b142f8d077c5b4c93285c48b63c7a99a5ed2/jiter-0.19.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fe16c8e0caf7513c6b4e1c6466761b153aa16c4e18a84ddcf6dcf731b2bace1a", size = 516223, upload-time = "2026-11-06T15:01:19.004Z" }, + { url = "https://files.pythonhosted.org/packages/3c/72/d7cc3fe03ded6f0c0c49329e542969ec180f3ecdb8c947f162914bd0c097/jiter-0.19.0-cp311-cp311-win32.whl", hash = "sha256:7f1ce80a4f1eee5570f824300bca01b5b1d4174a84ecca6d7019c1159176519b", size = 187725, upload-time = "2026-11-06T15:01:20.655Z" }, + { url = "https://files.pythonhosted.org/packages/6b/97/0550927e719aca463c4ef4858ade937c434efbb4a68a66a6943cb23167fd/jiter-0.19.0-cp311-cp311-win_amd64.whl", hash = "sha256:7b9107bb4ec6889f943c948d69cee0f0ef64f5c5a7f6a8a6a6c5f23e8ff5f557", size = 226786, upload-time = "2026-11-06T15:01:22.018Z" }, + { url = "https://files.pythonhosted.org/packages/f0/1a/b437e2536ff37ee461f0bfd8fd7c99f541753b3737ae3c4be22a03ed9707/jiter-0.19.0-cp311-cp311-win_arm64.whl", hash = "sha256:9cd6b141ccfac1fa05c49b579717505304caa0cfb41ab569baffcc109077e492", size = 185632, upload-time = "2026-11-06T15:01:23.47Z" }, + { url = "https://files.pythonhosted.org/packages/8c/cd/88cf9efec4d4b6cb816233a6fbfcd842e9675012b2827c6abee4f87e53f1/jiter-0.19.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:0282eae10bbccfabcb6001ced6a20abc5e05e26c6316e7729c8fc1510bd3b8e1", size = 290088, upload-time = "2026-11-06T15:01:25.103Z" }, + { url = "https://files.pythonhosted.org/packages/86/56/371651ed5fdbab064b9ca39f5ceddd1bad2175bc1d4c81915eb63ac1fa3d/jiter-0.19.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:730b0387fbea21b71b86b6975e20da7a364b04c4428eba0d15e6f0a7b20aa59b", size = 314238, upload-time = "2026-11-06T15:01:26.672Z" }, + { url = "https://files.pythonhosted.org/packages/71/56/357172c32d0763f5cf8eb1afb8f5ded5ba314856eccbdb600fc82efe8b18/jiter-0.19.0-cp312-cp312-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:cfbf731056b76d2d600f11ee895ca5d4d39d22d881562d65ada3ecbaf6053d25", size = 332123, upload-time = "2026-11-06T15:01:28.273Z" }, + { url = "https://files.pythonhosted.org/packages/b1/a8/9c0e83f11fd067d1973e8f801e78d0c2ea1186aef7cd6bf9e7c847c16836/jiter-0.19.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fcce75459e06cf811395581f6d256e2535d165ec4d223b809115a59b4ea6f398", size = 335561, upload-time = "2026-11-06T15:01:29.834Z" }, + { url = "https://files.pythonhosted.org/packages/0a/e9/d49c126dad2bc47d8e02392eb7ffae797134f021f4dcfc15bccc3b704c7a/jiter-0.19.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:10e863d52095bc1106d22a4b9285bbe722a56d7f3e65f9a5d09ec9814a31be43", size = 322601, upload-time = "2026-11-06T15:01:31.313Z" }, + { url = "https://files.pythonhosted.org/packages/ad/d3/9085b225b080218f7ae7f3f33b746686cabefa99cbc34895fd35221df4d6/jiter-0.19.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:bafc856de75f6d4400e2d839189a6aefa1c985a151893743262811495917c20c", size = 333667, upload-time = "2026-11-06T15:01:33.032Z" }, + { url = "https://files.pythonhosted.org/packages/fb/2d/d71dbb7bb2f5954e2f33151de25721abf03771fb5368acda88f781b419d0/jiter-0.19.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:562d329189727922d9ee2e58f37382de1d0ec0d7a69b8d9670a23ef7ea216a49", size = 348693, upload-time = "2026-11-06T15:01:34.541Z" }, + { url = "https://files.pythonhosted.org/packages/8c/41/22f74631763c50a6ec76fec1e6a9557ffba181fe5048135520284a5746f3/jiter-0.19.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0956b5f58b804221dfb929c120e6d4032138fed20c1cc0ef683a2d1326255e46", size = 338071, upload-time = "2026-11-06T15:01:35.871Z" }, + { url = "https://files.pythonhosted.org/packages/9b/4a/66e5d347e63b452eb160b549d1bb9bc88b2e7ad4d55c900afd278b8ec85b/jiter-0.19.0-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:aa8e941d7569417134d14ed982bd5cef2c9baa55748bd70601f29e59b65497a9", size = 314409, upload-time = "2026-11-06T15:01:38.148Z" }, + { url = "https://files.pythonhosted.org/packages/cf/19/919970ab010e41cc8daae6e3b225cf457b09f9ce1a8458a0b949272d312d/jiter-0.19.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:39032d61473b11a6201300a710d6f912935bb3c783f3b564f94caa4d8ea34f40", size = 480350, upload-time = "2026-11-06T15:01:39.515Z" }, + { url = "https://files.pythonhosted.org/packages/6c/53/fef6d7566fdc019201be101bb63056a01ac3746c4f072901318593c65a2b/jiter-0.19.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:1427fd34cf36db7c13d9643465a9fe00bfcc9ba969d8a633e43a4e2525afb565", size = 515375, upload-time = "2026-11-06T15:01:40.9Z" }, + { url = "https://files.pythonhosted.org/packages/50/94/0eb1a877a9e34fe757aa6fbcb9e19a996540283fafa4826c4fff816087bc/jiter-0.19.0-cp312-cp312-win32.whl", hash = "sha256:178bdffd86ccaf25fda33dee522b046720b1f617f5b72864a720a4e88d574fc6", size = 185353, upload-time = "2026-11-06T15:01:42.628Z" }, + { url = "https://files.pythonhosted.org/packages/10/7f/9d1dd194cc52698a9c7116b0b464826cc1a2feda2afd12fa562182ff27d6/jiter-0.19.0-cp312-cp312-win_amd64.whl", hash = "sha256:f64154096d9aa5462ef3c4f48d624492602d0073d54d30c20c08793387f67e42", size = 225500, upload-time = "2026-11-06T15:01:43.975Z" }, + { url = "https://files.pythonhosted.org/packages/98/d9/5065590d951e03216b7b0beba984d397d1e724201dc57184503f79d696eb/jiter-0.19.0-cp312-cp312-win_arm64.whl", hash = "sha256:d9cf0a878f99f97335023f51bf07e1f81c19ce13636b06347c8b548e3a26bc70", size = 181832, upload-time = "2026-11-06T15:01:45.279Z" }, + { url = "https://files.pythonhosted.org/packages/c4/b0/9af5c95d02e75ec5ee2c45ab37a7ead761cfbf1807b6b568944baa371699/jiter-0.19.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:ee63ba51f837d5a4bc2d79f6255ef0e754922519b172099fe4b9e8b1a6c85513", size = 289637, upload-time = "2026-11-06T15:01:46.615Z" }, + { url = "https://files.pythonhosted.org/packages/72/31/826662abf9197a96ac347f4f7456bca96e751de71ad8983de1ae06f210ef/jiter-0.19.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9ea284d5a9391fa7b6bec676569a91463325298532887d3b324b27d541f6ffc1", size = 315796, upload-time = "2026-11-06T15:01:48.327Z" }, + { url = "https://files.pythonhosted.org/packages/76/c2/a4e62a7af0cd7f17423593437b721f4035b025b1d4ac0f2b996ed6d059c4/jiter-0.19.0-cp313-cp313-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:345f9f5dc1496a17b83cbbe7c351f94ddcd77b853518b0382b82702652353c9e", size = 331137, upload-time = "2026-11-06T15:01:49.675Z" }, + { url = "https://files.pythonhosted.org/packages/aa/60/edd90b139888ec1f40ff1d37b5d446447164806dc607706b933172277ab3/jiter-0.19.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d056e8cf0ad1c4676ae559311d4a90b2613ca415452f5072bee62ee7424a094a", size = 335268, upload-time = "2026-11-06T15:01:51.172Z" }, + { url = "https://files.pythonhosted.org/packages/cf/d1/5a5a8684097942c24854f4308b36cf630ed573a94b06305dc146c74e0bb7/jiter-0.19.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:62fda39be2cd67deca433e8ff9b125b285a592c5b5a439a5e80ba18337a73d2a", size = 321592, upload-time = "2026-11-06T15:01:52.58Z" }, + { url = "https://files.pythonhosted.org/packages/fc/94/f4466e2ada992e82f4967021953121039998b8e4ad83ebfb2b6e2c2a401c/jiter-0.19.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:a09edc861155f4df705a382e0d241e0ba4bf504a1438a6cd3a94e8d3fe2cf37d", size = 332880, upload-time = "2026-11-06T15:01:53.849Z" }, + { url = "https://files.pythonhosted.org/packages/1f/b3/11a1d37dcdca6edc003ac6f2512c1dd37b0f0c2dbf7c988e5213e1b29d19/jiter-0.19.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:fc13db05062df81357bdb926fc6b1014ce8ebef511a0fe7520b818f43b74fe5b", size = 348166, upload-time = "2026-11-06T15:01:55.216Z" }, + { url = "https://files.pythonhosted.org/packages/30/f1/75de49da39833a8be13b47468b99876c1f4a96b301c6a3fa3ad6a7d87e7d/jiter-0.19.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3b27d6bec319dc17cdced13e495f90ce066676ca296fc56f2dd2128f6a7599ed", size = 335970, upload-time = "2026-11-06T15:01:56.493Z" }, + { url = "https://files.pythonhosted.org/packages/6a/95/6ceb994aae2511e94da56a3def4795e0b797357af252c824bdfdaae70323/jiter-0.19.0-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:541669df0273fafdc506e89d7750afd528b6094586f87c01291c62f3273575ed", size = 313765, upload-time = "2026-11-06T15:01:57.768Z" }, + { url = "https://files.pythonhosted.org/packages/02/a9/ee7f3f2ceacb6e4593cfe9d9b7eff3b2b404efe2e05e152070a50abe42a9/jiter-0.19.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:bcf434316c96f58b4623500c01498506cc1d3fb689e948158a5955dc245202a4", size = 479932, upload-time = "2026-11-06T15:01:59.149Z" }, + { url = "https://files.pythonhosted.org/packages/f5/50/127a653d5292c6d9e6ec993c3948e3b9f3d0fbc6af91094dbab175ee8d3e/jiter-0.19.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:8b9d75a51df8f3b6fa7e25a0c0d7c4735e9d2196d6441e5a7c5b4ef1b76cd8bd", size = 514729, upload-time = "2026-11-06T15:02:00.695Z" }, + { url = "https://files.pythonhosted.org/packages/54/23/17c033c7336a5ec7d4c6b10edb851c96ffc9c0652d9f5b14ea5bae6028de/jiter-0.19.0-cp313-cp313-win32.whl", hash = "sha256:a39f45078cc2b75ac91b48833093c033e374f8224ad38576ebba06398a1de96b", size = 184740, upload-time = "2026-11-06T15:02:02.231Z" }, + { url = "https://files.pythonhosted.org/packages/2d/ce/c11a38ccc9d4fdb0c092cf583919ecff62724d39ad3556b5324173dad1ee/jiter-0.19.0-cp313-cp313-win_amd64.whl", hash = "sha256:050dd505e407c028aa76b9b4a379a06f79f484c3b256d99a7fea118d863c9a79", size = 223145, upload-time = "2026-11-06T15:02:03.485Z" }, + { url = "https://files.pythonhosted.org/packages/4e/54/d63c0ed96e4d2b6f4a64ada70a8eaedbd8849416045821d70c27d26c2dcb/jiter-0.19.0-cp313-cp313-win_arm64.whl", hash = "sha256:96b8d6795c8e8121d0a99b2c8f60ca4db02ff8063205bf2c9712e2714a52ea9f", size = 181228, upload-time = "2026-11-06T15:02:04.664Z" }, + { url = "https://files.pythonhosted.org/packages/21/7c/4e294eece8901d8b56cb7c7d8504ad4da16a402867d89af1505034a0df93/jiter-0.19.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:cfcf2473b941e8695b496ce9dc155f772ad97d98be5071ebf1e4e4bbfe00f632", size = 291741, upload-time = "2026-11-06T15:02:05.931Z" }, + { url = "https://files.pythonhosted.org/packages/70/d2/c81dfd6c0c60891341ac7ae7e8d0a4c7eea5d9693a3ad205e053f6c50d4a/jiter-0.19.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e8dc4fb0fe3a5e36a373933340f4353da816c6de684a57908633504df3c2c90b", size = 316068, upload-time = "2026-11-06T15:02:07.193Z" }, + { url = "https://files.pythonhosted.org/packages/8f/51/5960eb532971f27ac0962f8a05c438224d1f9cd548772df14c4064a0c7fa/jiter-0.19.0-cp314-cp314-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:d2358442c7c45e1761b546b458a3c5bcd7d571838e2340a397464475f688494d", size = 334264, upload-time = "2026-11-06T15:02:08.514Z" }, + { url = "https://files.pythonhosted.org/packages/e5/7f/3b131a083dd46d495120ee92318f2dd07870eae853df3ab8c0a8f977f1a3/jiter-0.19.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:95b75f42a112e39ddd0b8683b4ccf6319a182460afdc4bb6828423eeeef97a6f", size = 338039, upload-time = "2026-11-06T15:02:09.819Z" }, + { url = "https://files.pythonhosted.org/packages/d9/2c/62c8ae6b16f3e369ed2d95690ba747b8319d0a96693d1d57ec2d306bf256/jiter-0.19.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:d5cdf03154ba3867707f48454e3f9235df7a0f772cf4c9f57e4004f7c67d9821", size = 324016, upload-time = "2026-11-06T15:02:11.195Z" }, + { url = "https://files.pythonhosted.org/packages/f7/e3/516e16d89f93b657bc62fbc010cf96cff967c58b23874da8ea494d420b08/jiter-0.19.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:dac2525467cca169c3f8049e04e69334eecbd38caa1b0b10a11d9cf07c7d5871", size = 335866, upload-time = "2026-11-06T15:02:12.701Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3d/0899ef2a0cc7a31935a450a0cadd9708754cd1e3498268d3bce44760f9a3/jiter-0.19.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:71361b3484086f538674ad37af5b4d5e86c04c39ca79b026cbd41cb63476dc72", size = 350517, upload-time = "2026-11-06T15:02:14.103Z" }, + { url = "https://files.pythonhosted.org/packages/d0/6a/8ec186d2307054a54a7656cb0fe1a186970f7b8740c08701874e3dffcf82/jiter-0.19.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:def1f12b5cef4f53c30ec89d1644c6c5500b343f1ec5e9ac8010dad8c0a41d7b", size = 338365, upload-time = "2026-11-06T15:02:15.515Z" }, + { url = "https://files.pythonhosted.org/packages/4c/4d/1f0c4a9d0e529025e5292416f52b0a0efff7f9b9efac56f345aea91ed0e7/jiter-0.19.0-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:62d0ab327933a8cc5cba2ff2a1ff83400eb10bee1694eb1cc0c4c83296855d56", size = 316480, upload-time = "2026-11-06T15:02:16.918Z" }, + { url = "https://files.pythonhosted.org/packages/95/c8/72f6f2a6ce44d5aca96440498d5144abd2a509c58e0f53e4a039bdebbf7a/jiter-0.19.0-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:9b9e55e0182f9ff9da2e34ee92492f30ab99bd276cad496fa56feb7a64148dd8", size = 482150, upload-time = "2026-11-06T15:02:18.285Z" }, + { url = "https://files.pythonhosted.org/packages/2a/53/f78cf27995858d32f212ff825addb32eabd70c896a530e624f36d20ac1f0/jiter-0.19.0-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:1433a914536ac5da69f91cc7743ac2f64d3705db2de52f0715ecd00fed2c95fa", size = 516946, upload-time = "2026-11-06T15:02:19.661Z" }, + { url = "https://files.pythonhosted.org/packages/ce/aa/14e436a6a0fa643a66867f32e68e9683e5ccfaa8ff6df13781611dc62783/jiter-0.19.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:707b8194222a343c4a5e1574df95f5ade03e3f1cbdba77d8c89c6af0f40d92cd", size = 111991, upload-time = "2026-11-06T15:02:21.062Z" }, + { url = "https://files.pythonhosted.org/packages/c7/e3/d80e254dd1a85d585943046b9ba652cf01b3338beabb2035a7f5df82a906/jiter-0.19.0-cp314-cp314-win32.whl", hash = "sha256:512b07721e67a3036db5966173885bebbffd1b0b1583b56f08bd52723865b382", size = 186542, upload-time = "2026-11-06T15:02:22.323Z" }, + { url = "https://files.pythonhosted.org/packages/62/02/0a387aedb729da03acb860ba38330a2abb94893809b47d3ce5088f3edc43/jiter-0.19.0-cp314-cp314-win_amd64.whl", hash = "sha256:76cb5b95b07f853911a39835de285da6954f44634890c26dd6ecdfc465fc977c", size = 225421, upload-time = "2026-11-06T15:02:23.586Z" }, + { url = "https://files.pythonhosted.org/packages/8e/cf/ce7abfc44da37c7807d244a400309c69d211a4704b2b37b2a3d022ea0897/jiter-0.19.0-cp314-cp314-win_arm64.whl", hash = "sha256:12d90242083e7ce352d12dc8b04daee4b6c29314385bc84ecd2b809d0607fbc3", size = 182873, upload-time = "2026-11-06T15:02:24.874Z" }, + { url = "https://files.pythonhosted.org/packages/16/b0/5f5bfb4fa82b85f6027eb9e46e4001a0d2ba3f92370c3cff565d87706419/jiter-0.19.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:d0b16e19a7ea17ab0fc6089ded12040d46afbd9681c7978012044dc7ff0073aa", size = 317990, upload-time = "2026-11-06T15:02:26.154Z" }, + { url = "https://files.pythonhosted.org/packages/79/fc/99ec7c673c2b5eff83e52bc1fd23265c4fac8a5236b19d21ddde05cbffc9/jiter-0.19.0-cp314-cp314t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:6f476b368da302a9cf6dece5af4979dac8b71a8986d69e47ce5a71f2cdea08ec", size = 334774, upload-time = "2026-11-06T15:02:27.53Z" }, + { url = "https://files.pythonhosted.org/packages/cd/6e/95ccd4c6770eeb9946733bea3eb19882cf170c02a5cabe23c3dc675ddb29/jiter-0.19.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c094e472d6e54bfed6c78ef8595c27cf46b76d287f5cebb5264569f9b02b3737", size = 336708, upload-time = "2026-11-06T15:02:28.897Z" }, + { url = "https://files.pythonhosted.org/packages/38/d8/8abec81697c8d6d6c0c55712ef6a57233e30913e849a4248fdfa859d1fdd/jiter-0.19.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:825a0b9c30ff5b12698cec9d034b568a1f26b2bc888acd1bd009d0efa1de081d", size = 322945, upload-time = "2026-11-06T15:02:30.174Z" }, + { url = "https://files.pythonhosted.org/packages/42/0a/159a0276519b1b30335e3f10b9518c696dd7a982208eb78d22ec7b595866/jiter-0.19.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e8f7d3072bd68b6ccc264bfe6600b0f730997bb414c7a274c317804f8f90c871", size = 335349, upload-time = "2026-11-06T15:02:32.366Z" }, + { url = "https://files.pythonhosted.org/packages/6c/f4/1dbc8a61d109985a65262972a9ce5bb59249585542d3ffd2d0cf7d6f1152/jiter-0.19.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:ab7a041b4c4a0afb160470839bbcafa3f5fea5572e0d1d46bd5239beeb30b19a", size = 350611, upload-time = "2026-11-06T15:02:34.094Z" }, + { url = "https://files.pythonhosted.org/packages/d6/59/0a6944592a79a78104cec927cb5ce68400c152299a9129fea63e1dc296ae/jiter-0.19.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f7cf95dcab93e61fb58f395eedd4924557c8b08cc044933a4b7918c3d20751d7", size = 338402, upload-time = "2026-11-06T15:02:35.352Z" }, + { url = "https://files.pythonhosted.org/packages/3c/eb/1ff411f106d18026527a12af8e4f2b0a4c589d64bec71d4f6eae3344fdd5/jiter-0.19.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:a01d50640fb033259858f9203292aaf4dc9eb903d5646c529ba5be655a982a9b", size = 316165, upload-time = "2026-11-06T15:02:37.14Z" }, + { url = "https://files.pythonhosted.org/packages/e4/73/17b8c34e48dc33c30a5db75550769cf930cc62de37d46b8c540f613081a2/jiter-0.19.0-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:4ddc2617d3725c37501737f9725694fac10f2fb3f274adbfabc521bea7200d9a", size = 481091, upload-time = "2026-11-06T15:02:39.009Z" }, + { url = "https://files.pythonhosted.org/packages/1d/1a/2ecaab02af01e885a216a0dc0930e060325b81f5580c80cd69cfdf1d9827/jiter-0.19.0-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:c528273371289b506762bfda85094b55e298082b7cc2259f0d01ee30d61b771c", size = 515502, upload-time = "2026-11-06T15:02:40.505Z" }, + { url = "https://files.pythonhosted.org/packages/ed/87/9c3917a60c381132af4d06eab58210a171b74a18060a27590f338dbf21b3/jiter-0.19.0-cp314-cp314t-win32.whl", hash = "sha256:521438d81c8c42293e09297441de331731f576ba647e7dd6c05698d873c17c34", size = 185092, upload-time = "2026-11-06T15:02:41.81Z" }, + { url = "https://files.pythonhosted.org/packages/4e/f5/0aea271de1d0194634c235d5d864006658282fad462beee2e5268ea57dd5/jiter-0.19.0-cp314-cp314t-win_amd64.whl", hash = "sha256:f2531f55026fca2c448148c7d9371117f801e0df7a084af62133b3d775564ebd", size = 227614, upload-time = "2026-11-06T15:02:43.234Z" }, + { url = "https://files.pythonhosted.org/packages/91/da/69a37a4c11a9d5a2f70e9704081474489a05a379e5baece7454fad5a7481/jiter-0.19.0-cp314-cp314t-win_arm64.whl", hash = "sha256:8167c2cd6fd39b2b9428061cbb03889ba17a45df2285307750eb720b9befee03", size = 183029, upload-time = "2026-11-06T15:02:44.597Z" }, + { url = "https://files.pythonhosted.org/packages/74/b7/ec514207195a7dbe7437239f9b55f36de1cd577716eddcc3cc69b5e8064c/jiter-0.19.0-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:1ed2bfe0518f584fb0dc22b36412d7c6d19529b5682de79e67b44666034938bd", size = 291909, upload-time = "2026-11-06T15:02:46.018Z" }, + { url = "https://files.pythonhosted.org/packages/68/66/09e6ba7930810191b798549c4cccbab65e5825bd27aa44b63caf8e303e67/jiter-0.19.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:baab631aa2a8bd139db09e56bd2f6358aebb5d7dddcac0713d07ac7fb0861ebb", size = 318969, upload-time = "2026-11-06T15:02:47.354Z" }, + { url = "https://files.pythonhosted.org/packages/ee/5c/7b4171cd22912b9c2bbc561e0d065439b4d65724d2c565aaeb0798c12db7/jiter-0.19.0-cp315-cp315-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:13c916eed31210fcf3b5d070709adaa6c2a39fdb0ad003962663460dd5cebcaa", size = 334730, upload-time = "2026-11-06T15:02:49.221Z" }, + { url = "https://files.pythonhosted.org/packages/e0/af/4119de31e174a529f20b9b51cf73f90cdbc89d3c6e9dc138fa3c0dbf8efe/jiter-0.19.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:63e17a237323b240cbb9be6c4157fcdb2b4edaf8aa267cefc52157ff6b27514e", size = 338040, upload-time = "2026-11-06T15:02:50.471Z" }, + { url = "https://files.pythonhosted.org/packages/3c/6e/d5b972d66811a6be98bc85087416a4cc7f38276903647fed708390862460/jiter-0.19.0-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:86946bc97afcc82c79b12ca8acc87223acc2fee9b25ed3455e6abb0f3c40f722", size = 324217, upload-time = "2026-11-06T15:02:51.723Z" }, + { url = "https://files.pythonhosted.org/packages/15/04/2ad357983c345a45474d029dee9f4b6f9f88a603e79692a4f5348b05568a/jiter-0.19.0-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f614930e5bfcaed1b18fc46c197b2df5f4172180ca07d7a2690b542cb21103a2", size = 335734, upload-time = "2026-11-06T15:02:53.221Z" }, + { url = "https://files.pythonhosted.org/packages/d0/b1/87f22901550c631b39de77f9376fc218d6e6c2055fe673904061f93cf812/jiter-0.19.0-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:5315406c0c95b18e07359113fcd96d219fafac94227be2b4e77d0e30ef6225ce", size = 350498, upload-time = "2026-11-06T15:02:54.576Z" }, + { url = "https://files.pythonhosted.org/packages/67/51/68340023ea8bbaf3abe4d37568d53c6a7f07bf498e2e9b0573d67614a493/jiter-0.19.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:daa5bd8317d7b9a56d95af3b0b054f0d06c94a8cb68e332943d4532ef8611eef", size = 338750, upload-time = "2026-11-06T15:02:55.916Z" }, + { url = "https://files.pythonhosted.org/packages/34/54/2e2e218e9b931cb7392e43902a05517d9ddbef687b3a081aa1669a65f0ae/jiter-0.19.0-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:977b59124adddc535a794ee75eb27f223c4dd677822a3fd74e0d17be6a52c39b", size = 316619, upload-time = "2026-11-06T15:02:57.249Z" }, + { url = "https://files.pythonhosted.org/packages/d1/3c/fdf1690bde9ca32e53424f92a0728576399bee18490b221603e5590fbb5c/jiter-0.19.0-cp315-cp315-musllinux_1_1_aarch64.whl", hash = "sha256:be19151fceb1a7fcdbe7b187cadf914dc54e6f0fcfe88df7a0616ee0baa71a2d", size = 482123, upload-time = "2026-11-06T15:02:58.559Z" }, + { url = "https://files.pythonhosted.org/packages/e9/f0/3e9c6d18b9618a4d8cfdd5ffe320004cd78459eb70c20bfd4de0b0827580/jiter-0.19.0-cp315-cp315-musllinux_1_1_x86_64.whl", hash = "sha256:fa03bfa89a25915283cb748153db3da0fbd8fb298ed55abfba32bf3bf23d2b68", size = 516970, upload-time = "2026-11-06T15:03:00.011Z" }, + { url = "https://files.pythonhosted.org/packages/f2/d6/93533d76fc10e7e06e97abf2bb6aa5bd83b9ec513e911a42cda4c7c6839a/jiter-0.19.0-cp315-cp315-win32.whl", hash = "sha256:11f14da1ec8f4bc673a4fa475e84c5c7261b0239e18e0db03af55294919b5be8", size = 186648, upload-time = "2026-11-06T15:03:01.346Z" }, + { url = "https://files.pythonhosted.org/packages/bf/6d/9b480cd3bb00423c8251e322e147c9659fe8120fc345dbc0e0e8b128872a/jiter-0.19.0-cp315-cp315-win_amd64.whl", hash = "sha256:7981d17671689181d8b6806fac508ba6a794381f9486e62c598ead75ac857704", size = 227504, upload-time = "2026-11-06T15:03:02.762Z" }, + { url = "https://files.pythonhosted.org/packages/3e/ee/6e552e437dca26dc447fd1d44141b2d37d1b00530bfb3c0b92fa61ca7c53/jiter-0.19.0-cp315-cp315-win_arm64.whl", hash = "sha256:50522b7e6f3d86f038b6d3be748fcd352c1611235d54442e70458b26de324df2", size = 183098, upload-time = "2026-11-06T15:03:03.971Z" }, + { url = "https://files.pythonhosted.org/packages/69/a4/2b95137709553f7820e3011389d6b5cac6a66fceec2484283d0b8e0be445/jiter-0.19.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:c3c3099dff0565e08ad503f2f9cf1ab8ec4a5b474042264c72517afc652e3285", size = 316134, upload-time = "2026-11-06T15:03:05.247Z" }, + { url = "https://files.pythonhosted.org/packages/ea/a9/05205b79e08d710bcc62de5472e7b208365cc047361d917a829421486da2/jiter-0.19.0-cp315-cp315t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:2b26727103c0121ed2ec2e78ea23d669db71dad09128d274f1ba0aa4c07f96c5", size = 335277, upload-time = "2026-11-06T15:03:07.09Z" }, + { url = "https://files.pythonhosted.org/packages/06/fe/2be55dea9b0d14d44245200ed306302c8bc0e5a73977749ae5925ffb7c47/jiter-0.19.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80d85202190ba13c3958bb01134bde8d81300a6530e2d5cfe73b63ae9a55f408", size = 336622, upload-time = "2026-11-06T15:03:08.366Z" }, + { url = "https://files.pythonhosted.org/packages/32/eb/9383e49faaf67b19f8ddb1b08963668a1c1cbd236ea25f22de19e3aa4908/jiter-0.19.0-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:cb7458f07137ed895d01344d321205f050fb15fa8597a29e5d9bdaac140d4678", size = 323119, upload-time = "2026-11-06T15:03:09.847Z" }, + { url = "https://files.pythonhosted.org/packages/cd/9f/75816f1f9cc27e5212991a27c99d14f9995d92e6cda2562ab527a3400f7f/jiter-0.19.0-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:7a01b76a206200d8a55111ac3d8fdc131dfdbefeaee0efca72597854aa71d6ea", size = 335134, upload-time = "2026-11-06T15:03:11.786Z" }, + { url = "https://files.pythonhosted.org/packages/d8/3b/9fcb38a871223a8759d46514594b2d146d4fd50890110e3b0e47d9b7775a/jiter-0.19.0-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a628bd3603bb4a9f73d6bf659fbf8565e30902b4d7ba915e125d00aa2c3cacf7", size = 350588, upload-time = "2026-11-06T15:03:13.177Z" }, + { url = "https://files.pythonhosted.org/packages/7e/e0/297733d77491186cad6b239ed87231bfd670d4224f6348217656e547ca47/jiter-0.19.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ca0bb11753d4e24d07f579ec4b62413bb43f88d8736216b57996f4011906b20c", size = 338023, upload-time = "2026-11-06T15:03:14.546Z" }, + { url = "https://files.pythonhosted.org/packages/c7/33/bfe34cf6f72ee13090169390e829b8339d769264fe3e92f2b8f211915782/jiter-0.19.0-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:f19ebbeeae0eade71b798efc2afacdfb07402e0fcc7c0943529759f31476985e", size = 315871, upload-time = "2026-11-06T15:03:15.857Z" }, + { url = "https://files.pythonhosted.org/packages/3d/12/2c095a7929daa0421e0ce631b12ce7374b41ac19a9a9141e79411d483868/jiter-0.19.0-cp315-cp315t-musllinux_1_1_aarch64.whl", hash = "sha256:49610246ac2dd94392659d94a53c8d71f2b2c92dc22f2b15a4d1b0d774f74c52", size = 480771, upload-time = "2026-11-06T15:03:17.113Z" }, + { url = "https://files.pythonhosted.org/packages/2d/d7/0df9bcc5a35180d05f3b1af2813434af1eeaa9ee4dd2f54cd79cddb7ef0f/jiter-0.19.0-cp315-cp315t-musllinux_1_1_x86_64.whl", hash = "sha256:1c77841a8e98c7c765fcc804f9c1c4f66905340cab7a81c3ebdca5c4d68bfe4a", size = 515629, upload-time = "2026-11-06T15:03:18.408Z" }, + { url = "https://files.pythonhosted.org/packages/cf/98/8c2a5ab47b4a8b4a9d9b6c12354a3a1497c20b779c44d38732a02e14e1c7/jiter-0.19.0-cp315-cp315t-win32.whl", hash = "sha256:3694d60669e7d8277f6366170a6944f8b9779d85417b3ee6dda3897300528141", size = 185198, upload-time = "2026-11-06T15:03:19.882Z" }, + { url = "https://files.pythonhosted.org/packages/ea/6f/736254f4a132622ee3481d90cf7a521b3b3d0f8c6e3794a87bb10b88388b/jiter-0.19.0-cp315-cp315t-win_amd64.whl", hash = "sha256:093add0b9c12cfa04920cb9fcdc9845ff580fb374ca6a645f6d74f471a5d25f7", size = 224870, upload-time = "2026-11-06T15:03:21.225Z" }, + { url = "https://files.pythonhosted.org/packages/49/cc/9bf0f4ea335a7b9468f7e72c2cc5d19a77f7d9ddf77f7fd9af69f82f489e/jiter-0.19.0-cp315-cp315t-win_arm64.whl", hash = "sha256:9f5ac1f8d1b0eda36d98ab5266c98deddf4d8dc5ff7e031c51f9e9f632abee2f", size = 183185, upload-time = "2026-11-06T15:03:22.475Z" }, + { url = "https://files.pythonhosted.org/packages/4c/67/66164d4be8991d7f3b7163be80c7c5e94040cc7d9ba62b4e4e4113da5f79/jiter-0.19.0-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:e7682cfd9561bcdc47dbd10d2546b5b37640b4bef407f76fb434c30e4cb0ae81", size = 287293, upload-time = "2026-11-06T15:03:23.746Z" }, + { url = "https://files.pythonhosted.org/packages/ba/8f/94f8b4d9be8cbf8e0be61c21b368ba367d8cb57d8f5d0ef71bcc8f61ef3d/jiter-0.19.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:bee08505baeb38c891d884e977b20924ec13bbedfc3ff1d32cfd66a867f8e9b1", size = 277813, upload-time = "2026-11-06T15:03:25.476Z" }, + { url = "https://files.pythonhosted.org/packages/b3/5e/1ba251fae0c9d689cc40b4dbedc9a6674db0d5ef5dae2af0a7a4ccaa8886/jiter-0.19.0-graalpy312-graalpy250_312_native-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:dd34bb5493184ca9816fc4ffb19ea7377940d5171512cfc107356a3a145a4ba2", size = 300193, upload-time = "2026-11-06T15:03:26.882Z" }, + { url = "https://files.pythonhosted.org/packages/7b/00/03f9750ce7fc6882c00e030f5843afaec7ab06813ebe2f0d363acaadb973/jiter-0.19.0-graalpy312-graalpy250_312_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:885673d25907536b3bce8d61accd67a534eb3ad5fa2dc7ebfa67c4842b3b0060", size = 301132, upload-time = "2026-11-06T15:03:28.217Z" }, + { url = "https://files.pythonhosted.org/packages/c1/43/f7adc61beb4d2f9990ad802856324cfa5968f6b54c9dff91e16acc866b0b/jiter-0.19.0-graalpy313-graalpy253_313_native-macosx_11_0_arm64.whl", hash = "sha256:50f9e5bde6bef0eef6a12315088e635b19d50cbceec745615eb8614f6bf4b52c", size = 277105, upload-time = "2026-11-06T15:03:29.514Z" }, + { url = "https://files.pythonhosted.org/packages/5d/56/9d34c6a580f010259c136a1354d0e51cbe1293aef4def5f6c42347c73727/jiter-0.19.0-graalpy313-graalpy253_313_native-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:42efe1a711c0745b6098b8bff931b0a2e7fff36098cbc2dc16b76497f1cbe834", size = 300134, upload-time = "2026-11-06T15:03:30.774Z" }, + { url = "https://files.pythonhosted.org/packages/e7/b7/dd4360ad780ea1455ff2607b43cd9fcd0fd785ae366c8a632785010e92ff/jiter-0.19.0-graalpy313-graalpy253_313_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2c82005ee84b348cee72a8df6672b5d6c9fe9db4b81c98b84a28155d447d2348", size = 300943, upload-time = "2026-11-06T15:03:32.042Z" }, ] [[package]] @@ -1847,30 +2026,30 @@ wheels = [ [[package]] name = "langchain" -version = "1.4.7" +version = "1.4.9" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "langchain-core" }, { name = "langgraph" }, { name = "pydantic" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d1/6b/7147b4cfa86091e05e3c0189952d976e13ef27249c8cd9e46d8c742a5b5c/langchain-1.4.7.tar.gz", hash = "sha256:818275348cd707f7fbbe92ece0a725c25823140a054cf29865f420e0200fa2af", size = 762840, upload-time = "2026-10-21T21:39:01.141Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/f4/97e0425ce79e67aeaa090be3ac1b5f51244837f48d99ea01e84820775607/langchain-1.4.9.tar.gz", hash = "sha256:449905dd841442562f897267ceaa05f80f42daa2cf019549b2650a9b02e85d8b", size = 771011, upload-time = "2026-11-04T17:07:22.158Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/93/2e/86a102e61fc88ede073aebdb795fef0eb058a887bed4aa862e8ca2697565/langchain-1.4.7-py3-none-any.whl", hash = "sha256:bc40d4a9a46f0c3d75e316c0e576931fe19bceef83912a71dc1e0df781eb8f82", size = 170549, upload-time = "2026-10-21T21:38:59.466Z" }, + { url = "https://files.pythonhosted.org/packages/39/35/d7af5ed4e82f8bb43b36460e72b6d43f4ac16626d79e31d25c49e6bee697/langchain-1.4.9-py3-none-any.whl", hash = "sha256:87cf3c15dfddaebd0e421d253e3b4abf70b70d6e18e56c45b9eb1873cc46f154", size = 171661, upload-time = "2026-11-04T17:07:20.201Z" }, ] [[package]] name = "langchain-anthropic" -version = "1.7.6" +version = "1.7.10" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anthropic" }, { name = "langchain-core" }, { name = "pydantic" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3c/45/b369666909be4a6f58877b18e692655ee792e06047c6c572d1218e09a31c/langchain_anthropic-1.7.6.tar.gz", hash = "sha256:e5b41959a39810e69bc608fd6622b7d5d017bde93f858b09332fbb6ac764c393", size = 765188, upload-time = "2026-10-12T14:39:58.537Z" } +sdist = { url = "https://files.pythonhosted.org/packages/cc/10/4fe4b78ec3f539447fa4774c5e8ef4ffa27c3394c1d93df646418cc97a5a/langchain_anthropic-1.7.10.tar.gz", hash = "sha256:72869686960b3d6665f99e7c91c9f6dd4a1d9ccf73d23edd8702eb603cc2e498", size = 768017, upload-time = "2026-11-04T16:50:53.531Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/97/d6/da1ba42b7c26cd511c9be5473dbb178c51b07a337e94f09188d45f0306a2/langchain_anthropic-1.7.6-py3-none-any.whl", hash = "sha256:06bee97006d99e9a04abc4bd56599fc356c0c7f7f2a97629645cb603d9785c73", size = 65535, upload-time = "2026-10-12T14:39:57.386Z" }, + { url = "https://files.pythonhosted.org/packages/c4/5f/145e047dffdb6778dd633c484f7c176dad6a8a99e11b156321ac2b3b147f/langchain_anthropic-1.7.10-py3-none-any.whl", hash = "sha256:9ba64332784bddedabbeb24f5f5759f2d0dfe58244e0ef07e313e039b21ecb1f", size = 65780, upload-time = "2026-11-04T16:50:52.027Z" }, ] [[package]] @@ -1917,9 +2096,10 @@ wheels = [ [[package]] name = "langchain-core" -version = "1.6.13" +version = "1.7.6" source = { registry = "https://pypi.org/simple" } dependencies = [ + { name = "certifi" }, { name = "httpx" }, { name = "jsonpatch" }, { name = "langchain-protocol" }, @@ -1931,14 +2111,14 @@ dependencies = [ { name = "typing-extensions" }, { name = "uuid-utils" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/40/76/0b8e5383a9c6a05bde284790d661487bb586cf101f43e8d4dac1fb3da1ee/langchain_core-1.6.13.tar.gz", hash = "sha256:756d8fd971cd7e3a5a19cf5453a81159351bd40cbfe62cbfe7e2ee3941008772", size = 1018477, upload-time = "2026-10-21T20:43:32.248Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1e/13/eef86ab444e9e797bb0e41f583904510fb36416571f6fbb93b9255e1e125/langchain_core-1.7.6.tar.gz", hash = "sha256:0833781e3a8e6fe83073c8412c21180a0545d5ccdf3437889951caf9589ece6c", size = 1037637, upload-time = "2026-11-05T00:21:56.343Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/2f/c15b026e7b4aa093bc237c909bf909e8a59143b1315efee43c296fad58ce/langchain_core-1.6.13-py3-none-any.whl", hash = "sha256:8605de6f84a49902ef6be03d6fe2a126e7dfc35184315989689f341181f0a8fb", size = 574683, upload-time = "2026-10-21T20:43:30.951Z" }, + { url = "https://files.pythonhosted.org/packages/9d/a2/34c24dfc27ebd5002580deffe82975c507bb96af2540849aaa02c66027af/langchain_core-1.7.6-py3-none-any.whl", hash = "sha256:f61908be526fbeb5da8cc1ffd9d24bce3b50cf45b3a2f1737c1a7a2958046ce6", size = 580547, upload-time = "2026-11-05T00:21:54.883Z" }, ] [[package]] name = "langchain-openai" -version = "1.7.2" +version = "1.7.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi" }, @@ -1946,21 +2126,21 @@ dependencies = [ { name = "openai" }, { name = "tiktoken" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/da/ca/b64799a9f2ee688aa6c238f5230b20d150b19cc5892bdcb6faf2b59866f1/langchain_openai-1.7.2.tar.gz", hash = "sha256:e1fcbc7a96f7c8c94679d61639a979bba88f27889c0a68dfa225b8057345328d", size = 3405949, upload-time = "2026-10-14T13:50:59.956Z" } +sdist = { url = "https://files.pythonhosted.org/packages/71/3c/10adfa3dcf1e7b93230b406a4c1db51cea59122a3eb70fed8109487beace/langchain_openai-1.7.4.tar.gz", hash = "sha256:8fd90e41588526d990f32262447adf8e130d7ce28ed66cefa315e64cc9dd12ce", size = 3410755, upload-time = "2026-11-04T16:55:37.274Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/39/5d/8c4888a21087e4cd1c32965613a1a17cfc8e90e41ba5205c3dad302f3410/langchain_openai-1.7.2-py3-none-any.whl", hash = "sha256:9be7980edf355ca2dd595b795a5125836ccf04515ef9377228913246156e59f5", size = 146367, upload-time = "2026-10-14T13:50:58.697Z" }, + { url = "https://files.pythonhosted.org/packages/46/c1/09d01a810d5f65f2f5f21231b6699e6efc241797790e18aba56c14aa754b/langchain_openai-1.7.4-py3-none-any.whl", hash = "sha256:aaee93369765bac7ebf640aab62f8ae16df403ed982737ae51f88f6a24a151ab", size = 146880, upload-time = "2026-11-04T16:55:35.897Z" }, ] [[package]] name = "langchain-protocol" -version = "0.0.20" +version = "0.0.21" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/cb/8b/d908d082c3cf5368ddd1816ed114de79c873f979ba7f98b95fab0e841643/langchain_protocol-0.0.20.tar.gz", hash = "sha256:0f5bd002474265648e91161771a9e0438fe9480bd55a416e51af0f60070637ec", size = 6280, upload-time = "2026-10-20T11:13:50.84Z" } +sdist = { url = "https://files.pythonhosted.org/packages/be/db/7f9195371c824e706231365b4c6c85573b12c4375286e7471d6a488e8091/langchain_protocol-0.0.21.tar.gz", hash = "sha256:04b3e80852233a8db39b39d3ad2438d892531dc0ecd41459e857a139ee0e601c", size = 6344, upload-time = "2026-11-05T16:16:47.078Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/02/4b/f1c99a0b27c5ff8b4b131c0d6e62012c17cc424089efe213767db927afd2/langchain_protocol-0.0.20-py3-none-any.whl", hash = "sha256:3c935e5e46b0f6f9cb52f45ba7cfa53d1b9fa80c82c4a277d47f03e07f7385b1", size = 7347, upload-time = "2026-10-20T11:13:49.566Z" }, + { url = "https://files.pythonhosted.org/packages/3f/f6/25232abfce5cc696c21f7947e6ae11cc6b124e5099783408ff8552c545a3/langchain_protocol-0.0.21-py3-none-any.whl", hash = "sha256:7f42f9eae7c08bb9d74850057da50b5483970a3df91b7a8a5aadec6a3dfa4d12", size = 7418, upload-time = "2026-11-05T16:16:45.444Z" }, ] [[package]] @@ -1977,7 +2157,7 @@ wheels = [ [[package]] name = "langgraph" -version = "1.2.16" +version = "1.2.20" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "langchain-core" }, @@ -1987,9 +2167,9 @@ dependencies = [ { name = "pydantic" }, { name = "xxhash" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/db/65/69de99a24546c1e3b75a67905dbcc17ed6cd0ed81694d4cc021ed688a60d/langgraph-1.2.16.tar.gz", hash = "sha256:e4dd63480bfd3ee14a6ab80ecf1311698780519693d8e3b67a28f3486e69e1f7", size = 772613, upload-time = "2026-10-16T22:11:14.147Z" } +sdist = { url = "https://files.pythonhosted.org/packages/41/77/892e53207bfadd4b114d274737735444d06216ec9a88dfc4def9bd888254/langgraph-1.2.20.tar.gz", hash = "sha256:79f86df92f2dd17d5ec464cab68dbb685439ab102ca39f0b1b7b198025a2414c", size = 786292, upload-time = "2026-11-05T02:20:41.279Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ad/eb/ceb9bed99f6549e9ec51c497b749062d19e0a1c68fea0ad801d55c4a9691/langgraph-1.2.16-py3-none-any.whl", hash = "sha256:aeceb1bc49488409f12b02f1e51881099391d9e85bcfd78e1dbead71831c41b5", size = 260357, upload-time = "2026-10-16T22:11:12.638Z" }, + { url = "https://files.pythonhosted.org/packages/6c/13/df761ed2ac03dfc3e639f10b1af13573fea27f0885b69081d79c513de04d/langgraph-1.2.20-py3-none-any.whl", hash = "sha256:2b9fd01c3d5e0652e6c9b436dc0341413788010eb279ac8c46a733cf485d848b", size = 263611, upload-time = "2026-11-05T02:20:37.999Z" }, ] [[package]] @@ -2674,39 +2854,43 @@ wheels = [ [[package]] name = "openai" -version = "2.54.0" +version = "3.46.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, - { name = "distro" }, - { name = "httpx" }, - { name = "jiter" }, + { name = "httpx2" }, + { name = "jiter", version = "0.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jiter", version = "0.19.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "pydantic" }, { name = "sniffio" }, - { name = "tqdm" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/50/9a/8c75e8c8a5b407a0586faeb2afac91674ff955c191ecc1d6d3b6669f6788/openai-2.54.0.tar.gz", hash = "sha256:e3e6f8bc1ba30ddf381ace1a14340eed381cb984a1a59bd0f34b5be3b5d49cfa", size = 1100285, upload-time = "2026-08-11T18:46:59.035Z" } +sdist = { url = "https://files.pythonhosted.org/packages/34/b6/23cddcb571d6eafe7b4bb58c7e0a068076121b7b001b776179994cca6a03/openai-3.46.0.tar.gz", hash = "sha256:fb34cd8cab6809ad0aa8dc42493fa622aaa87c814fd8e67a6fb3fa1f1e5d952d", size = 2408622, upload-time = "2026-11-05T00:55:55.463Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/64/a8/bb76c7356de8ad57f59d5ff993d434df0607f07f08bcc9c9a5c275e399c0/openai-2.54.0-py3-none-any.whl", hash = "sha256:89089789197ccdb87f173a03145ed1598d00795220c93e96cf712b1cbf5e5f2b", size = 1660351, upload-time = "2026-08-11T18:46:56.684Z" }, + { url = "https://files.pythonhosted.org/packages/f4/63/454e6faad68ac903e7669932db8d0a91c95dfca829ec9476e52045b17684/openai-3.46.0-py3-none-any.whl", hash = "sha256:7b650117e9bf539029bf880c2eff94a26f281394f6572284efa5d068d4b1c98e", size = 2438918, upload-time = "2026-11-05T00:55:53.301Z" }, ] [[package]] name = "openai-agents" -version = "0.18.3" +version = "0.24.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "griffelib" }, + { name = "httpx2" }, { name = "mcp" }, { name = "openai" }, { name = "pydantic" }, + { name = "pyjwt" }, + { name = "python-multipart" }, { name = "requests" }, + { name = "starlette" }, { name = "typing-extensions" }, + { name = "urllib3" }, { name = "websockets" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/80/3f/b1162cad8720fafc9cf658d6896027385967f5006adfb92ae0dab2b54a70/openai_agents-0.18.3.tar.gz", hash = "sha256:e637f5f5a50692ccbedb0e4f7f2e4f8e2facfcddd41142f35faf90c89b700fc3", size = 5577652, upload-time = "2026-07-17T03:40:25.208Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a5/36/537006bc2a22f3aa232ce0907f52a333f831a6a2f525894ff43747a7abee/openai_agents-0.24.0.tar.gz", hash = "sha256:4b4b285f4fed81fdf1b4ac426a9101658d9cd29b4fb1aaeee18f639b77e704e3", size = 7026950, upload-time = "2026-10-15T02:38:21.466Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e0/7c/08b9929a15131081898e38c5612d44ee293851d5c80f31ca1153efe82143/openai_agents-0.18.3-py3-none-any.whl", hash = "sha256:c6ed971fdeb34d39a9931787bd3960c1e84dc5d7345705794cc5cab8a1158d07", size = 880799, upload-time = "2026-07-17T03:40:23.163Z" }, + { url = "https://files.pythonhosted.org/packages/05/93/01efc034d7011b89381f96a9fb8957c09a16e3c190f3a5de128e1d0a42e9/openai_agents-0.24.0-py3-none-any.whl", hash = "sha256:18d4ac34e84ed937333ec8ce46395ed3521ffcbb0a521780a4c2eaa451467f49", size = 1242571, upload-time = "2026-10-15T02:38:18.835Z" }, ] [[package]] @@ -4595,18 +4779,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c7/18/c86eb8e0202e32dd3df50d43d7ff9854f8e0603945ff398974c1d91ac1ef/tomli_w-1.2.0-py3-none-any.whl", hash = "sha256:188306098d013b691fcadc011abd66727d3c414c571bb01b1a174ba8c983cf90", size = 6675, upload-time = "2025-01-15T12:07:22.074Z" }, ] -[[package]] -name = "tqdm" -version = "4.67.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a8/4b/29b4ef32e036bb34e4ab51796dd745cdba7ed47ad142a9f4a1eb8e0c744d/tqdm-4.67.1.tar.gz", hash = "sha256:f8aef9c52c08c13a65f30ea34f4e5aac3fd1a34959879d7e59e63027286627f2", size = 169737, upload-time = "2024-11-24T20:12:22.481Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d0/30/dc54f88dd4a2b5dc8a0279bdd7270e735851848b762aeb1c1184ed1f6b14/tqdm-4.67.1-py3-none-any.whl", hash = "sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2", size = 78540, upload-time = "2024-11-24T20:12:19.698Z" }, -] - [[package]] name = "truststore" version = "0.10.4" From f22511891225fb15a4e6a0f889e723e9b5d0ebe4 Mon Sep 17 00:00:00 2001 From: Asmi Date: Mon, 16 Nov 2026 23:40:46 +0530 Subject: [PATCH 32/33] docs: add docstrings to ExceptionCapture public methods (#1257) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs: add docstrings to ExceptionCapture public methods Add class-level docstring and per-method docstrings to ExceptionCapture, covering __init__, close, exception_handler, thread_exception_handler, exception_receiver, and capture_exception. No behaviour changes — documentation only. Signed-off-by: mi-vault * docs: clarify bucket_size capacity and exception_receiver caller scope Signed-off-by: mi-vault --------- Signed-off-by: mi-vault --- posthog/exception_capture.py | 79 ++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/posthog/exception_capture.py b/posthog/exception_capture.py index 6dac4057f..db43b65c2 100644 --- a/posthog/exception_capture.py +++ b/posthog/exception_capture.py @@ -20,6 +20,16 @@ class ExceptionCapture: + """Installs process-wide exception hooks that forward uncaught exceptions to PostHog. + + Hooks are installed on :attr:`sys.excepthook` (main-thread unhandled exceptions) and + :attr:`threading.excepthook` (exceptions that escape worker threads). The original + hooks are restored when :meth:`close` is called. + + Optionally enforces client-side rate limiting per exception type so that a sudden + burst of identical errors does not flood the PostHog ingestion pipeline. + """ + log = logging.getLogger("posthog") # more generous defaults than the browser SDK (10, 1, 10) because one @@ -36,6 +46,22 @@ def __init__( refill_rate=DEFAULT_REFILL_RATE, refill_interval_seconds=DEFAULT_REFILL_INTERVAL_SECONDS, ): + """Install exception hooks and configure optional rate limiting. + + Args: + client: The PostHog :class:`~posthog.client.Client` used to send captured exceptions. + rate_limiting_enabled: When ``True``, a :class:`~posthog.bucketed_rate_limiter.BucketedRateLimiter` + is created with the given bucket parameters to suppress excess captures of the same + exception type. + bucket_size: Token capacity of the rate-limiting bucket per exception type. + Because the call that empties the bucket is itself treated as rate-limited, + a fresh bucket permits ``bucket_size - 1`` captures before limiting takes + effect. Clamped to ``[0, 100]``. Default is :attr:`DEFAULT_BUCKET_SIZE` (``50``). + refill_rate: Tokens restored per completed ``refill_interval_seconds`` interval. + Clamped to ``[0, bucket_size]``. Default is :attr:`DEFAULT_REFILL_RATE` (``10``). + refill_interval_seconds: Duration of each refill interval in seconds. + Clamped to ``[0, 86400]``. Default is :attr:`DEFAULT_REFILL_INTERVAL_SECONDS` (``10``). + """ self.client = client self._closed = False self.original_excepthook = sys.excepthook @@ -55,6 +81,15 @@ def __init__( ) def close(self): + """Uninstall exception hooks and restore the hooks that were in place at construction time. + + Idempotent: calling :meth:`close` a second time has no effect. After closing, + the rate limiter (if any) is also stopped and its per-key buckets are cleared. + + This method is intentionally not thread-safe with respect to concurrent :meth:`close` + calls; callers that share an :class:`ExceptionCapture` across threads should arrange + external synchronisation if they need to close it concurrently. + """ if self._closed: return @@ -83,6 +118,17 @@ def close(self): self._rate_limiter.stop() def exception_handler(self, exc_type, exc_value, exc_traceback): + """Handle an unhandled exception from :attr:`sys.excepthook`. + + Forwards the exception to PostHog with ``level="fatal"`` and + ``mechanism.type="onuncaughtexception"``, then delegates to the previous + ``sys.excepthook`` so that normal Python crash output is preserved. + + Args: + exc_type: The exception class. + exc_value: The exception instance. + exc_traceback: The traceback object. + """ if not self._closed: capture_metadata: _ExceptionCaptureMetadata = { "level": "fatal", @@ -104,6 +150,16 @@ def exception_handler(self, exc_type, exc_value, exc_traceback): previous_hook(exc_type, exc_value, exc_traceback) def thread_exception_handler(self, args): + """Handle an unhandled exception from :attr:`threading.excepthook`. + + Forwards the exception to PostHog with ``level="error"`` and + ``mechanism.type="onuncaughtexception"``, then delegates to the previous + ``threading.excepthook``. + + Args: + args: The :class:`threading.ExceptHookArgs` object supplied by the threading machinery, + containing ``exc_type``, ``exc_value``, ``exc_traceback``, and ``thread``. + """ if not self._closed: capture_metadata: _ExceptionCaptureMetadata = { "level": "error", @@ -136,6 +192,17 @@ def _resolve_hook(hook, handler_name, previous_hook_name): hook = getattr(owner, previous_hook_name) def exception_receiver(self, exc_info, extra_properties): + """Receive an exception from an external caller and forward it to PostHog. + + Provides an entry point for external callers to pass an ``exc_info`` tuple + and extra properties (such as ``"distinct_id"``) into the exception capture + pipeline without going through :attr:`sys.excepthook`. + + Args: + exc_info: A three-tuple ``(exc_type, exc_value, exc_traceback)``. + extra_properties: A mapping of extra properties. If it contains a ``"distinct_id"`` + key, that value is used as the PostHog distinct ID for the captured event. + """ if "distinct_id" in extra_properties: metadata = {"distinct_id": extra_properties["distinct_id"]} else: @@ -143,6 +210,18 @@ def exception_receiver(self, exc_info, extra_properties): self.capture_exception((exc_info[0], exc_info[1], exc_info[2]), metadata) def capture_exception(self, exception, metadata=None): + """Capture a single exception and send it to PostHog. + + A convenience wrapper around the internal :meth:`_capture_exception` method intended + for direct call sites that already hold an exception object or ``(type, value, tb)`` + tuple outside of the ``sys.excepthook`` flow. + + Args: + exception: Either an :class:`Exception` instance or a three-tuple + ``(exc_type, exc_value, exc_traceback)`` as returned by :func:`sys.exc_info`. + metadata: Optional mapping with an optional ``"distinct_id"`` key to associate + the event with a specific PostHog person. + """ self._capture_exception(exception, metadata) def _capture_exception( From c8ab322d988b994bdff1392024106fc93751a456 Mon Sep 17 00:00:00 2001 From: Eli Reisman Date: Mon, 16 Nov 2026 10:14:32 -0800 Subject: [PATCH 33/33] docs: regenerate the 8.x reference with main's new API Co-Authored-By: Claude Opus 5.5 --- references/posthog-python-8.md | 90 ++++++++++++++++++++++------------ 1 file changed, 59 insertions(+), 31 deletions(-) diff --git a/references/posthog-python-8.md b/references/posthog-python-8.md index 7f7416cfa..a7d441aa7 100644 --- a/references/posthog-python-8.md +++ b/references/posthog-python-8.md @@ -662,7 +662,7 @@ Name | Type | Description | Default Type | Description ---- | ----------- -`Optional[FeatureFlagResult]` | Optional[FeatureFlagResult]: The feature flag result or None if disabled/not found. +`Optional[FeatureFlagResult]` | Optional[FeatureFlagResult]: The evaluated result, including a healthy disabled flag, or None when no result is available (for example, a missing flag or a server-marked failure without a successful fallback). ## Get feature flags @@ -1385,11 +1385,8 @@ Name | Type | Description `capture_exceptions` | `Optional[bool]` | `capture_tracing_headers` | | `client` | | -`extra_properties` | | `extra_tags` | | Compatibility alias for `extra_properties`. `get_response` | | -`properties_map` | | -`request_filter` | | `sync_capable` | | `tag_map` | | Compatibility alias for `properties_map`. `trust_tracing_headers` | `bool` | Deprecated alias for `capture_tracing_headers`. @@ -1460,12 +1457,6 @@ capture_tracing_headers = _resolve_capture_tracing_headers(capture_tracing_heade client = cast('Optional[Client]', settings.POSTHOG_MW_CLIENT) ``` -#### `posthog.integrations.django.PosthogContextMiddleware.extra_properties` - -```python -extra_properties = cast('Callable[[HttpRequest], Dict[str, Any]]', extra_properties) if callable(extra_properties) else None -``` - #### `posthog.integrations.django.PosthogContextMiddleware.extra_tags` ```python @@ -1521,18 +1512,6 @@ the middleware stack, so the context manager in __call__/__acall__ never sees th Note: Django's process_exception is always synchronous, even for async views. -#### `posthog.integrations.django.PosthogContextMiddleware.properties_map` - -```python -properties_map = cast('Callable[[Dict[str, Any]], Dict[str, Any]]', properties_map) if callable(properties_map) else None -``` - -#### `posthog.integrations.django.PosthogContextMiddleware.request_filter` - -```python -request_filter = cast('Optional[Callable[[HttpRequest], bool]]', settings.POSTHOG_MW_REQUEST_FILTER) -``` - #### `posthog.integrations.django.PosthogContextMiddleware.sync_capable` ```python @@ -3205,7 +3184,7 @@ Name | Description `get_flag` | Return the flag value. Fires `$feature_flag_called` on first access. `get_flag_payload` | Return the payload associated with a flag. `is_enabled` | Return whether the flag is enabled. Fires `$feature_flag_called` on the first access per (distinct_id, flag, value) tuple, deduped via the SDK's cache. -`only` | Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. +`only` | Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. Selected failures retain private diagnostics but remain absent from values, keys and enrichment; their existing missing-value warning is unchanged. `only_accessed` | Return a filtered copy containing only flags accessed via `is_enabled` or `get_flag` before this call. **Attributes:** @@ -3227,7 +3206,8 @@ Return the flag value. Fires `$feature_flag_called` on first access. Returns the variant string for multivariate flags, `True` for enabled flags without a variant, `False` for disabled flags, and `None` for flags that -were not returned by the evaluation. +were not returned or whose remote record was marked failed by the server. +An unreadable remote record retains its disabled (`False`) result. Pass `send_feature_flag_events=False` to skip the event for this read, as with `is_enabled`. @@ -3256,7 +3236,7 @@ first access per (distinct_id, flag, value) tuple, deduped via the SDK's cache. Name | Type | Description | Default ---- | ---- | ----------- | ------- `key` | `str` | The feature flag key. | *required* -`default_value` | `bool` | Returned when the flag has no value in this evaluation — the key was not part of the evaluated set, or the evaluation itself came back empty (failed `/flags` request, quota limit, or no resolvable `distinct_id`). Defaults to `False`. | `False` +`default_value` | `bool` | Returned when the flag has no value in this evaluation — the key was not part of the evaluated set, the server marked its record failed, or the evaluation itself came back empty (failed `/flags` request, quota limit, or no resolvable `distinct_id`). Defaults to `False`. | `False` `send_feature_flag_events` | `bool` | Whether this read sends `$feature_flag_called`. When `False`, no event is sent and the dedupe cache is left alone, but the key still counts as accessed for `only_accessed`. | `True` A flag that has a value always wins over `default_value`, including a @@ -3278,6 +3258,8 @@ only(keys: List[str]) -> FeatureFlagEvaluations Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning. +Selected failures retain private diagnostics but remain absent from values, +keys and enrichment; their existing missing-value warning is unchanged. #### `posthog.feature_flag_evaluations.FeatureFlagEvaluations.only_accessed` @@ -3290,6 +3272,7 @@ or `get_flag` before this call. Order-dependent: if nothing has been accessed yet, the returned snapshot is empty. The method honors its name — pre-access if you want a populated result. +Accessed failures retain private diagnostics, not values or enrichment. #### `posthog.feature_flag_evaluations.FeatureFlagEvaluations.unresolved_flags` @@ -3303,8 +3286,9 @@ left it without a value. A flag is listed when it has a loaded local definition, was in the requested scope, was inconclusive locally, and no remote value filled the gap. Listed flags are not part of `keys`, and reading one reports the -`local_evaluation_inconclusive` error instead of `flag_missing`. Reading -this mapping does not count as an access and does not fire any event. +`local_evaluation_inconclusive` error instead of `flag_missing`. +A server-marked failed fallback additionally reports `evaluation_failed`. +Reading this mapping does not count as an access and does not fire any event. Snapshots returned by `only` and `only_accessed`, and by `AsyncClient.evaluate_flags()`, which evaluates only remotely, carry no entries. @@ -3354,13 +3338,13 @@ Create a FeatureFlagResult from a FeatureFlag object. Name | Type | Description | Default ---- | ---- | ----------- | ------- `details` | `Union[FeatureFlag, None]` | The FeatureFlag object to convert. | *required* -`override_match_value` | `Optional[FlagValue]` | If provided, this value will be used to populate the enabled and variant fields instead of the values from the FeatureFlag. | `None` +`override_match_value` | `Optional[FlagValue]` | If provided, this value will be used to populate the enabled and variant fields instead of the values from the FeatureFlag. A server-marked failure returns None even when this override is provided. | `None` **Returns:** Type | Description ---- | ----------- -`FeatureFlagResult \| None` | FeatureFlagResult | None: A new FeatureFlagResult instance, or None if details is None. +`FeatureFlagResult \| None` | FeatureFlagResult | None: A new result, or None when details is absent or the server marked the record failed. Unreadable records are not treated as server-marked failures. #### `posthog.types.FeatureFlagResult.from_value_and_payload` @@ -4086,7 +4070,7 @@ Type | Description Type | Description ---- | ----------- -`EmailError` | PostHog did not queue the email, or the client could not tell whether it did. +`EmailError` | PostHog did not queue the email, or the client could not tell whether it did. With attachments, `code` is `too_many_attachments`, `message_too_large` or `invalid_attachment` before any request, `attachment_upload_failed` when the storage refused an upload, and `network_error` with `field` naming the attachment when the storage didn't answer. `(TypeError, ValueError)` | An argument has the wrong type or format. **Examples:** @@ -4305,6 +4289,10 @@ your app first. An optional field passed as `None` counts as left out. +A PostHog version that doesn't take a field yet, such as `cc`, refuses +the send with an error that names the field in `EmailError.field`. It +never drops the field and sends the rest. + **Parameters:** Name | Type | Description | Default @@ -4316,7 +4304,12 @@ Name | Type | Description | Default `text` | | The plain-text body. Without it, PostHog derives it from `html`. HTML with no text in it, such as a single image, goes out without a plain-text part. | `from_` | | A verified sender, such as `"Acme "`. | `reply_to` | | One address or a list of addresses. An empty list sends no reply-to. | -`capture_engagement` | | Capture the email's opens and clicks as events of the recipient. Defaults to `True`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. | +`cc` | | One address or a list of addresses that get a visible copy, at most 10. | +`bcc` | | One address or a list of addresses that get a hidden copy, at most 10. | +`attachments` | | Files sent with the email: at most 10 files and 40 MB per message after Base64 encoding, about 29 MB of files. The client checks both before any request. It uploads each file that PostHog doesn't hold yet, then sends the email. A file the client can't send raises `EmailError` with `code` `invalid_attachment`. | +`capture_engagement` | | Deprecated, use `tracking={"engagement": False}`. It keeps working, but PostHog refuses a send that sets both `capture_engagement` and `tracking`. Captures the email's engagement events as events of the recipient. Defaults to `True`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting, so the template form doesn't take it. | +`sensitive` | | Marks the email as sensitive, such as one that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `template_key` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. The template form doesn't take it. | +`tracking` | | What PostHog tracks for this email. Without it, PostHog counts opens with its open pixel, captures engagement events, and counts clicks only when the email isn't sensitive. `True` turns on opens, clicks and engagement events. `False` turns off all tracking, including kinds PostHog adds later: PostHog can't count the email's opens or clicks, and captures no engagement events. An `EmailTracking` dict turns each kind on or off, and a key you leave out keeps its default. Turn clicks on for a sensitive email only when its links are safe to send through PostHog's click tracking. The template form doesn't take it. | `distinct_id` | | The recipient's distinct ID in your product. | `idempotency_key` | | 1 to 255 visible ASCII characters. Template sends and code sends share one set of keys: a key already used for another email, or for a `template_id` send, raises `idempotency_key_reused`. A retry with the same key returns the first send's result, also when its workflow was paused since. | `max_retries` | | Overrides the client's maximum number of retries for this send. `0` turns retries off. | @@ -4325,17 +4318,34 @@ Name | Type | Description | Default Name | Type | Description ---- | ---- | ----------- +`attachments` | `NotRequired[Optional[Sequence[EmailAttachment]]]` | +`bcc` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | `capture_engagement` | `NotRequired[Optional[bool]]` | +`cc` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | `distinct_id` | `NotRequired[Optional[str]]` | `from_` | `NotRequired[Optional[str]]` | `html` | `NotRequired[Optional[str]]` | `idempotency_key` | `NotRequired[Optional[str]]` | `max_retries` | `NotRequired[Optional[int]]` | `reply_to` | `NotRequired[Optional[Union[str, Sequence[str]]]]` | +`sensitive` | `NotRequired[Optional[bool]]` | `subject` | `str` | `template_key` | `str` | `text` | `NotRequired[Optional[str]]` | `to` | `str` | +`tracking` | `NotRequired[Optional[Union[bool, EmailTracking]]]` | + +#### `posthog.emails.CodeEmailArgs.attachments` + +```python +attachments: NotRequired[Optional[Sequence[EmailAttachment]]] +``` + +#### `posthog.emails.CodeEmailArgs.bcc` + +```python +bcc: NotRequired[Optional[Union[str, Sequence[str]]]] +``` #### `posthog.emails.CodeEmailArgs.capture_engagement` @@ -4343,6 +4353,12 @@ Name | Type | Description capture_engagement: NotRequired[Optional[bool]] ``` +#### `posthog.emails.CodeEmailArgs.cc` + +```python +cc: NotRequired[Optional[Union[str, Sequence[str]]]] +``` + #### `posthog.emails.CodeEmailArgs.distinct_id` ```python @@ -4379,6 +4395,12 @@ max_retries: NotRequired[Optional[int]] reply_to: NotRequired[Optional[Union[str, Sequence[str]]]] ``` +#### `posthog.emails.CodeEmailArgs.sensitive` + +```python +sensitive: NotRequired[Optional[bool]] +``` + #### `posthog.emails.CodeEmailArgs.subject` ```python @@ -4402,3 +4424,9 @@ text: NotRequired[Optional[str]] ```python to: str ``` + +#### `posthog.emails.CodeEmailArgs.tracking` + +```python +tracking: NotRequired[Optional[Union[bool, EmailTracking]]] +```