Skip to content

feat: add opt-in macOS runtime metrics - #1063

Draft
marandaneto wants to merge 1 commit into
mainfrom
feat/macos-runtime-metrics
Draft

marandaneto wants to merge 1 commit into
mainfrom
feat/macos-runtime-metrics

Conversation

@marandaneto

Copy link
Copy Markdown
Member

💡 Motivation and Context

The metrics API currently requires applications to collect and submit process measurements themselves. This adds opt-in automatic runtime metrics on macOS without adding dependencies.

from posthog import Client

client = Client(
    "<project_api_key>",
    metrics={"capture_runtime_metrics": True},
)

Sampling starts when the client is created and uses flush_interval, which defaults to 10 seconds. It also runs with sync_mode=True. shutdown() collects a final sample, flushes, and stops the timer. Other platforms warn and skip automatic collection. The feature is disabled by default.

The collector follows the OpenTelemetry process and CPython runtime conventions for the metrics it implements:

  • process.cpu.time and process.cpu.utilization, split by cpu.mode.
  • process.memory.usage for current RSS and process.memory.utilization for RSS divided by total physical RAM. The latter is not utilization against a container limit.
  • process.thread.count for native threads, including threads created by C extensions.
  • cpython.gc.collections, cpython.gc.collected_objects, and cpython.gc.uncollectable_objects, split by generation. These measure collection activity, not heap size or GC pauses.

Two custom metrics supplement these conventions. app.process.cpu.percent treats 100% as one busy core. app.process.cpu.ctx_switch.total reports combined context switches because the native reader does not provide the voluntary/involuntary split required by the standard metric.

Only the current process is measured, not its children or the host as a whole. Forked workers get independent identities and CPU baselines. Automatic observations use cumulative sums where appropriate, while manual counts, gauges, and histograms keep their existing behavior. Collection uses the existing transport and before_send hook. The example menu includes a 60-second runtime metrics demo.

No published PostHog SDK spec currently defines automatic runtime metrics. This is a new metrics configuration option.

💚 How did you test it?

  • Full test suite: 4,654 passed, 16 skipped.
  • Focused runtime, metrics, and fork suites: 120 passed.
  • Ruff formatting and lint, baseline-filtered mypy, warning-free import, and public API snapshot checks passed.
  • Native macOS collection and local HTTP exports were checked against the OTLP protobuf schema. All ten metric names and 18 data points per complete sample were verified.
  • Verified native imports in the generated posthoganalytics mirror.
  • Controlled mutations confirmed that tests detect an incorrect memory utilization calculation, added rather than replaced cumulative observations, and incorrect OTLP temporality.
  • Ran real in-process workloads and verified ingestion in PostHog. The dashboard has one saved insight per metric, using Last 1 hour and 15-second intervals. Counters are charted as rates.
  • Isolated autoreview passed for commit de1c6209f4254aa359a8c2bab8402230e74ef433 with no actionable findings.

Dashboard

Python Runtime Metrics dashboard

📝 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

  • Added a minor Sampo changeset in .sampo/changesets/.

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Implemented with Pi, using Git, GitHub CLI, uv, PostHog tools, and native browser automation. The user directed the scope and chose dependency-free macOS collection with OpenTelemetry metric semantics. Profiling, host monitoring, additional platforms, and external runtime dependencies are not included. An isolated Pi autoreview checked the final branch diff. Human review is still required.

Pi session: 01a13c7d-7fef-7004-b65a-26fde3f09a6e (local session, not publicly shared).

@marandaneto marandaneto self-assigned this Oct 15, 2026
@github-actions

github-actions Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-15T01:27:37.476966+00:00
Duration: 260110ms

✅ 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 ✅ 519ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 513ms
Required Headers.Has Authorization Bearer Header ✅ 511ms
Required Headers.Has Content Type Json ✅ 514ms
Required Headers.Has Posthog Sdk Info Format ✅ 512ms
Required Headers.Has Posthog Attempt Header ✅ 511ms
Required Headers.Has Posthog Request Id ✅ 511ms
Required Headers.Has Posthog Request Timestamp ✅ 512ms
Required Headers.Has User Agent ✅ 511ms
Body Format.Body Has Created At And Batch ✅ 512ms
Body Format.No Api Key In Body ✅ 510ms
Body Format.No Sent At In Body ✅ 511ms
Event Format.Event Has Required Root Fields ✅ 512ms
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 ✅ 511ms
Event Format.Distinct Id At Root Not Properties ✅ 511ms
Event Format.Custom Properties Preserved ✅ 513ms
Event Format.Set Properties Preserved ✅ 511ms
Event Format.Set Once Properties Preserved ✅ 512ms
Event Format.Groups Properties Preserved ✅ 510ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 512ms
Event Format.Event Has Required Root Fields Batch ✅ 513ms
Event Format.Event Uuid Is Valid Batch ✅ 515ms
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 ✅ 514ms
Event Format.Set Properties Preserved Batch ✅ 521ms
Event Format.Set Once Properties Preserved Batch ✅ 515ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 515ms
Batch Behavior.Multiple Events In Single Batch ✅ 519ms
Batch Behavior.Batch Envelope Smoke ✅ 517ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 506ms
Batch Behavior.Flush At Triggers Batch ✅ 1013ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 512ms
Deduplication.Generates Unique Uuids ✅ 518ms
Deduplication.Different Events Same Content Different Uuids ✅ 515ms
Deduplication.Preserves Uuid On Retry ✅ 6521ms
Deduplication.Preserves Timestamp On Retry ✅ 6520ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6524ms
Deduplication.No Duplicate Events In Batch ✅ 520ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 514ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13528ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6517ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6516ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 514ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 516ms
Response Format Validation.Success No Retry After When All Ok ✅ 518ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1517ms
Response Format Validation.Success No Retry After When Drop Only ✅ 513ms
Response Format Validation.Response Echoes Request Id ✅ 511ms
Retry Behavior.Retries On 408 ✅ 6522ms
Retry Behavior.Retries On 500 ✅ 6522ms
Retry Behavior.Retries On 503 ✅ 8524ms
Retry Behavior.Retries On 504 ✅ 6520ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3517ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11521ms
Retry Behavior.Does Not Retry On 400 ✅ 2515ms
Retry Behavior.Does Not Retry On 401 ✅ 2516ms
Retry Behavior.Does Not Retry On 402 ✅ 2513ms
Retry Behavior.Does Not Retry On 413 ✅ 2519ms
Retry Behavior.Does Not Retry On 415 ✅ 2516ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2513ms
Retry Behavior.Implements Backoff ✅ 22528ms
Retry Behavior.Max Retries Respected ✅ 22540ms
Partial Batch Handling.Handles 200 Full Success ✅ 2513ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3520ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3519ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3519ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6523ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6518ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6525ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6525ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6517ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8523ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3518ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3521ms
Compression.Sends Gzip Content Encoding ✅ 511ms
Compression.No Content Encoding When Disabled ✅ 511ms
Compression.Compressed Body Is Decompressible ✅ 511ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2514ms
Event Options.Cookieless Mode Override ✅ 511ms
Event Options.Disable Skew Correction Override ✅ 511ms
Event Options.Process Person Profile Override ✅ 510ms
Event Options.Product Tour Id Override ✅ 513ms
Event Options.Unset Options Omitted ✅ 511ms
Event Options.Options Override In Batch ✅ 515ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 511ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 512ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 515ms

Capture_Ai Tests

✅ 5/5 tests passed

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

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 ✅ 8ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 10ms
Request Payload.Flags Request Omits Authorization Header ✅ 12ms
Request Payload.Token In Flags Body Matches Init ✅ 11ms
Request Payload.Groups Round Trip ✅ 10ms
Request Payload.Groups Default To Empty Object ✅ 9ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 10ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 9ms
Request Lifecycle.No Flags Request On Init Alone ✅ 4ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 510ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 17ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 11ms
Retry Behavior.Retries Flags On 502 ✅ 314ms
Retry Behavior.Retries Flags On 504 ✅ 317ms
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 ✅ 80ms
Versioned Boolean Matching.Matching Version 1 ✅ 78ms
Versioned Boolean Matching.Matching Version 2 ✅ 79ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 55ms

@posthog posthog Bot 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.

PostHog Review · Standard · reviewed de1c620: 1 Must fix, 2 Should fix.

This is the only automatic review while this pull request is a draft. Comment @posthog review to review new changes sooner. Otherwise, a review of the new changes runs when you mark it ready for review.

Comment on lines +501 to +504
self._collect_runtime_metrics()
try:
with self._flush_lock:
self._do_flush()

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 · Prevent overlapping runtime timer flushes

When exports take longer than flush_interval, _collect_runtime_metrics() arms another timer before the current export finishes. Subsequent ticks accumulate threads waiting on _flush_lock, and those queued flushes send immediately after failures, bypassing _do_flush() retry backoff. Keep one timer flush in flight and defer rearming until it completes.

Comment on lines +429 to +431
self._runtime_metrics = _MacOSProcessMetrics()
with self._lock:
self._arm_flush_timer()

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 · Serialize runtime collector startup with shutdown

When late module setup() enables runtime metrics concurrently with shutdown(), shutdown can finish while _MacOSProcessMetrics() initializes. Startup then installs the collector and arms its timer after _stop_runtime_metrics() has finished, so the closed client continues collecting and exporting. Serialize startup and stop under _runtime_lock and recheck lifecycle state.

"process.pid": self._pid,
"process.runtime_id": uuid4().hex,
}
self.start_time_ms = int(time() * 1000)

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 · Align cumulative counter values with their start timestamp

When collection starts after the process has consumed CPU or performed GC, _reset() declares collection startup as the cumulative start, but collect() exports lifetime totals. OTLP interprets the initial interval as accumulating from zero, attributing pre-start work to that interval and inflating its rates. Use the actual counter start or subtract initialization baselines.

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