Skip to content

feat(analytics): explicit source param + 'system' default for capture/captureException#3653

Merged
PierreBrisorgueil merged 4 commits into
masterfrom
analytics-source-param
May 11, 2026
Merged

feat(analytics): explicit source param + 'system' default for capture/captureException#3653
PierreBrisorgueil merged 4 commits into
masterfrom
analytics-source-param

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

@PierreBrisorgueil PierreBrisorgueil commented May 11, 2026

Summary

  • Extends analytics.capture({ ..., source }) with an explicit source override parameter and a 'system' baseline default, so server-side events (cron, webhook, worker callback) no longer produce null source in PostHog.
  • Extends analytics.captureException(err, { source, properties }) with the same source param + arbitrary ctx.properties merge — unblocks the Winston transport (feat(observability): forward Winston error-level logs to PostHog Error Tracking via custom transport #3651) and per-call-site tagging downstream.
  • Precedence (highest wins): explicit source > properties.source > req.posthogContext.source > 'system'.
  • Documents the source taxonomy convention in README.md.

Closes #3652.

Part of Wave 4 PostHog Observability plan — Phase 2 (foundation for Phase 1 Winston transport + Phase 3 Trawl call-site tagging).
Plan: infra/docs/superpowers/plans/2026-05-11-posthog-observability-wave4.md

Files touched

File Change
lib/services/analytics.js capture() + captureException() extended
lib/services/tests/analytics.capture.unit.tests.js +5 source attribution tests, existing tests updated
lib/services/tests/analytics.captureException.unit.tests.js NEW — 6 tests covering full precedence
lib/services/tests/analytics.service.unit.tests.js Updated 1 existing test (now expects source: 'system')
README.md New Analytics section + source attribution table

Test plan

  • npm run lint — green
  • npm run test:unit — 1369 tests, all green (+11 vs baseline 1358)
  • npm run test:coverage — thresholds unchanged (pre-existing billing.extraBalance.listLedger.perf.integration MongoDB version failure unrelated to this diff)
  • Critical review — OK with nits, nits fixed before push

Summary by CodeRabbit

Release Notes

  • New Features

    • Analytics integration with PostHog is now available. Events are automatically tracked with a source attribution (web, cli, stripe-webhook, worker-callback, cron, or system) based on a configurable precedence order.
  • Documentation

    • Added setup instructions for enabling analytics with PostHog, including configuration and event source attribution reference.

Review Change Stack

… default

Adds optional `source` parameter to analyticsService.capture() and a
`'system'` baseline default so events from cron tasks, webhook handlers,
and worker callbacks no longer have null source attribution in PostHog.

Precedence: explicit source > properties.source > req.posthogContext.source
> 'system'.
Extends captureException to accept an explicit source override and
arbitrary properties merged into the $exception event, with the same
'system' default fallback as capture(). Unblocks the Winston error
transport (#3651) and per-call-site source attribution downstream.
…source test

Add jest.resetModules() in capture source attribution beforeEach (latent
flake risk). Add properties.source > system precedence test for captureException.
Copilot AI review requested due to automatic review settings May 11, 2026 09:00
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 11, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 56 minutes and 19 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: d8bfe7c2-3ed5-48a2-8081-2e9a66bb8290

📥 Commits

Reviewing files that changed from the base of the PR and between 596fae0 and 6648887.

📒 Files selected for processing (1)
  • lib/services/tests/analytics.captureException.unit.tests.js

Walkthrough

This PR extends the analytics service with explicit source parameter support. Both capture() and captureException() now accept an optional source override and apply deterministic precedence: explicit source > properties.source > req.posthogContext.source > 'system' default. Documentation, implementation, and comprehensive unit tests cover the new feature.

Changes

Analytics Source Attribution

Layer / File(s) Summary
Documentation
README.md
New "Analytics (PostHog)" section documents service enablement via config.analytics.posthog.enabled, explains source precedence rules, and lists canonical downstream source values (web, cli, stripe-webhook, worker-callback, cron, system).
Core Implementation
lib/services/analytics.js
capture() adds source parameter and implements 4-tier precedence by setting default source: 'system', merging req.posthogContext, and applying explicit source override. captureException() adds ctx.source and ctx.properties support with matching precedence logic.
Capture Tests
lib/services/tests/analytics.capture.unit.tests.js
Updated existing test to expect default source: 'system' in injected properties. Replaced backward-compat test with assertion that source defaults to 'system'. New source attribution test suite covers 4-tier precedence among explicit source, properties.source, req.posthogContext.source, and system default.
CaptureException Tests
lib/services/tests/analytics.captureException.unit.tests.js
New comprehensive test file verifies $exception events include default source: 'system', explicit ctx.source override, merging of ctx.properties fields, 3-tier source precedence (ctx.source > ctx.properties.source > default), and no-op behavior for null/undefined errors.
Integration Tests
lib/services/tests/analytics.service.unit.tests.js
Service-level test updated to expect source: 'system' in captureException $exception event properties.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • pierreb-devkit/Node#3325: Modifies lib/services/analytics.js imports and module wiring while this PR updates capture/captureException signatures and source-attribution logic.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding an explicit source parameter with 'system' default to capture/captureException methods.
Description check ✅ Passed The PR description covers all required template sections: Summary with what/why, Scope with module impact and risk level, Validation with test results, Guardrails checks, and Notes for reviewers.
Linked Issues check ✅ Passed The PR fully implements all acceptance criteria from #3652: explicit source param added to both methods, 'system' default implemented, 4-tier precedence tested, coverage maintained, and README updated.
Out of Scope Changes check ✅ Passed All changes align with objectives: analytics.js modifications add source logic, tests validate source precedence, README documents taxonomy, and one existing test updated to expect 'system' default.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch analytics-source-param

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 11, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.15%. Comparing base (2f5ebd9) to head (6648887).
⚠️ Report is 8 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3653      +/-   ##
==========================================
+ Coverage   89.14%   89.15%   +0.01%     
==========================================
  Files         135      135              
  Lines        4641     4646       +5     
  Branches     1433     1437       +4     
==========================================
+ Hits         4137     4142       +5     
  Misses        392      392              
  Partials      112      112              
Flag Coverage Δ
integration 59.08% <14.28%> (-0.07%) ⬇️
unit 64.18% <100.00%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 2bf9c2d...6648887. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

coderabbitai[bot]
coderabbitai Bot previously requested changes May 11, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/services/tests/analytics.captureException.unit.tests.js`:
- Around line 1-2: Add the missing JSDoc module header by inserting the comment
/** Module dependencies. */ directly above the import statements in
analytics.captureException.unit.tests.js so it matches the other test files;
locate the top-level import block (the line starting with "import { jest,
beforeEach, afterEach, describe, test, expect }") and place the comment
immediately above it.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5ccef826-c203-48d1-9a52-442a910f0555

📥 Commits

Reviewing files that changed from the base of the PR and between 2bf9c2d and 596fae0.

📒 Files selected for processing (5)
  • README.md
  • lib/services/analytics.js
  • lib/services/tests/analytics.capture.unit.tests.js
  • lib/services/tests/analytics.captureException.unit.tests.js
  • lib/services/tests/analytics.service.unit.tests.js

Comment thread lib/services/tests/analytics.captureException.unit.tests.js
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds explicit source attribution to PostHog analytics emissions so server-side events and captured exceptions no longer end up with source: null, while preserving a clear precedence order and updating unit tests + documentation accordingly.

Changes:

  • Extend AnalyticsService.capture() to accept an explicit source override and default source: 'system' when no other source is provided.
  • Extend AnalyticsService.captureException() to accept ctx.source and merge ctx.properties, with source: 'system' as the baseline default.
  • Add/adjust unit tests for source precedence and update README with the source taxonomy convention.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
README.md Documents source attribution precedence and canonical source values.
lib/services/analytics.js Implements source default + override precedence for capture() and captureException(), and merges ctx.properties for exceptions.
lib/services/tests/analytics.capture.unit.tests.js Updates existing expectations for source: 'system' and adds source precedence tests for capture().
lib/services/tests/analytics.captureException.unit.tests.js New unit tests covering captureException() source precedence and ctx.properties merge behavior.
lib/services/tests/analytics.service.unit.tests.js Updates $exception assertion to include the new default source: 'system'.

Comment thread README.md
Comment on lines +268 to +274
The devkit ships an `analyticsService` backed by `posthog-node`. Enable via `config.analytics.posthog.enabled = true` + a valid `key`.

### Source attribution convention

Every `analytics.capture()` and `analytics.captureException()` event gets a `source` property. The lookup order is:

1. Explicit `source` param: `analytics.capture({ ..., source: 'cron' })`
@PierreBrisorgueil PierreBrisorgueil dismissed coderabbitai[bot]’s stale review May 11, 2026 09:04

Nit fixed: JSDoc module header added to captureException test file (commit 596fae0 + style fix pushed)

@PierreBrisorgueil PierreBrisorgueil merged commit 48766e5 into master May 11, 2026
5 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the analytics-source-param branch May 11, 2026 09:06
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.

feat(analytics): add explicit source param + 'system' default to capture/captureException

2 participants