Skip to content

feat(metrics): metrics autocapture for HTTP, database and runtime metrics - #992

Open
DanielVisca wants to merge 5 commits into
mainfrom
posthog/otel-metrics-autocapture
Open

DanielVisca wants to merge 5 commits into
mainfrom
posthog/otel-metrics-autocapture

Conversation

@DanielVisca

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Metrics needs hand-written client.metrics.* calls today. We want metrics to be the easiest setup: install the SDK, set one flag, and get HTTP, database and runtime metrics.

Why: #967 was closed because a hand-rolled HTTP wrapper duplicates OpenTelemetry instrumentation, and PostHog accepts OTLP directly (#914 took the hand-rolled route for runtime metrics). So this change starts the official OpenTelemetry instrumentors for you instead of writing new ones. Companion to PostHog/posthog-js#5149, with the same config shape.

posthog = Posthog("phc_...", metrics={"autocapture": True, "service_name": "billing-api"})
# or {"autocapture": {"http": True, "db": True, "runtime": False}}
  • New posthog[metrics] extra. opentelemetry-bootstrap -a install adds the instrumentors for the installed libraries; autocapture finds them through the opentelemetry_instrumentor entry points, as opentelemetry-instrument does.
  • HTTP: requests, urllib, urllib3, httpx, aiohttp, Django, Flask, FastAPI, Starlette, and more, with stable semantic convention names (http.server.request.duration, seconds), the same names posthog-node sends. Requests to the PostHog host are excluded.
  • DB: a span processor turns driver-level client spans (psycopg2, psycopg, asyncpg, pymysql, sqlite3, pymongo, redis, ...) into db.client.operation.duration. SQLAlchemy spans are not counted, because they wrap a driver span. Only bounded attributes; never the statement.
  • Runtime: process CPU, memory, threads, file descriptors and cpython.gc.* from system_metrics (process-level only, no host-wide system.*).
  • Private meter and tracer providers; nothing is set on the OpenTelemetry globals. If the app already has OpenTelemetry, it warns and does not start. Exports stop while the client is disabled. shutdown() exports the last window and uninstruments.
  • Resource has telemetry.distro.name=posthog-python so we can measure adoption.
  • Create the client before the web framework loads (Django: AppConfig.ready(); Flask: before Flask(...)).

💚 How did you test it?

  • TDD: posthog/test/test_metrics_autocapture.py (13 tests). ruff, mypy (baseline) and python -W error -c "import posthog" clean. Full suite: 4155 passed; 2 failures in test/ai/langchain/test_callbacks.py also fail on main in this sandbox (they need network access).
  • End to end against a local PostHog stack (hogli with the metrics intent): a Flask + SQLAlchemy/psycopg2 + redis + requests app. In ClickHouse I saw http.server.request.duration (with http.route), http.client.request.duration, db.client.operation.duration (postgresql and redis), process.* and cpython.gc.*. No series for the PostHog host.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed. (Follow-up: metrics docs "Autocapture" section.)
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

  • Written with Claude Code in PostHog Desktop. The user chose the OpenTelemetry-native approach, Node and Python together, and opt-in by default.
  • The sqlite3 instrumentor wraps cursors only, not the Connection.execute shortcut; drivers and SQLAlchemy use cursors, so the tests use cursors.

Created with PostHog Desktop

🤖 Generated with Claude Code

… metrics

`metrics={"autocapture": True}` starts the installed OpenTelemetry instrumentors with private meter and tracer providers and exports to `/i/v1/metrics`. The packages come from the new `posthog[metrics]` extra.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: ef9b57c2-47ff-47e6-a509-8873ffe1fab4
@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-08T16:39:10.734437+00:00
Duration: 259886ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 517ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 510ms
Required Headers.Has Authorization Bearer Header ✅ 511ms
Required Headers.Has Content Type Json ✅ 511ms
Required Headers.Has Posthog Sdk Info Format ✅ 511ms
Required Headers.Has Posthog Attempt Header ✅ 510ms
Required Headers.Has Posthog Request Id ✅ 510ms
Required Headers.Has Posthog Request Timestamp ✅ 510ms
Required Headers.Has User Agent ✅ 510ms
Body Format.Body Has Created At And Batch ✅ 511ms
Body Format.No Api Key In Body ✅ 510ms
Body Format.No Sent At In Body ✅ 511ms
Event Format.Event Has Required Root Fields ✅ 510ms
Event Format.Event Uuid Is Valid ✅ 510ms
Event Format.Event Timestamp Is Rfc3339 ✅ 510ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 516ms
Event Format.Distinct Id Is String ✅ 510ms
Event Format.Distinct Id At Root Not Properties ✅ 510ms
Event Format.Custom Properties Preserved ✅ 511ms
Event Format.Set Properties Preserved ✅ 510ms
Event Format.Set Once Properties Preserved ✅ 510ms
Event Format.Groups Properties Preserved ✅ 510ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 510ms
Event Format.Event Has Required Root Fields Batch ✅ 514ms
Event Format.Event Uuid Is Valid Batch ✅ 514ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 514ms
Event Format.Distinct Id Is String Batch ✅ 514ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 514ms
Event Format.Custom Properties Preserved Batch ✅ 513ms
Event Format.Set Properties Preserved Batch ✅ 514ms
Event Format.Set Once Properties Preserved Batch ✅ 513ms
Event Format.Groups Properties Preserved Batch ✅ 512ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 514ms
Batch Behavior.Multiple Events In Single Batch ✅ 517ms
Batch Behavior.Batch Envelope Smoke ✅ 516ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 507ms
Batch Behavior.Flush At Triggers Batch ✅ 1011ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 510ms
Deduplication.Generates Unique Uuids ✅ 518ms
Deduplication.Different Events Same Content Different Uuids ✅ 512ms
Deduplication.Preserves Uuid On Retry ✅ 6520ms
Deduplication.Preserves Timestamp On Retry ✅ 6516ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6523ms
Deduplication.No Duplicate Events In Batch ✅ 518ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 510ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13528ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6515ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6519ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 511ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 514ms
Response Format Validation.Success No Retry After When All Ok ✅ 513ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1516ms
Response Format Validation.Success No Retry After When Drop Only ✅ 513ms
Response Format Validation.Response Echoes Request Id ✅ 511ms
Retry Behavior.Retries On 408 ✅ 6520ms
Retry Behavior.Retries On 500 ✅ 6519ms
Retry Behavior.Retries On 503 ✅ 8523ms
Retry Behavior.Retries On 504 ✅ 6520ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3515ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11521ms
Retry Behavior.Does Not Retry On 400 ✅ 2513ms
Retry Behavior.Does Not Retry On 401 ✅ 2514ms
Retry Behavior.Does Not Retry On 402 ✅ 2513ms
Retry Behavior.Does Not Retry On 413 ✅ 2513ms
Retry Behavior.Does Not Retry On 415 ✅ 2514ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2513ms
Retry Behavior.Implements Backoff ✅ 22533ms
Retry Behavior.Max Retries Respected ✅ 22535ms
Partial Batch Handling.Handles 200 Full Success ✅ 2513ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3518ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3514ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3515ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6522ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6520ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6519ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6521ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6521ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6517ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8521ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3517ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3519ms
Compression.Sends Gzip Content Encoding ✅ 511ms
Compression.No Content Encoding When Disabled ✅ 510ms
Compression.Compressed Body Is Decompressible ✅ 510ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2513ms
Event Options.Cookieless Mode Override ✅ 511ms
Event Options.Disable Skew Correction Override ✅ 510ms
Event Options.Process Person Profile Override ✅ 511ms
Event Options.Product Tour Id Override ✅ 510ms
Event Options.Unset Options Omitted ✅ 512ms
Event Options.Options Override In Batch ✅ 513ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 510ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 510ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 510ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 511ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 510ms
Identity.Capture Ai Event Has Uuid ✅ 510ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 510ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 510ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 13ms
Request Payload.Flags Request Uses V2 Query Param ✅ 9ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 11ms
Request Payload.Flags Request Omits Authorization Header ✅ 9ms
Request Payload.Token In Flags Body Matches Init ✅ 10ms
Request Payload.Groups Round Trip ✅ 9ms
Request Payload.Groups Default To Empty Object ✅ 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 9ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 10ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 509ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 14ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 9ms
Retry Behavior.Retries Flags On 502 ✅ 313ms
Retry Behavior.Retries Flags On 504 ✅ 313ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 512ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 70ms
Versioned Boolean Matching.Matching Version 1 ✅ 68ms
Versioned Boolean Matching.Matching Version 2 ✅ 73ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 35ms

@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Retrigger

[Medium risk] Adds metrics collection for HTTP, database, and runtime operations.

The PR is not yet safe to merge because autocapture remains unusable in workers forked after initialization.

Reviews (2) · Last reviewed commit: "Merge branch 'main' into posthog/otel-me..."

Comment thread posthog/metrics_autocapture.py
Comment thread posthog/metrics_autocapture.py
Comment thread posthog/metrics_autocapture.py Outdated
Generated-By: PostHog Desktop
Task-Id: c0218209-575c-46f0-a201-d0c831e38096
Generated-By: PostHog Desktop
Task-Id: c49250e2-d173-455b-8165-d6d3285f87bb

Copy link
Copy Markdown
Contributor Author

Updated this branch from main with a signed merge. This brings in the MCP public API snapshot entry that was missing from the CI merge result. Observed checks now pass locally: make public_api_check, the snapshot script tests, and all 13 metrics autocapture tests. The PR stays in draft for the SDK API and documentation review.

Copy link
Copy Markdown
Contributor Author

CI is now green on the updated head, including the Public API snapshot check, Python test jobs, and SDK compliance checks. This remains draft because the new autocapture API and its documentation still need review.

@DanielVisca
DanielVisca marked this pull request as ready for review October 6, 2026 16:40
@DanielVisca
DanielVisca requested a review from a team as a code owner October 6, 2026 16:40

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not approved yet — waiting on the conditions below.

Re-add the stamphog label to request another review once you have addressed this.

stamphog can't auto-approve this pull request, and the refusal is final. Two gates refused it. The deny-list gate matched deps_toolchain, because pyproject.toml and uv.lock add a new metrics extra and many OpenTelemetry packages. It also matched public_api, because references/public_api_snapshot.txt changed. The tier gate classified the change as T2-never (1094 lines, 8 files, cross-cutting feature), a class that is never auto-approved.

The size gate passed, so splitting the PR won't clear the deny-list match on its own. The next step is to ask a human reviewer to look at it. If you'd like it reviewed in smaller pieces, you could separate the dependency and public API changes from the rest and ask a human to review each.

  • 👍 on the PR from greptile-apps[bot].
Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✗ matches: deps_toolchain, public_api
size ✓ 493L, 3F substantive, 1094L/8F incl. docs/generated/snapshots — within ceiling
tier ✗ classified as T2-never: T2-never (1094L, 8F, cross-cutting, feat)
stamphog 2.3.1 .stamphog/policy.yml @ unknown · reviewed head 3bfa7e1

Comment thread posthog/client.py Outdated
Comment thread posthog/metrics_autocapture.py
@veria-ai

veria-ai Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 2 · PR risk: 0/10

Generated-By: PostHog Desktop
Task-Id: 10838116-90e2-4d23-af38-8099d7887d07
- Honour send=False in the autocapture export gate.
- Strip trailing slashes from the host before building the metrics endpoint.
- Set OTEL_SEMCONV_STABILITY_OPT_IN only while the instrumentors load, then
  restore the process environment.
- Limit each synchronous instrument to 2000 attribute sets; send the rest to
  an otel.metric.overflow series, so user-supplied hosts cannot grow the SDK cache.
- After fork, replace the module lock and point the runtime instrumentor at
  the child process.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: 10838116-90e2-4d23-af38-8099d7887d07

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant