Skip to content

Instrument application with PostHog - #21

Open
posthog[bot] wants to merge 1 commit into
mainfrom
posthog/wizard-01a202e1f61e
Open

posthog[bot] wants to merge 1 commit into
mainfrom
posthog/wizard-01a202e1f61e

Conversation

@posthog

@posthog posthog Bot commented Nov 22, 2026

Copy link
Copy Markdown

PostHog setup report — FastAPI risk engine

PostHog is installed and initialized for the FastAPI risk engine, with request-scoped identity context, five completed-operation events, automatic exception capture, dedicated OTLP log export, and a starter dashboard.

Installed and initialized

  • Declared the Python posthog SDK and the OpenTelemetry log-export dependencies in requirements.txt.
  • The final dependency installation resolved PostHog 7.91.4 and OpenTelemetry 1.45.2 without resolver errors or peer warnings.
  • layer6/api.py creates one guarded, process-wide Posthog client from POSTHOG_PROJECT_TOKEN and POSTHOG_HOST, registers PosthogASGIMiddleware(client=posthog_client), and flushes/shuts down safely during application lifespan termination and process exit.
  • .env.example documents the required POSTHOG_PROJECT_TOKEN and POSTHOG_HOST variables. The real project environment has both keys configured.
  • The integration was compile-verified with .venv/bin/python3 -m compileall layer6/api.py. Dependency installation also completed successfully. No project type checker, linter, formatter, or corresponding script was available, and the runtime disallowed pip check.

Events instrumented

These events are implemented at successful completion paths only. The run verified their code and dashboard queries; it did not observe any event arrive in PostHog.

Event What it measures File
asset_risk_assessment_completed A single-asset climate risk assessment completed, including whether the response was served from cache. layer6/api.py
portfolio_risk_assessment_completed A portfolio climate risk assessment completed. layer6/api.py
risk_stress_test_completed A single-asset risk stress test completed. layer6/api.py
loss_histogram_generated A loss-distribution histogram was generated for an asset risk assessment. layer6/api.py
risk_simulation_completed A climate-event risk simulation completed. layer6/api.py

The guarded capture helper preserves successful engine responses if analytics delivery fails. Event properties are non-PII operational metadata, including scenario, asset type, cache status, result counts, duration, and target year; they do not include asset IDs, coordinates, country codes, asset values, or user-entered content.

Identification and attribution

Identification is wired through FastAPI's PostHog ASGI middleware rather than per-route identify calls. For every request, the middleware reads X-PostHog-Distinct-ID and X-PostHog-Session-ID, creates request context, and applies that identity/session to custom captures and automatically captured exceptions.

Follow-up issue: gateway identity propagation

The separately maintained Go gateway owns end-user identity and was outside this project's scope, so its forwarding behavior was not verified. It must forward a stable internal user ID (never an email) in X-PostHog-Distinct-ID, plus X-PostHog-Session-ID, on each proxied request. Without that propagation, events and exceptions can be unattributed or fragmented across identities, reducing the reliability of adoption and funnel analysis.

Error tracking

Error tracking is configured through the shared client with enable_exception_autocapture=True and the single global PosthogASGIMiddleware error boundary in layer6/api.py. Uncaught route exceptions should inherit request context without duplicate manual exception capture. The run verified the implementation but did not run the service or observe an exception arrive in PostHog.

AI Observability

AI Observability was not added because this repository has no production LLM call site. The legacy /analyze and /chat engine handlers return HTTP 410; the actual LLM routes are owned by an external Go API gateway that was not available in this project. No provider SDK, manual $ai_generation capture, AI environment configuration, or dependency was introduced.

When the gateway source is available, instrument its real provider calls there and make an explicit privacy-mode decision. Delivery is unconfirmed because no generation was run or observed.

Log capture

Configured guarded Python OTLP log export in layer6/api.py. The exporter uses the existing POSTHOG_PROJECT_TOKEN and POSTHOG_HOST configuration and is attached only to the dedicated meteorium.posthog.logs logger, so only purpose-written lines added in this run leave the service. It emits risk_engine_ready at successful engine initialization and asset_risk_assessment_completed after successful /risk/asset responses, with safe operational metadata only. The provider is shut down during FastAPI lifespan shutdown; startup does not wait for delivery.

Install the required OpenTelemetry packages before verification, then start the service and make a successful authenticated POST /risk/asset; search PostHog Logs for asset_risk_assessment_completed. Delivery is unverified until observed. To export existing application logs later, explicitly attach the same LoggingHandler to the root logger rather than the dedicated logger.

Starter analytics dashboard

Created and verified Analytics basics (wizard), with five 30-day trends for completed asset and portfolio risk assessments, stress tests, histogram generation, and simulations. The asset and portfolio tiles were corrected to query the current integration event names. The dashboard is ready to populate when the service begins sending production traffic.

All five dashboard tiles executed successfully with no warnings, but currently return zero events. This is expected until the newly instrumented service receives traffic; it is not evidence that any event has been delivered.

Build conflicts

No unresolved build conflict was reported. The only unavailable verification was pip check, which the runtime disallowed. No project type checker, linter, formatter, or associated script is declared, so those checks could not be run.

Next steps

  1. Deploy with the documented PostHog environment variables in every target environment.
  2. Confirm the Go gateway sends the stable request identity and session headers to this service.
  3. Exercise each completed risk-operation path in a non-production or production-safe environment, then confirm the five events and dashboard begin receiving data.
  4. Start the service and make a successful authenticated POST /risk/asset to verify the dedicated log export.
  5. Instrument the external Go gateway separately if its LLM functionality needs AI Observability.

Before you merge

  • Run the full production build and fix any generated-code errors. The wizard compile-verified layer6/api.py only; inspect the PostHog initialization, middleware, capture, and OTLP logger blocks in layer6/api.py (line numbers were not recorded by the run).
  • Run the complete test suite and update mocks or fixtures if needed for instrumented call sites in layer6/api.py (line numbers were not recorded by the run).
  • Set POSTHOG_PROJECT_TOKEN and POSTHOG_HOST from .env.example in each deployment environment and any bootstrap configuration; inspect the two variable entries in .env.example (line numbers were not recorded by the run).
  • Verify the external Go gateway forwards X-PostHog-Distinct-ID and X-PostHog-Session-ID to the middleware registration and capture paths in layer6/api.py (line numbers were not recorded by the run). Use a stable internal user ID, not an email.
  • Trigger each successful risk-operation path and confirm the matching event from .posthog-wizard-cache/.posthog-events.json appears in PostHog; inspect the corresponding capture call in layer6/api.py (line numbers were not recorded by the run).
  • Start the service and make a successful authenticated POST /risk/asset; confirm risk_engine_ready or asset_risk_assessment_completed appears in PostHog Logs. Inspect the dedicated meteorium.posthog.logs logger and /risk/asset completion log in layer6/api.py (line numbers were not recorded by the run).

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.

0 participants