Skip to content

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

Draft
DanielVisca wants to merge 1 commit into
mainfrom
posthog/otel-metrics-autocapture
Draft

DanielVisca wants to merge 1 commit 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-09-29T21:53:40.590014+00:00
Duration: 259437ms

✅ 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 ✅ 515ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 508ms
Required Headers.Has Authorization Bearer Header ✅ 509ms
Required Headers.Has Content Type Json ✅ 510ms
Required Headers.Has Posthog Sdk Info Format ✅ 508ms
Required Headers.Has Posthog Attempt Header ✅ 508ms
Required Headers.Has Posthog Request Id ✅ 509ms
Required Headers.Has Posthog Request Timestamp ✅ 508ms
Required Headers.Has User Agent ✅ 509ms
Body Format.Body Has Created At And Batch ✅ 509ms
Body Format.No Api Key In Body ✅ 508ms
Body Format.No Sent At In Body ✅ 509ms
Event Format.Event Has Required Root Fields ✅ 508ms
Event Format.Event Uuid Is Valid ✅ 509ms
Event Format.Event Timestamp Is Rfc3339 ✅ 509ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 513ms
Event Format.Distinct Id Is String ✅ 508ms
Event Format.Distinct Id At Root Not Properties ✅ 508ms
Event Format.Custom Properties Preserved ✅ 509ms
Event Format.Set Properties Preserved ✅ 508ms
Event Format.Set Once Properties Preserved ✅ 508ms
Event Format.Groups Properties Preserved ✅ 508ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 508ms
Event Format.Event Has Required Root Fields Batch ✅ 511ms
Event Format.Event Uuid Is Valid Batch ✅ 512ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 510ms
Event Format.Distinct Id Is String Batch ✅ 511ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 511ms
Event Format.Custom Properties Preserved Batch ✅ 511ms
Event Format.Set Properties Preserved Batch ✅ 511ms
Event Format.Set Once Properties Preserved Batch ✅ 512ms
Event Format.Groups Properties Preserved Batch ✅ 511ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 511ms
Batch Behavior.Multiple Events In Single Batch ✅ 514ms
Batch Behavior.Batch Envelope Smoke ✅ 512ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 506ms
Batch Behavior.Flush At Triggers Batch ✅ 1009ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 509ms
Deduplication.Generates Unique Uuids ✅ 514ms
Deduplication.Different Events Same Content Different Uuids ✅ 510ms
Deduplication.Preserves Uuid On Retry ✅ 6517ms
Deduplication.Preserves Timestamp On Retry ✅ 6513ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6516ms
Deduplication.No Duplicate Events In Batch ✅ 515ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 508ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13525ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6517ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3018ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6514ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 509ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 511ms
Response Format Validation.Success No Retry After When All Ok ✅ 511ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1513ms
Response Format Validation.Success No Retry After When Drop Only ✅ 511ms
Response Format Validation.Response Echoes Request Id ✅ 508ms
Retry Behavior.Retries On 408 ✅ 6513ms
Retry Behavior.Retries On 500 ✅ 6518ms
Retry Behavior.Retries On 503 ✅ 8521ms
Retry Behavior.Retries On 504 ✅ 6517ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3515ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11520ms
Retry Behavior.Does Not Retry On 400 ✅ 2512ms
Retry Behavior.Does Not Retry On 401 ✅ 2511ms
Retry Behavior.Does Not Retry On 402 ✅ 2510ms
Retry Behavior.Does Not Retry On 413 ✅ 2512ms
Retry Behavior.Does Not Retry On 415 ✅ 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2509ms
Retry Behavior.Implements Backoff ✅ 22533ms
Retry Behavior.Max Retries Respected ✅ 22532ms
Partial Batch Handling.Handles 200 Full Success ✅ 2511ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3515ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3513ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3514ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6519ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6515ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6521ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6518ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6515ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6518ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8520ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3514ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3517ms
Compression.Sends Gzip Content Encoding ✅ 510ms
Compression.No Content Encoding When Disabled ✅ 509ms
Compression.Compressed Body Is Decompressible ✅ 508ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2511ms
Event Options.Cookieless Mode Override ✅ 509ms
Event Options.Disable Skew Correction Override ✅ 508ms
Event Options.Process Person Profile Override ✅ 509ms
Event Options.Product Tour Id Override ✅ 508ms
Event Options.Unset Options Omitted ✅ 508ms
Event Options.Options Override In Batch ✅ 511ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 509ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 508ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 509ms

Capture_Ai Tests

✅ 5/5 tests passed

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

Feature_Flags Tests

✅ 17/17 tests passed

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

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 54ms
Versioned Boolean Matching.Matching Version 1 ✅ 52ms
Versioned Boolean Matching.Matching Version 2 ✅ 51ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 28ms

@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Retrigger

[Medium risk] Adds metrics autocapture feature using OpenTelemetry.

The PR is not ready to merge until prefork workers can initialize autocapture correctly.

Reviews (1) · Last reviewed commit: "feat(metrics): add metrics autocapture f..."

Comment on lines +272 to +276
if _active is not None:
log.warning(
"Metrics autocapture is already running in this process, so this client does not start it again."
)
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Autocapture survives fork unchanged If a client starts autocapture before a prefork server creates workers, each child inherits _active. The client's fork hook does not reinitialize autocapture, so a worker trying to start its own instance is told one is already running and cannot start it. Reinitialize the autocapture state, lock, and reader lifecycle in the child.

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/metrics_autocapture.py
Line: 272-276

Comment:
**Autocapture survives fork unchanged** If a client starts autocapture before a prefork server creates workers, each child inherits `_active`. The client's fork hook does not reinitialize autocapture, so a worker trying to start its own instance is told one is already running and cannot start it. Reinitialize the autocapture state, lock, and reader lifecycle in the child.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!


reader = sdk_metrics_export.PeriodicExportingMetricReader(
_GatedExporter(
endpoint=f"{host}/i/v1/metrics",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Trailing slash changes metrics path If a custom host ends in /, this builds an endpoint containing //i/v1/metrics. The existing event request path removes the trailing slash, so metrics can be sent to a different path and fail to arrive. Strip the trailing slash before appending the metrics path.

Suggested change
endpoint=f"{host}/i/v1/metrics",
endpoint=f"{host.rstrip('/')}/i/v1/metrics",
Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/metrics_autocapture.py
Line: 341

Comment:
**Trailing slash changes metrics path** If a custom host ends in `/`, this builds an endpoint containing `//i/v1/metrics`. The existing event request path removes the trailing slash, so metrics can be sent to a different path and fail to arrive. Strip the trailing slash before appending the metrics path.

```suggestion
                        endpoint=f"{host.rstrip('/')}/i/v1/metrics",
```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.


# Stable HTTP names (`http.server.request.duration`, seconds), the same
# names posthog-node sends. Read once, when the first instrumentor loads.
os.environ.setdefault("OTEL_SEMCONV_STABILITY_OPT_IN", "http")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Autocapture changes global conventions Starting autocapture sets OTEL_SEMCONV_STABILITY_OPT_IN for the whole process and shutdown does not restore it. If the application loads its own instrumentors later, their HTTP metric names and units can change without the application opting in. Avoid changing process-wide configuration, or restore it when autocapture stops.

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/metrics_autocapture.py
Line: 311

Comment:
**Autocapture changes global conventions** Starting autocapture sets `OTEL_SEMCONV_STABILITY_OPT_IN` for the whole process and shutdown does not restore it. If the application loads its own instrumentors later, their HTTP metric names and units can change without the application opting in. Avoid changing process-wide configuration, or restore it when autocapture stops.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

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