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/check_strict_types.sh b/.github/scripts/check_strict_types.sh index 4e41c9e8f..d1647516b 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") @@ -44,7 +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) -_ = (template_send, rendered_send) +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, invite_send, tracked_send, untracked_send, not_sensitive_send) async def async_email_types() -> None: @@ -73,6 +79,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' @@ -89,8 +110,13 @@ 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 +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/.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 ef0ff8a61..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: @@ -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: | @@ -205,8 +209,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 +218,7 @@ jobs: with: fetch-depth: 0 - - name: Check targeted mutation inputs changed + - name: Check utils quality inputs changed id: changes shell: bash run: | @@ -231,15 +235,20 @@ 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" - 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 @@ -260,36 +269,10 @@ 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 - - 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/.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: 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/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-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-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-crewai/uv.lock b/examples/example-ai-crewai/uv.lock index 514b96dff..0a0950f30 100644 --- a/examples/example-ai-crewai/uv.lock +++ b/examples/example-ai-crewai/uv.lock @@ -2363,14 +2363,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]] @@ -2467,29 +2467,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-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/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..8f3ba55e1 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]] @@ -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.86.6" +version = "7.91.1" 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" }, 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-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-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" }] 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" }] 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/openfeature-provider/CHANGELOG.md b/openfeature-provider/CHANGELOG.md index 9bb007b32..dd1423d8f 100644 --- a/openfeature-provider/CHANGELOG.md +++ b/openfeature-provider/CHANGELOG.md @@ -4,6 +4,49 @@ 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 + +- [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 + +- Updated dependencies: posthog@7.91.0 + +## 0.1.162 — 2026-11-13 + +### Patch changes + +- Updated dependencies: posthog@7.90.0 + +## 0.1.161 — 2026-11-12 + +### Patch changes + +- Updated dependencies: posthog@7.89.0 + +## 0.1.160 — 2026-11-12 + +### Patch changes + +- Updated dependencies: posthog@7.88.0 + +## 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 6ca561bfa..fed64fa5d 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.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 c554996eb..9d9cd52c4 100644 --- a/posthog/CHANGELOG.md +++ b/posthog/CHANGELOG.md @@ -1,5 +1,73 @@ # 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 + +- [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 + +- [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 + +- [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 + +- [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 + +- [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 + +- [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/__init__.py b/posthog/__init__.py index 9c821c9c4..cf5a54e94 100644 --- a/posthog/__init__.py +++ b/posthog/__init__.py @@ -1556,11 +1556,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. @@ -1576,6 +1572,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_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.py b/posthog/ai/anthropic/anthropic.py index 27399d516..f448be786 100644 --- a/posthog/ai/anthropic/anthropic.py +++ b/posthog/ai/anthropic/anthropic.py @@ -152,7 +152,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 473a39acc..50d113267 100644 --- a/posthog/ai/anthropic/anthropic_async.py +++ b/posthog/ai/anthropic/anthropic_async.py @@ -152,7 +152,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/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 79b51df3b..f8fb124e6 100644 --- a/posthog/ai/claude_agent_sdk/client.py +++ b/posthog/ai/claude_agent_sdk/client.py @@ -23,13 +23,18 @@ "Please install the Claude Agent SDK to use this feature: 'pip install claude-agent-sdk'" ) -from posthog.ai.claude_agent_sdk.formatting import ( - format_assistant_blocks, - format_tool_result_content, +from .formatting import ( + _append_assistant_output, + _format_user_input, + 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 @@ -135,101 +140,97 @@ 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): """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): + 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(): + 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 = None + self._pending_output = [] + + elif isinstance(message, AssistantMessage): + self._process_assistant_message(message) + + 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 + ) + + 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, + ) + if not _from_subagent(message): + self._pending_output = _append_assistant_output( + self._pending_output, message.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..bf8cbcbc6 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,60 @@ def format_assistant_blocks(blocks: Any) -> List[Dict[str, Any]]: else: out.append(to_plain(block)) 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 _append_user_input(previous, 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 _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 04bf4da16..ec9b46c3d 100644 --- a/posthog/ai/claude_agent_sdk/processor.py +++ b/posthog/ai/claude_agent_sdk/processor.py @@ -25,8 +25,10 @@ ) from posthog.ai.claude_agent_sdk.formatting import ( - format_assistant_blocks, - format_tool_result_content, + _append_assistant_output, + _format_user_input, + 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 from posthog.ai.utils import ( @@ -299,12 +301,14 @@ async def 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. current_input: Optional[List[Dict[str, Any]]] = initial_input or None next_input: Optional[List[Dict[str, Any]]] = None @@ -318,6 +322,14 @@ async def 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 @@ -337,9 +349,7 @@ async def query( groups, extra_options=extra_options, ) - # 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,35 +371,22 @@ async def query( groups, extra_options=extra_options, ) - output_content = format_assistant_blocks(message.content) - if output_content: - pending_output = [ - {"role": "assistant", "content": output_content} - ] - - 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}] + if not _from_subagent(message): + # A subagent's own API calls are not this query's generations. + pending_output = _append_assistant_output( + pending_output, message.content + ) + + 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 + ) elif isinstance(message, ResultMessage): # Fallback: if no StreamEvents were received, emit a single @@ -677,3 +674,24 @@ def _resolve_distinct_id( return str(override) # Fall back to instance default 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 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/_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 db0a5d695..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,9 +99,7 @@ def _upload_body(items: list[bytes], results: list[bytes]) -> 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. +def _result_declarations(results: tuple[EvaluationResult, ...]) -> dict[str, bytes]: identities: set[tuple[str, str]] = set() declarations: dict[str, bytes] = {} for result in results: @@ -114,44 +116,108 @@ def _chunks(results: tuple[EvaluationResult, ...]) -> list[_Chunk]: 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 + # 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 _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. + declarations = _result_declarations(results) chunks: list[_Chunk] = [] item_ids: set[str] = set() items: list[bytes] = [] 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, 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 = _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( + "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 +311,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/_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/_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/_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 595f06920..dab1d367f 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 @@ -191,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. @@ -199,10 +265,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 +280,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,27 +293,27 @@ def __init__( ) -> None: item_id = item.id if isinstance(item, EvaluationItem) else _uuid(item) version_id = _uuid(scorer_version_id) - 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, - "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) - 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, { @@ -253,13 +324,13 @@ 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 ) object.__setattr__(self, "scorer_version_id", version_id) + object.__setattr__(self, "calculate", calculate) object.__setattr__(self, "_json", _encode(data)) @property @@ -310,10 +381,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 +478,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,28 +516,47 @@ 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"]), + outcomes = tuple(_result_receipt(_object(row)) for row in data["results"]) + _validate_upload_identities(items, outcomes, results) + 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." ) - 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.") return UploadReceipt(items=items, results=outcomes) except (KeyError, TypeError, ValueError): 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/_shared.py b/posthog/ai/gemini/_shared.py index 92fc38c6d..4c30a6320 100644 --- a/posthog/ai/gemini/_shared.py +++ b/posthog/ai/gemini/_shared.py @@ -63,10 +63,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 9e17c017a..b06330aba 100644 --- a/posthog/ai/gemini/gemini.py +++ b/posthog/ai/gemini/gemini.py @@ -82,7 +82,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 @@ -166,7 +166,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 cd143ec3e..7e10a16ff 100644 --- a/posthog/ai/gemini/gemini_async.py +++ b/posthog/ai/gemini/gemini_async.py @@ -77,7 +77,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 @@ -149,7 +149,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_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 62ce088fe..0972cf43a 100644 --- a/posthog/ai/langchain/callbacks.py +++ b/posthog/ai/langchain/callbacks.py @@ -54,6 +54,7 @@ _privacy_mode_enabled, _redact_mcp_tool_credentials, _responses_stop_reason, + _stream_error_event_status, with_privacy_mode, ) from posthog.client import Client @@ -1101,6 +1102,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/langchain/middleware.py b/posthog/ai/langchain/middleware.py index 2d24e94d7..669a2d010 100644 --- a/posthog/ai/langchain/middleware.py +++ b/posthog/ai/langchain/middleware.py @@ -260,22 +260,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( @@ -376,4 +363,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 c8b18baf2..ba8778527 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/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/utils.py b/posthog/ai/utils.py index efc987c78..62bd937a6 100644 --- a/posthog/ai/utils.py +++ b/posthog/ai/utils.py @@ -518,6 +518,39 @@ def merge_system_prompt( return [] +# 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. @@ -526,7 +559,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/capture_compression.py b/posthog/capture_compression.py index 08db9e994..035cee26c 100644 --- a/posthog/capture_compression.py +++ b/posthog/capture_compression.py @@ -105,6 +105,10 @@ def _resolve_capture_compression( fallback = 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/client.py b/posthog/client.py index 7d47f8b02..67a10c710 100644 --- a/posthog/client.py +++ b/posthog/client.py @@ -695,18 +695,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 @@ -739,9 +740,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. @@ -4876,6 +4876,8 @@ def _get_feature_flag_result( 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) if errors: feature_flag_error = ",".join(errors) @@ -4907,10 +4909,10 @@ def _get_feature_flag_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 + # A successful payload override reports the caller's value. A failed + # record keeps its config version and reason code, never the override. + value_from_details = flag_details is not None and ( + override_match_value is None or flag_details._server_marked_failed ) except QuotaLimitError as e: self.log.warning(f"[FEATURE FLAGS] Quota limit exceeded: {e}") @@ -5020,7 +5022,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, @@ -5269,9 +5273,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] = { @@ -5337,9 +5340,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, @@ -5545,7 +5548,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}" @@ -5759,7 +5787,13 @@ def evaluate_flags( 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 + key: reason + for key, reason in unresolved.items() + if key not in records + or ( + isinstance(record := records[key], _RemoteFlagRecord) + and record.details._server_marked_failed + ) }, ) diff --git a/posthog/emails.py b/posthog/emails.py index bbfb85470..1f0bfaec4 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,8 +167,10 @@ __all__ = [ "AsyncEmails", "CodeEmailArgs", + "EmailAttachment", "EmailError", "EmailStatus", + "EmailTracking", "EmailWarning", "Emails", "SendEmailResult", @@ -140,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 @@ -147,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): @@ -216,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]] @@ -241,6 +311,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. @@ -249,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 @@ -260,11 +356,41 @@ 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. + 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 + 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 @@ -281,16 +407,27 @@ 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", } ) @@ -328,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: @@ -378,41 +535,66 @@ 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) 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), + ) + + +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: 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 - 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 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): + 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( @@ -424,6 +606,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): @@ -523,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) @@ -544,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 @@ -553,32 +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 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" + ) + 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" ) - 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 == 429: - return ( - "monthly_quota_exceeded" if code in _QUOTA_CODES else "rate_limit_exceeded" - ) - if status == 503: - return "service_unavailable" - return "application_error" + # 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: @@ -594,10 +966,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: @@ -608,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: @@ -637,9 +1019,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")) @@ -664,6 +1046,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: @@ -685,10 +1196,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 @@ -740,7 +1253,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): @@ -753,6 +1266,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, @@ -875,6 +1406,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: @@ -905,6 +1441,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, @@ -912,14 +1450,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. @@ -948,41 +1501,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: @@ -1089,6 +1662,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, @@ -1096,14 +1671,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. @@ -1114,42 +1704,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/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( diff --git a/posthog/exception_utils.py b/posthog/exception_utils.py index f597500b9..29c5fa6ec 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 @@ -694,9 +703,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) @@ -704,27 +740,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), ) @@ -733,27 +757,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__") @@ -844,17 +867,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( @@ -869,6 +882,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 @@ -964,13 +1003,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): @@ -1470,11 +1512,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: @@ -1490,16 +1545,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): @@ -1697,41 +1744,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. @@ -1743,6 +1779,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 @@ -1764,10 +1839,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): @@ -1776,7 +1859,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 @@ -1791,7 +1877,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) @@ -1799,24 +1889,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) @@ -1854,31 +1955,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: @@ -1888,6 +1965,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..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,14 +360,26 @@ def _record_access(self, key: str, send_feature_flag_events: bool) -> None: if not self._distinct_id: 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 + 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( + 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, + # 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, + ) + def _get_flag_called_properties(self, key, flag, response) -> Dict[str, Any]: properties: Dict[str, Any] = { "$feature_flag": key, "$feature_flag_response": response, @@ -353,49 +388,55 @@ 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) - # 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 errors: - properties["$feature_flag_error"] = ",".join(errors) + 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 + + +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 - 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 _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 d07bdbb7d..72711d4e5 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): @@ -258,13 +268,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) @@ -288,3 +292,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 32f035347..165facb82 100644 --- a/posthog/integrations/celery.py +++ b/posthog/integrations/celery.py @@ -401,18 +401,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: @@ -420,6 +409,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 4e12348de..927f41be7 100644 --- a/posthog/mcp/__init__.py +++ b/posthog/mcp/__init__.py @@ -307,6 +307,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: @@ -323,8 +324,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/_capture.py b/posthog/mcp/_capture.py index f74942de1..cd5c3c098 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"), @@ -69,6 +68,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"), "callback_event_options": event_input.get("callback_event_options"), @@ -84,3 +84,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/_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/_instrument_lowlevel.py b/posthog/mcp/_instrument_lowlevel.py index a8ab58671..b8cf5527d 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, wrap_error_result from .logger import log, warn from .tools import get_more_tools_result_text @@ -68,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) @@ -282,7 +284,10 @@ async def handler(req: Any) -> Any: start = time.monotonic() try: - result = await original(req) + 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( await registered_tool_exists(high_level, name) @@ -349,6 +354,7 @@ async def handler(req: Any) -> Any: call_result, duration_ms, conversation_id_delivered=delivered, + error=raised.error, ) return result @@ -724,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}") @@ -765,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 @@ -897,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) @@ -946,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 b7d597789..46d21a5af 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 @@ -554,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() @@ -673,7 +657,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 +687,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 @@ -874,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 37e88b7ff..8c76f0efd 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, @@ -684,7 +684,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) @@ -697,6 +702,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, @@ -832,14 +838,14 @@ 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) + event["error_status"] = http_status(error) props = await resolve_event_properties(data, request, extra) await _apply_event_options(data, event, request, extra) 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 a0611f855..45b1d4c02 100644 --- a/posthog/mcp/_posthog_events.py +++ b/posthog/mcp/_posthog_events.py @@ -144,18 +144,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 @@ -164,42 +153,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 @@ -210,6 +186,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"), ) @@ -283,6 +260,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: @@ -319,16 +298,17 @@ def _build_exception_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"] - 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_groups(event, properties) @@ -341,3 +321,37 @@ def _build_exception_event( "options": options, "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/_raised_tool_error.py b/posthog/mcp/_raised_tool_error.py new file mode 100644 index 000000000..6cb375f54 --- /dev/null +++ b/posthog/mcp/_raised_tool_error.py @@ -0,0 +1,121 @@ +"""Recover the exception behind an ``isError`` tool result. + +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 +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") + +# 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: + 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 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. + 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..145dfcec7 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` @@ -193,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, @@ -442,9 +435,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 +819,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) @@ -806,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/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/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 c424ca012..46896fed1 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, @@ -249,6 +249,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( @@ -500,40 +501,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, @@ -602,6 +609,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 @@ -619,6 +683,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 @@ -637,53 +722,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( @@ -713,10 +766,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) @@ -1014,3 +1064,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/mcp/types.py b/posthog/mcp/types.py index c5c30bba2..e4aee8d83 100644 --- a/posthog/mcp/types.py +++ b/posthog/mcp/types.py @@ -63,8 +63,8 @@ # 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: callback_event_options, client_name, -# client_version, conversation_id, duration, error, error_type, event_name, -# event_options, event_type, groups, id, identify_actor_data, +# client_version, conversation_id, duration, error, error_status, error_type, +# event_name, event_options, 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/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 e3aa43a97..4703d6ec9 100644 --- a/posthog/request.py +++ b/posthog/request.py @@ -295,24 +295,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() @@ -505,3 +488,26 @@ def encode(self, o: Any) -> str: except ValueError: pass 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.py b/posthog/test/ai/anthropic/test_anthropic.py index e3351e934..a12133625 100644 --- a/posthog/test/ai/anthropic/test_anthropic.py +++ b/posthog/test/ai/anthropic/test_anthropic.py @@ -2307,6 +2307,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_ai.call_count == 1 + props = mock_client.capture_ai.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) @@ -2349,6 +2369,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_ai.call_count == 1 + props = mock_client.capture_ai.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, ): 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..f902313e1 --- /dev/null +++ b/posthog/test/ai/claude_agent_sdk/test_client.py @@ -0,0 +1,601 @@ +"""Stateful Claude client delivery, turn boundaries, and teardown contracts.""" + +from dataclasses import replace +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_ai.call_args_list + if call.kwargs["event"] == name + ] + + +def event_options(event): + return event.get("options") or {} + + +@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_ai.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 event_options(generation)["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 event_options(events(ph, "$ai_trace")[0])["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_ai.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 event_options(generation)["process_person_profile"] is False + assert trace["distinct_id"] == ( + str(resolved) if resolved else trace["properties"]["$ai_trace_id"] + ) + assert ("process_person_profile" in event_options(trace)) 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_ai.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"}]} + ] 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/gemini/test_gemini_parity.py b/posthog/test/ai/gemini/test_gemini_parity.py index c117ee78c..b5d893e25 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]) 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/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/posthog/test/ai/test_http_status.py b/posthog/test/ai/test_http_status.py index 0e9f56c9a..85d744481 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_ai.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 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_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 new file mode 100644 index 000000000..23bb5ed74 --- /dev/null +++ b/posthog/test/mcp/test_fastmcp_tool_errors.py @@ -0,0 +1,230 @@ +"""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 httpx +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 _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() + 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, status", + [ + ( + _chained, + False, + "RuntimeError", + "lookup failed", + ["RuntimeError", "ConnectionError"], + None, + ), + ( + _chained, + True, + "RuntimeError", + "lookup failed", + ["RuntimeError", "ConnectionError"], + None, + ), + (_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, status +): + 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 + 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] + 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_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_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(): 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_pipeline.py b/posthog/test/mcp/test_pipeline.py index f317cc0f4..59cb0c46f 100644 --- a/posthog/test/mcp/test_pipeline.py +++ b/posthog/test/mcp/test_pipeline.py @@ -1,6 +1,9 @@ """Unit tests for the MCP analytics core pipeline (Milestone 1, no server).""" import copy +import json +import random +import re from datetime import datetime, timezone import pytest @@ -10,6 +13,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 @@ -91,6 +95,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") diff --git a/posthog/test/mcp/test_posthog_mcp.py b/posthog/test/mcp/test_posthog_mcp.py index 7677fdb20..c92559284 100644 --- a/posthog/test/mcp/test_posthog_mcp.py +++ b/posthog/test/mcp/test_posthog_mcp.py @@ -780,3 +780,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_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 30d86d243..27739006b 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 eaf1c0949..b2690cff0 100644 --- a/posthog/test/test_emails.py +++ b/posthog/test/test_emails.py @@ -1,12 +1,28 @@ from __future__ import annotations import asyncio +import base64 +import hashlib +import hmac import json import logging -from datetime import datetime, timezone +import re +import ssl +import threading +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 typing import Any, 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 @@ -620,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): @@ -693,11 +711,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] = [] @@ -766,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", { @@ -782,6 +878,58 @@ 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", + { + "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): @@ -799,3 +947,1834 @@ 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"} + + 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/posthog/test/test_evaluate_flags.py b/posthog/test/test_evaluate_flags.py index 6bca25e67..72efc507f 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( [ ( @@ -1207,6 +1281,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_experiment_exposure.py b/posthog/test/test_experiment_exposure.py index 6d583c40c..6148aa460 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..f17c6ede2 --- /dev/null +++ b/posthog/test/test_failed_flag_records.py @@ -0,0 +1,289 @@ +"""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" + # v1 passes snapshot flag properties to _enqueue separately. + flag_properties = enqueue.call_args.kwargs["flag_properties"] + assert flag_properties["$feature/off"] is False + assert "$feature/failed" not in flag_properties + assert "$feature/other-failed" not in flag_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_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_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 d86cf1d9f..ee5c367bf 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/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/test_utils.py b/posthog/test/test_utils.py index d002f5eab..ab5a759aa 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, contextmanager from unittest import mock from dataclasses import dataclass @@ -365,6 +366,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/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 3a3e4b398..156276e25 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..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, @@ -358,6 +363,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 +395,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. @@ -634,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: @@ -719,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 } @@ -731,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 } @@ -745,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 @@ -758,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/posthog/utils.py b/posthog/utils.py index 49e911124..a734fa2d3 100644 --- a/posthog/utils.py +++ b/posthog/utils.py @@ -5,7 +5,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 @@ -22,7 +22,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: @@ -37,14 +37,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) @@ -87,7 +85,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 ) @@ -114,7 +112,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) @@ -281,7 +279,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: @@ -688,7 +686,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 @@ -760,7 +758,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/posthog/version.py b/posthog/version.py index b650937f8..d29da7e01 100644 --- a/posthog/version.py +++ b/posthog/version.py @@ -1 +1 @@ -VERSION = "7.87.1" +VERSION = "7.91.2" diff --git a/pyproject.toml b/pyproject.toml index f0bd483f2..217f1b1e9 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.91.2" description = "Integrate PostHog into any python application." authors = [{ name = "PostHog", email = "engineering@posthog.com" }] maintainers = [{ name = "PostHog", email = "engineering@posthog.com" }] @@ -172,13 +172,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", diff --git a/references/posthog-python-7.md b/references/posthog-python-7.md index e8b38ed62..a9ed00bd7 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` @@ -3800,7 +3784,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 +3995,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,7 +4010,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. | @@ -4031,17 +4024,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` @@ -4049,6 +4059,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 @@ -4085,6 +4101,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 +4130,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-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]]] +``` diff --git a/references/posthog-python-reference.md b/references/posthog-python-reference.md index d48de7843..cae9b2aa5 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` @@ -3800,7 +3784,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 +3995,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,7 +4010,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. | @@ -4031,17 +4024,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` @@ -4049,6 +4059,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 @@ -4085,6 +4101,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 +4130,9 @@ text: NotRequired[Optional[str]] ```python to: str ``` + +#### `posthog.emails.CodeEmailArgs.tracking` + +```python +tracking: NotRequired[Optional[Union[bool, EmailTracking]]] +``` diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index 0cc76335e..c9e0b430e 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -474,6 +474,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 @@ -515,6 +516,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 @@ -524,25 +526,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 @@ -550,6 +572,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 @@ -785,6 +809,7 @@ attribute posthog.capture_send.CaptureEventResult.result: Optional[str] attribute posthog.capture_trace_context = False 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_ai_compression = _resolve_capture_ai_compression(capture_ai_compression) attribute posthog.client.Client.capture_compression = _resolve_capture_compression(capture_compression) attribute posthog.client.Client.capture_exception_code_variables = capture_exception_code_variables @@ -885,13 +910,22 @@ 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]]]] +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.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 @@ -906,6 +940,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 @@ -1026,6 +1063,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' @@ -1175,6 +1213,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' @@ -1266,7 +1305,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) @@ -1275,10 +1314,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, ...]) @@ -1342,8 +1384,10 @@ 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 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, ...] = ()) @@ -1670,13 +1714,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) @@ -1707,13 +1752,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, posthog_options: 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, posthog_options: 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, posthog_options: Optional[Dict[str, Any]] = None, **kwargs: Any) diff --git a/typings/requests/__init__.pyi b/typings/requests/__init__.pyi index a0edbb3c5..7504def75 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, diff --git a/uv.lock b/uv.lock index c66cd9299..593e7336a 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]] @@ -1289,7 +1291,7 @@ requests = [ [[package]] name = "google-genai" -version = "2.32.0" +version = "2.33.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, @@ -1303,9 +1305,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]] @@ -1650,74 +1652,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]] @@ -1838,30 +2017,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]] @@ -1908,9 +2087,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" }, @@ -1922,14 +2102,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" }, @@ -1937,21 +2117,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]] @@ -1968,7 +2148,7 @@ wheels = [ [[package]] name = "langgraph" -version = "1.2.16" +version = "1.2.20" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "langchain-core" }, @@ -1978,9 +2158,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]] @@ -2665,39 +2845,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]] @@ -2714,7 +2898,7 @@ wheels = [ [[package]] name = "openfeature-provider-posthog" -version = "0.1.158" +version = "0.1.165" source = { editable = "openfeature-provider" } dependencies = [ { name = "openfeature-sdk" }, @@ -2749,14 +2933,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]] @@ -2822,7 +3006,7 @@ wheels = [ [[package]] name = "opentelemetry-instrumentation" -version = "0.66b1" +version = "0.66b2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, @@ -2830,14 +3014,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" }, @@ -2846,28 +3030,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" }, @@ -2875,14 +3059,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" }, @@ -2891,14 +3075,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" }, @@ -2908,14 +3092,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" }, @@ -2924,14 +3108,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" }, @@ -2939,28 +3123,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" }, @@ -2968,14 +3152,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" }, @@ -2983,9 +3167,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]] @@ -3002,38 +3186,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]] @@ -3271,7 +3455,7 @@ wheels = [ [[package]] name = "posthog" -version = "7.87.1" +version = "7.91.2" source = { editable = "." } dependencies = [ { name = "distro" }, @@ -4584,18 +4768,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"