Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
5378ece
fix: keep frozenset and deque values when cleaning event properties (…
Ishkirat-Singh Nov 12, 2026
c0b0230
chore: Release v7.87.2 [skip ci]
releaser-posthog-python[bot] Nov 12, 2026
7eabca8
chore(deps): bump langgraph from 1.2.12 to 1.2.14 in /examples/exampl…
dependabot[bot] Nov 12, 2026
9636fa2
feat(llma): support composite offline scorers (#1235)
Radu-Raicea Nov 12, 2026
aaeedb0
chore: Release v7.88.0 [skip ci]
releaser-posthog-python[bot] Nov 12, 2026
ac25b4b
feat(emails): let a code send set its tracking and sensitivity (#1216)
Silthus Nov 12, 2026
71124f1
chore: Release v7.89.0 [skip ci]
releaser-posthog-python[bot] Nov 12, 2026
bf5f036
Update generated references
releaser-posthog-python[bot] Nov 12, 2026
e2fb8da
chore: remove mutation testing setup (#1239)
marandaneto Nov 12, 2026
0139861
fix(mcp): report the exception behind a FastMCP isError tool result (…
lucasheriques Nov 13, 2026
dd7577b
feat(mcp): set $mcp_error_status from the raised exception's cause ch…
lucasheriques Nov 13, 2026
9e4935f
fix(mcp): report the raised exception on mcp 1.x low-level isError re…
lucasheriques Nov 13, 2026
390f3dd
chore: Release v7.90.0 [skip ci]
releaser-posthog-python[bot] Nov 13, 2026
cd821fb
feat: send cc, bcc and attachments with emails.send (#1172)
Silthus Nov 13, 2026
7f5a6b3
chore: Release v7.91.0 [skip ci]
releaser-posthog-python[bot] Nov 13, 2026
f6f6183
Update generated references
releaser-posthog-python[bot] Nov 13, 2026
03174d0
refactor: reduce SDK complexity and improve CRAP analysis (#1242)
marandaneto Nov 13, 2026
3511570
fix: treat failed feature flag records as unevaluated (#1238)
marandaneto Nov 13, 2026
cd87bcd
chore: Release v7.91.1 [skip ci]
releaser-posthog-python[bot] Nov 13, 2026
6d21c7b
Update generated references
releaser-posthog-python[bot] Nov 13, 2026
ec112a6
docs: publish the posthog-python 8.x reference and migration guide pa…
gewenyu99 Nov 13, 2026
f040c02
chore(deps): bump opentelemetry-api from 1.45.1 to 1.45.2 (#1254)
dependabot[bot] Nov 15, 2026
7e7194e
chore(deps): bump the uv group across 4 directories with 1 update (#1…
dependabot[bot] Nov 15, 2026
652b979
chore(deps): bump the uv group across 26 directories with 1 update (#…
dependabot[bot] Nov 15, 2026
8415830
fix(gemini): honor GEMINI_API_KEY environment variable (#1258)
pcbeingused333 Nov 16, 2026
5340514
fix(ai): give Claude Agent SDK generations their tool results and eve…
MaiAditya Nov 16, 2026
92fae51
fix(ai): record an Anthropic stream error event's status, not 200 (#1…
jaeminbird Nov 16, 2026
ade1ff9
fix(ai): capture initial request errors in Anthropic messages.stream(…
pcbeingused333 Nov 16, 2026
eef61f6
chore: Release v7.91.2 [skip ci]
releaser-posthog-python[bot] Nov 16, 2026
ca1ac3a
chore(deps): bump the github-actions group with 5 updates (#1259)
dependabot[bot] Nov 16, 2026
83eee80
chore(deps): bump the ai-providers group with 9 updates (#1260)
dependabot[bot] Nov 16, 2026
f225118
docs: add docstrings to ExceptionCapture public methods (#1257)
mi-vault Nov 16, 2026
dd8ad56
chore: merge main (v7.87.2-v7.91.2) into v1
eli-r-ph Nov 16, 2026
c8ab322
docs: regenerate the 8.x reference with main's new API
eli-r-ph Nov 16, 2026
018d15d
chore: merge main (#1257) into v1
eli-r-ph Nov 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 59 additions & 15 deletions .github/scripts/check_crap_threshold.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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}")
Expand All @@ -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
Expand Down
3 changes: 3 additions & 0 deletions .github/scripts/check_public_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
30 changes: 28 additions & 2 deletions .github/scripts/check_strict_types.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ from posthog.ai.evaluations import (
AsyncOfflineEvaluations,
BooleanScorerConfig,
EvaluationItem,
EvaluationResult,
NumericPassingRule,
NumericScorerConfig,
OfflineEvaluations,
ScorerComposition,
)

client = Posthog("phc_test")
Expand All @@ -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="<p>Reset</p>", from_="Acme <security@example.com>", 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="<p>Invite</p>", 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="<p>Hi</p>", tracking={"clicks": True, "engagement": False})
untracked_send: SendEmailResult = emails.send(to="user@example.com", template_key="welcome", subject="Welcome", html="<p>Hi</p>", tracking=False)
not_sensitive_send: SendEmailResult = emails.send(to="user@example.com", template_key="newsletter", subject="News", html="<p>News</p>", sensitive=False)
_ = (template_send, rendered_send, invite_send, tracked_send, untracked_send, not_sensitive_send)


async def async_email_types() -> None:
Expand Down Expand Up @@ -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'
Expand All @@ -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="<p>Hi</p>") # 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="<p>Hi</p>", tracking={"open": False}) # expected-type-error
Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="<p>Hi</p>", template_data={"name": "Ada"}) # expected-type-error
Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="<p>Hi</p>", cc="team@example.com") # expected-type-error
Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="<p>Hi</p>", attachments=[{"filename": "a.txt", "content": [104, 105]}]) # expected-type-error
Emails("phs_example").send(to="user@example.com", template_key="welcome", subject="Hi", html="<p>Hi</p>", 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:
Expand Down
110 changes: 110 additions & 0 deletions .github/scripts/constructor_helper_attributes.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading