Skip to content

feat(metrics): support metrics config via module-level settings#753

Merged
DanielVisca merged 3 commits into
mainfrom
posthog-code/module-level-metrics-config
Jul 21, 2026
Merged

feat(metrics): support metrics config via module-level settings#753
DanielVisca merged 3 commits into
mainfrom
posthog-code/module-level-metrics-config

Conversation

@DanielVisca

@DanielVisca DanielVisca commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Apps configured through module attributes (posthog.api_key = ... + implicit setup()) — including PostHog's own Django monorepo via posthoganalytics — have no way to pass the metrics config dict. Every series they record through client.metrics ships service.name='unknown_service', which defeats the Metrics UI's service filtering.

This adds the module-level metrics attr (mirroring how every other Client kwarg is exposed as a module setting) and passes it through setup(). Because the config is consumed lazily on first .metrics access, a repeat setup() call also refreshes it until the metrics API is first used — Django ready() hooks that run after something already forced setup() still apply.

Groundwork for the monorepo's bump-ready client.metrics usage from web/celery (companion PR in PostHog/posthog).

💚 How did you test it?

  • Two new tests in posthog/test/test_metrics.py, red before the change (service.name came back unknown_service): module attr flows into the setup() client's OTLP resource attributes, and late assignment applies on repeat setup() until first use.
  • pytest --timeout=30: 1640 passed; the 9 failures are the pre-existing network-dependent posthog/test/ai/* integration tests (verified they fail identically on a clean checkout in the same sandbox).
  • ruff format --check, ruff check, mypy | mypy-baseline filter (no issues), python -W error -c "import posthog" all clean.
  • End to end: with this patch, a module-configured client in a forked child (celery-prefork shape) recorded and flushed real metrics that arrived in the Metrics product with the configured service name.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file (authored directly in .sampo/changesets/module-level-metrics-config.md — same format)

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Written by Claude (PostHog Code session) while making the PostHog monorepo bump-ready for client.metrics. TDD: the two tests were written and observed failing before the implementation. The late-assignment refresh in setup() follows the existing "always set in case user changes it" post-construction block, and is limited to before first .metrics use so an active aggregation window is never reconfigured mid-flight.


Created with PostHog Code

Apps configured through module attributes (posthog.api_key = ..., then setup()) had no way to pass the metrics config dict, so their client.metrics series all shipped service.name='unknown_service'. Adds the module-level `metrics` attr, passes it through setup(), and refreshes the lazily-consumed config on repeat setup() calls until the metrics API is first used, so Django-style ready() hooks that run after an early setup() still apply.

Generated-By: PostHog Code
Task-Id: 470062dd-05c0-40bf-bfa3-bc89b194121e
@DanielVisca DanielVisca self-assigned this Jul 20, 2026
Generated-By: PostHog Code
Task-Id: 470062dd-05c0-40bf-bfa3-bc89b194121e
@github-actions

github-actions Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-07-20 22:51:23 UTC
Duration: 338827ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 516ms
Endpoint And Method.Does Not Use Legacy Endpoints 1009ms
Required Headers.Has Authorization Bearer Header 1009ms
Required Headers.Has Content Type Json 1008ms
Required Headers.Has Posthog Sdk Info Format 1008ms
Required Headers.Has Posthog Attempt Header 1008ms
Required Headers.Has Posthog Request Id 1009ms
Required Headers.Has Posthog Request Timestamp 1007ms
Required Headers.Has User Agent 1007ms
Body Format.Body Has Created At And Batch 1007ms
Body Format.No Api Key In Body 1009ms
Body Format.No Sent At In Body 1008ms
Event Format.Event Has Required Root Fields 1008ms
Event Format.Event Uuid Is Valid 1008ms
Event Format.Event Timestamp Is Rfc3339 1009ms
Event Format.Distinct Id Is String 1008ms
Event Format.Distinct Id At Root Not Properties 1008ms
Event Format.Custom Properties Preserved 1009ms
Event Format.Set Properties Preserved 1008ms
Event Format.Set Once Properties Preserved 1009ms
Event Format.Groups Properties Preserved 1008ms
Event Format.Sdk Generates Uuid If Not Provided 1008ms
Event Format.Event Has Required Root Fields Batch 1012ms
Event Format.Event Uuid Is Valid Batch 1012ms
Event Format.Event Timestamp Is Rfc3339 Batch 1012ms
Event Format.Distinct Id Is String Batch 1012ms
Event Format.Distinct Id At Root Not Properties Batch 1011ms
Event Format.Custom Properties Preserved Batch 1012ms
Event Format.Set Properties Preserved Batch 1012ms
Event Format.Set Once Properties Preserved Batch 1013ms
Event Format.Groups Properties Preserved Batch 1012ms
Event Format.Sdk Generates Uuid If Not Provided Batch 1012ms
Batch Behavior.Multiple Events In Single Batch 1507ms
Batch Behavior.Batch Envelope Smoke 1014ms
Batch Behavior.Flush With No Events Sends Nothing 1005ms
Batch Behavior.Flush At Triggers Batch 1507ms
Batch Behavior.Created At Reflects Batch Creation Time 1011ms
Deduplication.Generates Unique Uuids 1507ms
Deduplication.Different Events Same Content Different Uuids 1506ms
Deduplication.Preserves Uuid On Retry 7516ms
Deduplication.Preserves Timestamp On Retry 7506ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 7512ms
Deduplication.No Duplicate Events In Batch 1507ms
Header Behavior On Retry.Attempt Header Starts At One 1009ms
Header Behavior On Retry.Attempt Header Increments On Retry 14515ms
Header Behavior On Retry.Request Id Preserved On Retry 7515ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3515ms
Header Behavior On Retry.Request Timestamp Changes On Retry 7514ms
Response Format Validation.Success Response Has Uuid Keyed Results 1005ms
Response Format Validation.Success Response Has Ok For Each Event 1506ms
Response Format Validation.Success No Retry After When All Ok 1507ms
Response Format Validation.Success Retry After Present When Retry Events 2509ms
Response Format Validation.Success No Retry After When Drop Only 1507ms
Response Format Validation.Response Echoes Request Id 1009ms
Retry Behavior.Retries On 408 7514ms
Retry Behavior.Retries On 500 7508ms
Retry Behavior.Retries On 503 9514ms
Retry Behavior.Retries On 504 7512ms
Retry Behavior.Retryable Errors Have Retry After 4513ms
Retry Behavior.Respects Retry After On Retryable Error 12516ms
Retry Behavior.Does Not Retry On 400 3503ms
Retry Behavior.Does Not Retry On 401 3508ms
Retry Behavior.Does Not Retry On 402 3507ms
Retry Behavior.Does Not Retry On 413 3506ms
Retry Behavior.Does Not Retry On 415 3508ms
Retry Behavior.Non Retryable Errors Have No Retry After 3508ms
Retry Behavior.Implements Backoff 23520ms
Retry Behavior.Max Retries Respected 23520ms
Partial Batch Handling.Handles 200 Full Success 3012ms
Partial Batch Handling.Handles 200 With All Ok 4508ms
Partial Batch Handling.Does Not Retry Dropped Events 4508ms
Partial Batch Handling.Does Not Retry Limited Events 4506ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 7515ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 7512ms
Partial Batch Handling.Retries Only Retry Events From Partial 7508ms
Partial Batch Handling.Partial Retry Preserves Uuids 7515ms
Partial Batch Handling.Partial Retry Attempt Header Increments 7506ms
Partial Batch Handling.Partial Retry Request Id Preserved 7516ms
Partial Batch Handling.Respects Retry After On Partial 9512ms
Partial Batch Handling.Unknown Result Treated As Terminal 4506ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 4508ms
Compression.Sends Gzip Content Encoding 1007ms
Compression.No Content Encoding When Disabled 1008ms
Compression.Compressed Body Is Decompressible 1009ms
Error Handling.Does Not Retry On Unknown 4Xx 3508ms
Event Options.Cookieless Mode Override 1007ms
Event Options.Disable Skew Correction Override 1008ms
Event Options.Process Person Profile Override 1008ms
Event Options.Product Tour Id Override 1009ms
Event Options.Unset Options Omitted 1008ms
Event Options.Options Override In Batch 1012ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 1008ms
Geoip And Historical Migration.Historical Migration Set In Body 1008ms
Geoip And Historical Migration.Historical Migration Absent By Default 1008ms

Feature_Flags Tests

17/17 tests passed

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

@greptile-apps

greptile-apps Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "chore: add changeset for module-level me..." | Re-trigger Greptile

Generated-By: PostHog Code
Task-Id: 470062dd-05c0-40bf-bfa3-bc89b194121e

Copy link
Copy Markdown
Contributor Author

sdk-dustin review — single pass

Fully automated AI review; comments were not individually reviewed by a human before posting. Applied sdk-dustin-code-review + sdk-dustin-sdk-review (single pass + calibration, per author request — no fix loop needed).

Verdict

APPROVE (agent pre-review; Client Libraries review still required) — no BLOCKING/IMPORTANT findings. One design question flagged below for a deliberate call before this ships in a minor release.

Existing supported workaround / API necessity

  • Desired outcome: module-configured apps (posthog.api_key = ... + implicit setup()) pass the metrics config so series don't ship service.name='unknown_service'.
  • Mechanisms searched: all module attrs mirrored into setup(); direct client construction; post-hoc mutation of default_client.
  • Strongest workaround: posthog.default_client = Client(api_key, metrics={...}) — validated against the checkout, but it bypasses setup()'s wiring (disabled/debug/before_send sync with module attrs), so workaround exists but has meaningful gaps.
  • Conclusion: the addition follows the SDK's uniform convention (every Client kwarg is exposed as a same-named module setting); justified. But see the naming flag.

Review comment drafts

[P2/design] posthog.metrics as a config attr spends the natural name of a future module-level metrics API.
posthog/__init__.py:381. The module exposes client APIs as proxy functions (posthog.capture(...), posthog.flush(...)); there is no metrics accessor yet. If one is ever added, the ergonomic, posthog-js-mirroring name is posthog.metrics.count(...) — which this attr forecloses: after this ships (minor release), posthog.metrics is publicly a Optional[dict], and posthog.metrics.count is an AttributeError on None. The kwarg-mirroring convention argues for the current name; reserving the accessor name argues for e.g. a metrics key consumed from a differently-named attr, or accepting that module-level users will always go through setup().metrics. Consider making this an explicit decision (a one-line note in the changeset would do) rather than an accident of convention.

Criteria summary

  • Backwards compatibility ✅ — pure addition; default None preserves existing behavior; snapshot updated.
  • API surface ⚠️ one new public module attr (see design flag); consistent with the established kwarg-mirroring pattern.
  • Entry-point tracing ✅ — setup() fresh-construct path passes the kwarg; repeat-setup() path applies via _metrics_config only while _metrics is None, matching the documented "until first use" contract. (The guard is belt-and-braces: config is only read at first .metrics access anyway.)
  • Performance ✅ — config plumbing only.
  • Test coverage ✅ — both paths executed locally (fresh setup + late assignment), module state restored; 36/36 suite green on this branch.
  • No throwing ✅ — invalid dicts degrade inside PostHogMetrics (hardened further by fix(metrics): harden attribute snapshots, retry backoff, and config validation #742).
  • Cross-SDK parity ✅/note — posthog-js configures metrics at init too; the naming flag above is where parity pressure will eventually appear.

Non-blocking observations

@dustinbyrne dustinbyrne left a comment

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.

recommend adding a client constructor argument for this as well

otherwise, users who don't use the default global posthog cannot set this (unless it already exists, i didn't check). if you do add it, make sure it's positioned as the last argument in the constructor for backwards compatibility

@DanielVisca

Copy link
Copy Markdown
Contributor Author

recommend adding a client constructor argument for this as well

otherwise, users who don't use the default global posthog cannot set this (unless it already exists, i didn't check). if you do add it, make sure it's positioned as the last argument in the constructor for backwards compatibility

Already there 👍🏽

@DanielVisca
DanielVisca merged commit 2d7f8cc into main Jul 21, 2026
37 checks passed
@DanielVisca
DanielVisca deleted the posthog-code/module-level-metrics-config branch July 21, 2026 20:33
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.

2 participants