Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Retire product upgrade metrics runtime

rcourtman99129d0c09a2
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 6908bfc067..cbc4f8b4e9 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -728,11 +728,12 @@ when staging a removal state, but they must not resurrect legacy
second hostname contract.
That same adjacent `internal/api/` router boundary now also keeps usage-data
controls out of lifecycle truth. Agent install, reporting, and setup surfaces
-may coexist with `/api/upgrade-metrics/*` and telemetry preview routes under
-shared licensing/auth routing, but they must not reinterpret local-only
-upgrade-event state, telemetry preview payloads, or published-release
-classification fields as enrollment evidence, agent freshness, or setup
-progress truth.
+must not depend on `/api/upgrade-metrics/*`, telemetry preview routes, or
+local-only upgrade-event state under shared licensing/auth routing. The normal
+customer product router must keep those retired commercial analytics routes
+absent, and lifecycle code must not reinterpret telemetry preview payloads or
+published-release classification fields as enrollment evidence, agent
+freshness, or setup progress truth.
That same adjacent `internal/api/` boundary now also keeps public demos from
leaking commercial state through lifecycle-adjacent surfaces. Agent install,
reporting, and setup flows may share backend helpers with billing or license
@@ -1276,10 +1277,11 @@ consume the settings-owned referral copy from
`frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts`
instead of carrying workspace-local commercial guidance or reaching back into
generic commercial presentation helpers from the hosted infrastructure route.
-Shared licensing routes under `internal/api/` may retain legacy
-`upgrade-metrics` route names for compatibility, but lifecycle-adjacent
-settings and install flows must treat them as local commercial handoff events,
-not as a reason to reintroduce default self-hosted upgrade prompts.
+Shared licensing routes under `internal/api/` must not retain normal-product
+`upgrade-metrics` route names for compatibility. Lifecycle-adjacent settings
+and install flows must treat that route family as retired local commercial
+analytics, not as a reason to reintroduce default self-hosted upgrade prompts
+or local handoff event capture.
That canonical /api/auto-register behavior now also includes hostname/IP continuity:
reruns that arrive through a different canonical host form must reuse the same
Pulse-managed node record and token instead of forking duplicate fleet entries.
@@ -1668,9 +1670,9 @@ That same shared diagnostics dependency now also assumes local commercial and
onboarding analytics stay out of user diagnostics entirely: lifecycle-adjacent
admin surfaces may consume operational diagnostics, but they must not restore
self-hosted upgrade-metric summaries or infrastructure-onboarding analytics to
-`internal/api/diagnostics.go` or the settings diagnostics panel. The local
-commercial metrics reporting routes remain API/cloud-paid admin settings
-surfaces and must not become lifecycle setup, install, or fleet-progress
+`internal/api/diagnostics.go` or the settings diagnostics panel. The retired
+local commercial metrics reporting routes must stay absent from the normal
+product API and must not become lifecycle setup, install, or fleet-progress
signals.
Lifecycle-adjacent Docker and Podman agent diagnostics are part of that same
shared backend dependency. When `internal/api/diagnostics.go` emits agent
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 3da512a8a3..5a3330e1f2 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -21,8 +21,8 @@
## Purpose
Own canonical runtime payload shapes between backend and frontend, including
-the privileged boundary between customer-safe support diagnostics and
-admin-only local commercial reporting routes.
+the trust boundary that keeps customer-safe support diagnostics and normal
+product API routes free of maintainer commercial analytics.
## Canonical Files
1. `internal/api/contract_test.go`
@@ -1810,24 +1810,21 @@ when a raw snapshot reaches the API layer without one, so
That same diagnostics boundary now explicitly excludes maintainer analytics.
`internal/api/diagnostics.go` must not serialize commercial funnel, sales
funnel, pricing/checkout conversion, or infrastructure onboarding telemetry in
-`/api/diagnostics`; local upgrade/onboarding metrics remain owned by the
-licensing/admin metrics routes and their admin gates rather than the customer
-support diagnostics contract. `frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs`
+`/api/diagnostics`; local upgrade/onboarding metrics must not reappear as
+normal product API routes, system settings fields, startup DB artifacts, or
+customer frontend state. `frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs`
now checks `internal/api/diagnostics.go` alongside the Settings diagnostics
frontend boundary through the canonical frontend audit runner, so this
admin-analytics payload class cannot return as a customer-visible diagnostics
contract.
-That same admin-analytics boundary applies to the local commercial metrics
-reporting routes themselves: `/api/upgrade-metrics/stats`,
-`/api/upgrade-metrics/health`, `/api/upgrade-metrics/config`, and
-`/api/admin/upgrade-metrics-funnel` must require admin/settings-scope access
-rather than becoming general authenticated product reads. Authenticated event
-ingestion at `/api/upgrade-metrics/events` may remain only as compatibility or
-admin-owned ingestion plumbing; customer frontend surfaces must not call it for
-pricing, checkout, paywall, commercial funnel, or infrastructure-onboarding
-signals, and must not keep customer-side commercial/onboarding metrics wrapper
-modules as a compatibility layer. Reporting and control stay on the privileged
-settings boundary.
+That same admin-analytics boundary now retires the local commercial metrics
+routes from the normal customer product API: `/api/upgrade-metrics/events`,
+`/api/upgrade-metrics/stats`, `/api/upgrade-metrics/health`,
+`/api/upgrade-metrics/config`, and `/api/admin/upgrade-metrics-funnel` must
+return `404` in normal router contracts. Customer frontend surfaces must not
+call local pricing, checkout, paywall, commercial funnel, or
+infrastructure-onboarding signals, and must not keep customer-side
+commercial/onboarding metrics wrapper modules as a compatibility layer.
That same public-demo API boundary must also hide runtime-admin operations
surfaces instead of treating them as harmless reads. Demo sessions must receive
`404` for `/api/diagnostics`, `/api/diagnostics/docker/prepare-token`, and the
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 2d9488e41f..f40aef52f3 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -526,30 +526,27 @@ runtime gating as separate unlinked claims.
grandfathered recurring customers cannot be downgraded to the partial
feature list carried by an old JWT or legacy plan row.
14. Keep self-hosted commercial funnel stage ownership out of the customer
- frontend. `pkg/licensing/conversion_events.go` and
- `pkg/licensing/conversion_store.go` may retain server/admin compatibility
- handling for local commercial reporting, while the customer frontend must
- not contain `upgradeMetrics`, `conversionEvents`, or infrastructure
- onboarding metrics wrappers or call sites at all. In-app `Plans & Billing`,
- pricing, checkout, paywall, or onboarding surfaces must not emit browser
- product events. `pulse-pro:license-server/v6_checkout.go` owns the Pulse
- Account handoff equivalents bound to `portal_handoff_id`.
+ product runtime. The customer frontend must not contain `upgradeMetrics`,
+ `conversionEvents`, or infrastructure onboarding metrics wrappers or call
+ sites at all. In-app `Plans & Billing`, pricing, checkout, paywall, or
+ onboarding surfaces must not emit browser product events, and the normal
+ self-hosted API must not register local upgrade-metrics ingestion, health,
+ config, stats, or funnel routes. `pulse-pro:license-server/v6_checkout.go`
+ owns the Pulse Account handoff equivalents bound to `portal_handoff_id`.
Pulse must not infer those portal stages from referrer state, and the
commercial service must keep those self-hosted handoffs on release track
`v6` even while the public site remains on `v5` before GA.
-15. Keep local commercial funnel reporting inside the self-hosted privacy
- boundary, not user diagnostics: local upgrade-metric summaries, daily
- buckets, surface/capability breakdowns, and infrastructure-onboarding
- analytics may remain in the dedicated local reporting/privacy path, but
- `internal/api/diagnostics.go`,
- `frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx`, and
- `frontend-modern/src/components/Settings/diagnosticsModel.ts` must not
- expose them in the customer support diagnostics payload or panel.
- The local reporting/control endpoints themselves must stay privileged:
- stats, health, config, and funnel reads must require admin plus
- settings-scope access; event ingestion may remain only for compatibility
- or admin-owned producers and must not be called by customer frontend
- interactions.
+15. Keep retired local commercial funnel reporting out of customer diagnostics,
+ settings, and product startup: `internal/api/diagnostics.go`,
+ `frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx`,
+ `frontend-modern/src/components/Settings/diagnosticsModel.ts`,
+ `internal/api/router_routes_licensing.go`, `internal/api/system_settings.go`,
+ `internal/config/config.go`, `internal/config/persistence.go`,
+ `pkg/server/server.go`, `frontend-modern/src/stores/systemSettings.ts`, and
+ `frontend-modern/src/types/config.ts` must not expose maintainer funnel,
+ pricing/checkout, upgrade-metrics, or infrastructure-onboarding analytics
+ fields, controls, routes, stores, or startup DB artifacts to normal product
+ users.
16. Keep ordinary self-hosted v6 commercial prompts opt-in. Cloud-paid runtime
may keep checkout, activation, recovery, and support-only trial plumbing
available for explicit handoffs and entitled installs, but default
@@ -810,15 +807,14 @@ filesystem read, write, rename, stat, or delete. Future licensing persistence
changes must not bypass that resolver with raw `filepath.Join(configDir, ...)`
joins or introduce caller-controlled persistence filenames.
That same local-persistence boundary also owns writable-but-not-owned runtime
-storage semantics for commercial state. `pkg/licensing/persistence.go` and
-`pkg/licensing/conversion_store.go` may harden directories they own to `0700`,
-but they must not assume they can chmod the root of a writable Kubernetes or
-container-mounted runtime data directory. When the mount root is writable but
-not owned by the Pulse process, canonical persistence must keep file-level
-secrets hardened at `0600`, validate that the resolved storage root is still
-the expected real directory rather than a symlink or other filesystem object,
-and continue operating instead of crashing just because the mount root itself
-cannot be chmod-ed.
+storage semantics for commercial state. `pkg/licensing/persistence.go` may
+harden directories it owns to `0700`, but it must not assume it can chmod the
+root of a writable Kubernetes or container-mounted runtime data directory. When
+the mount root is writable but not owned by the Pulse process, canonical
+persistence must keep file-level secrets hardened at `0600`, validate that the
+resolved storage root is still the expected real directory rather than a symlink
+or other filesystem object, and continue operating instead of crashing just
+because the mount root itself cannot be chmod-ed.
Hosted entitlement-source loading follows the same rule: `DatabaseSource` must
normalize persisted Cloud/MSP plan aliases and legacy limit keys before runtime
evaluation, but it must not fabricate a canonical `plan_version` from bare
@@ -1901,33 +1897,29 @@ live in non-release build-tagged helpers instead of shipping inside the primary
runtime service file.
The remaining cloud-paid runtime families now follow the same rule as well:
feature/limit primitives, billing and entitlement type shapes, commercial
-migration and trial flow, conversion telemetry, host lifecycle tracking, and
-public-key/build-mode boundaries should all resolve through explicit proof
-routes rather than a package-wide `pkg/licensing/` fallback.
-That same conversion-telemetry boundary now keeps self-hosted commercial
-progression out of customer-side browser analytics.
-`pkg/licensing/conversion_events.go` and `pkg/licensing/conversion_store.go`
-may own local server/admin reporting compatibility, while customer frontend
-source must not retain `upgradeMetrics`, `conversionEvents`, infrastructure
-onboarding metrics wrappers, or their call sites. The browser app must not emit
-local `pricing_viewed`, `checkout_clicked`, paywall, commercial funnel, or
-onboarding events from the in-app `Plans & Billing` plan surface.
+migration and trial flow, host lifecycle tracking, and public-key/build-mode
+boundaries should all resolve through explicit proof routes rather than a
+package-wide `pkg/licensing/` fallback.
+The retired conversion-telemetry boundary now keeps self-hosted commercial
+progression out of customer-side browser analytics and out of the compiled
+normal licensing package. Customer frontend source must not retain
+`upgradeMetrics`, `conversionEvents`, infrastructure onboarding metrics
+wrappers, or their call sites. The browser app must not emit local
+`pricing_viewed`, `checkout_clicked`, paywall, commercial funnel, or onboarding
+events from the in-app `Plans & Billing` plan surface.
`pulse-pro:license-server/v6_checkout.go` owns the Pulse Account handoff
equivalents bound to `portal_handoff_id` and the canonical checkout intent.
The browser app must not try to recreate those Pulse Account stages from
referrer state, and the commercial service must not collapse self-hosted v6
handoffs back onto the public-site release track when production public GA is
still on v5.
-That same local conversion store remains the canonical read model for
-self-hosted commercial reporting, but not for user support diagnostics:
-admin-owned reporting surfaces may read structured local funnel reports from
-`pkg/licensing/conversion_store.go`, while `/api/diagnostics` and the Settings
-support diagnostics panel must not expose pricing, checkout, conversion, or
-infrastructure-onboarding analytics. The API route boundary must preserve that
-same split: local commercial metric stats, health, config, and funnel reads are
-admin/settings-scope surfaces, while `/api/upgrade-metrics/events` remains only
-compatibility/admin-owned ingestion and must not be called by customer browser
-product interactions.
+That same retired local conversion store is no longer a normal product read
+model. `/api/diagnostics` and the Settings support diagnostics panel must not
+expose pricing, checkout, conversion, or infrastructure-onboarding analytics,
+and the normal API router must not register local commercial metric stats,
+health, config, ingestion, or funnel reads. Maintainer commercial reporting
+must live outside the self-hosted customer product runtime instead of reusing
+the Pulse settings or diagnostics surface.
Stripe checkout and subscription webhook persistence now also follows the
canonical Cloud/MSP limit rule: when paid state is granted, billing-state
writes must persist authoritative `limits.max_monitored_systems` derived from canonical
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 58682455a1..d8504bfb8a 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -1812,7 +1812,10 @@ diagnostics API, diagnostics results panel, or diagnostics payload model
reintroduce those analytics fields outside the defensive strip helper, and by
failing if production customer frontend source reintroduces the retired
commercial/onboarding analytics wrappers or `/api/upgrade-metrics/events`
-calls.
+calls. That same audit also fails if the retired conversion/funnel or metering
+packages return under the compiled product licensing path, because Settings
+support diagnostics cannot be the only customer-facing guard if the normal
+product binary still carries the maintainer analytics pipeline.
Diagnostics cards that summarize Docker and Podman agent coverage must use the
shared `docker` source-platform label from
`frontend-modern/src/utils/sourcePlatforms.ts` for their heading and body copy,
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index f1776f4a7c..c4f86cf517 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -1128,8 +1128,11 @@ The same hot-path discipline now applies to public-demo commercial reads.
Shared shells may consume the small `/api/license/runtime-capabilities`
contract for feature truth, but commercial demo routes stay hidden and the
browser must not keep retrying `/api/license/commercial-posture`,
-`/api/license/entitlements`, `/auth/license-purchase-start`, or other hidden
-commercial endpoints from performance-sensitive settings or route shells.
+`/api/license/entitlements`, `/auth/license-purchase-start`,
+`/api/upgrade-metrics/*`, `/api/admin/upgrade-metrics-funnel`, or other hidden
+commercial endpoints from performance-sensitive settings or route shells. The
+retired local commercial analytics routes must not become route-shell polling
+fallbacks or background bootstrap work after their normal product API removal.
Workloads and infrastructure summary consumers now also keep null-tolerant read
models on the shared hot path. Guest rows, stacked bars, anomaly summaries, and
resource detail mappers may accept partial platform metadata or undefined
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index b88c313b9f..d438458359 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -2324,26 +2324,6 @@
"pulse-pro:license-server/v6_checkout_test.go"
]
},
- {
- "id": "conversion-telemetry-pipeline",
- "label": "conversion telemetry pipeline proof",
- "match_prefixes": [
- "pkg/licensing/conversion_",
- "pkg/licensing/metering/"
- ],
- "match_files": [],
- "allow_same_subsystem_tests": false,
- "test_prefixes": [],
- "exact_files": [
- "pkg/licensing/conversion_api_helpers_test.go",
- "pkg/licensing/conversion_config_test.go",
- "pkg/licensing/conversion_events_test.go",
- "pkg/licensing/conversion_metrics_test.go",
- "pkg/licensing/conversion_quality_test.go",
- "pkg/licensing/conversion_recorder_test.go",
- "pkg/licensing/conversion_store_queryplan_test.go"
- ]
- },
{
"id": "host-lifecycle-tracking",
"label": "host lifecycle tracking proof",
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 9d3f69bd93..0b74253ac3 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -193,9 +193,8 @@ proxy for normal self-hosted v6 installs.
That shared settings boundary now also has an explicit split of responsibilities:
`frontend-modern/src/components/Settings/useSystemSettingsState.ts` remains the
canonical owner for customer-visible telemetry and auth/privacy runtime state,
-while internal commercial prompt and local-upgrade-metrics compatibility stay
-below the customer settings panel in the backend/settings-store compatibility
-path,
+while maintainer commercial analytics controls stay out of customer settings
+payloads and frontend settings state entirely.
`frontend-modern/src/components/Settings/GeneralSettingsPanel.tsx` stays a
customer-facing presentation boundary for outbound telemetry controls and
`frontend-modern/src/components/Settings/useSettingsSystemPanels.tsx` may only
@@ -207,14 +206,17 @@ That shell split now also applies to tab-save coordination: the dedicated
decide which settings tabs participate in shell-level save prompts, but it must
remain pure shell metadata. Telemetry and auth/privacy state transitions stay
canonically owned by `frontend-modern/src/components/Settings/useSystemSettingsState.ts`,
-while local commercial compatibility state remains an internal store/backend
-concern in `frontend-modern/src/stores/systemSettings.ts`, not settings
-navigation metadata or other frontend-primitives owners.
-Retired local-upgrade-metrics compatibility must not become customer-side
-commercial analytics emission; browser product surfaces must not POST pricing,
-checkout, paywall, funnel, or onboarding signals to `/api/upgrade-metrics/events`,
-and customer frontend source must not keep `upgradeMetrics`, `conversionEvents`,
-or infrastructure onboarding metrics wrappers as compatibility imports.
+and maintainer analytics state must not be carried by
+`frontend-modern/src/stores/systemSettings.ts`, settings navigation metadata, or
+other frontend-primitives owners.
+Retired local-upgrade-metrics compatibility must not become customer-side or
+runtime commercial analytics emission: browser product surfaces must not POST
+pricing, checkout, paywall, funnel, or onboarding signals to
+`/api/upgrade-metrics/events`; the normal product API must not register
+`/api/upgrade-metrics/*` or `/api/admin/upgrade-metrics-funnel`; product startup
+must not open or migrate `upgrade_metrics.db`; and customer frontend source must
+not keep `upgradeMetrics`, `conversionEvents`, or infrastructure onboarding
+metrics wrappers as compatibility imports.
The security transport surfaces remain intentionally shared with
`api-contracts`: token, auth, and telemetry settings payloads are still API
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index c4d96606fc..3f6cab3e1e 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -441,6 +441,11 @@ state.
bypass the shared secure callback policy that limits self-hosted commercial
return URLs to HTTPS instance origins or direct-loopback HTTP and keeps
hosted commercial follow-up fetches on the restricted outbound client.
+ The same adjacent commercial boundary owns the retired
+ `/api/upgrade-metrics/*` and `/api/admin/upgrade-metrics-funnel` route
+ family: storage and recovery flows must not synthesize recovery-local
+ stats, health, config, or funnel-report fallbacks when those routes are
+ absent from the normal customer product API.
That same adjacent commercial boundary also owns the plan-owned callback
framing for those routes: storage and recovery may coexist beside
`/settings/system/billing/plan`, but they must treat `Plans` and
@@ -1949,7 +1954,10 @@ only and must not become storage/recovery prompt, identity, or restore state.
Local commercial metrics reporting routes are part of the same adjacent
API/cloud-paid admin settings boundary: storage and recovery surfaces must not
read stats, health, config, or funnel reports as customer-visible recovery,
-storage-health, or setup state.
+storage-health, or setup state. In the normal customer product API those
+retired local commercial analytics routes must stay unregistered, so storage
+and recovery cannot use their absence as a reason to synthesize recovery-local
+commercial reporting or fallback state.
That same shared `internal/api/` dependency now also assumes adjacent
commercial helper surfaces speak in monitored-system terms: recovery- or
storage-adjacent API wiring may consume the canonical monitored-system ledger
diff --git a/frontend-modern/scripts/__tests__/settings-diagnostics-boundary-audit.test.mjs b/frontend-modern/scripts/__tests__/settings-diagnostics-boundary-audit.test.mjs
index 69b1a69385..e31aa55d0b 100644
--- a/frontend-modern/scripts/__tests__/settings-diagnostics-boundary-audit.test.mjs
+++ b/frontend-modern/scripts/__tests__/settings-diagnostics-boundary-audit.test.mjs
@@ -12,10 +12,23 @@ function writeFixture(root, repoRoot, files) {
const requiredFiles = {
[path.join(repoRoot, 'internal', 'api', 'diagnostics.go')]:
'package api\n\ntype DiagnosticsInfo struct {}\n',
+ [path.join(repoRoot, 'internal', 'api', 'router_routes_licensing.go')]:
+ 'package api\n\nfunc (r *Router) registerOrgLicenseRoutesGroup() {}\n',
+ [path.join(repoRoot, 'internal', 'api', 'system_settings.go')]:
+ 'package api\n\ntype SystemSettingsHandler struct {}\n',
+ [path.join(repoRoot, 'internal', 'config', 'config.go')]:
+ 'package config\n\ntype Config struct {}\n',
+ [path.join(repoRoot, 'internal', 'config', 'persistence.go')]:
+ 'package config\n\ntype SystemSettings struct {}\n',
+ [path.join(repoRoot, 'pkg', 'server', 'server.go')]: 'package server\n\nfunc Run() {}\n',
[path.join(root, 'src', 'components', 'Settings', 'DiagnosticsResultsPanel.tsx')]:
'export function DiagnosticsResultsPanel() { return null; }\n',
[path.join(root, 'src', 'components', 'Settings', 'diagnosticsModel.ts')]:
'export interface DiagnosticsInfo { version: string; }\n',
+ [path.join(root, 'src', 'stores', 'systemSettings.ts')]:
+ 'export function updateSystemSettingsFromResponse() {}\n',
+ [path.join(root, 'src', 'types', 'config.ts')]:
+ 'export interface SystemConfig { autoUpdateEnabled: boolean; }\n',
...files,
};
@@ -83,6 +96,73 @@ export function stripInternalAnalyticsDiagnosticsFields(payload) {
expect(collectUserDiagnosticsInternalAnalyticsFindings({ root, repoRoot })).toEqual([]);
});
+ it('reports commercial analytics routes, stores, and settings in product runtime files', () => {
+ const { root, repoRoot } = makeFixture(({ root, repoRoot }) => ({
+ [path.join(repoRoot, 'internal', 'api', 'router_routes_licensing.go')]: `
+package api
+
+func (r *Router) registerOrgLicenseRoutesGroup() {
+ r.mux.HandleFunc("POST /api/upgrade-metrics/events", NewConversionHandlers().HandleRecordEvent)
+ SetEnforcementConversionRecorder(nil, nil)
+}
+`,
+ [path.join(repoRoot, 'pkg', 'server', 'server.go')]: `
+package server
+
+func Run() {
+ _ = "upgrade_metrics.db"
+ _ = NewConversionStore
+}
+`,
+ [path.join(repoRoot, 'internal', 'config', 'config.go')]: `
+package config
+
+type Config struct {
+ DisableLocalUpgradeMetrics bool
+}
+`,
+ [path.join(root, 'src', 'types', 'config.ts')]: `
+export interface SystemConfig {
+ disableLocalUpgradeMetrics?: boolean;
+}
+`,
+ }));
+
+ const findings = collectUserDiagnosticsInternalAnalyticsFindings({ root, repoRoot });
+
+ expect(findings.map((finding) => finding.rule)).toEqual([
+ 'canonical-settings/no-product-commercial-analytics-routes',
+ 'canonical-settings/no-product-commercial-analytics-routes',
+ 'canonical-settings/no-product-commercial-analytics-routes',
+ 'canonical-settings/no-product-commercial-analytics-store',
+ 'canonical-settings/no-product-commercial-analytics-store',
+ 'canonical-settings/no-product-commercial-analytics-setting',
+ 'canonical-settings/no-product-commercial-analytics-setting',
+ ]);
+ });
+
+ it('reports retired commercial analytics packages in compiled product licensing code', () => {
+ const { root, repoRoot } = makeFixture(({ repoRoot }) => ({
+ [path.join(repoRoot, 'pkg', 'licensing', 'conversion_events.go')]: 'package licensing\n',
+ [path.join(repoRoot, 'pkg', 'licensing', 'metering', 'event.go')]: 'package metering\n',
+ [path.join(repoRoot, 'internal', 'license', 'conversion', 'events.go')]:
+ 'package conversion\n',
+ [path.join(repoRoot, 'internal', 'license', 'metering', 'event.go')]: 'package metering\n',
+ }));
+
+ const findings = collectUserDiagnosticsInternalAnalyticsFindings({ root, repoRoot });
+
+ expect(findings.map((finding) => finding.rule)).toEqual(
+ Array(4).fill('canonical-settings/no-product-commercial-analytics-package'),
+ );
+ expect(findings.map((finding) => finding.file)).toEqual([
+ '../pkg/licensing/conversion_events.go',
+ '../pkg/licensing/metering/event.go',
+ '../internal/license/conversion/events.go',
+ '../internal/license/metering/event.go',
+ ]);
+ });
+
it('reports production frontend commercial analytics shims', () => {
const { root, repoRoot } = makeFixture(({ root }) => ({
[path.join(root, 'src', 'components', 'Settings', 'CommercialProbe.tsx')]: `
diff --git a/frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs b/frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs
index c887c72c3a..59825aab22 100644
--- a/frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs
+++ b/frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs
@@ -17,7 +17,49 @@ const INTERNAL_ANALYTICS_RULES = [
regex:
/CommercialFunnel|commercialFunnel|Commercial Funnel|Sales Funnel|InfrastructureOnboarding|infrastructureOnboarding|Infrastructure Onboarding|pricing_viewed|checkout_clicked|credentials_opened/g,
message:
- 'Do not expose maintainer/admin analytics from /api/diagnostics. Keep commercial and onboarding analytics on admin-owned metrics routes.',
+ 'Do not expose maintainer/admin analytics from /api/diagnostics or customer product runtime.',
+ },
+ ],
+ },
+ {
+ getFilePath: ({ repoRoot }) =>
+ path.join(repoRoot, 'internal', 'api', 'router_routes_licensing.go'),
+ rules: [
+ {
+ rule: 'canonical-settings/no-product-commercial-analytics-routes',
+ regex:
+ /\/api\/upgrade-metrics|upgrade-metrics-funnel|NewConversionHandlers|SetConversionRecorder|SetEnforcementConversionRecorder/g,
+ message:
+ 'Do not register maintainer/admin commercial analytics ingestion or funnel routes in the customer product API.',
+ },
+ ],
+ },
+ {
+ getFilePath: ({ repoRoot }) => path.join(repoRoot, 'pkg', 'server', 'server.go'),
+ rules: [
+ {
+ rule: 'canonical-settings/no-product-commercial-analytics-store',
+ regex: /upgrade_metrics\.db|conversion\.db|NewConversionStore/g,
+ message:
+ 'Do not open or migrate local commercial analytics stores during customer product startup.',
+ },
+ ],
+ },
+ {
+ getFilePaths: ({ root, repoRoot }) => [
+ path.join(repoRoot, 'internal', 'config', 'config.go'),
+ path.join(repoRoot, 'internal', 'config', 'persistence.go'),
+ path.join(repoRoot, 'internal', 'api', 'system_settings.go'),
+ path.join(root, 'src', 'stores', 'systemSettings.ts'),
+ path.join(root, 'src', 'types', 'config.ts'),
+ ],
+ rules: [
+ {
+ rule: 'canonical-settings/no-product-commercial-analytics-setting',
+ regex:
+ /DisableLocalUpgradeMetrics|disableLocalUpgradeMetrics|PULSE_DISABLE_LOCAL_UPGRADE_METRICS/g,
+ message:
+ 'Do not carry maintainer/admin commercial analytics controls through customer system settings.',
},
],
},
@@ -67,6 +109,22 @@ const INTERNAL_ANALYTICS_RULES = [
},
];
+const INTERNAL_ANALYTICS_PATH_RULES = [
+ {
+ getFilePaths: ({ repoRoot }) => [
+ ...listExistingFiles(path.join(repoRoot, 'pkg', 'licensing')).filter((filePath) =>
+ /(?:^|\/)(?:conversion_[^/]+\.go|metering\/[^/]+\.go)$/.test(toPosixPath(filePath)),
+ ),
+ ...listExistingFiles(path.join(repoRoot, 'internal', 'license')).filter((filePath) =>
+ /(?:^|\/)(?:conversion|metering)\/[^/]+\.go$/.test(toPosixPath(filePath)),
+ ),
+ ],
+ rule: 'canonical-settings/no-product-commercial-analytics-package',
+ message:
+ 'Do not keep retired maintainer/admin commercial analytics packages in compiled customer product licensing code.',
+ },
+];
+
function isProductionSourceFile(filePath) {
if (!/\.(?:ts|tsx)$/.test(filePath)) return false;
if (filePath.includes(`${path.sep}__tests__${path.sep}`)) return false;
@@ -74,18 +132,22 @@ function isProductionSourceFile(filePath) {
return true;
}
-function listProductionSourceFiles(dir) {
+function toPosixPath(filePath) {
+ return filePath.replaceAll(path.sep, '/');
+}
+
+function listExistingFiles(dir) {
const files = [];
if (!fs.existsSync(dir)) return files;
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const entryPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
- files.push(...listProductionSourceFiles(entryPath));
+ files.push(...listExistingFiles(entryPath));
continue;
}
- if (entry.isFile() && isProductionSourceFile(entryPath)) {
+ if (entry.isFile()) {
files.push(entryPath);
}
}
@@ -93,6 +155,10 @@ function listProductionSourceFiles(dir) {
return files;
}
+function listProductionSourceFiles(dir) {
+ return listExistingFiles(dir).filter(isProductionSourceFile);
+}
+
function lineForIndex(content, index) {
let line = 1;
for (let i = 0; i < index; i += 1) {
@@ -131,6 +197,17 @@ export function collectUserDiagnosticsInternalAnalyticsFindings({
}
}
+ for (const { getFilePaths, rule, message } of INTERNAL_ANALYTICS_PATH_RULES) {
+ for (const filePath of getFilePaths({ root, repoRoot })) {
+ findings.push({
+ file: relativeToRoot(root, filePath),
+ line: 1,
+ rule,
+ message,
+ });
+ }
+ }
+
return findings;
}
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx b/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx
index edcb73c66a..f1a75854a4 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx
@@ -1,10 +1,9 @@
-import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { describe, expect, it } from 'vitest';
import { deriveTabFromPath, settingsTabPath, type SettingsTab } from '../settingsNavigationModel';
import { getTabLockReason, isTabLocked } from '../settingsFeatureGates';
import { getSettingsNavItem } from '../settingsNavCatalog';
import { shouldHideSettingsNavItem } from '../settingsNavVisibility';
import { getSettingsTabSaveBehavior } from '../settingsTabSaveBehavior';
-import { updateDisableLocalUpgradeMetricsSetting } from '@/stores/systemSettings';
const canonicalTabPaths = {
'infrastructure-systems': '/settings/infrastructure',
@@ -52,14 +51,6 @@ const gatedTabs: Array<[SettingsTab, string]> = [
];
describe('settingsNavigation integration scaffold', () => {
- beforeAll(() => {
- updateDisableLocalUpgradeMetricsSetting(true);
- });
-
- afterAll(() => {
- updateDisableLocalUpgradeMetricsSetting(false);
- });
-
it('hides organization navigation items unless multi-tenant is enabled', () => {
expect(
shouldHideSettingsNavItem('organization-overview', {
diff --git a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts
index 8d6f0db59f..4a4fbd36e0 100644
--- a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts
@@ -92,10 +92,9 @@ describe('useSystemSettingsState', () => {
},
}));
- vi.doMock('@/stores/systemSettings', () => ({
- updateDisableLocalUpgradeMetricsSetting: vi.fn(),
- updateDockerUpdateActionsSetting: vi.fn(),
- }));
+ vi.doMock('@/stores/systemSettings', () => ({
+ updateDockerUpdateActionsSetting: vi.fn(),
+ }));
({ useSystemSettingsState } = await import('../useSystemSettingsState'));
});
diff --git a/frontend-modern/src/stores/__tests__/systemSettings.test.ts b/frontend-modern/src/stores/__tests__/systemSettings.test.ts
index 7711fb91c9..6dd52a44b4 100644
--- a/frontend-modern/src/stores/__tests__/systemSettings.test.ts
+++ b/frontend-modern/src/stores/__tests__/systemSettings.test.ts
@@ -6,7 +6,6 @@ import { PRIVACY_DOC_URL } from '@/utils/docsLinks';
import {
areSystemSettingsLoaded,
markSystemSettingsLoadedWithDefaults,
- shouldDisableLocalUpgradeMetrics,
shouldHideDockerUpdateActions,
shouldReduceProUpsellNoise,
updateSystemSettingsFromResponse,
@@ -27,12 +26,10 @@ describe('systemSettings store', () => {
autoUpdateEnabled: false,
disableDockerUpdateActions: true,
reduceProUpsellNoise: true,
- disableLocalUpgradeMetrics: true,
});
expect(shouldHideDockerUpdateActions()).toBe(true);
expect(shouldReduceProUpsellNoise()).toBe(true);
- expect(shouldDisableLocalUpgradeMetrics()).toBe(true);
});
it('resets route and docker feature flags to safe defaults', () => {
@@ -40,13 +37,11 @@ describe('systemSettings store', () => {
autoUpdateEnabled: false,
disableDockerUpdateActions: true,
reduceProUpsellNoise: true,
- disableLocalUpgradeMetrics: true,
});
markSystemSettingsLoadedWithDefaults();
expect(shouldHideDockerUpdateActions()).toBe(false);
expect(shouldReduceProUpsellNoise()).toBe(false);
- expect(shouldDisableLocalUpgradeMetrics()).toBe(false);
});
it('keeps privacy and local paid-flow defaults safe when flags are omitted', () => {
@@ -57,7 +52,6 @@ describe('systemSettings store', () => {
expect(areSystemSettingsLoaded()).toBe(true);
expect(shouldHideDockerUpdateActions()).toBe(false);
expect(shouldReduceProUpsellNoise()).toBe(false);
- expect(shouldDisableLocalUpgradeMetrics()).toBe(false);
});
it('keeps the telemetry disclosure on the shipped local privacy doc', () => {
diff --git a/frontend-modern/src/stores/systemSettings.ts b/frontend-modern/src/stores/systemSettings.ts
index 91ddd8af60..e0a49fcc09 100644
--- a/frontend-modern/src/stores/systemSettings.ts
+++ b/frontend-modern/src/stores/systemSettings.ts
@@ -14,8 +14,6 @@ import type { SystemConfig } from '@/types/config';
const [disableDockerUpdateActions, setDisableDockerUpdateActions] = createSignal(false);
// Server-side compatibility setting for proactive commercial prompts
const [reduceProUpsellNoise, setReduceProUpsellNoise] = createSignal(false);
-// Server-side setting to disable local-only commercial handoff event collection
-const [disableLocalUpgradeMetrics, setDisableLocalUpgradeMetrics] = createSignal(false);
// Track if settings have been loaded
const [systemSettingsLoaded, setSystemSettingsLoaded] = createSignal(false);
@@ -27,12 +25,10 @@ const [systemSettingsLoaded, setSystemSettingsLoaded] = createSignal(false);
export function updateSystemSettingsFromResponse(settings: SystemConfig): void {
setDisableDockerUpdateActions(settings.disableDockerUpdateActions ?? false);
setReduceProUpsellNoise(settings.reduceProUpsellNoise ?? false);
- setDisableLocalUpgradeMetrics(settings.disableLocalUpgradeMetrics ?? false);
setSystemSettingsLoaded(true);
logger.debug('System settings updated from response', {
disableDockerUpdateActions: settings.disableDockerUpdateActions,
reduceProUpsellNoise: settings.reduceProUpsellNoise,
- disableLocalUpgradeMetrics: settings.disableLocalUpgradeMetrics,
});
}
@@ -50,7 +46,6 @@ export async function loadSystemSettings(): Promise<void> {
// Use safe defaults
setDisableDockerUpdateActions(false);
setReduceProUpsellNoise(false);
- setDisableLocalUpgradeMetrics(false);
setSystemSettingsLoaded(true);
}
}
@@ -67,10 +62,6 @@ export function shouldReduceProUpsellNoise(): boolean {
return reduceProUpsellNoise();
}
-export function shouldDisableLocalUpgradeMetrics(): boolean {
- return disableLocalUpgradeMetrics();
-}
-
/**
* Check if system settings have been loaded from the server.
*/
@@ -85,7 +76,6 @@ export function areSystemSettingsLoaded(): boolean {
export function markSystemSettingsLoadedWithDefaults(): void {
setDisableDockerUpdateActions(false);
setReduceProUpsellNoise(false);
- setDisableLocalUpgradeMetrics(false);
setSystemSettingsLoaded(true);
logger.debug('System settings marked as loaded with defaults');
}
@@ -100,7 +90,3 @@ export function updateDockerUpdateActionsSetting(disabled: boolean): void {
export function updateReduceProUpsellNoiseSetting(enabled: boolean): void {
setReduceProUpsellNoise(enabled);
}
-
-export function updateDisableLocalUpgradeMetricsSetting(disabled: boolean): void {
- setDisableLocalUpgradeMetrics(disabled);
-}
diff --git a/frontend-modern/src/types/config.ts b/frontend-modern/src/types/config.ts
index 92c2d3cebb..8c0e6830d9 100644
--- a/frontend-modern/src/types/config.ts
+++ b/frontend-modern/src/types/config.ts
@@ -50,7 +50,6 @@ export interface SystemConfig {
publicURL?: string; // Public URL for email notifications (e.g., http://198.51.100.100:8080)
disableDockerUpdateActions?: boolean; // Hide Docker update buttons while still detecting updates (server-wide)
reduceProUpsellNoise?: boolean; // Legacy compatibility preference for proactive commercial prompts
- disableLocalUpgradeMetrics?: boolean; // Disable local-only commercial handoff event collection
telemetryEnabled?: boolean; // Opt-in anonymous usage telemetry
}
diff --git a/internal/api/backend_conversion_events_test.go b/internal/api/backend_conversion_events_test.go
deleted file mode 100644
index 3454742d8e..0000000000
--- a/internal/api/backend_conversion_events_test.go
+++ /dev/null
@@ -1,256 +0,0 @@
-package api
-
-import (
- "bytes"
- "context"
- "io"
- "net/http"
- "net/http/httptest"
- "path/filepath"
- "testing"
- "time"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/config"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
- "github.com/rcourtman/pulse-go-rewrite/pkg/licensing/metering"
-)
-
-// newTestRecorderWithStore creates a conversion recorder backed by both an
-// in-memory aggregator and a SQLite durable store rooted in dir.
-func newTestRecorderWithStore(t *testing.T, dir string) (*pkglicensing.Recorder, *pkglicensing.ConversionStore) {
- t.Helper()
- store, err := pkglicensing.NewConversionStore(filepath.Join(dir, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore: %v", err)
- }
- t.Cleanup(func() { store.Close() })
- rec := pkglicensing.NewRecorderFromWindowedAggregator(metering.NewWindowedAggregator(), store)
- return rec, store
-}
-
-// queryAllEvents queries all events for an org within a generous time window.
-func queryAllEvents(t *testing.T, store *pkglicensing.ConversionStore, orgID string) []pkglicensing.StoredConversionEvent {
- t.Helper()
- from := time.Now().Add(-1 * time.Hour)
- to := time.Now().Add(1 * time.Hour)
- events, err := store.Query(orgID, from, to, "")
- if err != nil {
- t.Fatalf("Query(%q): %v", orgID, err)
- }
- return events
-}
-
-// --- LicenseHandlers.emitConversionEvent tests ---
-
-func TestLicenseHandlersEmitConversionEvent_ActivationFailedOnBadKey(t *testing.T) {
- baseDir := t.TempDir()
- mtp := config.NewMultiTenantPersistence(baseDir)
- h := NewLicenseHandlers(mtp, false)
-
- rec, store := newTestRecorderWithStore(t, baseDir)
- health := pkglicensing.NewPipelineHealth()
- h.SetConversionRecorder(rec, health)
-
- ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")
-
- body := []byte(`{"license_key":"invalid-key-that-will-fail"}`)
- req := httptest.NewRequest(http.MethodPost, "/api/license/activate", nil).WithContext(ctx)
- req.Body = io.NopCloser(bytes.NewReader(body))
- req.Header.Set("Content-Type", "application/json")
- w := httptest.NewRecorder()
- h.HandleActivateLicense(w, req)
-
- // Activation should fail (bad key).
- if w.Code != http.StatusBadRequest {
- t.Fatalf("HandleActivateLicense status=%d, want %d: %s", w.Code, http.StatusBadRequest, w.Body.String())
- }
-
- // We still expect a license_activation_failed event.
- events := queryAllEvents(t, store, "default")
- found := false
- for _, e := range events {
- if e.EventType == pkglicensing.EventLicenseActivationFailed && e.Surface == "license_api" {
- found = true
- break
- }
- }
- if !found {
- t.Fatalf("expected license_activation_failed event in store after bad key, got %d events: %+v", len(events), events)
- }
-}
-
-func TestLicenseHandlersEmitConversionEvent_LicenseActivatedDirectEmit(t *testing.T) {
- baseDir := t.TempDir()
- mtp := config.NewMultiTenantPersistence(baseDir)
- h := NewLicenseHandlers(mtp, false)
-
- rec, store := newTestRecorderWithStore(t, baseDir)
- h.SetConversionRecorder(rec, pkglicensing.NewPipelineHealth())
-
- h.emitConversionEvent("default", conversionEvent{
- Type: conversionEventLicenseActivated,
- Surface: "license_api",
- })
-
- events := queryAllEvents(t, store, "default")
- found := false
- for _, e := range events {
- if e.EventType == pkglicensing.EventLicenseActivated && e.Surface == "license_api" {
- found = true
- break
- }
- }
- if !found {
- t.Fatalf("expected license_activated event with surface=license_api, got %d events: %+v", len(events), events)
- }
-}
-
-// --- StripeWebhookHandlers.emitConversionEvent tests ---
-
-func TestStripeWebhookHandlersEmitConversionEvent_DirectEmit(t *testing.T) {
- dir := t.TempDir()
- rec, store := newTestRecorderWithStore(t, dir)
- health := pkglicensing.NewPipelineHealth()
-
- h := &StripeWebhookHandlers{
- conversionRecorder: rec,
- conversionHealth: health,
- }
-
- h.emitConversionEvent("org-stripe-1", conversionEvent{
- Type: conversionEventCheckoutCompleted,
- Surface: "stripe_webhook",
- })
-
- events := queryAllEvents(t, store, "org-stripe-1")
- if len(events) == 0 {
- t.Fatal("expected checkout_completed event in store, got none")
- }
- if events[0].EventType != pkglicensing.EventCheckoutCompleted {
- t.Fatalf("event type=%q, want %q", events[0].EventType, pkglicensing.EventCheckoutCompleted)
- }
- if events[0].Surface != "stripe_webhook" {
- t.Fatalf("surface=%q, want stripe_webhook", events[0].Surface)
- }
- if hs := health.CheckHealth(); hs.EventsTotal < 1 {
- t.Fatalf("pipeline health events_total=%d, want >=1", hs.EventsTotal)
- }
-}
-
-func TestStripeWebhookHandlersEmitConversionEvent_RespectsDisableMetrics(t *testing.T) {
- dir := t.TempDir()
- rec, store := newTestRecorderWithStore(t, dir)
-
- h := &StripeWebhookHandlers{
- conversionRecorder: rec,
- disableMetrics: func() bool { return true },
- }
-
- h.emitConversionEvent("org-stripe-2", conversionEvent{
- Type: conversionEventCheckoutCompleted,
- Surface: "stripe_webhook",
- })
-
- events := queryAllEvents(t, store, "org-stripe-2")
- if len(events) != 0 {
- t.Fatalf("expected no events when disableMetrics=true, got %d", len(events))
- }
-}
-
-func TestStripeWebhookHandlersEmitConversionEvent_NilRecorderDoesNotPanic(t *testing.T) {
- h := &StripeWebhookHandlers{} // no recorder
- // Should not panic.
- h.emitConversionEvent("org-stripe-3", conversionEvent{
- Type: conversionEventCheckoutCompleted,
- Surface: "stripe_webhook",
- })
-}
-
-func TestStripeWebhookHandlersEmitConversionEvent_DefaultsOrgIDToDefault(t *testing.T) {
- dir := t.TempDir()
- rec, store := newTestRecorderWithStore(t, dir)
-
- h := &StripeWebhookHandlers{
- conversionRecorder: rec,
- }
-
- h.emitConversionEvent("", conversionEvent{
- Type: conversionEventCheckoutCompleted,
- Surface: "stripe_webhook",
- })
-
- events := queryAllEvents(t, store, "default")
- if len(events) == 0 {
- t.Fatal("expected event with org_id=default when empty string passed, got none")
- }
-}
-
-// --- emitLimitBlockedEvent tests (package-level function) ---
-
-func TestEmitLimitBlockedEvent_RecordsEvent(t *testing.T) {
- dir := t.TempDir()
- rec, store := newTestRecorderWithStore(t, dir)
- health := pkglicensing.NewPipelineHealth()
-
- // Wire the package-level enforcement recorder.
- SetEnforcementConversionRecorder(rec, health)
- t.Cleanup(func() { SetEnforcementConversionRecorder(nil, nil, nil) })
-
- ctx := context.WithValue(context.Background(), OrgIDContextKey, "test-org")
- emitLimitBlockedEvent(ctx, 5, 5)
-
- events := queryAllEvents(t, store, "test-org")
- found := false
- for _, e := range events {
- if e.EventType == pkglicensing.EventLimitBlocked && e.Surface == "monitored_system_enforcement" {
- found = true
- break
- }
- }
- if !found {
- t.Fatalf("expected limit_blocked event with surface=monitored_system_enforcement, got %d events: %+v", len(events), events)
- }
- if hs := health.CheckHealth(); hs.EventsTotal < 1 {
- t.Fatalf("pipeline health events_total=%d, want >=1", hs.EventsTotal)
- }
-}
-
-func TestEmitLimitBlockedEvent_DefaultOrgWhenEmpty(t *testing.T) {
- dir := t.TempDir()
- rec, store := newTestRecorderWithStore(t, dir)
-
- SetEnforcementConversionRecorder(rec, nil)
- t.Cleanup(func() { SetEnforcementConversionRecorder(nil, nil, nil) })
-
- ctx := context.Background() // No org ID in context.
- emitLimitBlockedEvent(ctx, 5, 5)
-
- events := queryAllEvents(t, store, "default")
- if len(events) == 0 {
- t.Fatal("expected limit_blocked event with org_id=default, got none")
- }
-}
-
-func TestEmitLimitBlockedEvent_RespectsDisableAll(t *testing.T) {
- dir := t.TempDir()
- rec, store := newTestRecorderWithStore(t, dir)
-
- SetEnforcementConversionRecorder(rec, nil, func() bool { return true })
- t.Cleanup(func() { SetEnforcementConversionRecorder(nil, nil, nil) })
-
- ctx := context.WithValue(context.Background(), OrgIDContextKey, "test-org")
- emitLimitBlockedEvent(ctx, 5, 5)
-
- events := queryAllEvents(t, store, "test-org")
- if len(events) != 0 {
- t.Fatalf("expected no events when disableAll=true, got %d", len(events))
- }
-}
-
-func TestEmitLimitBlockedEvent_NilRecorderDoesNotPanic(t *testing.T) {
- SetEnforcementConversionRecorder(nil, nil)
- t.Cleanup(func() { SetEnforcementConversionRecorder(nil, nil, nil) })
-
- ctx := context.WithValue(context.Background(), OrgIDContextKey, "test-org")
- emitLimitBlockedEvent(ctx, 5, 5) // Should not panic.
-}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 75efa0fbc1..9bcb8b8e0e 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -2676,9 +2676,9 @@ func TestContract_ReportingCatalogRouteAccessibleWithoutReportingFeature(t *test
}
}
-func TestContract_LocalCommercialReportingRoutesRequireSettingsReadScope(t *testing.T) {
- rawToken := "commercial-reporting-contract-token-123.12345678"
- record := newTokenRecord(t, rawToken, []string{config.ScopeAgentReport}, nil)
+func TestContract_LocalCommercialAnalyticsRoutesAreNotRegistered(t *testing.T) {
+ rawToken := "retired-commercial-analytics-contract-token-123.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)
cfg := newTestConfigWithTokens(t, record)
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
@@ -2686,9 +2686,11 @@ func TestContract_LocalCommercialReportingRoutesRequireSettingsReadScope(t *test
method string
path string
}{
+ {method: http.MethodPost, path: "/api/upgrade-metrics/events"},
{method: http.MethodGet, path: "/api/upgrade-metrics/stats"},
{method: http.MethodGet, path: "/api/upgrade-metrics/health"},
{method: http.MethodGet, path: "/api/upgrade-metrics/config"},
+ {method: http.MethodPut, path: "/api/upgrade-metrics/config"},
{method: http.MethodGet, path: "/api/admin/upgrade-metrics-funnel"},
} {
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
@@ -2698,7 +2700,9 @@ func TestContract_LocalCommercialReportingRoutesRequireSettingsReadScope(t *test
router.Handler().ServeHTTP(rec, req)
- assertMissingScope(t, rec, config.ScopeSettingsRead, tc.method+" "+tc.path)
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("%s %s status=%d, want %d body=%s", tc.method, tc.path, rec.Code, http.StatusNotFound, rec.Body.String())
+ }
})
}
}
@@ -6439,8 +6443,6 @@ func TestContract_DemoModeCommercialSurfacePolicy(t *testing.T) {
{method: http.MethodPost, path: "/api/vmware/connections/conn-1/preview"},
{method: http.MethodGet, path: "/api/admin/orgs/t-tenant/billing-state"},
{method: http.MethodPut, path: "/api/admin/orgs/t-tenant/billing-state"},
- {method: http.MethodGet, path: "/api/upgrade-metrics/stats"},
- {method: http.MethodPost, path: "/api/upgrade-metrics/events"},
{method: http.MethodGet, path: "/api/diagnostics"},
{method: http.MethodPost, path: "/api/diagnostics/docker/prepare-token"},
{method: http.MethodGet, path: "/api/logs/stream"},
diff --git a/internal/api/conversion_handlers_test.go b/internal/api/conversion_handlers_test.go
deleted file mode 100644
index 0fb0da03f7..0000000000
--- a/internal/api/conversion_handlers_test.go
+++ /dev/null
@@ -1,675 +0,0 @@
-package api
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "net/http"
- "net/http/httptest"
- "path/filepath"
- "strings"
- "testing"
- "time"
-
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
- "github.com/rcourtman/pulse-go-rewrite/pkg/licensing/metering"
-)
-
-func TestConversionHandleRecordEventValidPOST(t *testing.T) {
- handlers := NewConversionHandlers(nil, nil, nil, nil, nil)
-
- body := []byte(fmt.Sprintf(`{
- "type":"paywall_viewed",
- "capability":"long_term_metrics",
- "surface":"history_chart",
- "tenant_mode":"single",
- "timestamp":%d,
- "idempotency_key":"paywall_viewed:history_chart:long_term_metrics:1"
- }`, time.Now().UnixMilli()))
-
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/events", bytes.NewReader(body))
- rec := httptest.NewRecorder()
-
- handlers.HandleRecordEvent(rec, req)
-
- if rec.Code != http.StatusAccepted {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusAccepted)
- }
-
- var resp map[string]bool
- if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
- t.Fatalf("failed decoding response: %v", err)
- }
- if !resp["accepted"] {
- t.Fatalf("accepted = %v, want true", resp["accepted"])
- }
-}
-
-func TestConversionHandleRecordEventInvalidBody(t *testing.T) {
- handlers := NewConversionHandlers(nil, nil, nil, nil, nil)
-
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/events", bytes.NewReader([]byte("{")))
- rec := httptest.NewRecorder()
-
- handlers.HandleRecordEvent(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusBadRequest)
- }
-
- var resp map[string]string
- if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
- t.Fatalf("failed decoding response: %v", err)
- }
- if resp["error"] != "validation_error" {
- t.Fatalf("error = %q, want validation_error", resp["error"])
- }
-}
-
-func TestConversionHandleRecordEventMissingRequiredFields(t *testing.T) {
- handlers := NewConversionHandlers(nil, nil, nil, nil, nil)
-
- body := []byte(fmt.Sprintf(`{
- "type":"paywall_viewed",
- "surface":"history_chart",
- "timestamp":%d,
- "idempotency_key":"paywall_viewed:history_chart::1"
- }`, time.Now().UnixMilli()))
-
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/events", bytes.NewReader(body))
- rec := httptest.NewRecorder()
-
- handlers.HandleRecordEvent(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusBadRequest)
- }
-
- var resp map[string]string
- if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
- t.Fatalf("failed decoding response: %v", err)
- }
- if resp["error"] != "validation_error" {
- t.Fatalf("error = %q, want validation_error", resp["error"])
- }
-}
-
-func TestConversionHandleRecordEventNonPOST(t *testing.T) {
- handlers := NewConversionHandlers(nil, nil, nil, nil, nil)
-
- req := httptest.NewRequest(http.MethodGet, "/api/upgrade-metrics/events", nil)
- rec := httptest.NewRecorder()
-
- handlers.HandleRecordEvent(rec, req)
-
- if rec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusMethodNotAllowed)
- }
-}
-
-func TestConversionHandleGetStats(t *testing.T) {
- agg := metering.NewWindowedAggregator()
- recorder := pkglicensing.NewRecorderFromWindowedAggregator(agg, nil)
- handlers := NewConversionHandlers(recorder, nil, nil, nil, nil)
-
- events := []pkglicensing.ConversionEvent{
- {
- Type: pkglicensing.EventPaywallViewed,
- OrgID: "default",
- Capability: "long_term_metrics",
- Surface: "history_chart",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "paywall_viewed:history_chart:long_term_metrics:1",
- },
- {
- Type: pkglicensing.EventPaywallViewed,
- OrgID: "default",
- Capability: "long_term_metrics",
- Surface: "history_chart",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "paywall_viewed:history_chart:long_term_metrics:2",
- },
- {
- Type: pkglicensing.EventTrialStarted,
- OrgID: "default",
- Surface: "license_panel",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "trial_started:license_panel::1",
- },
- }
- for _, event := range events {
- if err := recorder.Record(event); err != nil {
- t.Fatalf("record failed: %v", err)
- }
- }
-
- req := httptest.NewRequest(http.MethodGet, "/api/upgrade-metrics/stats", nil)
- rec := httptest.NewRecorder()
-
- handlers.HandleGetStats(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
- }
-
- var resp struct {
- WindowStart int64 `json:"window_start"`
- WindowEnd int64 `json:"window_end"`
- Buckets []struct {
- Type string `json:"type"`
- Key string `json:"key"`
- Count int64 `json:"count"`
- TotalValue int64 `json:"total_value"`
- } `json:"buckets"`
- TotalEvents int64 `json:"total_events"`
- }
- if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
- t.Fatalf("failed decoding response: %v", err)
- }
-
- if resp.WindowStart <= 0 {
- t.Fatalf("window_start = %d, want > 0", resp.WindowStart)
- }
- if resp.WindowEnd < resp.WindowStart {
- t.Fatalf("window_end = %d, want >= window_start %d", resp.WindowEnd, resp.WindowStart)
- }
- if len(resp.Buckets) != 2 {
- t.Fatalf("len(buckets) = %d, want 2", len(resp.Buckets))
- }
- if resp.TotalEvents != 3 {
- t.Fatalf("total_events = %d, want 3", resp.TotalEvents)
- }
-
- byKey := make(map[string]struct {
- Type string
- Count int64
- TotalValue int64
- }, len(resp.Buckets))
- for _, bucket := range resp.Buckets {
- byKey[bucket.Key] = struct {
- Type string
- Count int64
- TotalValue int64
- }{
- Type: bucket.Type,
- Count: bucket.Count,
- TotalValue: bucket.TotalValue,
- }
- }
-
- paywallBucket, ok := byKey["history_chart:long_term_metrics"]
- if !ok {
- t.Fatal("missing history_chart:long_term_metrics bucket")
- }
- if paywallBucket.Type != pkglicensing.EventPaywallViewed {
- t.Fatalf("paywall bucket type = %q, want %q", paywallBucket.Type, pkglicensing.EventPaywallViewed)
- }
- if paywallBucket.Count != 2 {
- t.Fatalf("paywall bucket count = %d, want 2", paywallBucket.Count)
- }
- if paywallBucket.TotalValue != 2 {
- t.Fatalf("paywall bucket total_value = %d, want 2", paywallBucket.TotalValue)
- }
-
- trialBucket, ok := byKey["license_panel:"]
- if !ok {
- t.Fatal("missing license_panel: bucket")
- }
- if trialBucket.Type != pkglicensing.EventTrialStarted {
- t.Fatalf("trial bucket type = %q, want %q", trialBucket.Type, pkglicensing.EventTrialStarted)
- }
- if trialBucket.Count != 1 {
- t.Fatalf("trial bucket count = %d, want 1", trialBucket.Count)
- }
- if trialBucket.TotalValue != 1 {
- t.Fatalf("trial bucket total_value = %d, want 1", trialBucket.TotalValue)
- }
-}
-
-func TestConversionHandleGetStatsNonGET(t *testing.T) {
- handlers := NewConversionHandlers(nil, nil, nil, nil, nil)
-
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/stats", nil)
- rec := httptest.NewRecorder()
-
- handlers.HandleGetStats(rec, req)
-
- if rec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusMethodNotAllowed)
- }
-}
-
-func TestConversionHandleGetHealth(t *testing.T) {
- health := pkglicensing.NewPipelineHealth()
- handlers := NewConversionHandlers(nil, health, nil, nil, nil)
-
- req := httptest.NewRequest(http.MethodGet, "/api/upgrade-metrics/health", nil)
- rec := httptest.NewRecorder()
-
- handlers.HandleGetHealth(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
- }
-
- var resp pkglicensing.HealthStatus
- if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
- t.Fatalf("failed decoding response: %v", err)
- }
-
- if resp.Status == "" {
- t.Fatal("status is empty")
- }
- if resp.StartedAt <= 0 {
- t.Fatalf("started_at = %d, want > 0", resp.StartedAt)
- }
- if resp.EventsByType == nil {
- t.Fatal("events_by_type is nil")
- }
-}
-
-func TestConversionHandleGetHealthNonGET(t *testing.T) {
- handlers := NewConversionHandlers(nil, nil, nil, nil, nil)
-
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/health", nil)
- rec := httptest.NewRecorder()
-
- handlers.HandleGetHealth(rec, req)
-
- if rec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusMethodNotAllowed)
- }
-}
-
-func TestConversionHandleRecordEventUpdatesHealth(t *testing.T) {
- agg := metering.NewWindowedAggregator()
- recorder := pkglicensing.NewRecorderFromWindowedAggregator(agg, nil)
- health := pkglicensing.NewPipelineHealth()
- handlers := NewConversionHandlers(recorder, health, nil, nil, nil)
-
- body := []byte(fmt.Sprintf(`{
- "type":"paywall_viewed",
- "capability":"long_term_metrics",
- "surface":"history_chart",
- "tenant_mode":"single",
- "timestamp":%d,
- "idempotency_key":"paywall_viewed:history_chart:long_term_metrics:health"
- }`, time.Now().UnixMilli()))
-
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/events", bytes.NewReader(body))
- rec := httptest.NewRecorder()
-
- handlers.HandleRecordEvent(rec, req)
-
- if rec.Code != http.StatusAccepted {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusAccepted)
- }
-
- healthReq := httptest.NewRequest(http.MethodGet, "/api/upgrade-metrics/health", nil)
- healthRec := httptest.NewRecorder()
- handlers.HandleGetHealth(healthRec, healthReq)
- if healthRec.Code != http.StatusOK {
- t.Fatalf("health status = %d, want %d", healthRec.Code, http.StatusOK)
- }
-
- var healthResp pkglicensing.HealthStatus
- if err := json.NewDecoder(healthRec.Body).Decode(&healthResp); err != nil {
- t.Fatalf("failed decoding health response: %v", err)
- }
- if healthResp.EventsTotal != 1 {
- t.Fatalf("health events_total = %d, want 1", healthResp.EventsTotal)
- }
- if healthResp.EventsByType[pkglicensing.EventPaywallViewed] != 1 {
- t.Fatalf("health events_by_type[%q] = %d, want 1", pkglicensing.EventPaywallViewed, healthResp.EventsByType[pkglicensing.EventPaywallViewed])
- }
-}
-
-func TestConversionHandleGetConfigDefaults(t *testing.T) {
- handlers := NewConversionHandlers(nil, nil, pkglicensing.NewCollectionConfig(), nil, nil)
-
- req := httptest.NewRequest(http.MethodGet, "/api/upgrade-metrics/config", nil)
- rec := httptest.NewRecorder()
-
- handlers.HandleGetConfig(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
- }
-
- var snapshot pkglicensing.CollectionConfigSnapshot
- if err := json.NewDecoder(rec.Body).Decode(&snapshot); err != nil {
- t.Fatalf("failed decoding response: %v", err)
- }
- if !snapshot.Enabled {
- t.Fatal("snapshot.Enabled = false, want true")
- }
- if len(snapshot.DisabledSurfaces) != 0 {
- t.Fatalf("len(snapshot.DisabledSurfaces) = %d, want 0", len(snapshot.DisabledSurfaces))
- }
-}
-
-func TestConversionHandleUpdateConfigDisablesCollection(t *testing.T) {
- config := pkglicensing.NewCollectionConfig()
- handlers := NewConversionHandlers(nil, nil, config, nil, nil)
-
- body := []byte(`{"enabled":false,"disabled_surfaces":["history_chart"]}`)
- req := httptest.NewRequest(http.MethodPut, "/api/upgrade-metrics/config", bytes.NewReader(body))
- rec := httptest.NewRecorder()
-
- handlers.HandleUpdateConfig(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
- }
-
- var snapshot pkglicensing.CollectionConfigSnapshot
- if err := json.NewDecoder(rec.Body).Decode(&snapshot); err != nil {
- t.Fatalf("failed decoding response: %v", err)
- }
- if snapshot.Enabled {
- t.Fatal("snapshot.Enabled = true, want false")
- }
- if config.IsEnabled() {
- t.Fatal("config.IsEnabled() = true, want false")
- }
-}
-
-func TestConversionHandleRecordEventReturnsAcceptedWhenCollectionDisabled(t *testing.T) {
- agg := metering.NewWindowedAggregator()
- recorder := pkglicensing.NewRecorderFromWindowedAggregator(agg, nil)
- config := pkglicensing.NewCollectionConfig()
- config.UpdateConfig(pkglicensing.CollectionConfigSnapshot{Enabled: false})
- handlers := NewConversionHandlers(recorder, nil, config, nil, nil)
-
- body := []byte(fmt.Sprintf(`{
- "type":"paywall_viewed",
- "capability":"long_term_metrics",
- "surface":"history_chart",
- "tenant_mode":"single",
- "timestamp":%d,
- "idempotency_key":"paywall_viewed:history_chart:long_term_metrics:disabled"
- }`, time.Now().UnixMilli()))
-
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/events", bytes.NewReader(body))
- rec := httptest.NewRecorder()
-
- handlers.HandleRecordEvent(rec, req)
-
- if rec.Code != http.StatusAccepted {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusAccepted)
- }
-
- buckets := recorder.Snapshot()
- if len(buckets) != 0 {
- t.Fatalf("len(recorder.Snapshot()) = %d, want 0", len(buckets))
- }
-}
-
-func TestConversionHandleRecordEventRejectsCrossTenantOrgIDSpoof(t *testing.T) {
- tmp := t.TempDir()
- store, err := pkglicensing.NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- recorder := pkglicensing.NewRecorder(nil, store, nil)
- handlers := NewConversionHandlers(recorder, nil, nil, store, nil)
-
- body := []byte(fmt.Sprintf(`{
- "type":"paywall_viewed",
- "org_id":"org-b",
- "capability":"long_term_metrics",
- "surface":"history_chart",
- "tenant_mode":"multi",
- "timestamp":%d,
- "idempotency_key":"org-spoof-attempt-1"
- }`, time.Now().UnixMilli()))
-
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/events", bytes.NewReader(body))
- req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))
- rec := httptest.NewRecorder()
-
- handlers.HandleRecordEvent(rec, req)
-
- if rec.Code != http.StatusForbidden {
- t.Fatalf("status = %d, want %d (%s)", rec.Code, http.StatusForbidden, rec.Body.String())
- }
-
- var resp map[string]string
- if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
- t.Fatalf("failed decoding response: %v", err)
- }
- if resp["error"] != "org_mismatch" {
- t.Fatalf("error = %q, want org_mismatch", resp["error"])
- }
-
- orgAEvents, err := store.Query("org-a", time.Time{}, time.Time{}, "")
- if err != nil {
- t.Fatalf("Query(org-a) error = %v", err)
- }
- if len(orgAEvents) != 0 {
- t.Fatalf("expected no org-a events, got %d", len(orgAEvents))
- }
-
- orgBEvents, err := store.Query("org-b", time.Time{}, time.Time{}, "")
- if err != nil {
- t.Fatalf("Query(org-b) error = %v", err)
- }
- if len(orgBEvents) != 0 {
- t.Fatalf("expected no org-b events, got %d", len(orgBEvents))
- }
-}
-
-func TestConversionHandleRecordEventAllowsMatchingOrgID(t *testing.T) {
- tmp := t.TempDir()
- store, err := pkglicensing.NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- recorder := pkglicensing.NewRecorder(nil, store, nil)
- handlers := NewConversionHandlers(recorder, nil, nil, store, nil)
-
- body := []byte(fmt.Sprintf(`{
- "type":"paywall_viewed",
- "org_id":"org-a",
- "capability":"long_term_metrics",
- "surface":"history_chart",
- "tenant_mode":"multi",
- "timestamp":%d,
- "idempotency_key":"org-matching-1"
- }`, time.Now().UnixMilli()))
-
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/events", bytes.NewReader(body))
- req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))
- rec := httptest.NewRecorder()
-
- handlers.HandleRecordEvent(rec, req)
-
- if rec.Code != http.StatusAccepted {
- t.Fatalf("status = %d, want %d (%s)", rec.Code, http.StatusAccepted, rec.Body.String())
- }
-
- orgAEvents, err := store.Query("org-a", time.Time{}, time.Time{}, "")
- if err != nil {
- t.Fatalf("Query(org-a) error = %v", err)
- }
- if len(orgAEvents) != 1 {
- t.Fatalf("expected one org-a event, got %d", len(orgAEvents))
- }
-}
-
-func TestConversionHandleConfigMethodNotAllowed(t *testing.T) {
- handlers := NewConversionHandlers(nil, nil, pkglicensing.NewCollectionConfig(), nil, nil)
-
- getReq := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/config", nil)
- getRec := httptest.NewRecorder()
- handlers.HandleGetConfig(getRec, getReq)
- if getRec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("GET handler status = %d, want %d", getRec.Code, http.StatusMethodNotAllowed)
- }
-
- putReq := httptest.NewRequest(http.MethodGet, "/api/upgrade-metrics/config", nil)
- putRec := httptest.NewRecorder()
- handlers.HandleUpdateConfig(putRec, putReq)
- if putRec.Code != http.StatusMethodNotAllowed {
- t.Fatalf("PUT handler status = %d, want %d", putRec.Code, http.StatusMethodNotAllowed)
- }
-}
-
-func TestConversionHandleConversionFunnelAggregatesPerOrg(t *testing.T) {
- tmp := t.TempDir()
- store, err := pkglicensing.NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- recorder := pkglicensing.NewRecorder(nil, store, nil)
- handlers := NewConversionHandlers(recorder, nil, nil, store, nil)
-
- now := time.Now().UTC()
- post := func(orgID string, payload string) {
- t.Helper()
- req := httptest.NewRequest(http.MethodPost, "/api/upgrade-metrics/events", bytes.NewReader([]byte(payload)))
- req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, orgID))
- rec := httptest.NewRecorder()
- handlers.HandleRecordEvent(rec, req)
- if rec.Code != http.StatusAccepted {
- t.Fatalf("record status = %d, want %d (%s)", rec.Code, http.StatusAccepted, rec.Body.String())
- }
- }
-
- post("org-a", fmt.Sprintf(`{"type":"pricing_viewed","capability":"self_hosted_plan","surface":"settings_self_hosted_billing_plan","timestamp":%d,"idempotency_key":"a:prv:1"}`, now.UnixMilli()))
- post("org-a", fmt.Sprintf(`{"type":"paywall_viewed","capability":"long_term_metrics","surface":"history_chart","timestamp":%d,"idempotency_key":"a:pv:1"}`, now.UnixMilli()))
- post("org-a", fmt.Sprintf(`{"type":"trial_started","surface":"license_panel","timestamp":%d,"idempotency_key":"a:ts:1"}`, now.UnixMilli()))
- post("org-a", fmt.Sprintf(`{"type":"upgrade_clicked","capability":"relay","surface":"paywall_modal","timestamp":%d,"idempotency_key":"a:uc:1"}`, now.UnixMilli()))
- post("org-a", fmt.Sprintf(`{"type":"checkout_clicked","capability":"self_hosted_plan","surface":"settings_self_hosted_billing_compare_prompt","timestamp":%d,"idempotency_key":"a:ck:1"}`, now.UnixMilli()))
- post("org-a", fmt.Sprintf(`{"type":"checkout_started","surface":"license_api","timestamp":%d,"idempotency_key":"a:cs:1"}`, now.UnixMilli()))
- post("org-a", fmt.Sprintf(`{"type":"checkout_completed","surface":"stripe_return","timestamp":%d,"idempotency_key":"a:cc:1"}`, now.UnixMilli()))
- post("org-a", fmt.Sprintf(`{"type":"license_activated","surface":"license_api","timestamp":%d,"idempotency_key":"a:la:1"}`, now.UnixMilli()))
- post("org-b", fmt.Sprintf(`{"type":"paywall_viewed","capability":"relay","surface":"mobile_onboarding","timestamp":%d,"idempotency_key":"b:pv:1"}`, now.UnixMilli()))
-
- from := now.Add(-1 * time.Hour)
- to := now.Add(1 * time.Hour)
-
- req := httptest.NewRequest(http.MethodGet, "/api/admin/upgrade-metrics-funnel", nil)
- req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))
- q := req.URL.Query()
- q.Set("org_id", "org-a")
- q.Set("from", from.Format(time.RFC3339Nano))
- q.Set("to", to.Format(time.RFC3339Nano))
- req.URL.RawQuery = q.Encode()
- rec := httptest.NewRecorder()
- handlers.HandleConversionFunnel(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("status = %d, want %d (%s)", rec.Code, http.StatusOK, rec.Body.String())
- }
-
- var summary pkglicensing.FunnelSummary
- if err := json.NewDecoder(rec.Body).Decode(&summary); err != nil {
- t.Fatalf("failed decoding response: %v", err)
- }
- if summary.PricingViewed != 1 {
- t.Fatalf("PricingViewed = %d, want 1", summary.PricingViewed)
- }
- if summary.PaywallViewed != 1 {
- t.Fatalf("PaywallViewed = %d, want 1", summary.PaywallViewed)
- }
- if summary.TrialStarted != 1 {
- t.Fatalf("TrialStarted = %d, want 1", summary.TrialStarted)
- }
- if summary.UpgradeClicked != 1 {
- t.Fatalf("UpgradeClicked = %d, want 1", summary.UpgradeClicked)
- }
- if summary.CheckoutClicked != 1 {
- t.Fatalf("CheckoutClicked = %d, want 1", summary.CheckoutClicked)
- }
- if summary.CheckoutStarted != 1 {
- t.Fatalf("CheckoutStarted = %d, want 1", summary.CheckoutStarted)
- }
- if summary.CheckoutCompleted != 1 {
- t.Fatalf("CheckoutCompleted = %d, want 1", summary.CheckoutCompleted)
- }
- if summary.LicenseActivated != 1 {
- t.Fatalf("LicenseActivated = %d, want 1", summary.LicenseActivated)
- }
-
- reqAll := httptest.NewRequest(http.MethodGet, "/api/admin/upgrade-metrics-funnel", nil)
- reqAll = reqAll.WithContext(context.WithValue(reqAll.Context(), OrgIDContextKey, "org-a"))
- qAll := reqAll.URL.Query()
- qAll.Set("from", from.Format(time.RFC3339Nano))
- qAll.Set("to", to.Format(time.RFC3339Nano))
- reqAll.URL.RawQuery = qAll.Encode()
- recAll := httptest.NewRecorder()
- handlers.HandleConversionFunnel(recAll, reqAll)
- if recAll.Code != http.StatusOK {
- t.Fatalf("status(all) = %d, want %d (%s)", recAll.Code, http.StatusOK, recAll.Body.String())
- }
- var summaryAll pkglicensing.FunnelSummary
- if err := json.NewDecoder(recAll.Body).Decode(&summaryAll); err != nil {
- t.Fatalf("failed decoding all-org response: %v", err)
- }
- if summaryAll.PaywallViewed != 1 {
- t.Fatalf("scoped PaywallViewed = %d, want 1", summaryAll.PaywallViewed)
- }
-}
-
-func TestConversionHandleConversionFunnelRejectsCrossTenantOrgOverride(t *testing.T) {
- tmp := t.TempDir()
- store, err := pkglicensing.NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- handlers := NewConversionHandlers(nil, nil, nil, store, nil)
- req := httptest.NewRequest(http.MethodGet, "/api/admin/upgrade-metrics-funnel?org_id=org-b", nil)
- req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-a"))
- rec := httptest.NewRecorder()
-
- handlers.HandleConversionFunnel(rec, req)
-
- if rec.Code != http.StatusForbidden {
- t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden)
- }
-}
-
-func TestConversionReportingRoutesRequireAdminProxyRole(t *testing.T) {
- cfg := newTestConfigWithTokens(t)
- cfg.ProxyAuthSecret = "proxy-secret"
- cfg.ProxyAuthUserHeader = "X-Proxy-User"
- cfg.ProxyAuthRoleHeader = "X-Proxy-Roles"
- cfg.ProxyAuthAdminRole = "admin"
-
- router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
-
- for _, tc := range []struct {
- method string
- path string
- body string
- }{
- {method: http.MethodGet, path: "/api/upgrade-metrics/stats"},
- {method: http.MethodGet, path: "/api/upgrade-metrics/health"},
- {method: http.MethodGet, path: "/api/upgrade-metrics/config"},
- {method: http.MethodPut, path: "/api/upgrade-metrics/config", body: `{"enabled":false}`},
- {method: http.MethodGet, path: "/api/admin/upgrade-metrics-funnel"},
- } {
- t.Run(tc.method+" "+tc.path, func(t *testing.T) {
- req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
- req.Header.Set("X-Proxy-Secret", cfg.ProxyAuthSecret)
- req.Header.Set(cfg.ProxyAuthUserHeader, "alice")
- req.Header.Set(cfg.ProxyAuthRoleHeader, "viewer|user")
- rec := httptest.NewRecorder()
-
- router.Handler().ServeHTTP(rec, req)
-
- if rec.Code != http.StatusForbidden {
- t.Fatalf("expected status %d, got %d (%s)", http.StatusForbidden, rec.Code, rec.Body.String())
- }
- })
- }
-}
diff --git a/internal/api/conversion_scope_test.go b/internal/api/conversion_scope_test.go
deleted file mode 100644
index 8dd40376f5..0000000000
--- a/internal/api/conversion_scope_test.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package api
-
-import (
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/config"
-)
-
-func TestConversionConfigReadRequiresSettingsReadScope(t *testing.T) {
- rawToken := "conversion-config-read-scope-token-123.12345678"
- record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsWrite}, nil)
- cfg := newTestConfigWithTokens(t, record)
- router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
-
- req := httptest.NewRequest(http.MethodGet, "/api/upgrade-metrics/config", nil)
- req.Header.Set("X-API-Token", rawToken)
- rec := httptest.NewRecorder()
- router.Handler().ServeHTTP(rec, req)
-
- assertMissingScope(t, rec, config.ScopeSettingsRead, req.Method+" "+req.URL.Path)
-}
-
-func TestConversionConfigWriteRequiresSettingsWriteScope(t *testing.T) {
- rawToken := "conversion-config-write-scope-token-123.12345678"
- record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)
- cfg := newTestConfigWithTokens(t, record)
- router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
-
- req := httptest.NewRequest(http.MethodPut, "/api/upgrade-metrics/config", strings.NewReader(`{"enabled":false}`))
- req.Header.Set("X-API-Token", rawToken)
- rec := httptest.NewRecorder()
- router.Handler().ServeHTTP(rec, req)
-
- assertMissingScope(t, rec, config.ScopeSettingsWrite, req.Method+" "+req.URL.Path)
-}
diff --git a/internal/api/demo_mode_commercial.go b/internal/api/demo_mode_commercial.go
index 136f635232..7c83cccf50 100644
--- a/internal/api/demo_mode_commercial.go
+++ b/internal/api/demo_mode_commercial.go
@@ -88,36 +88,6 @@ var publicDemoCommercialPolicies = []publicDemoCommercialRoutePolicy{
exposure: publicDemoCommercialExposureHidden,
matches: exactDemoCommercialConnectionActionPath(http.MethodPost, "/api/vmware/connections/", "preview"),
},
- {
- route: "POST /api/upgrade-metrics/events",
- exposure: publicDemoCommercialExposureHidden,
- matches: exactDemoCommercialMethodPath(http.MethodPost, "/api/upgrade-metrics/events"),
- },
- {
- route: "GET /api/upgrade-metrics/stats",
- exposure: publicDemoCommercialExposureHidden,
- matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/upgrade-metrics/stats"),
- },
- {
- route: "GET /api/upgrade-metrics/health",
- exposure: publicDemoCommercialExposureHidden,
- matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/upgrade-metrics/health"),
- },
- {
- route: "GET /api/upgrade-metrics/config",
- exposure: publicDemoCommercialExposureHidden,
- matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/upgrade-metrics/config"),
- },
- {
- route: "PUT /api/upgrade-metrics/config",
- exposure: publicDemoCommercialExposureHidden,
- matches: exactDemoCommercialMethodPath(http.MethodPut, "/api/upgrade-metrics/config"),
- },
- {
- route: "GET /api/admin/upgrade-metrics-funnel",
- exposure: publicDemoCommercialExposureHidden,
- matches: exactDemoCommercialMethodPath(http.MethodGet, "/api/admin/upgrade-metrics-funnel"),
- },
{
route: "GET /api/admin/orgs/{id}/billing-state",
exposure: publicDemoCommercialExposureHidden,
diff --git a/internal/api/demo_mode_commercial_test.go b/internal/api/demo_mode_commercial_test.go
index 6dffe58ba0..d8099dc157 100644
--- a/internal/api/demo_mode_commercial_test.go
+++ b/internal/api/demo_mode_commercial_test.go
@@ -165,14 +165,6 @@ func routeBelongsToPublicDemoCommercialBoundary(route string) bool {
return true
case route == "POST /api/vmware/connections/{id}/preview":
return true
- case strings.HasPrefix(route, "GET /api/upgrade-metrics/"):
- return true
- case strings.HasPrefix(route, "POST /api/upgrade-metrics/"):
- return true
- case strings.HasPrefix(route, "PUT /api/upgrade-metrics/"):
- return true
- case route == "GET /api/admin/upgrade-metrics-funnel":
- return true
case route == "GET /api/admin/orgs/{id}/billing-state":
return true
case route == "PUT /api/admin/orgs/{id}/billing-state":
diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.go
index 2daee57259..4328ba8c63 100644
--- a/internal/api/licensing_bridge.go
+++ b/internal/api/licensing_bridge.go
@@ -10,7 +10,6 @@ import (
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
agentsk8s "github.com/rcourtman/pulse-go-rewrite/pkg/agents/kubernetes"
pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
- "github.com/rcourtman/pulse-go-rewrite/pkg/licensing/metering"
)
// Sentinel errors for user-friendly activation error mapping.
@@ -46,24 +45,6 @@ type upgradeReasonModel = pkglicensing.UpgradeReason
type entitlementUsageSnapshotModel = pkglicensing.EntitlementUsageSnapshot
type legacyConnectionCountsModel = pkglicensing.LegacyConnectionCounts
type commercialMigrationStatusModel = pkglicensing.CommercialMigrationStatus
-type conversionRecorder = pkglicensing.Recorder
-type conversionPipelineHealth = pkglicensing.PipelineHealth
-type conversionCollectionConfig = pkglicensing.CollectionConfig
-type conversionStore = pkglicensing.ConversionStore
-type conversionEvent = pkglicensing.ConversionEvent
-type conversionHealthStatus = pkglicensing.HealthStatus
-type conversionCollectionConfigSnapshot = pkglicensing.CollectionConfigSnapshot
-type conversionFunnelStageCounts = pkglicensing.FunnelStageCounts
-type conversionFunnelSummary = pkglicensing.FunnelSummary
-type conversionFunnelDayBreakdown = pkglicensing.FunnelDayBreakdown
-type conversionFunnelDimensionBreakdown = pkglicensing.FunnelDimensionBreakdown
-type conversionFunnelReport = pkglicensing.FunnelReport
-type conversionInfrastructureOnboardingStageCounts = pkglicensing.InfrastructureOnboardingStageCounts
-type conversionInfrastructureOnboardingSummary = pkglicensing.InfrastructureOnboardingSummary
-type conversionInfrastructureOnboardingDayBreakdown = pkglicensing.InfrastructureOnboardingDayBreakdown
-type conversionInfrastructureOnboardingPathBreakdown = pkglicensing.InfrastructureOnboardingPathBreakdown
-type conversionInfrastructureOnboardingPlatformBreakdown = pkglicensing.InfrastructureOnboardingPlatformBreakdown
-type conversionInfrastructureOnboardingReport = pkglicensing.InfrastructureOnboardingReport
type purchaseReturnClaimsModel = pkglicensing.PurchaseReturnClaims
type entitlementLeaseClaimsModel = pkglicensing.EntitlementLeaseClaims
type licenseTier = pkglicensing.Tier
@@ -88,13 +69,6 @@ const (
subscriptionStateCanceledValue = pkglicensing.SubStateCanceled
subscriptionStateTrialValue = pkglicensing.SubStateTrial
activationKeyPrefixValue = pkglicensing.ActivationKeyPrefix
-
- // Conversion event type constants for backend-emitted events.
- conversionEventLicenseActivated = pkglicensing.EventLicenseActivated
- conversionEventLicenseActivationFailed = pkglicensing.EventLicenseActivationFailed
- conversionEventCheckoutStarted = pkglicensing.EventCheckoutStarted
- conversionEventCheckoutCompleted = pkglicensing.EventCheckoutCompleted
- conversionEventLimitBlocked = pkglicensing.EventLimitBlocked
)
func newLicenseService() *licenseService {
@@ -282,26 +256,6 @@ func limitStateFromLicensing(current, limit int64) string {
return pkglicensing.LimitState(current, limit)
}
-func newCollectionConfigFromLicensing() *conversionCollectionConfig {
- return pkglicensing.NewCollectionConfig()
-}
-
-func newConversionRecorderFromLicensing(store *conversionStore) *conversionRecorder {
- return pkglicensing.NewRecorderFromWindowedAggregator(metering.NewWindowedAggregator(), store)
-}
-
-func newConversionPipelineHealthFromLicensing() *conversionPipelineHealth {
- return pkglicensing.NewPipelineHealth()
-}
-
-func conversionValidationReasonFromLicensing(err error) string {
- return pkglicensing.ConversionValidationReason(err)
-}
-
-func parseOptionalTimeParamFromLicensing(raw string, defaultValue time.Time) (time.Time, error) {
- return pkglicensing.ParseOptionalTimeParam(raw, defaultValue)
-}
-
func trialActivationPublicKeyFromLicensing() (ed25519.PublicKey, error) {
return pkglicensing.HostedEntitlementPublicKey()
}
@@ -330,18 +284,6 @@ func writeLicenseRequiredFromLicensing(w http.ResponseWriter, feature, message s
pkglicensing.WriteLicenseRequired(w, feature, message, pkglicensing.UpgradeURLForFeature)
}
-func recordConversionInvalidMetric(reason string) {
- pkglicensing.GetConversionMetrics().RecordInvalid(reason)
-}
-
-func recordConversionSkippedMetric(reason string) {
- pkglicensing.GetConversionMetrics().RecordSkipped(reason)
-}
-
-func recordConversionEventMetric(eventType, surface string) {
- pkglicensing.GetConversionMetrics().RecordEvent(eventType, surface)
-}
-
// licenseTierFreeValue is the canonical free-tier constant for use outside the bridge.
const licenseTierFreeValue = pkglicensing.TierFree
diff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.go
index 0094b4f58f..37981e44f2 100644
--- a/internal/api/licensing_handlers.go
+++ b/internal/api/licensing_handlers.go
@@ -61,8 +61,6 @@ type LicenseHandlers struct {
purchaseReturnRedemptions *purchaseReturnRedemptionStore
monitor *monitoring.Monitor
mtMonitor *monitoring.MultiTenantMonitor
- conversionRecorder *conversionRecorder
- conversionHealth *conversionPipelineHealth
hostedLeaseRefresh sync.Map // map[string]*hostedEntitlementRefreshLoop
legacyGrandfatherReconcile sync.Map // map[string]*legacyGrandfatherReconcileLoop
runtimeVersion string
@@ -112,46 +110,6 @@ func (h *LicenseHandlers) SetRuntimeVersion(version string) {
h.runtimeVersion = strings.TrimSpace(version)
}
-// SetConversionRecorder wires the conversion event recorder for backend-emitted
-// conversion events (trial_started, license_activated, license_activation_failed).
-func (h *LicenseHandlers) SetConversionRecorder(rec *conversionRecorder, health *conversionPipelineHealth) {
- if h == nil {
- return
- }
- h.conversionRecorder = rec
- h.conversionHealth = health
-}
-
-// emitConversionEvent is a fire-and-forget helper that records a backend-emitted
-// conversion event. Respects the DisableLocalUpgradeMetrics config flag.
-// Errors are logged but never propagated to callers.
-func (h *LicenseHandlers) emitConversionEvent(orgID string, event conversionEvent) {
- if h == nil || h.conversionRecorder == nil {
- return
- }
- if h.cfg != nil && h.cfg.DisableLocalUpgradeMetrics {
- return
- }
- if orgID == "" {
- orgID = "default"
- }
- event.OrgID = orgID
- if event.Timestamp <= 0 {
- event.Timestamp = time.Now().UnixMilli()
- }
- if event.IdempotencyKey == "" {
- event.IdempotencyKey = fmt.Sprintf("backend:%s:%s:%s:%d", orgID, event.Type, event.Surface, event.Timestamp)
- }
- if err := h.conversionRecorder.Record(event); err != nil {
- log.Warn().Err(err).Str("event_type", event.Type).Str("org_id", orgID).Msg("Failed to record backend conversion event")
- } else {
- recordConversionEventMetric(event.Type, event.Surface)
- if h.conversionHealth != nil {
- h.conversionHealth.RecordEvent(event.Type)
- }
- }
-}
-
// StopAllBackgroundLoops stops grant refresh and revocation poll loops for all tenant services.
// Called during server shutdown to ensure clean goroutine termination.
func (h *LicenseHandlers) StopAllBackgroundLoops() {
@@ -993,10 +951,6 @@ func (h *LicenseHandlers) activateLicenseKey(ctx context.Context, licenseKey str
lic, err := service.Activate(trimmedKey)
if err != nil {
- h.emitConversionEvent(orgID, conversionEvent{
- Type: conversionEventLicenseActivationFailed,
- Surface: "license_api",
- })
return ActivateLicenseResponse{}, err
}
@@ -1034,11 +988,6 @@ func (h *LicenseHandlers) activateLicenseKey(ctx context.Context, licenseKey str
h.syncReleaseDemoFixtureRuntime(orgID, service)
- h.emitConversionEvent(orgID, conversionEvent{
- Type: conversionEventLicenseActivated,
- Surface: "license_api",
- })
-
successMessage := "License activated successfully"
if migratedLegacyKey && service.IsActivated() {
successMessage = "Pulse v5 license migrated and activated successfully"
diff --git a/internal/api/monitored_system_limit_enforcement.go b/internal/api/monitored_system_limit_enforcement.go
index 8b62e47ab4..e25c47f0c1 100644
--- a/internal/api/monitored_system_limit_enforcement.go
+++ b/internal/api/monitored_system_limit_enforcement.go
@@ -2,7 +2,6 @@ package api
import (
"context"
- "fmt"
"net/http"
"strings"
"sync"
@@ -15,7 +14,6 @@ import (
agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
agentsk8s "github.com/rcourtman/pulse-go-rewrite/pkg/agents/kubernetes"
- "github.com/rs/zerolog/log"
)
// overflowBaseDataDir is set during router initialization to allow the
@@ -25,11 +23,6 @@ var (
overflowBaseDataDirMu sync.RWMutex
overflowBaseDataDir string
- enforcementRecorderMu sync.RWMutex
- enforcementRecorder *conversionRecorder
- enforcementHealth *conversionPipelineHealth
- enforcementDisableAll func() bool
-
deployReservationCounterMu sync.RWMutex
deployReservationCounter func(ctx context.Context) int
)
@@ -61,18 +54,6 @@ func SetOverflowBaseDataDir(dir string) {
overflowBaseDataDir = dir
}
-// SetEnforcementConversionRecorder wires the conversion event recorder for
-// limit_blocked events emitted from monitored-system limit enforcement.
-func SetEnforcementConversionRecorder(rec *conversionRecorder, health *conversionPipelineHealth, disableAll ...func() bool) {
- enforcementRecorderMu.Lock()
- defer enforcementRecorderMu.Unlock()
- enforcementRecorder = rec
- enforcementHealth = health
- if len(disableAll) > 0 {
- enforcementDisableAll = disableAll[0]
- }
-}
-
func maxMonitoredSystemsLimitForContext(ctx context.Context) int {
service := getLicenseServiceForContext(ctx)
if service == nil {
@@ -403,7 +384,6 @@ func enforceMonitoredSystemLimitForConfigRegistration(
return false
}
- emitLimitBlockedEvent(ctx, decision.current, decision.limit)
writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -424,7 +404,6 @@ func enforceMonitoredSystemLimitForConfigReplacement(
return false
}
- emitLimitBlockedEvent(ctx, decision.current, decision.limit)
writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -461,51 +440,10 @@ func enforceMonitoredSystemLimitForHostReport(
return false
}
- emitLimitBlockedEvent(ctx, decision.current, decision.limit)
writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
-// emitLimitBlockedEvent fires a limit_blocked conversion event. Fire-and-forget.
-// Respects the DisableLocalUpgradeMetrics config flag.
-func emitLimitBlockedEvent(ctx context.Context, current, limit int) {
- enforcementRecorderMu.RLock()
- rec := enforcementRecorder
- health := enforcementHealth
- disableAll := enforcementDisableAll
- enforcementRecorderMu.RUnlock()
- if rec == nil {
- return
- }
- if disableAll != nil && disableAll() {
- return
- }
-
- orgID := GetOrgID(ctx)
- if orgID == "" {
- orgID = "default"
- }
- now := time.Now().UnixMilli()
- event := conversionEvent{
- Type: conversionEventLimitBlocked,
- OrgID: orgID,
- Surface: "monitored_system_enforcement",
- LimitKey: "max_monitored_systems",
- CurrentValue: int64(current),
- LimitValue: int64(limit),
- Timestamp: now,
- IdempotencyKey: fmt.Sprintf("backend:%s:%s:%s:%d", orgID, conversionEventLimitBlocked, "monitored_system_enforcement", now),
- }
- if err := rec.Record(event); err != nil {
- log.Warn().Err(err).Str("org_id", orgID).Msg("Failed to record limit_blocked conversion event")
- } else {
- recordConversionEventMetric(event.Type, event.Surface)
- if health != nil {
- health.RecordEvent(event.Type)
- }
- }
-}
-
// enforceMonitoredSystemLimitForDockerReport checks whether a docker report
// would create a new counted top-level monitored system.
func enforceMonitoredSystemLimitForDockerReport(
@@ -541,7 +479,6 @@ func enforceMonitoredSystemLimitForDockerReport(
return false
}
- emitLimitBlockedEvent(ctx, decision.current, decision.limit)
writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -581,7 +518,6 @@ func enforceMonitoredSystemLimitForKubernetesReport(
return false
}
- emitLimitBlockedEvent(ctx, decision.current, decision.limit)
writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
diff --git a/internal/api/payments_webhook_handlers.go b/internal/api/payments_webhook_handlers.go
index a5311a86c7..fa59bc147b 100644
--- a/internal/api/payments_webhook_handlers.go
+++ b/internal/api/payments_webhook_handlers.go
@@ -48,56 +48,9 @@ type StripeWebhookHandlers struct {
deduper *stripeWebhookDeduper
index *stripeCustomerOrgIndex
- conversionRecorder *conversionRecorder
- conversionHealth *conversionPipelineHealth
- disableMetrics func() bool
-
now func() time.Time
}
-// SetConversionRecorder wires the conversion event recorder for backend-emitted
-// conversion events (checkout_completed on checkout.session.completed webhook).
-func (h *StripeWebhookHandlers) SetConversionRecorder(rec *conversionRecorder, health *conversionPipelineHealth, disableAll ...func() bool) {
- if h == nil {
- return
- }
- h.conversionRecorder = rec
- h.conversionHealth = health
- if len(disableAll) > 0 {
- h.disableMetrics = disableAll[0]
- }
-}
-
-// emitConversionEvent is a fire-and-forget helper that records a backend-emitted
-// conversion event. Respects the DisableLocalUpgradeMetrics config flag.
-// Errors are logged but never propagated to callers.
-func (h *StripeWebhookHandlers) emitConversionEvent(orgID string, event conversionEvent) {
- if h == nil || h.conversionRecorder == nil {
- return
- }
- if h.disableMetrics != nil && h.disableMetrics() {
- return
- }
- if orgID == "" {
- orgID = "default"
- }
- event.OrgID = orgID
- if event.Timestamp <= 0 {
- event.Timestamp = time.Now().UnixMilli()
- }
- if event.IdempotencyKey == "" {
- event.IdempotencyKey = fmt.Sprintf("backend:%s:%s:%s:%d", orgID, event.Type, event.Surface, event.Timestamp)
- }
- if err := h.conversionRecorder.Record(event); err != nil {
- log.Warn().Err(err).Str("event_type", event.Type).Str("org_id", orgID).Msg("Failed to record backend conversion event")
- } else {
- recordConversionEventMetric(event.Type, event.Surface)
- if h.conversionHealth != nil {
- h.conversionHealth.RecordEvent(event.Type)
- }
- }
-}
-
func NewStripeWebhookHandlers(
billingStore *config.FileBillingStore,
persistence *config.MultiTenantPersistence,
@@ -386,11 +339,6 @@ func (h *StripeWebhookHandlers) handleCheckoutSessionCompleted(ctx context.Conte
}
}
- h.emitConversionEvent(orgID, conversionEvent{
- Type: conversionEventCheckoutCompleted,
- Surface: "stripe_webhook",
- })
-
log.Info().
Str("org_id", orgID).
Str("email", email).
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index 951acd136f..79f2344050 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -463,12 +463,6 @@ var allRouteAllowlist = []string{
"GET /api/license/monitored-system-ledger",
"POST /api/license/monitored-system-ledger/explain",
"POST /api/license/monitored-system-ledger/preview",
- "POST /api/upgrade-metrics/events",
- "GET /api/upgrade-metrics/stats",
- "GET /api/upgrade-metrics/health",
- "GET /api/upgrade-metrics/config",
- "PUT /api/upgrade-metrics/config",
- "GET /api/admin/upgrade-metrics-funnel",
"GET /auth/license-purchase-start",
"GET /api/orgs",
"POST /api/orgs",
diff --git a/internal/api/router.go b/internal/api/router.go
index f2707f0fa7..82407d11e4 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -140,7 +140,6 @@ type Router struct {
lifecycleCtx context.Context
lifecycleCancel context.CancelFunc
hostedMode bool
- conversionStore *conversionStore
stripeWebhookHandlers *StripeWebhookHandlers
patrolLifecycleMu sync.Mutex
startedPatrolOrgs map[string]bool
@@ -200,12 +199,7 @@ func isDirectLoopbackRequest(req *http.Request) bool {
}
// NewRouter creates a new router instance
-func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monitoring.MultiTenantMonitor, wsHub *websocket.Hub, reloadFunc func() error, serverVersion string, conversionStores ...*conversionStore) *Router {
- var store *conversionStore
- if len(conversionStores) > 0 {
- store = conversionStores[0]
- }
-
+func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monitoring.MultiTenantMonitor, wsHub *websocket.Hub, reloadFunc func() error, serverVersion string) *Router {
// Initialize persistent auth stores and capture the exact workers this router owns.
sessionStore := ensureSessionStore(cfg.DataPath)
csrfStore := ensureCSRFStore(cfg.DataPath)
@@ -249,7 +243,6 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monit
lifecycleCtx: lifecycleCtx,
lifecycleCancel: lifecycleCancel,
hostedMode: os.Getenv("PULSE_HOSTED_MODE") == "true",
- conversionStore: store,
monitorResourceAdapters: make(map[string]*unifiedresources.MonitorAdapter),
monitorSupplementalRecords: make(map[unifiedresources.DataSource]monitoring.MonitorSupplementalRecordsProvider),
startedPatrolOrgs: make(map[string]bool),
@@ -605,6 +598,9 @@ func (r *Router) setupRoutes() {
r.aiHandler = NewAIHandler(r.multiTenant, r.mtMonitor, r.agentExecServer)
r.aiHandler.SetReadState(r.defaultReadState())
r.aiHandler.SetRecoveryManager(recoveryManager)
+ r.aiHandler.SetControlLevelResolver(func(ctx context.Context, cfg *config.AIConfig) string {
+ return r.aiSettingsHandler.EffectiveControlLevel(ctx, cfg)
+ })
r.aiHandler.SetServiceInitializer(func(ctx context.Context, service AIService) {
r.wireAIChatDependenciesForService(ctx, service)
})
diff --git a/internal/api/router_integration_test.go b/internal/api/router_integration_test.go
index d0d87e0042..65b59ed7ed 100644
--- a/internal/api/router_integration_test.go
+++ b/internal/api/router_integration_test.go
@@ -128,7 +128,7 @@ func newIntegrationServerWithRuntimeMode(
router := api.NewRouter(cfg, monitor, nil, hub, func() error {
monitor.SyncAlertState()
return nil
- }, version, nil)
+ }, version)
srv := newIPv4HTTPServer(t, router.Handler())
t.Cleanup(func() {
diff --git a/internal/api/router_routes_licensing.go b/internal/api/router_routes_licensing.go
index f919451934..3970884ae0 100644
--- a/internal/api/router_routes_licensing.go
+++ b/internal/api/router_routes_licensing.go
@@ -10,28 +10,6 @@ import (
)
func (r *Router) registerOrgLicenseRoutesGroup(orgHandlers *OrgHandlers, rbacHandlers *RBACHandlers, auditHandlers *AuditHandlers) {
- conversionConfig := newCollectionConfigFromLicensing()
- sharedRecorder := newConversionRecorderFromLicensing(r.conversionStore)
- sharedHealth := newConversionPipelineHealthFromLicensing()
- disableAll := func() bool { return r != nil && r.config != nil && r.config.DisableLocalUpgradeMetrics }
- conversionHandlers := NewConversionHandlers(
- sharedRecorder,
- sharedHealth,
- conversionConfig,
- r.conversionStore,
- disableAll,
- )
-
- // Wire the shared recorder into LicenseHandlers, StripeWebhookHandlers,
- // and the enforcement path so backend-emitted conversion events
- // (trial_started, license_activated, checkout_completed, limit_blocked, etc.)
- // flow through the same pipeline as frontend events.
- r.licenseHandlers.SetConversionRecorder(sharedRecorder, sharedHealth)
- if r.stripeWebhookHandlers != nil {
- r.stripeWebhookHandlers.SetConversionRecorder(sharedRecorder, sharedHealth, disableAll)
- }
- SetEnforcementConversionRecorder(sharedRecorder, sharedHealth, disableAll)
-
// License routes (Pulse Pro)
r.mux.HandleFunc("/api/license/status", RequireAdmin(r.config, r.licenseHandlers.HandleLicenseStatus))
r.mux.HandleFunc("/api/license/features", RequireAuth(r.config, r.licenseHandlers.HandleLicenseFeatures))
@@ -44,15 +22,6 @@ func (r *Router) registerOrgLicenseRoutesGroup(orgHandlers *OrgHandlers, rbacHan
r.mux.HandleFunc("POST /api/license/monitored-system-ledger/explain", RequireAuth(r.config, r.handleMonitoredSystemLedgerExplain))
r.mux.HandleFunc("POST /api/license/monitored-system-ledger/preview", RequireAuth(r.config, r.handleMonitoredSystemLedgerPreview))
- // Local-only commercial handoff events (legacy route names retain "upgrade-metrics" for compatibility).
- // These are local-only signals used to debug explicit paid-plan handoffs; no external export.
- r.mux.HandleFunc("POST /api/upgrade-metrics/events", RequireAuth(r.config, conversionHandlers.HandleRecordEvent))
- r.mux.HandleFunc("GET /api/upgrade-metrics/stats", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, conversionHandlers.HandleGetStats)))
- r.mux.HandleFunc("GET /api/upgrade-metrics/health", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, conversionHandlers.HandleGetHealth)))
- r.mux.HandleFunc("GET /api/upgrade-metrics/config", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, conversionHandlers.HandleGetConfig)))
- r.mux.HandleFunc("PUT /api/upgrade-metrics/config", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, conversionHandlers.HandleUpdateConfig)))
- r.mux.HandleFunc("GET /api/admin/upgrade-metrics-funnel", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, conversionHandlers.HandleConversionFunnel)))
-
// Organization routes (multi-tenant foundation)
r.mux.HandleFunc("GET /api/orgs", RequireAuth(r.config, RequireScope(config.ScopeSettingsRead, orgHandlers.HandleListOrgs)))
r.mux.HandleFunc("POST /api/orgs", RequireAuth(r.config, RequireScope(config.ScopeSettingsWrite, orgHandlers.HandleCreateOrg)))
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 3f2b3a06c0..de44948299 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -3551,7 +3551,6 @@ func TestPrivilegedSecurityEndpointsRejectNonAdminSession(t *testing.T) {
{method: http.MethodGet, path: "/api/admin/rbac/integrity", body: ``},
{method: http.MethodPost, path: "/api/admin/rbac/reset-admin", body: `{}`},
{method: http.MethodGet, path: "/api/admin/webhooks/audit", body: ``},
- {method: http.MethodPut, path: "/api/upgrade-metrics/config", body: `{"enabled":true}`},
{method: http.MethodGet, path: "/api/onboarding/qr", body: ``},
{method: http.MethodGet, path: "/api/onboarding/deep-link", body: ``},
{method: http.MethodPost, path: "/api/onboarding/validate", body: `{}`},
diff --git a/internal/api/system_settings.go b/internal/api/system_settings.go
index 2c60b89d77..16635297c9 100644
--- a/internal/api/system_settings.go
+++ b/internal/api/system_settings.go
@@ -409,12 +409,6 @@ func validateSystemSettings(_ *config.SystemSettings, rawRequest map[string]inte
}
}
- if val, ok := rawRequest["disableLocalUpgradeMetrics"]; ok {
- if _, ok := val.(bool); !ok {
- return fmt.Errorf("disableLocalUpgradeMetrics must be a boolean")
- }
- }
-
if val, ok := rawRequest["reduceProUpsellNoise"]; ok {
if _, ok := val.(bool); !ok {
return fmt.Errorf("reduceProUpsellNoise must be a boolean")
@@ -863,9 +857,6 @@ func (h *SystemSettingsHandler) HandleUpdateSystemSettings(w http.ResponseWriter
if _, ok := rawRequest["disableDockerUpdateActions"]; ok {
settings.DisableDockerUpdateActions = updates.DisableDockerUpdateActions
}
- if _, ok := rawRequest["disableLocalUpgradeMetrics"]; ok {
- settings.DisableLocalUpgradeMetrics = updates.DisableLocalUpgradeMetrics
- }
if _, ok := rawRequest["reduceProUpsellNoise"]; ok {
settings.ReduceProUpsellNoise = updates.ReduceProUpsellNoise
}
@@ -963,7 +954,6 @@ func (h *SystemSettingsHandler) HandleUpdateSystemSettings(w http.ResponseWriter
h.config.TemperatureMonitoringEnabled = settings.TemperatureMonitoringEnabled
}
h.config.DisableDockerUpdateActions = settings.DisableDockerUpdateActions
- h.config.DisableLocalUpgradeMetrics = settings.DisableLocalUpgradeMetrics
if _, ok := rawRequest["telemetryEnabled"]; ok && settings.TelemetryEnabled != nil {
h.config.TelemetryEnabled = *settings.TelemetryEnabled
if h.telemetryToggleFunc != nil {
diff --git a/internal/api/truenas_handlers.go b/internal/api/truenas_handlers.go
index 88e147b3d8..cef3950c9a 100644
--- a/internal/api/truenas_handlers.go
+++ b/internal/api/truenas_handlers.go
@@ -611,7 +611,6 @@ func (h *TrueNASHandlers) enforceMonitoredSystemLimit(
return false
}
- emitLimitBlockedEvent(r.Context(), decision.current, decision.limit)
writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -642,7 +641,6 @@ func (h *TrueNASHandlers) enforceMonitoredSystemLimitReplacement(
return false
}
- emitLimitBlockedEvent(r.Context(), decision.current, decision.limit)
writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
diff --git a/internal/api/upgrade_metrics_handlers.go b/internal/api/upgrade_metrics_handlers.go
deleted file mode 100644
index ecc7594ba0..0000000000
--- a/internal/api/upgrade_metrics_handlers.go
+++ /dev/null
@@ -1,312 +0,0 @@
-package api
-
-import (
- "encoding/json"
- "net/http"
- "strings"
- "time"
-
- "github.com/rs/zerolog/log"
-)
-
-type ConversionHandlers struct {
- recorder *conversionRecorder
- health *conversionPipelineHealth
- config *conversionCollectionConfig
- store *conversionStore
- // disableAll, when true, forces all event ingestion to be skipped for privacy.
- // This is a hard override; runtime collection config remains mutable but is ignored.
- disableAll func() bool
-}
-
-func NewConversionHandlers(recorder *conversionRecorder, health *conversionPipelineHealth, config *conversionCollectionConfig, store *conversionStore, disableAll func() bool) *ConversionHandlers {
- return &ConversionHandlers{
- recorder: recorder,
- health: health,
- config: config,
- store: store,
- disableAll: disableAll,
- }
-}
-
-func (h *ConversionHandlers) HandleRecordEvent(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPost {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- var event conversionEvent
- if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
- recordConversionInvalidMetric("invalid_request_body")
- writeConversionValidationError(w, "invalid request body")
- return
- }
-
- if err := event.Validate(); err != nil {
- recordConversionInvalidMetric(conversionValidationReason(err))
- writeConversionValidationError(w, err.Error())
- return
- }
-
- contextOrgID := strings.TrimSpace(GetOrgID(r.Context()))
- if contextOrgID == "" {
- contextOrgID = "default"
- }
- if !isValidOrganizationID(contextOrgID) {
- recordConversionInvalidMetric("invalid_context_org_id")
- writeConversionValidationError(w, "invalid tenant context")
- return
- }
-
- event.OrgID = strings.TrimSpace(event.OrgID)
- if event.OrgID == "" {
- event.OrgID = contextOrgID
- } else {
- if !isValidOrganizationID(event.OrgID) {
- recordConversionInvalidMetric("invalid_event_org_id")
- writeConversionValidationError(w, "invalid org_id")
- return
- }
- if event.OrgID != contextOrgID {
- recordConversionInvalidMetric("org_id_mismatch")
- writeConversionJSONResponse(w, http.StatusForbidden, map[string]string{
- "error": "org_mismatch",
- "message": "org_id does not match authenticated tenant",
- }, "HandleRecordEvent")
- return
- }
- }
-
- if h != nil && h.disableAll != nil && h.disableAll() {
- recordConversionSkippedMetric("system_disabled")
- writeConversionAccepted(w)
- return
- }
-
- if h != nil && h.config != nil && !h.config.IsSurfaceEnabled(event.Surface) {
- reason := "surface_disabled"
- if !h.config.IsEnabled() {
- reason = "collection_disabled"
- }
- recordConversionSkippedMetric(reason)
- writeConversionAccepted(w)
- return
- }
-
- if h != nil && h.recorder != nil {
- if err := h.recorder.Record(event); err != nil {
- // Analytics ingestion is fire-and-forget; do not fail UX if recording fails.
- log.Warn().Err(err).Str("event_type", event.Type).Msg("Failed to record conversion event")
- } else {
- recordConversionEventMetric(event.Type, event.Surface)
- if h.health != nil {
- h.health.RecordEvent(event.Type)
- }
- }
- }
-
- writeConversionAccepted(w)
-}
-
-// HandleConversionFunnel returns conversion funnel counts for admin reporting.
-// GET /api/admin/upgrade-metrics-funnel?org_id=...&from=...&to=...
-func (h *ConversionHandlers) HandleConversionFunnel(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- if h == nil || h.store == nil {
- http.Error(w, "Conversion store unavailable", http.StatusServiceUnavailable)
- return
- }
-
- orgID := strings.TrimSpace(r.URL.Query().Get("org_id"))
- contextOrgID := strings.TrimSpace(GetOrgID(r.Context()))
- if orgID == "" {
- orgID = contextOrgID
- } else if contextOrgID != "" && orgID != contextOrgID {
- http.Error(w, "forbidden", http.StatusForbidden)
- return
- }
- if orgID == "" {
- http.Error(w, "org_id is required", http.StatusBadRequest)
- return
- }
-
- now := time.Now().UTC()
- to, err := parseOptionalTimeParam(r.URL.Query().Get("to"), now)
- if err != nil {
- http.Error(w, "invalid to", http.StatusBadRequest)
- return
- }
- fromDefault := to.Add(-30 * 24 * time.Hour)
- from, err := parseOptionalTimeParam(r.URL.Query().Get("from"), fromDefault)
- if err != nil {
- http.Error(w, "invalid from", http.StatusBadRequest)
- return
- }
- if from.After(to) {
- http.Error(w, "from must be <= to", http.StatusBadRequest)
- return
- }
-
- summary, err := h.store.FunnelSummary(orgID, from, to)
- if err != nil {
- http.Error(w, "failed to query funnel", http.StatusInternalServerError)
- return
- }
-
- writeConversionJSONResponse(w, http.StatusOK, summary, "HandleConversionFunnel")
-}
-
-// HandleGetHealth returns conversion pipeline health status.
-func (h *ConversionHandlers) HandleGetHealth(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- status := conversionHealthStatus{
- Status: "healthy",
- LastEventAgeSeconds: 0,
- EventsTotal: 0,
- EventsByType: map[string]int64{},
- StartedAt: time.Now().UnixMilli(),
- }
- if h != nil && h.health != nil {
- status = h.health.CheckHealth()
- }
-
- writeConversionJSONResponse(w, http.StatusOK, status, "HandleGetHealth")
-}
-
-type conversionStatsBucket struct {
- Type string `json:"type"`
- Key string `json:"key"`
- Count int64 `json:"count"`
- TotalValue int64 `json:"total_value"`
-}
-
-type conversionStatsResponse struct {
- WindowStart int64 `json:"window_start"`
- WindowEnd int64 `json:"window_end"`
- Buckets []conversionStatsBucket `json:"buckets"`
- TotalEvents int64 `json:"total_events"`
-}
-
-// HandleGetStats returns a snapshot of current conversion aggregation window state.
-func (h *ConversionHandlers) HandleGetStats(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- snapshot := []conversionStatsBucket{}
- windowStart := time.Now()
- windowEnd := windowStart
- var totalEvents int64
-
- if h != nil && h.recorder != nil {
- buckets := h.recorder.Snapshot()
- snapshot = make([]conversionStatsBucket, 0, len(buckets))
- if len(buckets) > 0 {
- windowStart = buckets[0].WindowStart
- windowEnd = buckets[0].WindowEnd
- }
- for _, bucket := range buckets {
- snapshot = append(snapshot, conversionStatsBucket{
- Type: string(bucket.Type),
- Key: bucket.Key,
- Count: bucket.Count,
- TotalValue: bucket.TotalValue,
- })
- totalEvents += bucket.Count
- }
- }
-
- writeConversionJSONResponse(w, http.StatusOK, conversionStatsResponse{
- WindowStart: windowStart.UnixMilli(),
- WindowEnd: windowEnd.UnixMilli(),
- Buckets: snapshot,
- TotalEvents: totalEvents,
- }, "HandleGetStats")
-}
-
-// HandleGetConfig returns runtime conversion collection controls.
-func (h *ConversionHandlers) HandleGetConfig(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- snapshot := conversionCollectionConfigSnapshot{
- Enabled: true,
- DisabledSurfaces: []string{},
- }
- if h != nil && h.config != nil {
- snapshot = h.config.GetConfig()
- }
-
- writeConversionJSONResponse(w, http.StatusOK, snapshot, "HandleGetConfig")
-}
-
-// HandleUpdateConfig updates runtime conversion collection controls.
-func (h *ConversionHandlers) HandleUpdateConfig(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPut {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- var snapshot conversionCollectionConfigSnapshot
- decoder := json.NewDecoder(r.Body)
- decoder.DisallowUnknownFields()
- if err := decoder.Decode(&snapshot); err != nil {
- http.Error(w, "invalid request body", http.StatusBadRequest)
- return
- }
-
- if h != nil {
- if h.config == nil {
- h.config = newCollectionConfigFromLicensing()
- }
- h.config.UpdateConfig(snapshot)
- snapshot = h.config.GetConfig()
- } else {
- cfg := newCollectionConfigFromLicensing()
- cfg.UpdateConfig(snapshot)
- snapshot = cfg.GetConfig()
- }
-
- writeConversionJSONResponse(w, http.StatusOK, snapshot, "HandleUpdateConfig")
-}
-
-func conversionValidationReason(err error) string {
- return conversionValidationReasonFromLicensing(err)
-}
-
-func writeConversionValidationError(w http.ResponseWriter, message string) {
- writeConversionJSONResponse(w, http.StatusBadRequest, map[string]string{
- "error": "validation_error",
- "message": message,
- }, "writeConversionValidationError")
-}
-
-func writeConversionAccepted(w http.ResponseWriter) {
- writeConversionJSONResponse(w, http.StatusAccepted, map[string]bool{"accepted": true}, "writeConversionAccepted")
-}
-
-func writeConversionJSONResponse(w http.ResponseWriter, status int, payload interface{}, operation string) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(status)
- if err := json.NewEncoder(w).Encode(payload); err != nil {
- log.Warn().
- Err(err).
- Str("operation", operation).
- Msg("Failed to encode conversion API response")
- }
-}
-
-func parseOptionalTimeParam(raw string, defaultValue time.Time) (time.Time, error) {
- return parseOptionalTimeParamFromLicensing(raw, defaultValue)
-}
diff --git a/internal/api/vmware_handlers.go b/internal/api/vmware_handlers.go
index ae2c12b750..f27bd03456 100644
--- a/internal/api/vmware_handlers.go
+++ b/internal/api/vmware_handlers.go
@@ -709,7 +709,6 @@ func (h *VMwareHandlers) enforceMonitoredSystemLimit(
return false
}
- emitLimitBlockedEvent(r.Context(), decision.current, decision.limit)
writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
@@ -760,7 +759,6 @@ func (h *VMwareHandlers) enforceMonitoredSystemLimitReplacement(
return false
}
- emitLimitBlockedEvent(r.Context(), decision.current, decision.limit)
writeMaxMonitoredSystemsLimitExceeded(w, decision)
return true
}
diff --git a/internal/config/config.go b/internal/config/config.go
index 587dcd3c9e..98234ae624 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -200,7 +200,6 @@ type Config struct {
AllowedOrigins string `envconfig:"ALLOWED_ORIGINS" default:"*"`
HideLocalLogin bool `envconfig:"PULSE_AUTH_HIDE_LOCAL_LOGIN" default:"false"`
DisableDockerUpdateActions bool `envconfig:"PULSE_DISABLE_DOCKER_UPDATE_ACTIONS" default:"false"` // Hide Docker update buttons (read-only mode for containers)
- DisableLocalUpgradeMetrics bool `envconfig:"PULSE_DISABLE_LOCAL_UPGRADE_METRICS" default:"false"` // Disable local-only upgrade event collection
TelemetryEnabled bool `envconfig:"PULSE_TELEMETRY" default:"true"` // Anonymous outbound usage telemetry enabled by default (install ID, version, resource counts, feature flags — opt out any time)
MultiTenantEnabled bool `envconfig:"PULSE_MULTI_TENANT_ENABLED" default:"false"` // Enable multi-tenant support
MetricsToken string `envconfig:"PULSE_METRICS_TOKEN" default:"" json:"-"` // Bearer token for /metrics endpoint (empty = unauthenticated)
@@ -870,8 +869,6 @@ func load(initLogging bool) (*Config, error) {
cfg.HideLocalLogin = systemSettings.HideLocalLogin
// Load DisableDockerUpdateActions (hide Docker update buttons)
cfg.DisableDockerUpdateActions = systemSettings.DisableDockerUpdateActions
- // Load DisableLocalUpgradeMetrics (privacy: local-only upgrade UX metrics)
- cfg.DisableLocalUpgradeMetrics = systemSettings.DisableLocalUpgradeMetrics
// Load TelemetryEnabled (enabled by default; nil means true for upgrading users)
if systemSettings.TelemetryEnabled != nil {
cfg.TelemetryEnabled = *systemSettings.TelemetryEnabled
@@ -1044,17 +1041,6 @@ func load(initLogging bool) (*Config, error) {
}
}
- if disableLocalUpgradeMetricsStr := utils.GetenvTrim("PULSE_DISABLE_LOCAL_UPGRADE_METRICS"); disableLocalUpgradeMetricsStr != "" {
- if disabled, err := strconv.ParseBool(disableLocalUpgradeMetricsStr); err == nil {
- cfg.DisableLocalUpgradeMetrics = disabled
- cfg.EnvOverrides["PULSE_DISABLE_LOCAL_UPGRADE_METRICS"] = true
- cfg.EnvOverrides["disableLocalUpgradeMetrics"] = true
- log.Info().Bool("disabled", disabled).Msg("Overriding local-only commercial events setting from environment")
- } else {
- log.Warn().Str("value", disableLocalUpgradeMetricsStr).Msg("Invalid PULSE_DISABLE_LOCAL_UPGRADE_METRICS value, ignoring")
- }
- }
-
if telemetryStr := utils.GetenvTrim("PULSE_TELEMETRY"); telemetryStr != "" {
if enabled, err := strconv.ParseBool(telemetryStr); err == nil {
cfg.TelemetryEnabled = enabled
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index db31e9d35f..3f42e59fa3 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -75,7 +75,6 @@ func TestLoad_EnvOverrides(t *testing.T) {
t.Setenv("PULSE_DATA_DIR", tempDir)
t.Setenv("HTTPS_ENABLED", "true")
t.Setenv("PULSE_AUTH_USER", "admin")
- t.Setenv("PULSE_DISABLE_LOCAL_UPGRADE_METRICS", "true")
cfg, err := Load()
require.NoError(t, err)
@@ -84,9 +83,6 @@ func TestLoad_EnvOverrides(t *testing.T) {
assert.Equal(t, tempDir, cfg.DataPath)
assert.True(t, cfg.HTTPSEnabled)
assert.Equal(t, "admin", cfg.AuthUser)
- assert.True(t, cfg.DisableLocalUpgradeMetrics)
- assert.True(t, cfg.EnvOverrides["PULSE_DISABLE_LOCAL_UPGRADE_METRICS"])
- assert.True(t, cfg.EnvOverrides["disableLocalUpgradeMetrics"])
}
func TestLoad_DotEnv(t *testing.T) {
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index 1181c77934..7f03874ec5 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -1364,8 +1364,7 @@ type SystemSettings struct {
DisableDockerUpdateActions bool `json:"disableDockerUpdateActions"` // Hide update buttons while still detecting updates
// UX + privacy knobs (server-wide)
- ReduceProUpsellNoise bool `json:"reduceProUpsellNoise,omitempty"` // Legacy compatibility preference for proactive commercial prompts
- DisableLocalUpgradeMetrics bool `json:"disableLocalUpgradeMetrics,omitempty"` // Disable local-only commercial handoff metrics collection (no network calls)
+ ReduceProUpsellNoise bool `json:"reduceProUpsellNoise,omitempty"` // Legacy compatibility preference for proactive commercial prompts
// Telemetry (enabled by default, opt-out)
TelemetryEnabled *bool `json:"telemetryEnabled,omitempty"` // Send anonymous usage telemetry (install ID, version, resource counts, feature flags — no PII)
diff --git a/internal/license/conversion/config.go b/internal/license/conversion/config.go
deleted file mode 100644
index e1852c4bfe..0000000000
--- a/internal/license/conversion/config.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package conversion
-
-import pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
-
-type CollectionConfigSnapshot = pkglicensing.CollectionConfigSnapshot
-type CollectionConfig = pkglicensing.CollectionConfig
-
-// NewCollectionConfig returns a default runtime config with collection enabled.
-func NewCollectionConfig() *CollectionConfig {
- return pkglicensing.NewCollectionConfig()
-}
diff --git a/internal/license/conversion/config_test.go b/internal/license/conversion/config_test.go
deleted file mode 100644
index 950deb0c70..0000000000
--- a/internal/license/conversion/config_test.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package conversion
-
-import (
- "sync"
- "testing"
-)
-
-func TestCollectionConfigDefaultsToEnabled(t *testing.T) {
- cfg := NewCollectionConfig()
-
- if !cfg.IsEnabled() {
- t.Fatal("IsEnabled() = false, want true")
- }
- if !cfg.IsSurfaceEnabled("history_chart") {
- t.Fatal("IsSurfaceEnabled(history_chart) = false, want true")
- }
-
- snapshot := cfg.GetConfig()
- if !snapshot.Enabled {
- t.Fatal("snapshot.Enabled = false, want true")
- }
- if len(snapshot.DisabledSurfaces) != 0 {
- t.Fatalf("len(snapshot.DisabledSurfaces) = %d, want 0", len(snapshot.DisabledSurfaces))
- }
-}
-
-func TestCollectionConfigGlobalDisable(t *testing.T) {
- cfg := NewCollectionConfig()
- cfg.UpdateConfig(CollectionConfigSnapshot{
- Enabled: false,
- })
-
- if cfg.IsEnabled() {
- t.Fatal("IsEnabled() = true, want false")
- }
- if cfg.IsSurfaceEnabled("history_chart") {
- t.Fatal("IsSurfaceEnabled(history_chart) = true, want false")
- }
- if cfg.IsSurfaceEnabled("ai_intelligence") {
- t.Fatal("IsSurfaceEnabled(ai_intelligence) = true, want false")
- }
-}
-
-func TestCollectionConfigPerSurfaceDisable(t *testing.T) {
- cfg := NewCollectionConfig()
- cfg.UpdateConfig(CollectionConfigSnapshot{
- Enabled: true,
- DisabledSurfaces: []string{"history_chart"},
- })
-
- if !cfg.IsEnabled() {
- t.Fatal("IsEnabled() = false, want true")
- }
- if cfg.IsSurfaceEnabled("history_chart") {
- t.Fatal("IsSurfaceEnabled(history_chart) = true, want false")
- }
- if !cfg.IsSurfaceEnabled("ai_intelligence") {
- t.Fatal("IsSurfaceEnabled(ai_intelligence) = false, want true")
- }
-}
-
-func TestCollectionConfigUpdateRoundTrip(t *testing.T) {
- cfg := NewCollectionConfig()
-
- input := CollectionConfigSnapshot{
- Enabled: true,
- DisabledSurfaces: []string{"history_chart", "ai_intelligence"},
- }
- cfg.UpdateConfig(input)
- got := cfg.GetConfig()
-
- if got.Enabled != input.Enabled {
- t.Fatalf("snapshot.Enabled = %v, want %v", got.Enabled, input.Enabled)
- }
- if len(got.DisabledSurfaces) != len(input.DisabledSurfaces) {
- t.Fatalf("len(snapshot.DisabledSurfaces) = %d, want %d", len(got.DisabledSurfaces), len(input.DisabledSurfaces))
- }
-
- seen := make(map[string]bool, len(got.DisabledSurfaces))
- for _, surface := range got.DisabledSurfaces {
- seen[surface] = true
- }
- for _, surface := range input.DisabledSurfaces {
- if !seen[surface] {
- t.Fatalf("missing surface %q in snapshot", surface)
- }
- }
-}
-
-func TestCollectionConfigConcurrentAccess(t *testing.T) {
- cfg := NewCollectionConfig()
- const workers = 16
- const iterations = 300
-
- var wg sync.WaitGroup
- wg.Add(workers)
-
- for i := 0; i < workers; i++ {
- go func(worker int) {
- defer wg.Done()
- for j := 0; j < iterations; j++ {
- if (worker+j)%4 == 0 {
- cfg.UpdateConfig(CollectionConfigSnapshot{
- Enabled: (worker+j)%2 == 0,
- DisabledSurfaces: []string{
- "history_chart",
- "ai_intelligence",
- },
- })
- continue
- }
-
- _ = cfg.IsEnabled()
- _ = cfg.IsSurfaceEnabled("history_chart")
- _ = cfg.GetConfig()
- }
- }(i)
- }
-
- wg.Wait()
-
- snapshot := cfg.GetConfig()
- if snapshot.DisabledSurfaces == nil {
- t.Fatal("snapshot.DisabledSurfaces is nil, want non-nil slice")
- }
-}
diff --git a/internal/license/conversion/events.go b/internal/license/conversion/events.go
deleted file mode 100644
index 36283192f9..0000000000
--- a/internal/license/conversion/events.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package conversion
-
-import pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
-
-const (
- EventPricingViewed = pkglicensing.EventPricingViewed
- EventPaywallViewed = pkglicensing.EventPaywallViewed
- EventTrialStarted = pkglicensing.EventTrialStarted
- EventLicenseActivated = pkglicensing.EventLicenseActivated
- EventLicenseActivationFailed = pkglicensing.EventLicenseActivationFailed
- EventUpgradeClicked = pkglicensing.EventUpgradeClicked
- EventCheckoutClicked = pkglicensing.EventCheckoutClicked
- EventCheckoutStarted = pkglicensing.EventCheckoutStarted
- EventCheckoutCompleted = pkglicensing.EventCheckoutCompleted
- EventLimitWarningShown = pkglicensing.EventLimitWarningShown
- EventLimitBlocked = pkglicensing.EventLimitBlocked
- EventAgentInstallTokenGenerated = pkglicensing.EventAgentInstallTokenGenerated
- EventAgentInstallCommandCopied = pkglicensing.EventAgentInstallCommandCopied
- EventAgentInstallProfileSelected = pkglicensing.EventAgentInstallProfileSelected
- EventAgentFirstConnected = pkglicensing.EventAgentFirstConnected
- EventInfrastructureOnboardingOpened = pkglicensing.EventInfrastructureOnboardingOpened
- EventInfrastructureOnboardingPathSelected = pkglicensing.EventInfrastructureOnboardingPathSelected
- EventInfrastructureOnboardingProbeResult = pkglicensing.EventInfrastructureOnboardingProbeResult
- EventInfrastructureOnboardingCatalogSelected = pkglicensing.EventInfrastructureOnboardingCatalogSelected
- EventInfrastructureOnboardingCredentialsOpened = pkglicensing.EventInfrastructureOnboardingCredentialsOpened
-)
-
-type ConversionEvent = pkglicensing.ConversionEvent
diff --git a/internal/license/conversion/events_test.go b/internal/license/conversion/events_test.go
deleted file mode 100644
index d29f454c97..0000000000
--- a/internal/license/conversion/events_test.go
+++ /dev/null
@@ -1,145 +0,0 @@
-package conversion
-
-import (
- "strings"
- "testing"
- "time"
-)
-
-func TestConversionEventValidate(t *testing.T) {
- now := time.Now().UnixMilli()
-
- tests := []struct {
- name string
- event ConversionEvent
- wantError string
- }{
- {
- name: "missing type",
- event: ConversionEvent{Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "type is required",
- },
- {
- name: "unknown type",
- event: ConversionEvent{Type: "unknown", Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "is not supported",
- },
- {
- name: "missing surface",
- event: ConversionEvent{Type: EventTrialStarted, Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "surface is required",
- },
- {
- name: "missing timestamp",
- event: ConversionEvent{Type: EventTrialStarted, Surface: "dashboard", IdempotencyKey: "id-1"},
- wantError: "timestamp is required",
- },
- {
- name: "missing idempotency key",
- event: ConversionEvent{Type: EventTrialStarted, Surface: "dashboard", Timestamp: now},
- wantError: "idempotency_key is required",
- },
- {
- name: "invalid tenant mode",
- event: ConversionEvent{Type: EventTrialStarted, Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1", TenantMode: "invalid"},
- wantError: "tenant_mode must be",
- },
- {
- name: "paywall requires capability",
- event: ConversionEvent{Type: EventPaywallViewed, Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "capability is required",
- },
- {
- name: "valid pricing viewed event",
- event: ConversionEvent{
- Type: EventPricingViewed,
- Surface: "settings_self_hosted_billing_plan",
- Capability: "self_hosted_plan",
- Timestamp: now,
- IdempotencyKey: "id-pricing-viewed-1",
- },
- },
- {
- name: "valid checkout clicked event",
- event: ConversionEvent{
- Type: EventCheckoutClicked,
- Surface: "settings_self_hosted_billing_compare_prompt",
- Capability: "self_hosted_plan",
- Timestamp: now,
- IdempotencyKey: "id-checkout-clicked-1",
- },
- },
- {
- name: "valid infrastructure onboarding path event",
- event: ConversionEvent{
- Type: EventInfrastructureOnboardingPathSelected,
- Surface: "settings_infrastructure_add",
- Capability: "api",
- Timestamp: now,
- IdempotencyKey: "id-infra-onboarding-path-1",
- },
- },
- {
- name: "limit warning requires limit key",
- event: ConversionEvent{Type: EventLimitWarningShown, Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "limit_key is required",
- },
- {
- name: "limit blocked requires limit key",
- event: ConversionEvent{Type: EventLimitBlocked, Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "limit_key is required",
- },
- {
- name: "valid paywall event",
- event: ConversionEvent{
- Type: EventPaywallViewed,
- Surface: "dashboard",
- Capability: "relay",
- Timestamp: now,
- IdempotencyKey: "id-1",
- TenantMode: "single",
- },
- },
- {
- name: "valid trial started with multi tenant mode",
- event: ConversionEvent{
- Type: EventTrialStarted,
- Surface: "dashboard",
- Timestamp: now,
- IdempotencyKey: "id-2",
- TenantMode: "multi",
- },
- },
- }
-
- for _, tc := range tests {
- tc := tc
- t.Run(tc.name, func(t *testing.T) {
- err := tc.event.Validate()
- if tc.wantError == "" && err != nil {
- t.Fatalf("expected nil error, got %v", err)
- }
- if tc.wantError != "" {
- if err == nil {
- t.Fatalf("expected error containing %q, got nil", tc.wantError)
- }
- if !strings.Contains(err.Error(), tc.wantError) {
- t.Fatalf("expected error containing %q, got %q", tc.wantError, err.Error())
- }
- }
- })
- }
-}
-
-func TestConversionEventValidateRejectsUnknownType(t *testing.T) {
- event := ConversionEvent{
- Type: "not_a_real_event",
- Surface: "settings_unified_agents",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "not_a_real_event:settings_unified_agents::1",
- }
-
- if err := event.Validate(); err == nil {
- t.Fatal("Validate() error = nil, want unsupported type error")
- }
-}
diff --git a/internal/license/conversion/metrics.go b/internal/license/conversion/metrics.go
deleted file mode 100644
index fb6e854d47..0000000000
--- a/internal/license/conversion/metrics.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package conversion
-
-import pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
-
-type ConversionMetrics = pkglicensing.ConversionMetrics
-
-// GetConversionMetrics returns the singleton conversion metrics instance.
-func GetConversionMetrics() *ConversionMetrics {
- return pkglicensing.GetConversionMetrics()
-}
diff --git a/internal/license/conversion/metrics_test.go b/internal/license/conversion/metrics_test.go
deleted file mode 100644
index fb5d5c042e..0000000000
--- a/internal/license/conversion/metrics_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package conversion
-
-import "testing"
-
-func TestGetConversionMetricsSingleton(t *testing.T) {
- first := GetConversionMetrics()
- second := GetConversionMetrics()
- if first != second {
- t.Fatal("expected GetConversionMetrics to return singleton instance")
- }
-}
-
-func TestGetConversionMetricsRecordMethods(t *testing.T) {
- metrics := GetConversionMetrics()
- if metrics == nil {
- t.Fatal("GetConversionMetrics() returned nil")
- }
-
- // Compatibility shim should preserve behavior and remain no-panic for callers.
- metrics.RecordEvent("", "")
- metrics.RecordEvent("checkout_completed", "pricing_modal")
- metrics.RecordInvalid("")
- metrics.RecordInvalid("schema")
- metrics.RecordSkipped("")
- metrics.RecordSkipped("disabled")
-}
diff --git a/internal/license/conversion/quality.go b/internal/license/conversion/quality.go
deleted file mode 100644
index d8e2c9c34c..0000000000
--- a/internal/license/conversion/quality.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package conversion
-
-import (
- "time"
-
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
-)
-
-type HealthStatus = pkglicensing.HealthStatus
-type PipelineHealth = pkglicensing.PipelineHealth
-type PipelineHealthOption = pkglicensing.PipelineHealthOption
-
-var knownConversionEventTypes = pkglicensing.KnownConversionEventTypes()
-
-// NewPipelineHealth creates a health tracker initialized at current time.
-func NewPipelineHealth(opts ...PipelineHealthOption) *PipelineHealth {
- return pkglicensing.NewPipelineHealth(opts...)
-}
-
-func WithPipelineHealthNow(now func() time.Time) PipelineHealthOption {
- return pkglicensing.WithPipelineHealthNow(now)
-}
-
-func WithPipelineHealthStaleThreshold(threshold time.Duration) PipelineHealthOption {
- return pkglicensing.WithPipelineHealthStaleThreshold(threshold)
-}
diff --git a/internal/license/conversion/quality_test.go b/internal/license/conversion/quality_test.go
deleted file mode 100644
index 2e460e3770..0000000000
--- a/internal/license/conversion/quality_test.go
+++ /dev/null
@@ -1,116 +0,0 @@
-package conversion
-
-import (
- "sync"
- "testing"
- "time"
-)
-
-func TestPipelineHealthHealthy(t *testing.T) {
- health := NewPipelineHealth()
- health.RecordEvent(EventPaywallViewed)
- health.RecordEvent(EventTrialStarted)
- health.RecordEvent(EventUpgradeClicked)
- health.RecordEvent(EventCheckoutCompleted)
-
- status := health.CheckHealth()
-
- if status.Status != "healthy" {
- t.Fatalf("status = %q, want healthy", status.Status)
- }
- if status.EventsTotal != 4 {
- t.Fatalf("events_total = %d, want 4", status.EventsTotal)
- }
- if len(status.EventsByType) != 4 {
- t.Fatalf("len(events_by_type) = %d, want 4", len(status.EventsByType))
- }
- if status.StartedAt <= 0 {
- t.Fatalf("started_at = %d, want > 0", status.StartedAt)
- }
-}
-
-func TestPipelineHealthStaleNoEvents(t *testing.T) {
- baseNow := time.Now()
- currentNow := baseNow
- health := NewPipelineHealth(
- WithPipelineHealthNow(func() time.Time { return currentNow }),
- WithPipelineHealthStaleThreshold(5*time.Minute),
- )
- currentNow = baseNow.Add(6 * time.Minute)
-
- status := health.CheckHealth()
-
- if status.Status != "stale" {
- t.Fatalf("status = %q, want stale", status.Status)
- }
- if status.EventsTotal != 0 {
- t.Fatalf("events_total = %d, want 0", status.EventsTotal)
- }
-}
-
-func TestPipelineHealthDegradedCoverage(t *testing.T) {
- health := NewPipelineHealth()
- for i := 0; i < 5; i++ {
- health.RecordEvent(EventPaywallViewed)
- }
-
- status := health.CheckHealth()
-
- if status.Status != "degraded" {
- t.Fatalf("status = %q, want degraded", status.Status)
- }
- if status.EventsByType[EventPaywallViewed] != 5 {
- t.Fatalf("events_by_type[%q] = %d, want 5", EventPaywallViewed, status.EventsByType[EventPaywallViewed])
- }
-}
-
-func TestPipelineHealthColdStartHealthy(t *testing.T) {
- health := NewPipelineHealth()
-
- status := health.CheckHealth()
-
- if status.Status != "healthy" {
- t.Fatalf("status = %q, want healthy", status.Status)
- }
- if status.EventsTotal != 0 {
- t.Fatalf("events_total = %d, want 0", status.EventsTotal)
- }
-}
-
-func TestPipelineHealthConcurrentAccess(t *testing.T) {
- health := NewPipelineHealth()
- eventTypes := append([]string(nil), knownConversionEventTypes...)
-
- const goroutines = 16
- const recordsPerGoroutine = 200
-
- var wg sync.WaitGroup
- wg.Add(goroutines)
- for g := 0; g < goroutines; g++ {
- go func(id int) {
- defer wg.Done()
- for i := 0; i < recordsPerGoroutine; i++ {
- health.RecordEvent(eventTypes[(id+i)%len(eventTypes)])
- _ = health.CheckHealth()
- }
- }(g)
- }
- wg.Wait()
-
- status := health.CheckHealth()
- wantTotal := int64(goroutines * recordsPerGoroutine)
- if status.EventsTotal != wantTotal {
- t.Fatalf("events_total = %d, want %d", status.EventsTotal, wantTotal)
- }
-
- var summed int64
- for _, count := range status.EventsByType {
- summed += count
- }
- if summed != wantTotal {
- t.Fatalf("sum(events_by_type) = %d, want %d", summed, wantTotal)
- }
- if status.Status != "healthy" {
- t.Fatalf("status = %q, want healthy", status.Status)
- }
-}
diff --git a/internal/license/conversion/recorder.go b/internal/license/conversion/recorder.go
deleted file mode 100644
index ca7f1dbdf5..0000000000
--- a/internal/license/conversion/recorder.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package conversion
-
-import (
- "errors"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/license/metering"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
-)
-
-// Recorder records conversion events through the metering aggregator.
-type Recorder struct {
- inner *pkglicensing.Recorder
-}
-
-func NewRecorder(agg *metering.WindowedAggregator, store *ConversionStore) *Recorder {
- var wrapped pkglicensing.ConversionAggregator
- if agg != nil {
- wrapped = &meteringAggregatorAdapter{agg: agg}
- }
-
- return &Recorder{
- inner: pkglicensing.NewRecorder(
- wrapped,
- store,
- func(err error) bool { return errors.Is(err, metering.ErrDuplicateEvent) },
- ),
- }
-}
-
-// Record validates and records a conversion event as a metering event.
-func (r *Recorder) Record(event ConversionEvent) error {
- if r == nil {
- var inner *pkglicensing.Recorder
- return inner.Record(event)
- }
- if r.inner == nil {
- return nil
- }
- return r.inner.Record(event)
-}
-
-// Snapshot returns a non-destructive copy of the current aggregation window buckets.
-func (r *Recorder) Snapshot() []metering.AggregatedBucket {
- if r == nil || r.inner == nil {
- return []metering.AggregatedBucket{}
- }
-
- snapshot := r.inner.Snapshot()
- out := make([]metering.AggregatedBucket, 0, len(snapshot))
- for _, bucket := range snapshot {
- out = append(out, metering.AggregatedBucket{
- TenantID: bucket.TenantID,
- Type: metering.EventType(bucket.Type),
- Key: bucket.Key,
- Count: bucket.Count,
- TotalValue: bucket.TotalValue,
- WindowStart: bucket.WindowStart,
- WindowEnd: bucket.WindowEnd,
- })
- }
- return out
-}
-
-type meteringAggregatorAdapter struct {
- agg *metering.WindowedAggregator
-}
-
-func (a *meteringAggregatorAdapter) Record(event pkglicensing.MeteringEvent) error {
- if a == nil || a.agg == nil {
- return nil
- }
- return a.agg.Record(metering.Event{
- Type: metering.EventType(event.Type),
- TenantID: event.TenantID,
- Key: event.Key,
- Value: event.Value,
- Timestamp: event.Timestamp,
- IdempotencyKey: event.IdempotencyKey,
- })
-}
-
-func (a *meteringAggregatorAdapter) Snapshot() []pkglicensing.MeteringBucket {
- if a == nil || a.agg == nil {
- return []pkglicensing.MeteringBucket{}
- }
-
- buckets := a.agg.Snapshot()
- out := make([]pkglicensing.MeteringBucket, 0, len(buckets))
- for _, bucket := range buckets {
- out = append(out, pkglicensing.MeteringBucket{
- TenantID: bucket.TenantID,
- Type: string(bucket.Type),
- Key: bucket.Key,
- Count: bucket.Count,
- TotalValue: bucket.TotalValue,
- WindowStart: bucket.WindowStart,
- WindowEnd: bucket.WindowEnd,
- })
- }
- return out
-}
diff --git a/internal/license/conversion/recorder_test.go b/internal/license/conversion/recorder_test.go
deleted file mode 100644
index c3d33a065c..0000000000
--- a/internal/license/conversion/recorder_test.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package conversion
-
-import (
- "testing"
- "time"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/license/metering"
-)
-
-func TestRecorderRecordValidEvent(t *testing.T) {
- agg := metering.NewWindowedAggregator()
- recorder := NewRecorder(agg, nil)
-
- err := recorder.Record(ConversionEvent{
- Type: EventPaywallViewed,
- OrgID: "default",
- Capability: "long_term_metrics",
- Surface: "history_chart",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "paywall:history_chart:long_term_metrics:1",
- })
- if err != nil {
- t.Fatalf("Record() error = %v, want nil", err)
- }
-
- buckets := agg.Flush()
- if len(buckets) != 1 {
- t.Fatalf("len(Flush()) = %d, want 1", len(buckets))
- }
-
- got := buckets[0]
- if got.Type != metering.EventType(EventPaywallViewed) {
- t.Fatalf("bucket type = %q, want %q", got.Type, EventPaywallViewed)
- }
- if got.TenantID != "default" {
- t.Fatalf("bucket tenant = %q, want default", got.TenantID)
- }
- if got.Key != "history_chart:long_term_metrics" {
- t.Fatalf("bucket key = %q, want history_chart:long_term_metrics", got.Key)
- }
- if got.Count != 1 {
- t.Fatalf("bucket count = %d, want 1", got.Count)
- }
-}
-
-func TestRecorderRecordIdempotency(t *testing.T) {
- agg := metering.NewWindowedAggregator()
- recorder := NewRecorder(agg, nil)
-
- event := ConversionEvent{
- Type: EventUpgradeClicked,
- OrgID: "default",
- Capability: "ai_autofix",
- Surface: "ai_intelligence",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "upgrade_clicked:ai_intelligence:ai_autofix:42",
- }
-
- if err := recorder.Record(event); err != nil {
- t.Fatalf("first Record() error = %v, want nil", err)
- }
- if err := recorder.Record(event); err != nil {
- t.Fatalf("second Record() error = %v, want nil (dedup accepted)", err)
- }
-
- buckets := agg.Flush()
- if len(buckets) != 1 {
- t.Fatalf("len(Flush()) = %d, want 1", len(buckets))
- }
- if buckets[0].Count != 1 {
- t.Fatalf("bucket count = %d, want 1", buckets[0].Count)
- }
-}
-
-func TestRecorderRecordValidationRejection(t *testing.T) {
- agg := metering.NewWindowedAggregator()
- recorder := NewRecorder(agg, nil)
-
- err := recorder.Record(ConversionEvent{
- Type: EventPaywallViewed,
- OrgID: "default",
- Surface: "settings_tab",
- Timestamp: time.Now().UnixMilli(),
- // missing capability for paywall_viewed
- IdempotencyKey: "paywall:settings_tab::1",
- })
- if err == nil {
- t.Fatal("Record() error = nil, want validation error")
- }
-}
-
-func TestRecorderRecordNilAggregator(t *testing.T) {
- recorder := NewRecorder(nil, nil)
-
- err := recorder.Record(ConversionEvent{
- Type: EventTrialStarted,
- Surface: "license_panel",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "trial_started:license_panel::1",
- })
- if err != nil {
- t.Fatalf("Record() error = %v, want nil", err)
- }
-}
diff --git a/internal/license/conversion/store.go b/internal/license/conversion/store.go
deleted file mode 100644
index f16188ef4d..0000000000
--- a/internal/license/conversion/store.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package conversion
-
-import pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
-
-type ConversionStore = pkglicensing.ConversionStore
-type StoredConversionEvent = pkglicensing.StoredConversionEvent
-type FunnelStageCounts = pkglicensing.FunnelStageCounts
-type FunnelSummary = pkglicensing.FunnelSummary
-type FunnelDayBreakdown = pkglicensing.FunnelDayBreakdown
-type FunnelDimensionBreakdown = pkglicensing.FunnelDimensionBreakdown
-type FunnelReport = pkglicensing.FunnelReport
-
-func NewConversionStore(dbPath string) (*ConversionStore, error) {
- return pkglicensing.NewConversionStore(dbPath)
-}
diff --git a/internal/license/conversion/store_test.go b/internal/license/conversion/store_test.go
deleted file mode 100644
index 4300ef8d91..0000000000
--- a/internal/license/conversion/store_test.go
+++ /dev/null
@@ -1,526 +0,0 @@
-package conversion
-
-import (
- "database/sql"
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "testing"
- "time"
-
- _ "modernc.org/sqlite"
-)
-
-func TestConversionStoreRecordAndQueryRoundTrip(t *testing.T) {
- tmp := t.TempDir()
- store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- now := time.Now().UTC().Truncate(time.Second)
- ev := StoredConversionEvent{
- OrgID: "org-a",
- EventType: EventPaywallViewed,
- Surface: "history_chart",
- Capability: "long_term_metrics",
- IdempotencyKey: "paywall_viewed:history_chart:long_term_metrics:1",
- CreatedAt: now,
- }
- if err := store.Record(ev); err != nil {
- t.Fatalf("Record() error = %v", err)
- }
-
- got, err := store.Query("org-a", now.Add(-time.Minute), now.Add(time.Minute), "")
- if err != nil {
- t.Fatalf("Query() error = %v", err)
- }
- if len(got) != 1 {
- t.Fatalf("len(Query()) = %d, want 1", len(got))
- }
- if got[0].OrgID != "org-a" {
- t.Fatalf("OrgID = %q, want org-a", got[0].OrgID)
- }
- if got[0].EventType != EventPaywallViewed {
- t.Fatalf("EventType = %q, want %q", got[0].EventType, EventPaywallViewed)
- }
- if got[0].Surface != "history_chart" {
- t.Fatalf("Surface = %q, want history_chart", got[0].Surface)
- }
- if got[0].Capability != "long_term_metrics" {
- t.Fatalf("Capability = %q, want long_term_metrics", got[0].Capability)
- }
- if got[0].IdempotencyKey != ev.IdempotencyKey {
- t.Fatalf("IdempotencyKey = %q, want %q", got[0].IdempotencyKey, ev.IdempotencyKey)
- }
-}
-
-func TestConversionStoreIdempotency(t *testing.T) {
- tmp := t.TempDir()
- store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- now := time.Now().UTC().Truncate(time.Second)
- ev := StoredConversionEvent{
- OrgID: "org-a",
- EventType: EventTrialStarted,
- Surface: "license_panel",
- Capability: "",
- IdempotencyKey: "trial_started:license_panel::1",
- CreatedAt: now,
- }
-
- if err := store.Record(ev); err != nil {
- t.Fatalf("first Record() error = %v", err)
- }
- if err := store.Record(ev); err != nil {
- t.Fatalf("second Record() error = %v", err)
- }
-
- got, err := store.Query("org-a", now.Add(-time.Minute), now.Add(time.Minute), "")
- if err != nil {
- t.Fatalf("Query() error = %v", err)
- }
- if len(got) != 1 {
- t.Fatalf("len(Query()) = %d, want 1", len(got))
- }
-}
-
-func TestConversionStoreSchemaHasCreatedAtIndex(t *testing.T) {
- tmp := t.TempDir()
- dbPath := filepath.Join(tmp, "conversion.db")
- store, err := NewConversionStore(dbPath)
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- db, err := sql.Open("sqlite", dbPath)
- if err != nil {
- t.Fatalf("failed to open sqlite db directly: %v", err)
- }
- defer db.Close()
-
- var count int
- err = db.QueryRow(
- `SELECT COUNT(1)
- FROM sqlite_master
- WHERE type = 'index' AND name = 'idx_conversion_events_time'`,
- ).Scan(&count)
- if err != nil {
- t.Fatalf("failed to query sqlite_master: %v", err)
- }
- if count != 1 {
- t.Fatalf("idx_conversion_events_time missing, count = %d", count)
- }
-}
-
-func TestConversionStoreFunnelSummaryAggregation(t *testing.T) {
- tmp := t.TempDir()
- store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- from := time.Now().UTC().Add(-1 * time.Hour).Truncate(time.Second)
- to := from.Add(2 * time.Hour)
-
- events := []StoredConversionEvent{
- {OrgID: "org-a", EventType: EventPricingViewed, Surface: "s0", Capability: "self_hosted_plan", IdempotencyKey: "k0", CreatedAt: from.Add(30 * time.Second)},
- {OrgID: "org-a", EventType: EventPaywallViewed, Surface: "s1", Capability: "c1", IdempotencyKey: "k1", CreatedAt: from.Add(1 * time.Minute)},
- {OrgID: "org-a", EventType: EventPaywallViewed, Surface: "s1", Capability: "c1", IdempotencyKey: "k2", CreatedAt: from.Add(2 * time.Minute)},
- {OrgID: "org-a", EventType: EventTrialStarted, Surface: "s2", Capability: "", IdempotencyKey: "k3", CreatedAt: from.Add(3 * time.Minute)},
- {OrgID: "org-a", EventType: EventUpgradeClicked, Surface: "s3", Capability: "relay", IdempotencyKey: "k4", CreatedAt: from.Add(4 * time.Minute)},
- {OrgID: "org-a", EventType: EventCheckoutClicked, Surface: "s4", Capability: "self_hosted_plan", IdempotencyKey: "k5", CreatedAt: from.Add(5 * time.Minute)},
- {OrgID: "org-a", EventType: EventCheckoutStarted, Surface: "s5", Capability: "", IdempotencyKey: "k6", CreatedAt: from.Add(6 * time.Minute)},
- {OrgID: "org-a", EventType: EventCheckoutCompleted, Surface: "s6", Capability: "", IdempotencyKey: "k7", CreatedAt: from.Add(7 * time.Minute)},
- {OrgID: "org-a", EventType: EventLicenseActivated, Surface: "s7", Capability: "", IdempotencyKey: "k8", CreatedAt: from.Add(8 * time.Minute)},
- {OrgID: "org-a", EventType: EventLicenseActivationFailed, Surface: "s8", Capability: "", IdempotencyKey: "k9", CreatedAt: from.Add(9 * time.Minute)},
- }
- for _, ev := range events {
- if err := store.Record(ev); err != nil {
- t.Fatalf("Record(%s) error = %v", ev.IdempotencyKey, err)
- }
- }
-
- summary, err := store.FunnelSummary("org-a", from, to)
- if err != nil {
- t.Fatalf("FunnelSummary() error = %v", err)
- }
- if summary.PaywallViewed != 2 {
- t.Fatalf("PaywallViewed = %d, want 2", summary.PaywallViewed)
- }
- if summary.PricingViewed != 1 {
- t.Fatalf("PricingViewed = %d, want 1", summary.PricingViewed)
- }
- if summary.TrialStarted != 1 {
- t.Fatalf("TrialStarted = %d, want 1", summary.TrialStarted)
- }
- if summary.UpgradeClicked != 1 {
- t.Fatalf("UpgradeClicked = %d, want 1", summary.UpgradeClicked)
- }
- if summary.CheckoutClicked != 1 {
- t.Fatalf("CheckoutClicked = %d, want 1", summary.CheckoutClicked)
- }
- if summary.CheckoutStarted != 1 {
- t.Fatalf("CheckoutStarted = %d, want 1", summary.CheckoutStarted)
- }
- if summary.CheckoutCompleted != 1 {
- t.Fatalf("CheckoutCompleted = %d, want 1", summary.CheckoutCompleted)
- }
- if summary.LicenseActivated != 1 {
- t.Fatalf("LicenseActivated = %d, want 1", summary.LicenseActivated)
- }
- if summary.LicenseActivationFailed != 1 {
- t.Fatalf("LicenseActivationFailed = %d, want 1", summary.LicenseActivationFailed)
- }
- if !summary.Period.From.Equal(from.UTC()) || !summary.Period.To.Equal(to.UTC()) {
- t.Fatalf("Period = %v..%v, want %v..%v", summary.Period.From, summary.Period.To, from.UTC(), to.UTC())
- }
-}
-
-func TestConversionStoreFunnelReportIncludesDailySurfaceAndCapabilityBreakdowns(t *testing.T) {
- tmp := t.TempDir()
- store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- from := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
- to := from.Add(3 * 24 * time.Hour)
-
- events := []StoredConversionEvent{
- {
- OrgID: "org-a",
- EventType: EventPricingViewed,
- Surface: "settings_self_hosted_billing_plan",
- Capability: "self_hosted_plan",
- IdempotencyKey: "funnel:1",
- CreatedAt: from.Add(2 * time.Hour),
- },
- {
- OrgID: "org-a",
- EventType: EventCheckoutClicked,
- Surface: "settings_self_hosted_billing_compare_prompt",
- Capability: "self_hosted_plan",
- IdempotencyKey: "funnel:2",
- CreatedAt: from.Add(3 * time.Hour),
- },
- {
- OrgID: "org-a",
- EventType: EventCheckoutStarted,
- Surface: "license_api",
- Capability: "self_hosted_plan",
- IdempotencyKey: "funnel:3",
- CreatedAt: from.Add(4 * time.Hour),
- },
- {
- OrgID: "org-a",
- EventType: EventLicenseActivated,
- Surface: "license_api",
- Capability: "self_hosted_plan",
- IdempotencyKey: "funnel:4",
- CreatedAt: from.Add(27 * time.Hour),
- },
- {
- OrgID: "org-a",
- EventType: EventTrialStarted,
- Surface: "license_panel",
- Capability: "relay",
- IdempotencyKey: "funnel:5",
- CreatedAt: from.Add(28 * time.Hour),
- },
- {
- OrgID: "org-a",
- EventType: EventPricingViewed,
- Surface: "paywall_modal",
- Capability: "relay",
- IdempotencyKey: "funnel:6",
- CreatedAt: from.Add(50 * time.Hour),
- },
- }
- for _, ev := range events {
- if err := store.Record(ev); err != nil {
- t.Fatalf("Record(%s) error = %v", ev.IdempotencyKey, err)
- }
- }
-
- report, err := store.FunnelReport("org-a", from, to)
- if err != nil {
- t.Fatalf("FunnelReport() error = %v", err)
- }
-
- if report.Summary.PricingViewed != 2 {
- t.Fatalf("Summary.PricingViewed = %d, want 2", report.Summary.PricingViewed)
- }
- if report.Summary.CheckoutClicked != 1 {
- t.Fatalf("Summary.CheckoutClicked = %d, want 1", report.Summary.CheckoutClicked)
- }
- if report.Summary.LicenseActivated != 1 {
- t.Fatalf("Summary.LicenseActivated = %d, want 1", report.Summary.LicenseActivated)
- }
- if len(report.Daily) != 3 {
- t.Fatalf("len(Daily) = %d, want 3", len(report.Daily))
- }
- if report.Daily[0].Day != "2026-04-01" || report.Daily[0].PricingViewed != 1 || report.Daily[0].CheckoutClicked != 1 {
- t.Fatalf("unexpected first daily bucket: %+v", report.Daily[0])
- }
- if report.Daily[1].Day != "2026-04-02" || report.Daily[1].LicenseActivated != 1 || report.Daily[1].TrialStarted != 1 {
- t.Fatalf("unexpected second daily bucket: %+v", report.Daily[1])
- }
- if report.Daily[2].Day != "2026-04-03" || report.Daily[2].PricingViewed != 1 {
- t.Fatalf("unexpected third daily bucket: %+v", report.Daily[2])
- }
-
- if len(report.Surfaces) < 3 {
- t.Fatalf("len(Surfaces) = %d, want >= 3", len(report.Surfaces))
- }
- if report.Surfaces[0].Key != "settings_self_hosted_billing_compare_prompt" {
- t.Fatalf("Surfaces[0].Key = %q, want settings_self_hosted_billing_compare_prompt", report.Surfaces[0].Key)
- }
- if report.Surfaces[0].CheckoutClicked != 1 {
- t.Fatalf("Surfaces[0].CheckoutClicked = %d, want 1", report.Surfaces[0].CheckoutClicked)
- }
-
- if len(report.Capabilities) != 2 {
- t.Fatalf("len(Capabilities) = %d, want 2", len(report.Capabilities))
- }
- if report.Capabilities[0].Key != "self_hosted_plan" {
- t.Fatalf("Capabilities[0].Key = %q, want self_hosted_plan", report.Capabilities[0].Key)
- }
- if report.Capabilities[0].PricingViewed != 1 || report.Capabilities[0].LicenseActivated != 1 {
- t.Fatalf("unexpected self_hosted_plan capability bucket: %+v", report.Capabilities[0])
- }
- if report.Capabilities[1].Key != "relay" {
- t.Fatalf("Capabilities[1].Key = %q, want relay", report.Capabilities[1].Key)
- }
-}
-
-func TestConversionStoreOrgIsolation(t *testing.T) {
- tmp := t.TempDir()
- store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- now := time.Now().UTC().Truncate(time.Second)
- if err := store.Record(StoredConversionEvent{
- OrgID: "org-a",
- EventType: EventPaywallViewed,
- Surface: "s",
- Capability: "c",
- IdempotencyKey: "org-a-k1",
- CreatedAt: now,
- }); err != nil {
- t.Fatalf("Record() error = %v", err)
- }
-
- got, err := store.Query("org-b", now.Add(-time.Minute), now.Add(time.Minute), "")
- if err != nil {
- t.Fatalf("Query() error = %v", err)
- }
- if len(got) != 0 {
- t.Fatalf("len(Query(org-b)) = %d, want 0", len(got))
- }
-}
-
-func TestConversionStoreRequiresOrgScopeForReads(t *testing.T) {
- tmp := t.TempDir()
- store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- now := time.Now().UTC().Truncate(time.Second)
- if _, err := store.Query("", now.Add(-time.Minute), now.Add(time.Minute), ""); err == nil {
- t.Fatal("Query() with empty org_id error = nil, want error")
- }
-
- if _, err := store.FunnelSummary("", now.Add(-time.Minute), now.Add(time.Minute)); err == nil {
- t.Fatal("FunnelSummary() with empty org_id error = nil, want error")
- }
- if _, err := store.FunnelDailyBreakdown("", now.Add(-time.Minute), now.Add(time.Minute)); err == nil {
- t.Fatal("FunnelDailyBreakdown() with empty org_id error = nil, want error")
- }
- if _, err := store.FunnelDimensionBreakdown("", now.Add(-time.Minute), now.Add(time.Minute), "surface"); err == nil {
- t.Fatal("FunnelDimensionBreakdown() with empty org_id error = nil, want error")
- }
-}
-
-func TestConversionStoreTimeRangeFiltering(t *testing.T) {
- tmp := t.TempDir()
- store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- base := time.Now().UTC().Truncate(time.Second)
- if err := store.Record(StoredConversionEvent{
- OrgID: "org-a",
- EventType: EventPaywallViewed,
- Surface: "s",
- Capability: "c",
- IdempotencyKey: "old",
- CreatedAt: base.Add(-2 * time.Hour),
- }); err != nil {
- t.Fatalf("Record(old) error = %v", err)
- }
- if err := store.Record(StoredConversionEvent{
- OrgID: "org-a",
- EventType: EventPaywallViewed,
- Surface: "s",
- Capability: "c",
- IdempotencyKey: "new",
- CreatedAt: base.Add(-10 * time.Minute),
- }); err != nil {
- t.Fatalf("Record(new) error = %v", err)
- }
-
- from := base.Add(-30 * time.Minute)
- to := base.Add(30 * time.Minute)
- got, err := store.Query("org-a", from, to, "")
- if err != nil {
- t.Fatalf("Query() error = %v", err)
- }
- if len(got) != 1 {
- t.Fatalf("len(Query()) = %d, want 1", len(got))
- }
- if got[0].IdempotencyKey != "new" {
- t.Fatalf("IdempotencyKey = %q, want new", got[0].IdempotencyKey)
- }
-}
-
-func TestConversionStoreConcurrentWrites(t *testing.T) {
- tmp := t.TempDir()
- store, err := NewConversionStore(filepath.Join(tmp, "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- start := time.Now().UTC().Truncate(time.Second)
-
- const goroutines = 5
- const perG = 100
-
- var wg sync.WaitGroup
- errCh := make(chan error, goroutines*perG)
- wg.Add(goroutines)
- for g := 0; g < goroutines; g++ {
- go func(id int) {
- defer wg.Done()
- for i := 0; i < perG; i++ {
- key := fmt.Sprintf("org-a:%d:%d", id, i)
- if err := store.Record(StoredConversionEvent{
- OrgID: "org-a",
- EventType: EventPaywallViewed,
- Surface: "s",
- Capability: "c",
- IdempotencyKey: key,
- CreatedAt: start.Add(time.Duration(i) * time.Second),
- }); err != nil {
- errCh <- err
- return
- }
- }
- }(g)
- }
- wg.Wait()
- close(errCh)
- for err := range errCh {
- if err != nil {
- t.Fatalf("concurrent Record() error = %v", err)
- }
- }
-
- got, err := store.Query("org-a", start.Add(-time.Minute), start.Add(10*time.Minute), EventPaywallViewed)
- if err != nil {
- t.Fatalf("Query() error = %v", err)
- }
- want := goroutines * perG
- if len(got) != want {
- t.Fatalf("len(Query()) = %d, want %d", len(got), want)
- }
-}
-
-func TestConversionStoreEnforcesOwnerOnlyPermissions(t *testing.T) {
- tmp := t.TempDir()
- if err := os.Chmod(tmp, 0755); err != nil {
- t.Fatalf("failed to relax temp dir perms: %v", err)
- }
-
- dbPath := filepath.Join(tmp, "conversion.db")
- store, err := NewConversionStore(dbPath)
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- if err := store.Record(StoredConversionEvent{
- OrgID: "org-a",
- EventType: EventPaywallViewed,
- Surface: "s",
- Capability: "c",
- IdempotencyKey: "perm-check",
- CreatedAt: time.Now().UTC(),
- }); err != nil {
- t.Fatalf("Record() error = %v", err)
- }
-
- dirInfo, err := os.Stat(tmp)
- if err != nil {
- t.Fatalf("failed to stat dir: %v", err)
- }
- if got := dirInfo.Mode().Perm(); got != 0700 {
- t.Fatalf("dir perms = %o, want 700", got)
- }
-
- dbInfo, err := os.Stat(dbPath)
- if err != nil {
- t.Fatalf("failed to stat db: %v", err)
- }
- if got := dbInfo.Mode().Perm(); got != 0600 {
- t.Fatalf("db perms = %o, want 600", got)
- }
-
- for _, sidecar := range []string{"-wal", "-shm"} {
- path := dbPath + sidecar
- if info, err := os.Stat(path); err == nil {
- if got := info.Mode().Perm(); got != 0600 {
- t.Fatalf("%s perms = %o, want 600", sidecar, got)
- }
- }
- }
-}
-
-func TestConversionStoreRejectsSymlinkDBPath(t *testing.T) {
- tmp := t.TempDir()
- target := filepath.Join(tmp, "real.db")
- if err := os.WriteFile(target, []byte(""), 0600); err != nil {
- t.Fatalf("failed to create target db file: %v", err)
- }
-
- linkPath := filepath.Join(tmp, "conversion.db")
- if err := os.Symlink(target, linkPath); err != nil {
- t.Skipf("symlink unsupported on this platform: %v", err)
- }
-
- _, err := NewConversionStore(linkPath)
- if err == nil {
- t.Fatal("expected NewConversionStore to reject symlink db path")
- }
- if !strings.Contains(err.Error(), "symlink") {
- t.Fatalf("expected symlink error, got: %v", err)
- }
-}
diff --git a/internal/license/conversion/upgrade_reasons.go b/internal/license/conversion/upgrade_reasons.go
deleted file mode 100644
index c522140778..0000000000
--- a/internal/license/conversion/upgrade_reasons.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package conversion
-
-import pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
-
-// ReasonEntry defines an actionable upgrade prompt tied to a missing feature.
-type ReasonEntry = pkglicensing.ReasonEntry
-
-// UpgradeReasonMatrix is the canonical feature-to-upgrade-reason mapping.
-var UpgradeReasonMatrix = pkglicensing.UpgradeReasonMatrix
-
-// GenerateUpgradeReasons returns upgrade reasons for features missing in capabilities.
-func GenerateUpgradeReasons(capabilities []string) []ReasonEntry {
- return pkglicensing.GenerateUpgradeReasons(capabilities)
-}
-
-// UpgradeURLForFeature returns the action URL for a given feature from the upgrade matrix.
-// Falls back to a generic pricing URL if the feature is not in the matrix.
-func UpgradeURLForFeature(feature string) string {
- return pkglicensing.UpgradeURLForFeature(feature)
-}
diff --git a/internal/license/conversion/upgrade_reasons_test.go b/internal/license/conversion/upgrade_reasons_test.go
deleted file mode 100644
index 0b4d907bea..0000000000
--- a/internal/license/conversion/upgrade_reasons_test.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package conversion
-
-import (
- "testing"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/license"
-)
-
-func TestGenerateUpgradeReasons_EmptyCapabilitiesReturnsAll(t *testing.T) {
- reasons := GenerateUpgradeReasons(nil)
- if len(reasons) != len(UpgradeReasonMatrix) {
- t.Fatalf("expected %d reasons, got %d", len(UpgradeReasonMatrix), len(reasons))
- }
-}
-
-func TestGenerateUpgradeReasons_ProCapabilitiesReturnsEmpty(t *testing.T) {
- capabilities := append([]string(nil), license.TierFeatures[license.TierPro]...)
- reasons := GenerateUpgradeReasons(capabilities)
- if len(reasons) != 0 {
- t.Fatalf("expected 0 reasons for pro capabilities, got %d", len(reasons))
- }
-}
-
-func TestGenerateUpgradeReasons_SortedByPriority(t *testing.T) {
- reasons := GenerateUpgradeReasons(nil)
- for i := 1; i < len(reasons); i++ {
- if reasons[i-1].Priority > reasons[i].Priority {
- t.Fatalf(
- "expected reasons sorted by priority at index %d: %d > %d",
- i,
- reasons[i-1].Priority,
- reasons[i].Priority,
- )
- }
- }
-}
-
-func TestGenerateUpgradeReasons_EntriesHaveRequiredFields(t *testing.T) {
- reasons := GenerateUpgradeReasons(nil)
- for i, reason := range reasons {
- if reason.Feature == "" {
- t.Fatalf("entry %d has empty feature", i)
- }
- if reason.Reason == "" {
- t.Fatalf("entry %d has empty reason", i)
- }
- if reason.ActionURL == "" {
- t.Fatalf("entry %d has empty action_url", i)
- }
- }
-}
-
-func TestUpgradeReasonMatrix_CompletenessAgainstProMinusFree(t *testing.T) {
- expected := expectedProOnlyFeatureSet()
- seen := make(map[string]struct{}, len(UpgradeReasonMatrix))
-
- if len(UpgradeReasonMatrix) != len(expected) {
- t.Fatalf("expected %d matrix entries, got %d", len(expected), len(UpgradeReasonMatrix))
- }
-
- for _, entry := range UpgradeReasonMatrix {
- if _, exists := seen[entry.Feature]; exists {
- t.Fatalf("duplicate matrix feature entry: %s", entry.Feature)
- }
- seen[entry.Feature] = struct{}{}
- if _, ok := expected[entry.Feature]; !ok {
- t.Fatalf("unexpected matrix feature: %s", entry.Feature)
- }
- }
-
- for feature := range expected {
- if _, ok := seen[feature]; !ok {
- t.Fatalf("missing matrix feature: %s", feature)
- }
- }
-}
-
-func TestUpgradeURLForFeature(t *testing.T) {
- for _, entry := range UpgradeReasonMatrix {
- got := UpgradeURLForFeature(entry.Feature)
- if got != entry.ActionURL {
- t.Fatalf("expected action URL %q for feature %q, got %q", entry.ActionURL, entry.Feature, got)
- }
- }
-}
-
-func TestUpgradeURLForFeatureUnknownFallsBackToGenericPricing(t *testing.T) {
- const expected = "https://pulserelay.pro/pricing?utm_source=pulse&utm_medium=app&utm_campaign=upgrade"
- if got := UpgradeURLForFeature("nonexistent_feature"); got != expected {
- t.Fatalf("expected generic pricing URL %q, got %q", expected, got)
- }
-}
-
-func TestUpgradeReasonMatrix_OperatorOutcomeCopyRemainsCanonical(t *testing.T) {
- expected := map[string]string{
- license.FeatureRelay: "Get Relay so Pulse stays reachable securely from anywhere instead of only on the local dashboard.",
- license.FeatureLongTermMetrics: "Get Relay for 14 days of history, or Pro for 90 days, so you can see what changed before and after an incident.",
- license.FeatureAIAlerts: "Upgrade to Pro so alerts arrive with root-cause analysis instead of a stack of symptoms.",
- license.FeatureAIAutoFix: "Upgrade to Pro so Pulse can move from finding issues to governed remediation with your approval or autonomy policy.",
- }
-
- for _, entry := range UpgradeReasonMatrix {
- want, ok := expected[entry.Feature]
- if !ok {
- continue
- }
- if entry.Reason != want {
- t.Fatalf("expected canonical reason %q for feature %q, got %q", want, entry.Feature, entry.Reason)
- }
- }
-}
-
-func expectedProOnlyFeatureSet() map[string]struct{} {
- proFeatures := make(map[string]struct{}, len(license.TierFeatures[license.TierPro]))
- for _, feature := range license.TierFeatures[license.TierPro] {
- proFeatures[feature] = struct{}{}
- }
- for _, feature := range license.TierFeatures[license.TierFree] {
- delete(proFeatures, feature)
- }
- for feature := range proFeatures {
- if license.IsCompatibilityOnlyFeature(feature) {
- delete(proFeatures, feature)
- }
- }
- return proFeatures
-}
diff --git a/internal/license/metering/aggregator.go b/internal/license/metering/aggregator.go
deleted file mode 100644
index 61076581da..0000000000
--- a/internal/license/metering/aggregator.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package metering
-
-import pkgmetering "github.com/rcourtman/pulse-go-rewrite/pkg/licensing/metering"
-
-const (
- MaxCardinalityPerTenant = pkgmetering.MaxCardinalityPerTenant
- MaxIdempotencyKeysPerWindow = pkgmetering.MaxIdempotencyKeysPerWindow
-)
-
-var (
- ErrCardinalityExceeded = pkgmetering.ErrCardinalityExceeded
- ErrDuplicateEvent = pkgmetering.ErrDuplicateEvent
- ErrIdempotencyKeyLimitExceeded = pkgmetering.ErrIdempotencyKeyLimitExceeded
-)
-
-type WindowedAggregator = pkgmetering.WindowedAggregator
-
-func NewWindowedAggregator() *WindowedAggregator {
- return pkgmetering.NewWindowedAggregator()
-}
diff --git a/internal/license/metering/aggregator_test.go b/internal/license/metering/aggregator_test.go
deleted file mode 100644
index 6c1cbabd34..0000000000
--- a/internal/license/metering/aggregator_test.go
+++ /dev/null
@@ -1,466 +0,0 @@
-package metering
-
-import (
- "errors"
- "fmt"
- "sync"
- "testing"
-)
-
-func TestAggregatorRecord(t *testing.T) {
- agg := NewWindowedAggregator()
-
- for i := 0; i < 3; i++ {
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- })
- if err != nil {
- t.Fatalf("record failed: %v", err)
- }
- }
-
- if got := agg.BucketCount(); got != 1 {
- t.Fatalf("BucketCount() = %d, want 1", got)
- }
-
- buckets := agg.Flush()
- if len(buckets) != 1 {
- t.Fatalf("len(flush) = %d, want 1", len(buckets))
- }
-
- if buckets[0].Count != 3 {
- t.Fatalf("bucket count = %d, want 3", buckets[0].Count)
- }
-}
-
-func TestAggregatorRecordDifferentKeys(t *testing.T) {
- agg := NewWindowedAggregator()
-
- keys := []string{"agent-1", "agent-2", "agent-3"}
- for _, key := range keys {
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: key,
- Value: 1,
- })
- if err != nil {
- t.Fatalf("record failed for key %q: %v", key, err)
- }
- }
-
- if got := agg.BucketCount(); got != len(keys) {
- t.Fatalf("BucketCount() = %d, want %d", got, len(keys))
- }
-}
-
-func TestAggregatorIdempotency(t *testing.T) {
- agg := NewWindowedAggregator()
-
- once := Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- IdempotencyKey: "abc",
- }
-
- if err := agg.Record(once); err != nil {
- t.Fatalf("first record failed: %v", err)
- }
-
- if err := agg.Record(once); !errors.Is(err, ErrDuplicateEvent) {
- t.Fatalf("second record error = %v, want %v", err, ErrDuplicateEvent)
- }
-
- firstFlush := agg.Flush()
- if len(firstFlush) != 1 {
- t.Fatalf("len(firstFlush) = %d, want 1", len(firstFlush))
- }
- if firstFlush[0].Count != 1 {
- t.Fatalf("firstFlush count = %d, want 1", firstFlush[0].Count)
- }
-
- withoutKey := Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- }
- if err := agg.Record(withoutKey); err != nil {
- t.Fatalf("record without idempotency key failed: %v", err)
- }
- if err := agg.Record(withoutKey); err != nil {
- t.Fatalf("second record without idempotency key failed: %v", err)
- }
-
- secondFlush := agg.Flush()
- if len(secondFlush) != 1 {
- t.Fatalf("len(secondFlush) = %d, want 1", len(secondFlush))
- }
- if secondFlush[0].Count != 2 {
- t.Fatalf("secondFlush count = %d, want 2", secondFlush[0].Count)
- }
-}
-
-func TestAggregatorIdempotencyKeyLimit(t *testing.T) {
- agg := NewWindowedAggregator()
-
- for i := 0; i < MaxIdempotencyKeysPerWindow; i++ {
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- IdempotencyKey: fmt.Sprintf("idem-%d", i),
- })
- if err != nil {
- t.Fatalf("record at i=%d failed: %v", i, err)
- }
- }
-
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- IdempotencyKey: "idem-overflow",
- }); !errors.Is(err, ErrIdempotencyKeyLimitExceeded) {
- t.Fatalf("overflow idempotency key error = %v, want %v", err, ErrIdempotencyKeyLimitExceeded)
- }
-
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- IdempotencyKey: "idem-1",
- }); !errors.Is(err, ErrDuplicateEvent) {
- t.Fatalf("duplicate idempotency key error = %v, want %v", err, ErrDuplicateEvent)
- }
-
- _ = agg.Flush()
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- IdempotencyKey: "idem-after-flush",
- }); err != nil {
- t.Fatalf("record after flush failed: %v", err)
- }
-}
-
-func TestAggregatorCardinalityLimit(t *testing.T) {
- agg := NewWindowedAggregator()
-
- for i := 0; i < MaxCardinalityPerTenant; i++ {
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: fmt.Sprintf("agent-%d", i),
- Value: 1,
- })
- if err != nil {
- t.Fatalf("record at i=%d failed: %v", i, err)
- }
- }
-
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-0",
- Value: 1,
- }); err != nil {
- t.Fatalf("record for existing key failed: %v", err)
- }
-
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-overflow",
- Value: 1,
- }); !errors.Is(err, ErrCardinalityExceeded) {
- t.Fatalf("overflow record error = %v, want %v", err, ErrCardinalityExceeded)
- }
-
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-b",
- Key: "agent-overflow",
- Value: 1,
- }); err != nil {
- t.Fatalf("different tenant record failed: %v", err)
- }
-
- if err := agg.Record(Event{
- Type: EventRelayBytes,
- TenantID: "tenant-a",
- Key: "stream-1",
- Value: 42,
- }); err != nil {
- t.Fatalf("different event type record failed: %v", err)
- }
-}
-
-func TestAggregatorFlush(t *testing.T) {
- agg := NewWindowedAggregator()
-
- events := []Event{
- {Type: EventAgentSeen, TenantID: "tenant-a", Key: "agent-1", Value: 1},
- {Type: EventAgentSeen, TenantID: "tenant-a", Key: "agent-1", Value: 1},
- {Type: EventRelayBytes, TenantID: "tenant-a", Key: "relay-1", Value: 100},
- {Type: EventRelayBytes, TenantID: "tenant-a", Key: "relay-1", Value: 50},
- }
- for _, event := range events {
- if err := agg.Record(event); err != nil {
- t.Fatalf("record failed: %v", err)
- }
- }
-
- buckets := agg.Flush()
- if len(buckets) != 2 {
- t.Fatalf("len(flush) = %d, want 2", len(buckets))
- }
-
- byBucket := make(map[string]AggregatedBucket, len(buckets))
- for _, b := range buckets {
- byBucket[bucketID(b)] = b
- if b.WindowStart.IsZero() {
- t.Fatal("WindowStart is zero, want initialized window start")
- }
- if b.WindowEnd.Before(b.WindowStart) {
- t.Fatalf("WindowEnd (%v) is before WindowStart (%v)", b.WindowEnd, b.WindowStart)
- }
- }
-
- agentBucket, ok := byBucket["tenant-a|agent_seen|agent-1"]
- if !ok {
- t.Fatal("agent bucket not found")
- }
- if agentBucket.Count != 2 {
- t.Fatalf("agent bucket count = %d, want 2", agentBucket.Count)
- }
- if agentBucket.TotalValue != 2 {
- t.Fatalf("agent bucket total = %d, want 2", agentBucket.TotalValue)
- }
-
- relayBucket, ok := byBucket["tenant-a|relay_bytes|relay-1"]
- if !ok {
- t.Fatal("relay bucket not found")
- }
- if relayBucket.Count != 2 {
- t.Fatalf("relay bucket count = %d, want 2", relayBucket.Count)
- }
- if relayBucket.TotalValue != 150 {
- t.Fatalf("relay bucket total = %d, want 150", relayBucket.TotalValue)
- }
-
- if got := agg.BucketCount(); got != 0 {
- t.Fatalf("BucketCount() after flush = %d, want 0", got)
- }
-
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- }); err != nil {
- t.Fatalf("record after flush failed: %v", err)
- }
-
- afterFlush := agg.Flush()
- if len(afterFlush) != 1 {
- t.Fatalf("len(afterFlush) = %d, want 1", len(afterFlush))
- }
- if !afterFlush[0].WindowStart.Equal(agentBucket.WindowEnd) {
- t.Fatalf("new window start = %v, want %v", afterFlush[0].WindowStart, agentBucket.WindowEnd)
- }
-}
-
-func TestAggregatorFlushEmpty(t *testing.T) {
- agg := NewWindowedAggregator()
-
- buckets := agg.Flush()
- if buckets == nil {
- t.Fatal("Flush() returned nil, want empty slice")
- }
- if len(buckets) != 0 {
- t.Fatalf("len(flush) = %d, want 0", len(buckets))
- }
-}
-
-func TestAggregatorSnapshotEmpty(t *testing.T) {
- agg := NewWindowedAggregator()
-
- buckets := agg.Snapshot()
- if buckets == nil {
- t.Fatal("Snapshot() returned nil, want empty slice")
- }
- if len(buckets) != 0 {
- t.Fatalf("len(snapshot) = %d, want 0", len(buckets))
- }
- if got := agg.BucketCount(); got != 0 {
- t.Fatalf("BucketCount() = %d, want 0", got)
- }
-}
-
-func TestAggregatorSnapshotNonDestructive(t *testing.T) {
- agg := NewWindowedAggregator()
-
- events := []Event{
- {Type: EventAgentSeen, TenantID: "tenant-a", Key: "agent-1", Value: 1},
- {Type: EventAgentSeen, TenantID: "tenant-a", Key: "agent-1", Value: 1},
- {Type: EventRelayBytes, TenantID: "tenant-a", Key: "relay-1", Value: 100},
- }
- for _, event := range events {
- if err := agg.Record(event); err != nil {
- t.Fatalf("record failed: %v", err)
- }
- }
-
- snapshot := agg.Snapshot()
- if len(snapshot) != 2 {
- t.Fatalf("len(snapshot) = %d, want 2", len(snapshot))
- }
-
- if got := agg.BucketCount(); got != 2 {
- t.Fatalf("BucketCount() after snapshot = %d, want 2", got)
- }
-
- flushed := agg.Flush()
- if len(flushed) != 2 {
- t.Fatalf("len(flush) = %d, want 2", len(flushed))
- }
-
- snapshotBuckets := make(map[string]AggregatedBucket, len(snapshot))
- for _, bucket := range snapshot {
- snapshotBuckets[bucketID(bucket)] = bucket
- }
- for _, bucket := range flushed {
- snap, ok := snapshotBuckets[bucketID(bucket)]
- if !ok {
- t.Fatalf("snapshot missing bucket %q", bucketID(bucket))
- }
- if snap.Count != bucket.Count {
- t.Fatalf("bucket %q count = %d in snapshot, want %d", bucketID(bucket), snap.Count, bucket.Count)
- }
- if snap.TotalValue != bucket.TotalValue {
- t.Fatalf("bucket %q total = %d in snapshot, want %d", bucketID(bucket), snap.TotalValue, bucket.TotalValue)
- }
- }
-}
-
-func TestAggregatorSnapshotReturnsCopy(t *testing.T) {
- agg := NewWindowedAggregator()
-
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- }); err != nil {
- t.Fatalf("record failed: %v", err)
- }
-
- first := agg.Snapshot()
- if len(first) != 1 {
- t.Fatalf("len(first snapshot) = %d, want 1", len(first))
- }
- first[0].Key = "mutated"
- first[0].Count = 999
- first[0].TotalValue = 999
-
- second := agg.Snapshot()
- if len(second) != 1 {
- t.Fatalf("len(second snapshot) = %d, want 1", len(second))
- }
- if second[0].Key != "agent-1" {
- t.Fatalf("second snapshot key = %q, want agent-1", second[0].Key)
- }
- if second[0].Count != 1 {
- t.Fatalf("second snapshot count = %d, want 1", second[0].Count)
- }
- if second[0].TotalValue != 1 {
- t.Fatalf("second snapshot total = %d, want 1", second[0].TotalValue)
- }
-}
-
-func TestAggregatorSnapshotPreservesIdempotencyState(t *testing.T) {
- agg := NewWindowedAggregator()
-
- event := Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- IdempotencyKey: "idem-key",
- }
- if err := agg.Record(event); err != nil {
- t.Fatalf("first record failed: %v", err)
- }
-
- _ = agg.Snapshot()
-
- if err := agg.Record(event); !errors.Is(err, ErrDuplicateEvent) {
- t.Fatalf("second record error = %v, want %v", err, ErrDuplicateEvent)
- }
-}
-
-func TestAggregatorConcurrency(t *testing.T) {
- agg := NewWindowedAggregator()
-
- const (
- goroutines = 10
- eventsPerGor = 100
- )
-
- var wg sync.WaitGroup
- errCh := make(chan error, goroutines)
-
- for g := 0; g < goroutines; g++ {
- wg.Add(1)
- go func(worker int) {
- defer wg.Done()
- for i := 0; i < eventsPerGor; i++ {
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-a",
- Key: "agent-1",
- Value: 1,
- })
- if err != nil {
- errCh <- fmt.Errorf("worker=%d i=%d: %w", worker, i, err)
- return
- }
- }
- }(g)
- }
-
- wg.Wait()
- close(errCh)
-
- for err := range errCh {
- t.Fatalf("concurrent record error: %v", err)
- }
-
- buckets := agg.Flush()
- if len(buckets) != 1 {
- t.Fatalf("len(flush) = %d, want 1", len(buckets))
- }
-
- wantTotal := int64(goroutines * eventsPerGor)
- if buckets[0].Count != wantTotal {
- t.Fatalf("count = %d, want %d", buckets[0].Count, wantTotal)
- }
- if buckets[0].TotalValue != wantTotal {
- t.Fatalf("total value = %d, want %d", buckets[0].TotalValue, wantTotal)
- }
-}
-
-func bucketID(b AggregatedBucket) string {
- return fmt.Sprintf("%s|%s|%s", b.TenantID, b.Type, b.Key)
-}
diff --git a/internal/license/metering/event.go b/internal/license/metering/event.go
deleted file mode 100644
index 016a6ea0c3..0000000000
--- a/internal/license/metering/event.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package metering
-
-import pkgmetering "github.com/rcourtman/pulse-go-rewrite/pkg/licensing/metering"
-
-type EventType = pkgmetering.EventType
-
-const (
- EventAgentSeen = pkgmetering.EventAgentSeen
- EventRelayBytes = pkgmetering.EventRelayBytes
-)
-
-type Event = pkgmetering.Event
-type AggregatedBucket = pkgmetering.AggregatedBucket
diff --git a/internal/repoctl/canonical_development_protocol_test.go b/internal/repoctl/canonical_development_protocol_test.go
index e5844fc478..b8b3ecf2ac 100644
--- a/internal/repoctl/canonical_development_protocol_test.go
+++ b/internal/repoctl/canonical_development_protocol_test.go
@@ -400,7 +400,6 @@ func TestSubsystemRegistryExistsAndReferencesContracts(t *testing.T) {
"pkg/licensing/persistence.go",
"pkg/licensing/activation_store.go",
"pkg/licensing/trial_activation.go",
- "pkg/licensing/conversion_",
"pkg/licensing/public_key.go",
"pkg/licensing/trial_start.go",
"internal/api/licensing_",
diff --git a/pkg/licensing/conversion_api_helpers.go b/pkg/licensing/conversion_api_helpers.go
deleted file mode 100644
index 5a5ea280ab..0000000000
--- a/pkg/licensing/conversion_api_helpers.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package licensing
-
-import (
- "fmt"
- "strconv"
- "strings"
- "time"
-)
-
-func ConversionValidationReason(err error) string {
- if err == nil {
- return "unknown"
- }
-
- msg := strings.ToLower(err.Error())
- switch {
- case strings.Contains(msg, "type is required"):
- return "missing_type"
- case strings.Contains(msg, "is not supported"):
- return "unsupported_type"
- case strings.Contains(msg, "surface is required"):
- return "missing_surface"
- case strings.Contains(msg, "timestamp is required"):
- return "missing_timestamp"
- case strings.Contains(msg, "idempotency_key is required"):
- return "missing_idempotency_key"
- case strings.Contains(msg, "tenant_mode must be"):
- return "invalid_tenant_mode"
- case strings.Contains(msg, "capability is required"):
- return "missing_capability"
- case strings.Contains(msg, "limit_key is required"):
- return "missing_limit_key"
- default:
- return "validation_error"
- }
-}
-
-func ParseOptionalTimeParam(raw string, defaultValue time.Time) (time.Time, error) {
- raw = strings.TrimSpace(raw)
- if raw == "" {
- return defaultValue.UTC(), nil
- }
-
- // RFC3339 / RFC3339Nano
- if t, err := time.Parse(time.RFC3339Nano, raw); err == nil {
- return t.UTC(), nil
- }
- if t, err := time.Parse(time.RFC3339, raw); err == nil {
- return t.UTC(), nil
- }
-
- // Date-only (local midnight is ambiguous; use UTC midnight).
- if t, err := time.ParseInLocation("2006-01-02", raw, time.UTC); err == nil {
- return t.UTC(), nil
- }
-
- // Unix seconds or milliseconds.
- if i, err := strconv.ParseInt(raw, 10, 64); err == nil {
- // Heuristic: >= 10^12 is likely ms.
- if i >= 1_000_000_000_000 {
- return time.UnixMilli(i).UTC(), nil
- }
- return time.Unix(i, 0).UTC(), nil
- }
-
- return time.Time{}, fmt.Errorf("unsupported time format")
-}
diff --git a/pkg/licensing/conversion_api_helpers_test.go b/pkg/licensing/conversion_api_helpers_test.go
deleted file mode 100644
index ec5ee99a04..0000000000
--- a/pkg/licensing/conversion_api_helpers_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package licensing
-
-import (
- "errors"
- "testing"
- "time"
-)
-
-func TestConversionValidationReason(t *testing.T) {
- tests := []struct {
- name string
- err error
- want string
- }{
- {name: "nil", err: nil, want: "unknown"},
- {name: "missing type", err: errors.New("type is required"), want: "missing_type"},
- {name: "unsupported type", err: errors.New("event type foo is not supported"), want: "unsupported_type"},
- {name: "missing surface", err: errors.New("surface is required"), want: "missing_surface"},
- {name: "missing timestamp", err: errors.New("timestamp is required"), want: "missing_timestamp"},
- {name: "missing idempotency key", err: errors.New("idempotency_key is required"), want: "missing_idempotency_key"},
- {name: "invalid tenant mode", err: errors.New("tenant_mode must be one of"), want: "invalid_tenant_mode"},
- {name: "missing capability", err: errors.New("capability is required"), want: "missing_capability"},
- {name: "missing limit key", err: errors.New("limit_key is required"), want: "missing_limit_key"},
- {name: "fallback", err: errors.New("something else"), want: "validation_error"},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := ConversionValidationReason(tt.err); got != tt.want {
- t.Fatalf("reason=%q, want %q", got, tt.want)
- }
- })
- }
-}
-
-func TestParseOptionalTimeParam(t *testing.T) {
- defaultTime := time.Unix(1700000000, 0).UTC()
-
- tests := []struct {
- name string
- raw string
- want time.Time
- wantErr bool
- }{
- {name: "empty defaults", raw: "", want: defaultTime, wantErr: false},
- {name: "rfc3339", raw: "2026-01-02T03:04:05Z", want: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), wantErr: false},
- {name: "date only", raw: "2026-01-02", want: time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC), wantErr: false},
- {name: "unix seconds", raw: "1700000000", want: time.Unix(1700000000, 0).UTC(), wantErr: false},
- {name: "unix millis", raw: "1700000000000", want: time.UnixMilli(1700000000000).UTC(), wantErr: false},
- {name: "invalid", raw: "not-a-time", wantErr: true},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got, err := ParseOptionalTimeParam(tt.raw, defaultTime)
- if tt.wantErr {
- if err == nil {
- t.Fatal("expected error, got nil")
- }
- return
- }
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if !got.Equal(tt.want) {
- t.Fatalf("time=%s, want %s", got.Format(time.RFC3339Nano), tt.want.Format(time.RFC3339Nano))
- }
- })
- }
-}
diff --git a/pkg/licensing/conversion_config.go b/pkg/licensing/conversion_config.go
deleted file mode 100644
index 4b8739ac9d..0000000000
--- a/pkg/licensing/conversion_config.go
+++ /dev/null
@@ -1,99 +0,0 @@
-package licensing
-
-import (
- "sort"
- "strings"
- "sync"
-)
-
-// CollectionConfigSnapshot is the API-facing runtime configuration state.
-type CollectionConfigSnapshot struct {
- Enabled bool `json:"enabled"`
- DisabledSurfaces []string `json:"disabled_surfaces"`
-}
-
-// CollectionConfig controls runtime conversion event collection.
-type CollectionConfig struct {
- mu sync.RWMutex
- enabled bool
- disabledSurfaces map[string]bool
-}
-
-// NewCollectionConfig returns a default runtime config with collection enabled.
-func NewCollectionConfig() *CollectionConfig {
- return &CollectionConfig{
- enabled: true,
- disabledSurfaces: make(map[string]bool),
- }
-}
-
-// IsEnabled reports whether global conversion collection is enabled.
-func (c *CollectionConfig) IsEnabled() bool {
- if c == nil {
- return true
- }
-
- c.mu.RLock()
- defer c.mu.RUnlock()
- return c.enabled
-}
-
-// IsSurfaceEnabled reports whether the given surface can collect events.
-func (c *CollectionConfig) IsSurfaceEnabled(surface string) bool {
- if c == nil {
- return true
- }
-
- c.mu.RLock()
- defer c.mu.RUnlock()
- if !c.enabled {
- return false
- }
- return !c.disabledSurfaces[strings.TrimSpace(surface)]
-}
-
-// GetConfig returns a copy of the current runtime config.
-func (c *CollectionConfig) GetConfig() CollectionConfigSnapshot {
- if c == nil {
- return CollectionConfigSnapshot{
- Enabled: true,
- DisabledSurfaces: []string{},
- }
- }
-
- c.mu.RLock()
- defer c.mu.RUnlock()
-
- disabled := make([]string, 0, len(c.disabledSurfaces))
- for surface := range c.disabledSurfaces {
- disabled = append(disabled, surface)
- }
- sort.Strings(disabled)
-
- return CollectionConfigSnapshot{
- Enabled: c.enabled,
- DisabledSurfaces: disabled,
- }
-}
-
-// UpdateConfig atomically replaces current runtime config with the snapshot.
-func (c *CollectionConfig) UpdateConfig(snapshot CollectionConfigSnapshot) {
- if c == nil {
- return
- }
-
- disabled := make(map[string]bool, len(snapshot.DisabledSurfaces))
- for _, surface := range snapshot.DisabledSurfaces {
- trimmed := strings.TrimSpace(surface)
- if trimmed == "" {
- continue
- }
- disabled[trimmed] = true
- }
-
- c.mu.Lock()
- defer c.mu.Unlock()
-
- c.enabled = snapshot.Enabled
- c.disabledSurfaces = disabled
-}
diff --git a/pkg/licensing/conversion_config_test.go b/pkg/licensing/conversion_config_test.go
deleted file mode 100644
index 1d82ca0cc9..0000000000
--- a/pkg/licensing/conversion_config_test.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package licensing
-
-import (
- "sync"
- "testing"
-)
-
-func TestCollectionConfigDefaultsToEnabled(t *testing.T) {
- cfg := NewCollectionConfig()
-
- if !cfg.IsEnabled() {
- t.Fatal("IsEnabled() = false, want true")
- }
- if !cfg.IsSurfaceEnabled("history_chart") {
- t.Fatal("IsSurfaceEnabled(history_chart) = false, want true")
- }
-
- snapshot := cfg.GetConfig()
- if !snapshot.Enabled {
- t.Fatal("snapshot.Enabled = false, want true")
- }
- if len(snapshot.DisabledSurfaces) != 0 {
- t.Fatalf("len(snapshot.DisabledSurfaces) = %d, want 0", len(snapshot.DisabledSurfaces))
- }
-}
-
-func TestCollectionConfigGlobalDisable(t *testing.T) {
- cfg := NewCollectionConfig()
- cfg.UpdateConfig(CollectionConfigSnapshot{
- Enabled: false,
- })
-
- if cfg.IsEnabled() {
- t.Fatal("IsEnabled() = true, want false")
- }
- if cfg.IsSurfaceEnabled("history_chart") {
- t.Fatal("IsSurfaceEnabled(history_chart) = true, want false")
- }
- if cfg.IsSurfaceEnabled("ai_intelligence") {
- t.Fatal("IsSurfaceEnabled(ai_intelligence) = true, want false")
- }
-}
-
-func TestCollectionConfigPerSurfaceDisable(t *testing.T) {
- cfg := NewCollectionConfig()
- cfg.UpdateConfig(CollectionConfigSnapshot{
- Enabled: true,
- DisabledSurfaces: []string{"history_chart"},
- })
-
- if !cfg.IsEnabled() {
- t.Fatal("IsEnabled() = false, want true")
- }
- if cfg.IsSurfaceEnabled("history_chart") {
- t.Fatal("IsSurfaceEnabled(history_chart) = true, want false")
- }
- if !cfg.IsSurfaceEnabled("ai_intelligence") {
- t.Fatal("IsSurfaceEnabled(ai_intelligence) = false, want true")
- }
-}
-
-func TestCollectionConfigUpdateRoundTrip(t *testing.T) {
- cfg := NewCollectionConfig()
-
- input := CollectionConfigSnapshot{
- Enabled: true,
- DisabledSurfaces: []string{"history_chart", "ai_intelligence"},
- }
- cfg.UpdateConfig(input)
- got := cfg.GetConfig()
-
- if got.Enabled != input.Enabled {
- t.Fatalf("snapshot.Enabled = %v, want %v", got.Enabled, input.Enabled)
- }
- if len(got.DisabledSurfaces) != len(input.DisabledSurfaces) {
- t.Fatalf("len(snapshot.DisabledSurfaces) = %d, want %d", len(got.DisabledSurfaces), len(input.DisabledSurfaces))
- }
-
- seen := make(map[string]bool, len(got.DisabledSurfaces))
- for _, surface := range got.DisabledSurfaces {
- seen[surface] = true
- }
- for _, surface := range input.DisabledSurfaces {
- if !seen[surface] {
- t.Fatalf("missing surface %q in snapshot", surface)
- }
- }
-}
-
-func TestCollectionConfigConcurrentAccess(t *testing.T) {
- cfg := NewCollectionConfig()
- const workers = 16
- const iterations = 300
-
- var wg sync.WaitGroup
- wg.Add(workers)
-
- for i := 0; i < workers; i++ {
- go func(worker int) {
- defer wg.Done()
- for j := 0; j < iterations; j++ {
- if (worker+j)%4 == 0 {
- cfg.UpdateConfig(CollectionConfigSnapshot{
- Enabled: (worker+j)%2 == 0,
- DisabledSurfaces: []string{
- "history_chart",
- "ai_intelligence",
- },
- })
- continue
- }
-
- _ = cfg.IsEnabled()
- _ = cfg.IsSurfaceEnabled("history_chart")
- _ = cfg.GetConfig()
- }
- }(i)
- }
-
- wg.Wait()
-
- snapshot := cfg.GetConfig()
- if snapshot.DisabledSurfaces == nil {
- t.Fatal("snapshot.DisabledSurfaces is nil, want non-nil slice")
- }
-}
diff --git a/pkg/licensing/conversion_events.go b/pkg/licensing/conversion_events.go
deleted file mode 100644
index d62561d757..0000000000
--- a/pkg/licensing/conversion_events.go
+++ /dev/null
@@ -1,112 +0,0 @@
-package licensing
-
-import (
- "fmt"
- "strings"
-)
-
-const (
- EventPricingViewed = "pricing_viewed"
- EventPaywallViewed = "paywall_viewed"
- EventTrialStarted = "trial_started"
- EventLicenseActivated = "license_activated"
- EventLicenseActivationFailed = "license_activation_failed"
- EventUpgradeClicked = "upgrade_clicked"
- EventCheckoutClicked = "checkout_clicked"
- EventCheckoutStarted = "checkout_started"
- EventCheckoutCompleted = "checkout_completed"
- EventLimitWarningShown = "limit_warning_shown"
- EventLimitBlocked = "limit_blocked"
- EventAgentInstallTokenGenerated = "agent_install_token_generated"
- EventAgentInstallCommandCopied = "agent_install_command_copied"
- EventAgentInstallProfileSelected = "agent_install_profile_selected"
- EventAgentFirstConnected = "agent_first_connected"
- EventInfrastructureOnboardingOpened = "infrastructure_onboarding_opened"
- EventInfrastructureOnboardingPathSelected = "infrastructure_onboarding_path_selected"
- EventInfrastructureOnboardingProbeResult = "infrastructure_onboarding_probe_result"
- EventInfrastructureOnboardingCatalogSelected = "infrastructure_onboarding_catalog_selected"
- EventInfrastructureOnboardingCredentialsOpened = "infrastructure_onboarding_credentials_opened"
-)
-
-var supportedConversionEventTypes = map[string]struct{}{
- EventPricingViewed: {},
- EventPaywallViewed: {},
- EventTrialStarted: {},
- EventLicenseActivated: {},
- EventLicenseActivationFailed: {},
- EventUpgradeClicked: {},
- EventCheckoutClicked: {},
- EventCheckoutStarted: {},
- EventCheckoutCompleted: {},
- EventLimitWarningShown: {},
- EventLimitBlocked: {},
- EventAgentInstallTokenGenerated: {},
- EventAgentInstallCommandCopied: {},
- EventAgentInstallProfileSelected: {},
- EventAgentFirstConnected: {},
- EventInfrastructureOnboardingOpened: {},
- EventInfrastructureOnboardingPathSelected: {},
- EventInfrastructureOnboardingProbeResult: {},
- EventInfrastructureOnboardingCatalogSelected: {},
- EventInfrastructureOnboardingCredentialsOpened: {},
-}
-
-// ConversionEvent is the canonical conversion instrumentation envelope.
-type ConversionEvent struct {
- Type string `json:"type"`
- OrgID string `json:"org_id,omitempty"`
- Capability string `json:"capability,omitempty"`
- Surface string `json:"surface"`
- TenantMode string `json:"tenant_mode,omitempty"`
- LimitKey string `json:"limit_key,omitempty"`
- CurrentValue int64 `json:"current_value,omitempty"`
- LimitValue int64 `json:"limit_value,omitempty"`
- Timestamp int64 `json:"timestamp"`
- IdempotencyKey string `json:"idempotency_key"`
-}
-
-// Validate ensures required fields and event-specific constraints are present.
-func (e ConversionEvent) Validate() error {
- eventType := strings.TrimSpace(e.Type)
- if eventType == "" {
- return fmt.Errorf("type is required")
- }
- if !IsKnownConversionEventType(eventType) {
- return fmt.Errorf("type %q is not supported", eventType)
- }
-
- if strings.TrimSpace(e.Surface) == "" {
- return fmt.Errorf("surface is required")
- }
- if e.Timestamp <= 0 {
- return fmt.Errorf("timestamp is required")
- }
- if strings.TrimSpace(e.IdempotencyKey) == "" {
- return fmt.Errorf("idempotency_key is required")
- }
-
- switch strings.TrimSpace(e.TenantMode) {
- case "", "single", "multi":
- default:
- return fmt.Errorf("tenant_mode must be \"single\" or \"multi\"")
- }
-
- switch eventType {
- case EventPaywallViewed:
- if strings.TrimSpace(e.Capability) == "" {
- return fmt.Errorf("capability is required for %s", EventPaywallViewed)
- }
- case EventLimitWarningShown, EventLimitBlocked:
- if strings.TrimSpace(e.LimitKey) == "" {
- return fmt.Errorf("limit_key is required for %s", eventType)
- }
- }
-
- return nil
-}
-
-// IsKnownConversionEventType reports whether the event type is supported.
-func IsKnownConversionEventType(eventType string) bool {
- _, ok := supportedConversionEventTypes[strings.TrimSpace(eventType)]
- return ok
-}
diff --git a/pkg/licensing/conversion_events_test.go b/pkg/licensing/conversion_events_test.go
deleted file mode 100644
index d8e3e2c7e2..0000000000
--- a/pkg/licensing/conversion_events_test.go
+++ /dev/null
@@ -1,145 +0,0 @@
-package licensing
-
-import (
- "strings"
- "testing"
- "time"
-)
-
-func TestConversionEventValidate(t *testing.T) {
- now := time.Now().UnixMilli()
-
- tests := []struct {
- name string
- event ConversionEvent
- wantError string
- }{
- {
- name: "missing type",
- event: ConversionEvent{Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "type is required",
- },
- {
- name: "unknown type",
- event: ConversionEvent{Type: "unknown", Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "is not supported",
- },
- {
- name: "missing surface",
- event: ConversionEvent{Type: EventTrialStarted, Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "surface is required",
- },
- {
- name: "missing timestamp",
- event: ConversionEvent{Type: EventTrialStarted, Surface: "dashboard", IdempotencyKey: "id-1"},
- wantError: "timestamp is required",
- },
- {
- name: "missing idempotency key",
- event: ConversionEvent{Type: EventTrialStarted, Surface: "dashboard", Timestamp: now},
- wantError: "idempotency_key is required",
- },
- {
- name: "invalid tenant mode",
- event: ConversionEvent{Type: EventTrialStarted, Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1", TenantMode: "invalid"},
- wantError: "tenant_mode must be",
- },
- {
- name: "paywall requires capability",
- event: ConversionEvent{Type: EventPaywallViewed, Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "capability is required",
- },
- {
- name: "valid pricing viewed event",
- event: ConversionEvent{
- Type: EventPricingViewed,
- Surface: "settings_self_hosted_billing_plan",
- Capability: "self_hosted_plan",
- Timestamp: now,
- IdempotencyKey: "id-pricing-viewed-1",
- },
- },
- {
- name: "valid checkout clicked event",
- event: ConversionEvent{
- Type: EventCheckoutClicked,
- Surface: "settings_self_hosted_billing_compare_prompt",
- Capability: "self_hosted_plan",
- Timestamp: now,
- IdempotencyKey: "id-checkout-clicked-1",
- },
- },
- {
- name: "valid infrastructure onboarding path event",
- event: ConversionEvent{
- Type: EventInfrastructureOnboardingPathSelected,
- Surface: "settings_infrastructure_add",
- Capability: "api",
- Timestamp: now,
- IdempotencyKey: "id-infra-onboarding-path-1",
- },
- },
- {
- name: "limit warning requires limit key",
- event: ConversionEvent{Type: EventLimitWarningShown, Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "limit_key is required",
- },
- {
- name: "limit blocked requires limit key",
- event: ConversionEvent{Type: EventLimitBlocked, Surface: "dashboard", Timestamp: now, IdempotencyKey: "id-1"},
- wantError: "limit_key is required",
- },
- {
- name: "valid paywall event",
- event: ConversionEvent{
- Type: EventPaywallViewed,
- Surface: "dashboard",
- Capability: "relay",
- Timestamp: now,
- IdempotencyKey: "id-1",
- TenantMode: "single",
- },
- },
- {
- name: "valid trial started with multi tenant mode",
- event: ConversionEvent{
- Type: EventTrialStarted,
- Surface: "dashboard",
- Timestamp: now,
- IdempotencyKey: "id-2",
- TenantMode: "multi",
- },
- },
- }
-
- for _, tc := range tests {
- tc := tc
- t.Run(tc.name, func(t *testing.T) {
- err := tc.event.Validate()
- if tc.wantError == "" && err != nil {
- t.Fatalf("expected nil error, got %v", err)
- }
- if tc.wantError != "" {
- if err == nil {
- t.Fatalf("expected error containing %q, got nil", tc.wantError)
- }
- if !strings.Contains(err.Error(), tc.wantError) {
- t.Fatalf("expected error containing %q, got %q", tc.wantError, err.Error())
- }
- }
- })
- }
-}
-
-func TestConversionEventValidateRejectsUnknownType(t *testing.T) {
- event := ConversionEvent{
- Type: "not_a_real_event",
- Surface: "settings_unified_agents",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "not_a_real_event:settings_unified_agents::1",
- }
-
- if err := event.Validate(); err == nil {
- t.Fatal("Validate() error = nil, want unsupported type error")
- }
-}
diff --git a/pkg/licensing/conversion_metrics.go b/pkg/licensing/conversion_metrics.go
deleted file mode 100644
index f7c228e96b..0000000000
--- a/pkg/licensing/conversion_metrics.go
+++ /dev/null
@@ -1,117 +0,0 @@
-package licensing
-
-import (
- "sync"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-// ConversionMetrics manages Prometheus instrumentation for conversion events.
-type ConversionMetrics struct {
- eventsTotal *prometheus.CounterVec
- invalidTotal *prometheus.CounterVec
- skippedTotal *prometheus.CounterVec
-}
-
-var (
- conversionMetricsInstance *ConversionMetrics
- conversionMetricsOnce sync.Once
- conversionMetricsFactory = defaultConversionMetricsFactory
-)
-
-// GetConversionMetrics returns the singleton conversion metrics instance.
-func GetConversionMetrics() *ConversionMetrics {
- conversionMetricsOnce.Do(func() {
- conversionMetricsInstance = conversionMetricsFactory()
- })
- return conversionMetricsInstance
-}
-
-func defaultConversionMetricsFactory() *ConversionMetrics {
- return newConversionMetrics(prometheus.DefaultRegisterer)
-}
-
-func newConversionMetrics(registerer prometheus.Registerer) *ConversionMetrics {
- if registerer == nil {
- registerer = prometheus.DefaultRegisterer
- }
-
- m := &ConversionMetrics{
- eventsTotal: prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Namespace: "pulse",
- Subsystem: "conversion",
- Name: "events_total",
- Help: "Total accepted conversion events by type and surface",
- },
- []string{"type", "surface"},
- ),
- invalidTotal: prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Namespace: "pulse",
- Subsystem: "conversion",
- Name: "events_invalid_total",
- Help: "Total invalid conversion events by reason",
- },
- []string{"reason"},
- ),
- skippedTotal: prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Namespace: "pulse",
- Subsystem: "conversion",
- Name: "events_skipped_total",
- Help: "Total conversion events skipped by collection reason",
- },
- []string{"reason"},
- ),
- }
-
- m.eventsTotal = registerCounterVec(registerer, m.eventsTotal)
- m.invalidTotal = registerCounterVec(registerer, m.invalidTotal)
- m.skippedTotal = registerCounterVec(registerer, m.skippedTotal)
-
- return m
-}
-
-func registerCounterVec(registerer prometheus.Registerer, counter *prometheus.CounterVec) *prometheus.CounterVec {
- if err := registerer.Register(counter); err != nil {
- if alreadyRegisteredErr, ok := err.(prometheus.AlreadyRegisteredError); ok {
- if existing, ok := alreadyRegisteredErr.ExistingCollector.(*prometheus.CounterVec); ok {
- return existing
- }
- }
- panic(err)
- }
- return counter
-}
-
-func defaultLabel(value string) string {
- if value == "" {
- return "unknown"
- }
- return value
-}
-
-// RecordEvent records an accepted conversion event.
-func (m *ConversionMetrics) RecordEvent(eventType, surface string) {
- if m == nil || m.eventsTotal == nil {
- return
- }
- m.eventsTotal.WithLabelValues(defaultLabel(eventType), defaultLabel(surface)).Inc()
-}
-
-// RecordInvalid records a conversion event validation failure.
-func (m *ConversionMetrics) RecordInvalid(reason string) {
- if m == nil || m.invalidTotal == nil {
- return
- }
- m.invalidTotal.WithLabelValues(defaultLabel(reason)).Inc()
-}
-
-// RecordSkipped records a conversion event skipped by runtime collection controls.
-func (m *ConversionMetrics) RecordSkipped(reason string) {
- if m == nil || m.skippedTotal == nil {
- return
- }
- m.skippedTotal.WithLabelValues(defaultLabel(reason)).Inc()
-}
diff --git a/pkg/licensing/conversion_metrics_test.go b/pkg/licensing/conversion_metrics_test.go
deleted file mode 100644
index a8776f8187..0000000000
--- a/pkg/licensing/conversion_metrics_test.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package licensing
-
-import (
- "sync"
- "testing"
-
- "github.com/prometheus/client_golang/prometheus"
- "github.com/prometheus/client_golang/prometheus/testutil"
-)
-
-func TestGetConversionMetricsSingletonAndCounters(t *testing.T) {
- registry := prometheus.NewRegistry()
- withConversionMetricsFactoryForTest(t, func() *ConversionMetrics {
- return newConversionMetrics(registry)
- })
-
- first := GetConversionMetrics()
- second := GetConversionMetrics()
- if first != second {
- t.Fatal("expected GetConversionMetrics to return singleton instance")
- }
-
- first.RecordEvent("", "")
- first.RecordEvent("checkout_completed", "pricing_modal")
- first.RecordInvalid("")
- first.RecordInvalid("schema")
- first.RecordSkipped("")
- first.RecordSkipped("disabled")
-
- if got := testutil.ToFloat64(first.eventsTotal.WithLabelValues("unknown", "unknown")); got != 1 {
- t.Fatalf("expected events_total unknown/unknown to be 1, got %v", got)
- }
- if got := testutil.ToFloat64(first.eventsTotal.WithLabelValues("checkout_completed", "pricing_modal")); got != 1 {
- t.Fatalf("expected events_total checkout_completed/pricing_modal to be 1, got %v", got)
- }
- if got := testutil.ToFloat64(first.invalidTotal.WithLabelValues("unknown")); got != 1 {
- t.Fatalf("expected invalid_total unknown to be 1, got %v", got)
- }
- if got := testutil.ToFloat64(first.invalidTotal.WithLabelValues("schema")); got != 1 {
- t.Fatalf("expected invalid_total schema to be 1, got %v", got)
- }
- if got := testutil.ToFloat64(first.skippedTotal.WithLabelValues("unknown")); got != 1 {
- t.Fatalf("expected skipped_total unknown to be 1, got %v", got)
- }
- if got := testutil.ToFloat64(first.skippedTotal.WithLabelValues("disabled")); got != 1 {
- t.Fatalf("expected skipped_total disabled to be 1, got %v", got)
- }
-}
-
-func TestNewConversionMetricsReusesAlreadyRegisteredCollectors(t *testing.T) {
- registry := prometheus.NewRegistry()
-
- first := newConversionMetrics(registry)
- second := newConversionMetrics(registry)
-
- if first.eventsTotal != second.eventsTotal {
- t.Fatal("events_total collector was not reused")
- }
- if first.invalidTotal != second.invalidTotal {
- t.Fatal("events_invalid_total collector was not reused")
- }
- if first.skippedTotal != second.skippedTotal {
- t.Fatal("events_skipped_total collector was not reused")
- }
-}
-
-func withConversionMetricsFactoryForTest(t *testing.T, factory func() *ConversionMetrics) {
- t.Helper()
-
- prevInstance := conversionMetricsInstance
- prevFactory := conversionMetricsFactory
-
- conversionMetricsInstance = nil
- conversionMetricsOnce = sync.Once{}
- conversionMetricsFactory = factory
-
- t.Cleanup(func() {
- conversionMetricsInstance = prevInstance
- conversionMetricsFactory = prevFactory
- conversionMetricsOnce = sync.Once{}
- if prevInstance != nil {
- conversionMetricsOnce.Do(func() {})
- }
- })
-}
diff --git a/pkg/licensing/conversion_quality.go b/pkg/licensing/conversion_quality.go
deleted file mode 100644
index 0bb64b79a5..0000000000
--- a/pkg/licensing/conversion_quality.go
+++ /dev/null
@@ -1,202 +0,0 @@
-package licensing
-
-import (
- "strings"
- "sync"
- "time"
-)
-
-const defaultPipelineStaleThreshold = 5 * time.Minute
-
-var pipelineCoverageEventTypes = []string{
- EventPaywallViewed,
- EventTrialStarted,
- EventUpgradeClicked,
- EventCheckoutCompleted,
-}
-
-// HealthStatus describes conversion pipeline health and recent activity.
-type HealthStatus struct {
- Status string `json:"status"`
- LastEventAgeSeconds float64 `json:"last_event_age_seconds"`
- EventsTotal int64 `json:"events_total"`
- EventsByType map[string]int64 `json:"events_by_type"`
- StartedAt int64 `json:"started_at"`
-}
-
-// PipelineHealthOption configures pipeline health behavior.
-type PipelineHealthOption func(*pipelineHealthOptions)
-
-type pipelineHealthOptions struct {
- now func() time.Time
- staleThreshold time.Duration
-}
-
-// WithPipelineHealthNow sets the clock source used by PipelineHealth.
-func WithPipelineHealthNow(now func() time.Time) PipelineHealthOption {
- return func(options *pipelineHealthOptions) {
- options.now = now
- }
-}
-
-// WithPipelineHealthStaleThreshold sets the stale threshold used by PipelineHealth.
-func WithPipelineHealthStaleThreshold(threshold time.Duration) PipelineHealthOption {
- return func(options *pipelineHealthOptions) {
- options.staleThreshold = threshold
- }
-}
-
-// PipelineHealth tracks conversion pipeline activity for health checks.
-type PipelineHealth struct {
- mu sync.RWMutex
- now func() time.Time
- staleThreshold time.Duration
- startedAt time.Time
- lastEventTime time.Time
- eventsTotal int64
- eventsByType map[string]int64
-}
-
-// NewPipelineHealth creates a health tracker initialized at current time.
-func NewPipelineHealth(opts ...PipelineHealthOption) *PipelineHealth {
- options := pipelineHealthOptions{
- now: time.Now,
- staleThreshold: defaultPipelineStaleThreshold,
- }
- for _, opt := range opts {
- if opt == nil {
- continue
- }
- opt(&options)
- }
- if options.now == nil {
- options.now = time.Now
- }
- if options.staleThreshold <= 0 {
- options.staleThreshold = defaultPipelineStaleThreshold
- }
-
- return &PipelineHealth{
- now: options.now,
- staleThreshold: options.staleThreshold,
- startedAt: options.now(),
- eventsByType: make(map[string]int64),
- }
-}
-
-// RecordEvent records an event occurrence for health tracking.
-func (p *PipelineHealth) RecordEvent(eventType string) {
- if p == nil {
- return
- }
-
- normalized := strings.TrimSpace(eventType)
- if normalized == "" {
- return
- }
-
- now := p.clockNow()
-
- p.mu.Lock()
- defer p.mu.Unlock()
-
- if p.startedAt.IsZero() {
- p.startedAt = now
- }
- if p.eventsByType == nil {
- p.eventsByType = make(map[string]int64)
- }
-
- p.lastEventTime = now
- p.eventsTotal++
- p.eventsByType[normalized]++
-}
-
-// CheckHealth returns the current conversion pipeline health assessment.
-func (p *PipelineHealth) CheckHealth() HealthStatus {
- now := time.Now()
- if p == nil {
- return HealthStatus{
- Status: "healthy",
- LastEventAgeSeconds: 0,
- EventsTotal: 0,
- EventsByType: map[string]int64{},
- StartedAt: now.UnixMilli(),
- }
- }
- now = p.clockNow()
- staleThreshold := p.staleThreshold
- if staleThreshold <= 0 {
- staleThreshold = defaultPipelineStaleThreshold
- }
-
- p.mu.RLock()
- startedAt := p.startedAt
- lastEventTime := p.lastEventTime
- eventsTotal := p.eventsTotal
- eventsByType := make(map[string]int64, len(p.eventsByType))
- for eventType, count := range p.eventsByType {
- eventsByType[eventType] = count
- }
- p.mu.RUnlock()
-
- if startedAt.IsZero() {
- startedAt = now
- }
-
- lastEventAge := now.Sub(startedAt).Seconds()
- if !lastEventTime.IsZero() {
- lastEventAge = now.Sub(lastEventTime).Seconds()
- }
- if lastEventAge < 0 {
- lastEventAge = 0
- }
-
- status := "healthy"
- if eventsTotal == 0 {
- if now.Sub(startedAt) > staleThreshold {
- status = "stale"
- }
- } else if now.Sub(lastEventTime) > staleThreshold {
- status = "stale"
- } else if !hasSufficientCoverage(eventsByType) {
- status = "degraded"
- }
-
- return HealthStatus{
- Status: status,
- LastEventAgeSeconds: lastEventAge,
- EventsTotal: eventsTotal,
- EventsByType: eventsByType,
- StartedAt: startedAt.UnixMilli(),
- }
-}
-
-// KnownConversionEventTypes returns the event types used by quality coverage checks.
-func KnownConversionEventTypes() []string {
- out := make([]string, len(pipelineCoverageEventTypes))
- copy(out, pipelineCoverageEventTypes)
- return out
-}
-
-func (p *PipelineHealth) clockNow() time.Time {
- if p == nil || p.now == nil {
- return time.Now()
- }
- return p.now()
-}
-
-func hasSufficientCoverage(eventsByType map[string]int64) bool {
- if len(pipelineCoverageEventTypes) == 0 {
- return true
- }
-
- seen := 0
- for _, eventType := range pipelineCoverageEventTypes {
- if eventsByType[eventType] > 0 {
- seen++
- }
- }
-
- return float64(seen) >= float64(len(pipelineCoverageEventTypes))*0.5
-}
diff --git a/pkg/licensing/conversion_quality_test.go b/pkg/licensing/conversion_quality_test.go
deleted file mode 100644
index eaf8263115..0000000000
--- a/pkg/licensing/conversion_quality_test.go
+++ /dev/null
@@ -1,116 +0,0 @@
-package licensing
-
-import (
- "sync"
- "testing"
- "time"
-)
-
-func TestPipelineHealthHealthy(t *testing.T) {
- health := NewPipelineHealth()
- health.RecordEvent(EventPaywallViewed)
- health.RecordEvent(EventTrialStarted)
- health.RecordEvent(EventUpgradeClicked)
- health.RecordEvent(EventCheckoutCompleted)
-
- status := health.CheckHealth()
-
- if status.Status != "healthy" {
- t.Fatalf("status = %q, want healthy", status.Status)
- }
- if status.EventsTotal != 4 {
- t.Fatalf("events_total = %d, want 4", status.EventsTotal)
- }
- if len(status.EventsByType) != 4 {
- t.Fatalf("len(events_by_type) = %d, want 4", len(status.EventsByType))
- }
- if status.StartedAt <= 0 {
- t.Fatalf("started_at = %d, want > 0", status.StartedAt)
- }
-}
-
-func TestPipelineHealthStaleNoEvents(t *testing.T) {
- baseNow := time.Now()
- currentNow := baseNow
- health := NewPipelineHealth(
- WithPipelineHealthNow(func() time.Time { return currentNow }),
- WithPipelineHealthStaleThreshold(5*time.Minute),
- )
- currentNow = baseNow.Add(6 * time.Minute)
-
- status := health.CheckHealth()
-
- if status.Status != "stale" {
- t.Fatalf("status = %q, want stale", status.Status)
- }
- if status.EventsTotal != 0 {
- t.Fatalf("events_total = %d, want 0", status.EventsTotal)
- }
-}
-
-func TestPipelineHealthDegradedCoverage(t *testing.T) {
- health := NewPipelineHealth()
- for i := 0; i < 5; i++ {
- health.RecordEvent(EventPaywallViewed)
- }
-
- status := health.CheckHealth()
-
- if status.Status != "degraded" {
- t.Fatalf("status = %q, want degraded", status.Status)
- }
- if status.EventsByType[EventPaywallViewed] != 5 {
- t.Fatalf("events_by_type[%q] = %d, want 5", EventPaywallViewed, status.EventsByType[EventPaywallViewed])
- }
-}
-
-func TestPipelineHealthColdStartHealthy(t *testing.T) {
- health := NewPipelineHealth()
-
- status := health.CheckHealth()
-
- if status.Status != "healthy" {
- t.Fatalf("status = %q, want healthy", status.Status)
- }
- if status.EventsTotal != 0 {
- t.Fatalf("events_total = %d, want 0", status.EventsTotal)
- }
-}
-
-func TestPipelineHealthConcurrentAccess(t *testing.T) {
- health := NewPipelineHealth()
- eventTypes := KnownConversionEventTypes()
-
- const goroutines = 16
- const recordsPerGoroutine = 200
-
- var wg sync.WaitGroup
- wg.Add(goroutines)
- for g := 0; g < goroutines; g++ {
- go func(id int) {
- defer wg.Done()
- for i := 0; i < recordsPerGoroutine; i++ {
- health.RecordEvent(eventTypes[(id+i)%len(eventTypes)])
- _ = health.CheckHealth()
- }
- }(g)
- }
- wg.Wait()
-
- status := health.CheckHealth()
- wantTotal := int64(goroutines * recordsPerGoroutine)
- if status.EventsTotal != wantTotal {
- t.Fatalf("events_total = %d, want %d", status.EventsTotal, wantTotal)
- }
-
- var summed int64
- for _, count := range status.EventsByType {
- summed += count
- }
- if summed != wantTotal {
- t.Fatalf("sum(events_by_type) = %d, want %d", summed, wantTotal)
- }
- if status.Status != "healthy" {
- t.Fatalf("status = %q, want healthy", status.Status)
- }
-}
diff --git a/pkg/licensing/conversion_recorder.go b/pkg/licensing/conversion_recorder.go
deleted file mode 100644
index ae805b6c6b..0000000000
--- a/pkg/licensing/conversion_recorder.go
+++ /dev/null
@@ -1,108 +0,0 @@
-package licensing
-
-import (
- "fmt"
- "strings"
- "time"
-)
-
-// MeteringEvent is the canonical event shape expected by conversion recorders.
-type MeteringEvent struct {
- Type string
- TenantID string
- Key string
- Value int64
- Timestamp time.Time
- IdempotencyKey string
-}
-
-// MeteringBucket is the canonical snapshot bucket shape for conversion stats.
-type MeteringBucket struct {
- TenantID string
- Type string
- Key string
- Count int64
- TotalValue int64
- WindowStart time.Time
- WindowEnd time.Time
-}
-
-// ConversionAggregator is the runtime aggregation dependency used by Recorder.
-type ConversionAggregator interface {
- Record(event MeteringEvent) error
- Snapshot() []MeteringBucket
-}
-
-// Recorder records conversion events through an aggregator and optional durable store.
-type Recorder struct {
- agg ConversionAggregator
- store *ConversionStore
- isDuplicateError func(error) bool
-}
-
-// NewRecorder creates a recorder backed by the given aggregator and store.
-func NewRecorder(agg ConversionAggregator, store *ConversionStore, isDuplicateError func(error) bool) *Recorder {
- return &Recorder{
- agg: agg,
- store: store,
- isDuplicateError: isDuplicateError,
- }
-}
-
-// Record validates and records a conversion event as a metering event.
-func (r *Recorder) Record(event ConversionEvent) error {
- if err := event.Validate(); err != nil {
- return fmt.Errorf("validate conversion event: %w", err)
- }
- if r == nil {
- return nil
- }
- if r.agg == nil && r.store == nil {
- return nil
- }
-
- orgID := strings.TrimSpace(event.OrgID)
- if orgID == "" {
- return fmt.Errorf("org_id is required")
- }
-
- if r.store != nil {
- if err := r.store.Record(StoredConversionEvent{
- OrgID: orgID,
- EventType: event.Type,
- Surface: event.Surface,
- Capability: event.Capability,
- IdempotencyKey: event.IdempotencyKey,
- CreatedAt: time.UnixMilli(event.Timestamp).UTC(),
- }); err != nil {
- return fmt.Errorf("persist conversion event: %w", err)
- }
- }
-
- if r.agg != nil {
- err := r.agg.Record(MeteringEvent{
- Type: event.Type,
- TenantID: orgID,
- Key: event.Surface + ":" + event.Capability,
- Value: 1,
- Timestamp: time.UnixMilli(event.Timestamp),
- IdempotencyKey: event.IdempotencyKey,
- })
- if err != nil && r.isDuplicateError != nil && r.isDuplicateError(err) {
- return nil
- }
- if err != nil {
- return fmt.Errorf("record metering conversion event: %w", err)
- }
- }
-
- return nil
-}
-
-// Snapshot returns a non-destructive copy of the current aggregation window buckets.
-func (r *Recorder) Snapshot() []MeteringBucket {
- if r == nil || r.agg == nil {
- return []MeteringBucket{}
- }
- return r.agg.Snapshot()
-}
diff --git a/pkg/licensing/conversion_recorder_metering.go b/pkg/licensing/conversion_recorder_metering.go
deleted file mode 100644
index 25946a7237..0000000000
--- a/pkg/licensing/conversion_recorder_metering.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package licensing
-
-import (
- "errors"
-
- "github.com/rcourtman/pulse-go-rewrite/pkg/licensing/metering"
-)
-
-// NewRecorderFromWindowedAggregator creates a conversion recorder backed by
-// metering.WindowedAggregator and optional durable conversion store.
-func NewRecorderFromWindowedAggregator(agg *metering.WindowedAggregator, store *ConversionStore) *Recorder {
- var wrapped ConversionAggregator
- if agg != nil {
- wrapped = &windowedAggregatorAdapter{agg: agg}
- }
-
- return NewRecorder(
- wrapped,
- store,
- func(err error) bool { return errors.Is(err, metering.ErrDuplicateEvent) },
- )
-}
-
-type windowedAggregatorAdapter struct {
- agg *metering.WindowedAggregator
-}
-
-func (a *windowedAggregatorAdapter) Record(event MeteringEvent) error {
- if a == nil || a.agg == nil {
- return nil
- }
- return a.agg.Record(metering.Event{
- Type: metering.EventType(event.Type),
- TenantID: event.TenantID,
- Key: event.Key,
- Value: event.Value,
- Timestamp: event.Timestamp,
- IdempotencyKey: event.IdempotencyKey,
- })
-}
-
-func (a *windowedAggregatorAdapter) Snapshot() []MeteringBucket {
- if a == nil || a.agg == nil {
- return []MeteringBucket{}
- }
-
- buckets := a.agg.Snapshot()
- out := make([]MeteringBucket, 0, len(buckets))
- for _, bucket := range buckets {
- out = append(out, MeteringBucket{
- TenantID: bucket.TenantID,
- Type: string(bucket.Type),
- Key: bucket.Key,
- Count: bucket.Count,
- TotalValue: bucket.TotalValue,
- WindowStart: bucket.WindowStart,
- WindowEnd: bucket.WindowEnd,
- })
- }
- return out
-}
diff --git a/pkg/licensing/conversion_recorder_test.go b/pkg/licensing/conversion_recorder_test.go
deleted file mode 100644
index f69e9048b8..0000000000
--- a/pkg/licensing/conversion_recorder_test.go
+++ /dev/null
@@ -1,124 +0,0 @@
-package licensing
-
-import (
- "errors"
- "strings"
- "testing"
- "time"
-)
-
-func TestRecorderRecordValidEvent(t *testing.T) {
- agg := &fakeConversionAggregator{}
- recorder := NewRecorder(agg, nil, nil)
-
- err := recorder.Record(ConversionEvent{
- Type: EventPaywallViewed,
- OrgID: "default",
- Capability: "long_term_metrics",
- Surface: "history_chart",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "paywall:history_chart:long_term_metrics:1",
- })
- if err != nil {
- t.Fatalf("Record() error = %v, want nil", err)
- }
-
- if len(agg.recorded) != 1 {
- t.Fatalf("len(recorded) = %d, want 1", len(agg.recorded))
- }
- got := agg.recorded[0]
- if got.Type != EventPaywallViewed {
- t.Fatalf("recorded type = %q, want %q", got.Type, EventPaywallViewed)
- }
- if got.TenantID != "default" {
- t.Fatalf("recorded tenant = %q, want default", got.TenantID)
- }
- if got.Key != "history_chart:long_term_metrics" {
- t.Fatalf("recorded key = %q, want history_chart:long_term_metrics", got.Key)
- }
- if got.Value != 1 {
- t.Fatalf("recorded value = %d, want 1", got.Value)
- }
-}
-
-func TestRecorderRecordIdempotencyPredicate(t *testing.T) {
- duplicateErr := errors.New("duplicate")
- agg := &fakeConversionAggregator{recordErr: duplicateErr}
- recorder := NewRecorder(agg, nil, func(err error) bool { return errors.Is(err, duplicateErr) })
-
- err := recorder.Record(ConversionEvent{
- Type: EventUpgradeClicked,
- OrgID: "default",
- Capability: "ai_autofix",
- Surface: "ai_intelligence",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "upgrade_clicked:ai_intelligence:ai_autofix:42",
- })
- if err != nil {
- t.Fatalf("Record() error = %v, want nil for duplicate event", err)
- }
-}
-
-func TestRecorderRecordValidationRejection(t *testing.T) {
- agg := &fakeConversionAggregator{}
- recorder := NewRecorder(agg, nil, nil)
-
- err := recorder.Record(ConversionEvent{
- Type: EventPaywallViewed,
- OrgID: "default",
- Surface: "settings_tab",
- Timestamp: time.Now().UnixMilli(),
- // missing capability for paywall_viewed
- IdempotencyKey: "paywall:settings_tab::1",
- })
- if err == nil {
- t.Fatal("Record() error = nil, want validation error")
- }
-}
-
-func TestRecorderRecordUnexpectedAggregatorError(t *testing.T) {
- agg := &fakeConversionAggregator{recordErr: errors.New("write failed")}
- recorder := NewRecorder(agg, nil, nil)
-
- err := recorder.Record(ConversionEvent{
- Type: EventTrialStarted,
- OrgID: "default",
- Surface: "license_panel",
- Timestamp: time.Now().UnixMilli(),
- IdempotencyKey: "trial_started:license_panel::1",
- })
- if err == nil {
- t.Fatal("Record() error = nil, want wrapped error")
- }
- if !strings.Contains(err.Error(), "record metering conversion event") {
- t.Fatalf("Record() error = %v, want wrapped metering error", err)
- }
-}
-
-func TestRecorderSnapshotNilAggregator(t *testing.T) {
- recorder := NewRecorder(nil, nil, nil)
- buckets := recorder.Snapshot()
- if len(buckets) != 0 {
- t.Fatalf("len(Snapshot()) = %d, want 0", len(buckets))
- }
-}
-
-type fakeConversionAggregator struct {
- recorded []MeteringEvent
- snapshot []MeteringBucket
- recordErr error
-}
-
-func (f *fakeConversionAggregator) Record(event MeteringEvent) error {
- f.recorded = append(f.recorded, event)
- return f.recordErr
-}
-
-func (f *fakeConversionAggregator) Snapshot() []MeteringBucket {
- if f.snapshot == nil {
- return []MeteringBucket{}
- }
- out := make([]MeteringBucket, len(f.snapshot))
- copy(out, f.snapshot)
- return out
-}
diff --git a/pkg/licensing/conversion_store.go b/pkg/licensing/conversion_store.go
deleted file mode 100644
index 303a5d6c4b..0000000000
--- a/pkg/licensing/conversion_store.go
+++ /dev/null
@@ -1,878 +0,0 @@
-package licensing
-
-import (
- "database/sql"
- "errors"
- "fmt"
- "net/url"
- "os"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
- _ "modernc.org/sqlite"
-)
-
-const (
- privateDirPerm = 0o700
- privateFilePerm = 0o600
-)
-
-type ConversionStore struct {
- db *sql.DB
-}
-
-type StoredConversionEvent struct {
- ID int64
- OrgID string
- EventType string
- Surface string
- Capability string
- IdempotencyKey string
- CreatedAt time.Time
-}
-
-type FunnelStageCounts struct {
- PricingViewed int64 `json:"pricing_viewed"`
- PaywallViewed int64 `json:"paywall_viewed"`
- TrialStarted int64 `json:"trial_started"`
- UpgradeClicked int64 `json:"upgrade_clicked"`
- CheckoutClicked int64 `json:"checkout_clicked"`
- CheckoutStarted int64 `json:"checkout_started"`
- CheckoutCompleted int64 `json:"checkout_completed"`
- LicenseActivated int64 `json:"license_activated"`
- LicenseActivationFailed int64 `json:"license_activation_failed"`
-}
-
-type FunnelSummary struct {
- FunnelStageCounts
- Period struct {
- From time.Time `json:"from"`
- To time.Time `json:"to"`
- } `json:"period"`
-}
-
-type FunnelDayBreakdown struct {
- Day string `json:"day"`
- FunnelStageCounts
-}
-
-type FunnelDimensionBreakdown struct {
- Key string `json:"key"`
- FunnelStageCounts
-}
-
-type FunnelReport struct {
- Summary FunnelSummary `json:"summary"`
- Daily []FunnelDayBreakdown `json:"daily"`
- Surfaces []FunnelDimensionBreakdown `json:"surfaces"`
- Capabilities []FunnelDimensionBreakdown `json:"capabilities"`
-}
-
-type InfrastructureOnboardingStageCounts struct {
- Opened int64 `json:"opened"`
- APIPathSelected int64 `json:"api_path_selected"`
- AgentPathSelected int64 `json:"agent_path_selected"`
- ProbeDetected int64 `json:"probe_detected"`
- ProbeNoMatch int64 `json:"probe_no_match"`
- ProbeError int64 `json:"probe_error"`
- CatalogSelected int64 `json:"catalog_selected"`
- CredentialsOpened int64 `json:"credentials_opened"`
-}
-
-type InfrastructureOnboardingSummary struct {
- InfrastructureOnboardingStageCounts
- Period struct {
- From time.Time `json:"from"`
- To time.Time `json:"to"`
- } `json:"period"`
-}
-
-type InfrastructureOnboardingDayBreakdown struct {
- Day string `json:"day"`
- InfrastructureOnboardingStageCounts
-}
-
-type InfrastructureOnboardingPathBreakdown struct {
- Key string `json:"key"`
- Count int64 `json:"count"`
-}
-
-type InfrastructureOnboardingPlatformBreakdown struct {
- Key string `json:"key"`
- CatalogSelected int64 `json:"catalog_selected"`
- CredentialsOpened int64 `json:"credentials_opened"`
-}
-
-type InfrastructureOnboardingReport struct {
- Summary InfrastructureOnboardingSummary `json:"summary"`
- Daily []InfrastructureOnboardingDayBreakdown `json:"daily"`
- Paths []InfrastructureOnboardingPathBreakdown `json:"paths"`
- Platforms []InfrastructureOnboardingPlatformBreakdown `json:"platforms"`
-}
-
-var infrastructureOnboardingEventTypes = []string{
- EventInfrastructureOnboardingOpened,
- EventInfrastructureOnboardingPathSelected,
- EventInfrastructureOnboardingProbeResult,
- EventInfrastructureOnboardingCatalogSelected,
- EventInfrastructureOnboardingCredentialsOpened,
-}
-
-var infrastructureOnboardingPlatformCapabilities = map[string]struct{}{
- "vmware": {},
- "truenas": {},
- "pve": {},
- "pbs": {},
- "pmg": {},
-}
-
-func applyFunnelStageCount(counts *FunnelStageCounts, eventType string, count int64) {
- if counts == nil {
- return
- }
-
- switch strings.TrimSpace(eventType) {
- case EventPricingViewed:
- counts.PricingViewed = count
- case EventPaywallViewed:
- counts.PaywallViewed = count
- case EventTrialStarted:
- counts.TrialStarted = count
- case EventUpgradeClicked:
- counts.UpgradeClicked = count
- case EventCheckoutClicked:
- counts.CheckoutClicked = count
- case EventCheckoutStarted:
- counts.CheckoutStarted = count
- case EventCheckoutCompleted:
- counts.CheckoutCompleted = count
- case EventLicenseActivated:
- counts.LicenseActivated = count
- case EventLicenseActivationFailed:
- counts.LicenseActivationFailed = count
- }
-}
-
-func compareFunnelBreakdowns(a, b FunnelDimensionBreakdown) int {
- switch {
- case a.CheckoutClicked != b.CheckoutClicked:
- if a.CheckoutClicked > b.CheckoutClicked {
- return -1
- }
- return 1
- case a.PricingViewed != b.PricingViewed:
- if a.PricingViewed > b.PricingViewed {
- return -1
- }
- return 1
- case a.LicenseActivated != b.LicenseActivated:
- if a.LicenseActivated > b.LicenseActivated {
- return -1
- }
- return 1
- case a.TrialStarted != b.TrialStarted:
- if a.TrialStarted > b.TrialStarted {
- return -1
- }
- return 1
- case a.Key < b.Key:
- return -1
- case a.Key > b.Key:
- return 1
- default:
- return 0
- }
-}
-
-func applyInfrastructureOnboardingStageCount(
- counts *InfrastructureOnboardingStageCounts,
- eventType string,
- capability string,
- count int64,
-) {
- if counts == nil {
- return
- }
-
- switch strings.TrimSpace(eventType) {
- case EventInfrastructureOnboardingOpened:
- counts.Opened += count
- case EventInfrastructureOnboardingPathSelected:
- switch strings.TrimSpace(capability) {
- case "api":
- counts.APIPathSelected += count
- case "agent":
- counts.AgentPathSelected += count
- }
- case EventInfrastructureOnboardingProbeResult:
- switch strings.TrimSpace(capability) {
- case "detected":
- counts.ProbeDetected += count
- case "no-match":
- counts.ProbeNoMatch += count
- case "error":
- counts.ProbeError += count
- }
- case EventInfrastructureOnboardingCatalogSelected:
- counts.CatalogSelected += count
- case EventInfrastructureOnboardingCredentialsOpened:
- counts.CredentialsOpened += count
- }
-}
-
-func compareInfrastructureOnboardingPathBreakdowns(
- a,
- b InfrastructureOnboardingPathBreakdown,
-) int {
- switch {
- case a.Count != b.Count:
- if a.Count > b.Count {
- return -1
- }
- return 1
- case a.Key < b.Key:
- return -1
- case a.Key > b.Key:
- return 1
- default:
- return 0
- }
-}
-
-func compareInfrastructureOnboardingPlatformBreakdowns(
- a,
- b InfrastructureOnboardingPlatformBreakdown,
-) int {
- switch {
- case a.CredentialsOpened != b.CredentialsOpened:
- if a.CredentialsOpened > b.CredentialsOpened {
- return -1
- }
- return 1
- case a.CatalogSelected != b.CatalogSelected:
- if a.CatalogSelected > b.CatalogSelected {
- return -1
- }
- return 1
- case a.Key < b.Key:
- return -1
- case a.Key > b.Key:
- return 1
- default:
- return 0
- }
-}
-
-func isInfrastructureOnboardingPlatformCapability(capability string) bool {
- _, ok := infrastructureOnboardingPlatformCapabilities[strings.TrimSpace(capability)]
- return ok
-}
-
-func ensureOwnerOnlyDir(dir string) error {
- return securityutil.EnsureSecureStorageDir(dir, privateDirPerm)
-}
-
-func rejectSymlinkOrNonRegular(path string) error {
- info, err := os.Lstat(path)
- if err != nil {
- return err
- }
- if info.Mode()&os.ModeSymlink != 0 {
- return fmt.Errorf("unsafe sqlite path %q: symlink is not allowed", path)
- }
- if !info.Mode().IsRegular() {
- return fmt.Errorf("unsafe sqlite path %q: non-regular file is not allowed", path)
- }
- return nil
-}
-
-func hardenSQLiteFile(path string) error {
- if err := rejectSymlinkOrNonRegular(path); err != nil {
- return err
- }
- return os.Chmod(path, privateFilePerm)
-}
-
-func hardenSQLiteArtifacts(dbPath string) error {
- artifacts := []string{dbPath, dbPath + "-wal", dbPath + "-shm"}
- for _, path := range artifacts {
- if err := hardenSQLiteFile(path); err != nil {
- if errors.Is(err, os.ErrNotExist) {
- continue
- }
- return err
- }
- }
- return nil
-}
-
-func NewConversionStore(dbPath string) (*ConversionStore, error) {
- dbPath = filepath.Clean(strings.TrimSpace(dbPath))
- if dbPath == "" {
- return nil, fmt.Errorf("conversion db path is required")
- }
-
- dir := filepath.Dir(dbPath)
- if err := ensureOwnerOnlyDir(dir); err != nil {
- return nil, fmt.Errorf("failed to create conversion db directory: %w", err)
- }
- if err := rejectSymlinkOrNonRegular(dbPath); err != nil && !errors.Is(err, os.ErrNotExist) {
- return nil, err
- }
-
- dsn := dbPath + "?" + url.Values{
- "_pragma": []string{
- "busy_timeout(30000)",
- "journal_mode(WAL)",
- "synchronous(NORMAL)",
- "foreign_keys(ON)",
- },
- }.Encode()
- db, err := sql.Open("sqlite", dsn)
- if err != nil {
- return nil, fmt.Errorf("failed to open conversion db: %w", err)
- }
- db.SetMaxOpenConns(1)
- db.SetMaxIdleConns(1)
- db.SetConnMaxLifetime(0)
-
- store := &ConversionStore{db: db}
- if err := store.initSchema(); err != nil {
- initErr := fmt.Errorf("initialize conversion schema: %w", err)
- if closeErr := db.Close(); closeErr != nil {
- return nil, errors.Join(initErr, fmt.Errorf("close conversion db after init failure: %w", closeErr))
- }
- return nil, initErr
- }
- if err := hardenSQLiteArtifacts(dbPath); err != nil {
- _ = db.Close()
- return nil, fmt.Errorf("failed to secure conversion db files: %w", err)
- }
- return store, nil
-}
-
-func (s *ConversionStore) ensureInitialized() error {
- if s == nil || s.db == nil {
- return fmt.Errorf("conversion store is not initialized")
- }
- return nil
-}
-
-func formatTimeForDB(t time.Time) string {
- return t.UTC().Truncate(time.Second).Format(time.RFC3339)
-}
-
-func (s *ConversionStore) initSchema() error {
- if err := s.ensureInitialized(); err != nil {
- return err
- }
-
- schema := `
- CREATE TABLE IF NOT EXISTS conversion_events (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- org_id TEXT NOT NULL,
- event_type TEXT NOT NULL,
- surface TEXT NOT NULL DEFAULT '',
- capability TEXT NOT NULL DEFAULT '',
- idempotency_key TEXT NOT NULL,
- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(idempotency_key)
- );
- CREATE INDEX IF NOT EXISTS idx_conversion_events_org_time ON conversion_events(org_id, created_at);
- CREATE INDEX IF NOT EXISTS idx_conversion_events_type ON conversion_events(event_type, created_at);
- CREATE INDEX IF NOT EXISTS idx_conversion_events_time ON conversion_events(created_at);
- `
-
- if _, err := s.db.Exec(schema); err != nil {
- return fmt.Errorf("failed to initialize conversion schema: %w", err)
- }
-
- return nil
-}
-
-func (s *ConversionStore) Record(event StoredConversionEvent) error {
- if err := s.ensureInitialized(); err != nil {
- return err
- }
-
- orgID := strings.TrimSpace(event.OrgID)
- if orgID == "" {
- return fmt.Errorf("org_id is required")
- }
- eventType := strings.TrimSpace(event.EventType)
- if eventType == "" {
- return fmt.Errorf("event_type is required")
- }
- idempotencyKey := strings.TrimSpace(event.IdempotencyKey)
- if idempotencyKey == "" {
- return fmt.Errorf("idempotency_key is required")
- }
-
- createdAt := event.CreatedAt
- if createdAt.IsZero() {
- createdAt = time.Now().UTC()
- }
- createdAtValue := formatTimeForDB(createdAt)
-
- _, err := s.db.Exec(
- `INSERT OR IGNORE INTO conversion_events (org_id, event_type, surface, capability, idempotency_key, created_at)
- VALUES (?, ?, ?, ?, ?, ?)`,
- orgID,
- eventType,
- strings.TrimSpace(event.Surface),
- strings.TrimSpace(event.Capability),
- idempotencyKey,
- createdAtValue,
- )
- if err != nil {
- return fmt.Errorf("failed to insert conversion event: %w", err)
- }
- return nil
-}
-
-func (s *ConversionStore) Query(orgID string, from, to time.Time, eventType string) (events []StoredConversionEvent, retErr error) {
- if s == nil || s.db == nil {
- return nil, fmt.Errorf("conversion store is not initialized")
- }
- orgID = strings.TrimSpace(orgID)
- if orgID == "" {
- return nil, fmt.Errorf("org_id is required")
- }
-
- where := make([]string, 0, 8)
- args := make([]any, 0, 8)
-
- where = append(where, "org_id = ?")
- args = append(args, orgID)
- eventType = strings.TrimSpace(eventType)
- if eventType != "" {
- where = append(where, "event_type = ?")
- args = append(args, eventType)
- }
- if !from.IsZero() {
- where = append(where, "created_at >= ?")
- args = append(args, formatTimeForDB(from))
- }
- if !to.IsZero() {
- where = append(where, "created_at < ?")
- args = append(args, formatTimeForDB(to))
- }
-
- query := `
- SELECT
- id,
- org_id,
- event_type,
- surface,
- capability,
- idempotency_key,
- CAST(strftime('%s', created_at) AS INTEGER) AS created_at_unix
- FROM conversion_events
- `
- if len(where) > 0 {
- query += " WHERE " + strings.Join(where, " AND ")
- }
- query += " ORDER BY created_at ASC, id ASC"
-
- rows, err := s.db.Query(query, args...)
- if err != nil {
- return nil, fmt.Errorf("failed to query conversion events: %w", err)
- }
- defer func() {
- if closeErr := rows.Close(); closeErr != nil {
- wrappedCloseErr := fmt.Errorf("close conversion event rows: %w", closeErr)
- if retErr != nil {
- retErr = errors.Join(retErr, wrappedCloseErr)
- return
- }
- retErr = wrappedCloseErr
- }
- }()
-
- events = make([]StoredConversionEvent, 0)
- for rows.Next() {
- var ev StoredConversionEvent
- var createdAtUnix int64
- if err := rows.Scan(
- &ev.ID,
- &ev.OrgID,
- &ev.EventType,
- &ev.Surface,
- &ev.Capability,
- &ev.IdempotencyKey,
- &createdAtUnix,
- ); err != nil {
- return nil, fmt.Errorf("failed to scan conversion event: %w", err)
- }
- ev.CreatedAt = time.Unix(createdAtUnix, 0).UTC()
- events = append(events, ev)
- }
- if err := rows.Err(); err != nil {
- return nil, fmt.Errorf("failed to iterate conversion events: %w", err)
- }
- return events, nil
-}
-
-func (s *ConversionStore) FunnelSummary(orgID string, from, to time.Time) (summary *FunnelSummary, retErr error) {
- if s == nil || s.db == nil {
- return nil, fmt.Errorf("conversion store is not initialized")
- }
- if from.IsZero() || to.IsZero() {
- return nil, fmt.Errorf("from/to are required")
- }
-
- orgID = strings.TrimSpace(orgID)
- if orgID == "" {
- return nil, fmt.Errorf("org_id is required")
- }
-
- where := []string{"created_at >= ?", "created_at < ?", "org_id = ?"}
- args := []any{
- from.UTC().Truncate(time.Second).Format(time.RFC3339),
- to.UTC().Truncate(time.Second).Format(time.RFC3339),
- orgID,
- }
-
- query := `
- SELECT event_type, COUNT(1)
- FROM conversion_events
- WHERE ` + strings.Join(where, " AND ") + `
- GROUP BY event_type
- `
-
- rows, err := s.db.Query(query, args...)
- if err != nil {
- return nil, fmt.Errorf("failed to query funnel summary: %w", err)
- }
- defer func() {
- if closeErr := rows.Close(); closeErr != nil {
- wrappedCloseErr := fmt.Errorf("close funnel summary rows: %w", closeErr)
- if retErr != nil {
- retErr = errors.Join(retErr, wrappedCloseErr)
- return
- }
- retErr = wrappedCloseErr
- }
- }()
-
- summary = &FunnelSummary{}
- summary.Period.From = from.UTC()
- summary.Period.To = to.UTC()
-
- for rows.Next() {
- var eventType string
- var count int64
- if err := rows.Scan(&eventType, &count); err != nil {
- return nil, fmt.Errorf("failed to scan funnel summary row: %w", err)
- }
- applyFunnelStageCount(&summary.FunnelStageCounts, eventType, count)
- }
- if err := rows.Err(); err != nil {
- return nil, fmt.Errorf("failed to iterate funnel summary rows: %w", err)
- }
- return summary, nil
-}
-
-func (s *ConversionStore) FunnelDailyBreakdown(orgID string, from, to time.Time) (breakdown []FunnelDayBreakdown, retErr error) {
- if s == nil || s.db == nil {
- return nil, fmt.Errorf("conversion store is not initialized")
- }
- if from.IsZero() || to.IsZero() {
- return nil, fmt.Errorf("from/to are required")
- }
-
- orgID = strings.TrimSpace(orgID)
- if orgID == "" {
- return nil, fmt.Errorf("org_id is required")
- }
-
- startDay := from.UTC().Truncate(24 * time.Hour)
- endDay := to.UTC().Truncate(24 * time.Hour)
- if !to.UTC().Equal(endDay) {
- endDay = endDay.Add(24 * time.Hour)
- }
- if !startDay.Before(endDay) {
- return []FunnelDayBreakdown{}, nil
- }
-
- query := `
- SELECT strftime('%Y-%m-%d', created_at) AS bucket_day, event_type, COUNT(1)
- FROM conversion_events
- WHERE created_at >= ? AND created_at < ? AND org_id = ?
- GROUP BY bucket_day, event_type
- ORDER BY bucket_day ASC
- `
-
- rows, err := s.db.Query(
- query,
- from.UTC().Truncate(time.Second).Format(time.RFC3339),
- to.UTC().Truncate(time.Second).Format(time.RFC3339),
- orgID,
- )
- if err != nil {
- return nil, fmt.Errorf("failed to query funnel daily breakdown: %w", err)
- }
- defer func() {
- if closeErr := rows.Close(); closeErr != nil {
- wrappedCloseErr := fmt.Errorf("close funnel daily rows: %w", closeErr)
- if retErr != nil {
- retErr = errors.Join(retErr, wrappedCloseErr)
- return
- }
- retErr = wrappedCloseErr
- }
- }()
-
- buckets := make(map[string]*FunnelDayBreakdown)
- breakdown = make([]FunnelDayBreakdown, 0, int(endDay.Sub(startDay)/(24*time.Hour)))
- for day := startDay; day.Before(endDay); day = day.Add(24 * time.Hour) {
- entry := FunnelDayBreakdown{Day: day.Format("2006-01-02")}
- breakdown = append(breakdown, entry)
- buckets[entry.Day] = &breakdown[len(breakdown)-1]
- }
-
- for rows.Next() {
- var day string
- var eventType string
- var count int64
- if err := rows.Scan(&day, &eventType, &count); err != nil {
- return nil, fmt.Errorf("failed to scan funnel daily row: %w", err)
- }
- if entry := buckets[strings.TrimSpace(day)]; entry != nil {
- applyFunnelStageCount(&entry.FunnelStageCounts, eventType, count)
- }
- }
- if err := rows.Err(); err != nil {
- return nil, fmt.Errorf("failed to iterate funnel daily rows: %w", err)
- }
-
- return breakdown, nil
-}
-
-func (s *ConversionStore) FunnelDimensionBreakdown(orgID string, from, to time.Time, dimension string) (breakdown []FunnelDimensionBreakdown, retErr error) {
- if s == nil || s.db == nil {
- return nil, fmt.Errorf("conversion store is not initialized")
- }
- if from.IsZero() || to.IsZero() {
- return nil, fmt.Errorf("from/to are required")
- }
-
- orgID = strings.TrimSpace(orgID)
- if orgID == "" {
- return nil, fmt.Errorf("org_id is required")
- }
-
- column := ""
- switch strings.TrimSpace(dimension) {
- case "surface":
- column = "surface"
- case "capability":
- column = "capability"
- default:
- return nil, fmt.Errorf("unsupported breakdown dimension %q", dimension)
- }
-
- query := fmt.Sprintf(`
- SELECT %s AS bucket_key, event_type, COUNT(1)
- FROM conversion_events
- WHERE created_at >= ? AND created_at < ? AND org_id = ? AND TRIM(%s) <> ''
- GROUP BY bucket_key, event_type
- `, column, column)
-
- rows, err := s.db.Query(
- query,
- from.UTC().Truncate(time.Second).Format(time.RFC3339),
- to.UTC().Truncate(time.Second).Format(time.RFC3339),
- orgID,
- )
- if err != nil {
- return nil, fmt.Errorf("failed to query funnel %s breakdown: %w", dimension, err)
- }
- defer func() {
- if closeErr := rows.Close(); closeErr != nil {
- wrappedCloseErr := fmt.Errorf("close funnel %s rows: %w", dimension, closeErr)
- if retErr != nil {
- retErr = errors.Join(retErr, wrappedCloseErr)
- return
- }
- retErr = wrappedCloseErr
- }
- }()
-
- buckets := make(map[string]int)
- for rows.Next() {
- var key string
- var eventType string
- var count int64
- if err := rows.Scan(&key, &eventType, &count); err != nil {
- return nil, fmt.Errorf("failed to scan funnel %s row: %w", dimension, err)
- }
- key = strings.TrimSpace(key)
- if key == "" {
- continue
- }
- entryIndex, ok := buckets[key]
- if !ok {
- breakdown = append(breakdown, FunnelDimensionBreakdown{Key: key})
- entryIndex = len(breakdown) - 1
- buckets[key] = entryIndex
- }
- applyFunnelStageCount(&breakdown[entryIndex].FunnelStageCounts, eventType, count)
- }
- if err := rows.Err(); err != nil {
- return nil, fmt.Errorf("failed to iterate funnel %s rows: %w", dimension, err)
- }
-
- sort.SliceStable(breakdown, func(i, j int) bool {
- return compareFunnelBreakdowns(breakdown[i], breakdown[j]) < 0
- })
-
- return breakdown, nil
-}
-
-func (s *ConversionStore) FunnelReport(orgID string, from, to time.Time) (*FunnelReport, error) {
- summary, err := s.FunnelSummary(orgID, from, to)
- if err != nil {
- return nil, err
- }
- daily, err := s.FunnelDailyBreakdown(orgID, from, to)
- if err != nil {
- return nil, err
- }
- surfaces, err := s.FunnelDimensionBreakdown(orgID, from, to, "surface")
- if err != nil {
- return nil, err
- }
- capabilities, err := s.FunnelDimensionBreakdown(orgID, from, to, "capability")
- if err != nil {
- return nil, err
- }
-
- return &FunnelReport{
- Summary: *summary,
- Daily: daily,
- Surfaces: surfaces,
- Capabilities: capabilities,
- }, nil
-}
-
-func (s *ConversionStore) InfrastructureOnboardingReport(
- orgID string,
- from,
- to time.Time,
-) (*InfrastructureOnboardingReport, error) {
- if s == nil || s.db == nil {
- return nil, fmt.Errorf("conversion store is not initialized")
- }
- if from.IsZero() || to.IsZero() {
- return nil, fmt.Errorf("from/to are required")
- }
-
- orgID = strings.TrimSpace(orgID)
- if orgID == "" {
- return nil, fmt.Errorf("org_id is required")
- }
-
- startDay := from.UTC().Truncate(24 * time.Hour)
- endDay := to.UTC().Truncate(24 * time.Hour)
- if !to.UTC().Equal(endDay) {
- endDay = endDay.Add(24 * time.Hour)
- }
-
- report := &InfrastructureOnboardingReport{}
- report.Summary.Period.From = from.UTC()
- report.Summary.Period.To = to.UTC()
-
- dayBuckets := make(map[string]*InfrastructureOnboardingDayBreakdown)
- if startDay.Before(endDay) {
- report.Daily = make([]InfrastructureOnboardingDayBreakdown, 0, int(endDay.Sub(startDay)/(24*time.Hour)))
- for day := startDay; day.Before(endDay); day = day.Add(24 * time.Hour) {
- entry := InfrastructureOnboardingDayBreakdown{Day: day.Format("2006-01-02")}
- report.Daily = append(report.Daily, entry)
- dayBuckets[entry.Day] = &report.Daily[len(report.Daily)-1]
- }
- }
-
- pathBuckets := make(map[string]int)
- platformBuckets := make(map[string]int)
-
- recordEvent := func(event StoredConversionEvent) {
- capability := strings.TrimSpace(event.Capability)
- applyInfrastructureOnboardingStageCount(
- &report.Summary.InfrastructureOnboardingStageCounts,
- event.EventType,
- capability,
- 1,
- )
-
- dayKey := event.CreatedAt.UTC().Format("2006-01-02")
- if dayEntry := dayBuckets[dayKey]; dayEntry != nil {
- applyInfrastructureOnboardingStageCount(
- &dayEntry.InfrastructureOnboardingStageCounts,
- event.EventType,
- capability,
- 1,
- )
- }
-
- if event.EventType == EventInfrastructureOnboardingPathSelected && capability != "" {
- entryIndex, ok := pathBuckets[capability]
- if !ok {
- report.Paths = append(report.Paths, InfrastructureOnboardingPathBreakdown{Key: capability})
- entryIndex = len(report.Paths) - 1
- pathBuckets[capability] = entryIndex
- }
- report.Paths[entryIndex].Count++
- }
-
- if !isInfrastructureOnboardingPlatformCapability(capability) {
- return
- }
- if event.EventType != EventInfrastructureOnboardingCatalogSelected &&
- event.EventType != EventInfrastructureOnboardingCredentialsOpened {
- return
- }
-
- entryIndex, ok := platformBuckets[capability]
- if !ok {
- report.Platforms = append(report.Platforms, InfrastructureOnboardingPlatformBreakdown{Key: capability})
- entryIndex = len(report.Platforms) - 1
- platformBuckets[capability] = entryIndex
- }
- switch event.EventType {
- case EventInfrastructureOnboardingCatalogSelected:
- report.Platforms[entryIndex].CatalogSelected++
- case EventInfrastructureOnboardingCredentialsOpened:
- report.Platforms[entryIndex].CredentialsOpened++
- }
- }
-
- for _, eventType := range infrastructureOnboardingEventTypes {
- events, err := s.Query(orgID, from, to, eventType)
- if err != nil {
- return nil, err
- }
- for _, event := range events {
- recordEvent(event)
- }
- }
-
- sort.SliceStable(report.Paths, func(i, j int) bool {
- return compareInfrastructureOnboardingPathBreakdowns(report.Paths[i], report.Paths[j]) < 0
- })
- sort.SliceStable(report.Platforms, func(i, j int) bool {
- return compareInfrastructureOnboardingPlatformBreakdowns(report.Platforms[i], report.Platforms[j]) < 0
- })
-
- return report, nil
-}
-
-func (s *ConversionStore) Close() error {
- if s == nil || s.db == nil {
- return nil
- }
- return s.db.Close()
-}
diff --git a/pkg/licensing/conversion_store_onboarding_report_test.go b/pkg/licensing/conversion_store_onboarding_report_test.go
deleted file mode 100644
index 37a64aa34b..0000000000
--- a/pkg/licensing/conversion_store_onboarding_report_test.go
+++ /dev/null
@@ -1,211 +0,0 @@
-package licensing
-
-import (
- "path/filepath"
- "testing"
- "time"
-)
-
-func TestConversionStoreInfrastructureOnboardingReport(t *testing.T) {
- store, err := NewConversionStore(filepath.Join(t.TempDir(), "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- windowStart := time.Date(2026, 4, 20, 0, 0, 0, 0, time.UTC)
- windowEnd := windowStart.Add(48 * time.Hour)
-
- for _, event := range []StoredConversionEvent{
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingOpened,
- Surface: "settings_infrastructure_add",
- IdempotencyKey: "org-a:opened:1",
- CreatedAt: windowStart.Add(2 * time.Hour),
- },
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingPathSelected,
- Surface: "settings_infrastructure_add",
- Capability: "api",
- IdempotencyKey: "org-a:path:api",
- CreatedAt: windowStart.Add(2*time.Hour + time.Minute),
- },
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingProbeResult,
- Surface: "settings_infrastructure_add",
- Capability: "no-match",
- IdempotencyKey: "org-a:probe:no-match",
- CreatedAt: windowStart.Add(2*time.Hour + 2*time.Minute),
- },
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingPathSelected,
- Surface: "settings_infrastructure_add",
- Capability: "agent",
- IdempotencyKey: "org-a:path:agent",
- CreatedAt: windowStart.Add(2*time.Hour + 3*time.Minute),
- },
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingCredentialsOpened,
- Surface: "settings_infrastructure_add",
- Capability: "agent",
- IdempotencyKey: "org-a:credentials:agent",
- CreatedAt: windowStart.Add(2*time.Hour + 4*time.Minute),
- },
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingOpened,
- Surface: "settings_infrastructure_add",
- IdempotencyKey: "org-a:opened:2",
- CreatedAt: windowStart.Add(26 * time.Hour),
- },
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingPathSelected,
- Surface: "settings_infrastructure_add",
- Capability: "api",
- IdempotencyKey: "org-a:path:api:2",
- CreatedAt: windowStart.Add(26*time.Hour + time.Minute),
- },
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingProbeResult,
- Surface: "settings_infrastructure_add",
- Capability: "detected",
- IdempotencyKey: "org-a:probe:detected",
- CreatedAt: windowStart.Add(26*time.Hour + 2*time.Minute),
- },
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingCatalogSelected,
- Surface: "settings_infrastructure_add",
- Capability: "truenas",
- IdempotencyKey: "org-a:catalog:truenas",
- CreatedAt: windowStart.Add(26*time.Hour + 3*time.Minute),
- },
- {
- OrgID: "org-a",
- EventType: EventInfrastructureOnboardingCredentialsOpened,
- Surface: "settings_infrastructure_add",
- Capability: "truenas",
- IdempotencyKey: "org-a:credentials:truenas",
- CreatedAt: windowStart.Add(26*time.Hour + 4*time.Minute),
- },
- {
- OrgID: "org-b",
- EventType: EventInfrastructureOnboardingOpened,
- Surface: "settings_infrastructure_add",
- IdempotencyKey: "org-b:opened:1",
- CreatedAt: windowStart.Add(2 * time.Hour),
- },
- } {
- if err := store.Record(event); err != nil {
- t.Fatalf("Record(%s) error = %v", event.IdempotencyKey, err)
- }
- }
-
- report, err := store.InfrastructureOnboardingReport("org-a", windowStart, windowEnd)
- if err != nil {
- t.Fatalf("InfrastructureOnboardingReport() error = %v", err)
- }
-
- if report.Summary.Opened != 2 {
- t.Fatalf("Opened = %d, want 2", report.Summary.Opened)
- }
- if report.Summary.APIPathSelected != 2 {
- t.Fatalf("APIPathSelected = %d, want 2", report.Summary.APIPathSelected)
- }
- if report.Summary.AgentPathSelected != 1 {
- t.Fatalf("AgentPathSelected = %d, want 1", report.Summary.AgentPathSelected)
- }
- if report.Summary.ProbeNoMatch != 1 || report.Summary.ProbeDetected != 1 {
- t.Fatalf("unexpected probe summary: %+v", report.Summary.InfrastructureOnboardingStageCounts)
- }
- if report.Summary.CatalogSelected != 1 {
- t.Fatalf("CatalogSelected = %d, want 1", report.Summary.CatalogSelected)
- }
- if report.Summary.CredentialsOpened != 2 {
- t.Fatalf("CredentialsOpened = %d, want 2", report.Summary.CredentialsOpened)
- }
-
- if len(report.Daily) != 2 {
- t.Fatalf("len(Daily) = %d, want 2", len(report.Daily))
- }
- if report.Daily[0].ProbeNoMatch != 1 || report.Daily[1].ProbeDetected != 1 {
- t.Fatalf("unexpected daily breakdown: %+v", report.Daily)
- }
-
- if len(report.Paths) != 2 {
- t.Fatalf("len(Paths) = %d, want 2", len(report.Paths))
- }
- if report.Paths[0].Key != "api" || report.Paths[0].Count != 2 {
- t.Fatalf("unexpected path ranking: %+v", report.Paths)
- }
-
- if len(report.Platforms) != 1 {
- t.Fatalf("len(Platforms) = %d, want 1", len(report.Platforms))
- }
- if report.Platforms[0].Key != "truenas" ||
- report.Platforms[0].CatalogSelected != 1 ||
- report.Platforms[0].CredentialsOpened != 1 {
- t.Fatalf("unexpected platform breakdown: %+v", report.Platforms)
- }
-}
-
-func TestConversionStoreFunnelDimensionBreakdownAccumulatesAcrossMultipleKeys(t *testing.T) {
- store, err := NewConversionStore(filepath.Join(t.TempDir(), "conversion.db"))
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- defer store.Close()
-
- windowStart := time.Date(2026, 4, 20, 0, 0, 0, 0, time.UTC)
- windowEnd := windowStart.Add(24 * time.Hour)
-
- for _, event := range []StoredConversionEvent{
- {
- OrgID: "org-a",
- EventType: EventCheckoutClicked,
- Surface: "settings_self_hosted_billing_compare_prompt",
- IdempotencyKey: "org-a:checkout:1",
- CreatedAt: windowStart.Add(time.Hour),
- },
- {
- OrgID: "org-a",
- EventType: EventPricingViewed,
- Surface: "settings_self_hosted_billing_plan",
- IdempotencyKey: "org-a:pricing:1",
- CreatedAt: windowStart.Add(2 * time.Hour),
- },
- {
- OrgID: "org-a",
- EventType: EventCheckoutClicked,
- Surface: "settings_self_hosted_billing_compare_prompt",
- IdempotencyKey: "org-a:checkout:2",
- CreatedAt: windowStart.Add(3 * time.Hour),
- },
- } {
- if err := store.Record(event); err != nil {
- t.Fatalf("Record(%s) error = %v", event.IdempotencyKey, err)
- }
- }
-
- breakdown, err := store.FunnelDimensionBreakdown("org-a", windowStart, windowEnd, "surface")
- if err != nil {
- t.Fatalf("FunnelDimensionBreakdown() error = %v", err)
- }
-
- if len(breakdown) != 2 {
- t.Fatalf("len(breakdown) = %d, want 2", len(breakdown))
- }
- if breakdown[0].Key != "settings_self_hosted_billing_compare_prompt" || breakdown[0].CheckoutClicked != 2 {
- t.Fatalf("unexpected primary breakdown entry: %+v", breakdown)
- }
- if breakdown[1].Key != "settings_self_hosted_billing_plan" || breakdown[1].PricingViewed != 1 {
- t.Fatalf("unexpected secondary breakdown entry: %+v", breakdown)
- }
-}
diff --git a/pkg/licensing/conversion_store_queryplan_test.go b/pkg/licensing/conversion_store_queryplan_test.go
deleted file mode 100644
index 7ae03391d7..0000000000
--- a/pkg/licensing/conversion_store_queryplan_test.go
+++ /dev/null
@@ -1,281 +0,0 @@
-package licensing
-
-import (
- "database/sql"
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "testing"
- "time"
-)
-
-// TestConversionStoreQueryPlansUseIndexes validates that the runtime
-// conversion-store read paths continue to use indexed lookups on
-// conversion_events instead of regressing to full table scans.
-//
-// The SQL here is intentionally duplicated from conversion_store.go so a query
-// shape change must update the guardrail in lockstep.
-func TestConversionStoreQueryPlansUseIndexes(t *testing.T) {
- t.Parallel()
-
- store := newConversionPlanTestStore(t)
-
- tests := []struct {
- name string
- query string
- args []any
- wantIndex string
- allowTempBTreeGroupBy bool
- }{
- {
- name: "query by org ordered by time",
- query: `
- SELECT
- id,
- org_id,
- event_type,
- surface,
- capability,
- idempotency_key,
- CAST(strftime('%s', created_at) AS INTEGER) AS created_at_unix
- FROM conversion_events
- WHERE org_id = ?
- ORDER BY created_at ASC, id ASC
- `,
- args: []any{"org-03"},
- wantIndex: "idx_conversion_events_org_time",
- },
- {
- name: "query by org time range and type",
- query: `
- SELECT
- id,
- org_id,
- event_type,
- surface,
- capability,
- idempotency_key,
- CAST(strftime('%s', created_at) AS INTEGER) AS created_at_unix
- FROM conversion_events
- WHERE org_id = ? AND event_type = ? AND created_at >= ? AND created_at < ?
- ORDER BY created_at ASC, id ASC
- `,
- args: []any{
- "org-03",
- EventTrialStarted,
- time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
- time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
- },
- wantIndex: "idx_conversion_events_org_time",
- },
- {
- name: "funnel summary by org and time range",
- query: `
- SELECT event_type, COUNT(1)
- FROM conversion_events
- WHERE created_at >= ? AND created_at < ? AND org_id = ?
- GROUP BY event_type
- `,
- args: []any{
- time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
- time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
- "org-03",
- },
- wantIndex: "idx_conversion_events_org_time",
- allowTempBTreeGroupBy: true,
- },
- {
- name: "funnel daily breakdown by org and time range",
- query: `
- SELECT strftime('%Y-%m-%d', created_at) AS bucket_day, event_type, COUNT(1)
- FROM conversion_events
- WHERE created_at >= ? AND created_at < ? AND org_id = ?
- GROUP BY bucket_day, event_type
- ORDER BY bucket_day ASC
- `,
- args: []any{
- time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
- time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
- "org-03",
- },
- wantIndex: "idx_conversion_events_org_time",
- allowTempBTreeGroupBy: true,
- },
- {
- name: "funnel surface breakdown by org and time range",
- query: `
- SELECT surface AS bucket_key, event_type, COUNT(1)
- FROM conversion_events
- WHERE created_at >= ? AND created_at < ? AND org_id = ? AND TRIM(surface) <> ''
- GROUP BY bucket_key, event_type
- `,
- args: []any{
- time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
- time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC).Format(time.RFC3339),
- "org-03",
- },
- wantIndex: "idx_conversion_events_org_time",
- allowTempBTreeGroupBy: true,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- plan := explainConversionQueryPlan(t, store.db, tt.query, tt.args...)
-
- if containsConversionFullTableScan(plan) {
- t.Fatalf("query uses full table scan on conversion_events\nPlan:\n%s", plan)
- }
- if !containsConversionSearchWithIndex(plan, tt.wantIndex) {
- t.Fatalf("expected SEARCH on conversion_events using index %q\nPlan:\n%s", tt.wantIndex, plan)
- }
- if strings.Contains(plan, "USE TEMP B-TREE FOR GROUP BY") && !tt.allowTempBTreeGroupBy {
- t.Fatalf("unexpected temp B-tree group-by spill\nPlan:\n%s", plan)
- }
- })
- }
-}
-
-func TestNewConversionStore_SecuresOwnedDirectoryAndArtifacts(t *testing.T) {
- t.Parallel()
-
- baseDir := t.TempDir()
- if err := os.Chmod(baseDir, 0o755); err != nil {
- t.Fatalf("failed to loosen base dir perms: %v", err)
- }
-
- dbPath := filepath.Join(baseDir, "conversion.db")
- store, err := NewConversionStore(dbPath)
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- t.Cleanup(func() { _ = store.Close() })
-
- dirInfo, err := os.Stat(baseDir)
- if err != nil {
- t.Fatalf("stat base dir: %v", err)
- }
- if got := dirInfo.Mode().Perm(); got != 0o700 {
- t.Fatalf("base dir perms = %o, want 700", got)
- }
-
- dbInfo, err := os.Stat(dbPath)
- if err != nil {
- t.Fatalf("stat db path: %v", err)
- }
- if got := dbInfo.Mode().Perm(); got != 0o600 {
- t.Fatalf("db perms = %o, want 600", got)
- }
-}
-
-func newConversionPlanTestStore(t *testing.T) *ConversionStore {
- t.Helper()
-
- dbPath := filepath.Join(t.TempDir(), "conversion.db")
- store, err := NewConversionStore(dbPath)
- if err != nil {
- t.Fatalf("NewConversionStore() error = %v", err)
- }
- t.Cleanup(func() { _ = store.Close() })
-
- base := time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)
- eventTypes := []string{
- EventPaywallViewed,
- EventTrialStarted,
- EventUpgradeClicked,
- EventCheckoutCompleted,
- }
-
- for i := 0; i < 512; i++ {
- event := StoredConversionEvent{
- OrgID: "org-" + twoDigit(i%12),
- EventType: eventTypes[i%len(eventTypes)],
- Surface: "settings",
- Capability: "pro",
- IdempotencyKey: "evt-" + threeDigit(i),
- CreatedAt: base.Add(time.Duration(i) * time.Minute),
- }
- if err := store.Record(event); err != nil {
- t.Fatalf("Record(%d) error = %v", i, err)
- }
- }
-
- if _, err := store.db.Exec(`ANALYZE`); err != nil {
- t.Fatalf("ANALYZE: %v", err)
- }
-
- return store
-}
-
-func explainConversionQueryPlan(t *testing.T, db *sql.DB, query string, args ...any) string {
- t.Helper()
-
- rows, err := db.Query("EXPLAIN QUERY PLAN "+query, args...)
- if err != nil {
- t.Fatalf("EXPLAIN QUERY PLAN: %v\nQuery: %s", err, query)
- }
- defer rows.Close()
-
- var lines []string
- for rows.Next() {
- var (
- id int
- parent int
- aux int
- detail string
- )
- if err := rows.Scan(&id, &parent, &aux, &detail); err != nil {
- t.Fatalf("scan plan row: %v", err)
- }
- lines = append(lines, detail)
- }
- if err := rows.Err(); err != nil {
- t.Fatalf("plan rows: %v", err)
- }
- if len(lines) == 0 {
- t.Fatal("EXPLAIN QUERY PLAN returned no rows")
- }
- return strings.Join(lines, "\n")
-}
-
-func containsConversionSearchWithIndex(plan, indexName string) bool {
- for _, line := range strings.Split(plan, "\n") {
- if strings.Contains(line, "SEARCH") &&
- conversionLineRefersToEvents(line) &&
- strings.Contains(line, indexName) {
- return true
- }
- }
- return false
-}
-
-func containsConversionFullTableScan(plan string) bool {
- for _, line := range strings.Split(plan, "\n") {
- if !strings.Contains(line, "SCAN") || !conversionLineRefersToEvents(line) {
- continue
- }
- if strings.Contains(line, "USING") && strings.Contains(line, "INDEX") {
- continue
- }
- return true
- }
- return false
-}
-
-func conversionLineRefersToEvents(line string) bool {
- for _, needle := range []string{"conversion_events ", "conversion_events("} {
- if strings.Contains(line, needle) {
- return true
- }
- }
- return strings.HasSuffix(strings.TrimSpace(line), "conversion_events")
-}
-
-func twoDigit(v int) string {
- return fmt.Sprintf("%02d", v)
-}
-
-func threeDigit(v int) string {
- return fmt.Sprintf("%03d", v)
-}
diff --git a/pkg/licensing/metering/aggregator.go b/pkg/licensing/metering/aggregator.go
deleted file mode 100644
index 9e298a73e4..0000000000
--- a/pkg/licensing/metering/aggregator.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package metering
-
-import (
- "errors"
- "sync"
- "time"
-)
-
-const (
- // MaxCardinalityPerTenant is the maximum number of unique keys per tenant per event type.
- // Prevents attribute explosion attacks.
- MaxCardinalityPerTenant = 1000
- // MaxIdempotencyKeysPerWindow bounds memory used by deduplication state.
- MaxIdempotencyKeysPerWindow = 10000
-)
-
-// Errors
-var (
- ErrCardinalityExceeded = errors.New("cardinality limit exceeded for tenant")
- ErrDuplicateEvent = errors.New("duplicate event (idempotency key already seen)")
- ErrIdempotencyKeyLimitExceeded = errors.New("idempotency key limit exceeded for window")
-)
-
-// bucketKey uniquely identifies an aggregation bucket.
-type bucketKey struct {
- TenantID string
- Type EventType
- Key string
-}
-
-// WindowedAggregator aggregates metering events in memory with hourly flush windows.
-type WindowedAggregator struct {
- mu sync.RWMutex
-
- // counters holds the current window's aggregation buckets.
- // map[bucketKey]*bucket
- counters map[bucketKey]*bucket
-
- // seenIdempotencyKeys tracks idempotency keys for dedup within the current window.
- seenIdempotencyKeys map[string]bool
-
- // cardinalityCounts tracks unique keys per tenant per event type.
- // map[tenantID]map[EventType]int
- cardinalityCounts map[string]map[EventType]int
-
- // windowStart is when the current aggregation window began.
- windowStart time.Time
-}
-
-type bucket struct {
- count int64
- totalValue int64
-}
-
-// NewWindowedAggregator creates a new aggregator starting now.
-func NewWindowedAggregator() *WindowedAggregator {
- return &WindowedAggregator{
- counters: make(map[bucketKey]*bucket),
- seenIdempotencyKeys: make(map[string]bool),
- cardinalityCounts: make(map[string]map[EventType]int),
- windowStart: time.Now(),
- }
-}
-
-// Record records a metering event into the current window.
-// Returns ErrDuplicateEvent if the IdempotencyKey was already seen.
-// Returns ErrCardinalityExceeded if the tenant has too many unique keys for this event type.
-func (w *WindowedAggregator) Record(event Event) error {
- w.mu.Lock()
- defer w.mu.Unlock()
-
- if event.IdempotencyKey != "" && w.seenIdempotencyKeys[event.IdempotencyKey] {
- return ErrDuplicateEvent
- }
- if event.IdempotencyKey != "" && len(w.seenIdempotencyKeys) >= MaxIdempotencyKeysPerWindow {
- return ErrIdempotencyKeyLimitExceeded
- }
-
- key := bucketKey{
- TenantID: event.TenantID,
- Type: event.Type,
- Key: event.Key,
- }
-
- currentBucket, exists := w.counters[key]
- if !exists {
- tenantCardinality, ok := w.cardinalityCounts[event.TenantID]
- if !ok {
- tenantCardinality = make(map[EventType]int)
- w.cardinalityCounts[event.TenantID] = tenantCardinality
- }
-
- if tenantCardinality[event.Type] >= MaxCardinalityPerTenant {
- return ErrCardinalityExceeded
- }
-
- tenantCardinality[event.Type]++
- currentBucket = &bucket{}
- w.counters[key] = currentBucket
- }
-
- currentBucket.count++
- currentBucket.totalValue += event.Value
-
- if event.IdempotencyKey != "" {
- w.seenIdempotencyKeys[event.IdempotencyKey] = true
- }
-
- return nil
-}
-
-// Flush returns all aggregated buckets for the current window and resets.
-// The returned buckets include the window start/end times.
-// After flush, counters, idempotency keys, and cardinality counts are all reset.
-func (w *WindowedAggregator) Flush() []AggregatedBucket {
- w.mu.Lock()
- defer w.mu.Unlock()
-
- windowEnd := time.Now()
- out := make([]AggregatedBucket, 0, len(w.counters))
- for key, b := range w.counters {
- out = append(out, AggregatedBucket{
- TenantID: key.TenantID,
- Type: key.Type,
- Key: key.Key,
- Count: b.count,
- TotalValue: b.totalValue,
- WindowStart: w.windowStart,
- WindowEnd: windowEnd,
- })
- }
-
- w.counters = make(map[bucketKey]*bucket)
- w.seenIdempotencyKeys = make(map[string]bool)
- w.cardinalityCounts = make(map[string]map[EventType]int)
- w.windowStart = windowEnd
-
- return out
-}
-
-// Snapshot returns all aggregated buckets for the current window without resetting state.
-// The returned slice is a copy and is safe for callers to modify.
-func (w *WindowedAggregator) Snapshot() []AggregatedBucket {
- if w == nil {
- return []AggregatedBucket{}
- }
-
- w.mu.RLock()
- defer w.mu.RUnlock()
-
- windowEnd := time.Now()
- out := make([]AggregatedBucket, 0, len(w.counters))
- for key, b := range w.counters {
- out = append(out, AggregatedBucket{
- TenantID: key.TenantID,
- Type: key.Type,
- Key: key.Key,
- Count: b.count,
- TotalValue: b.totalValue,
- WindowStart: w.windowStart,
- WindowEnd: windowEnd,
- })
- }
-
- return out
-}
-
-// BucketCount returns the number of active aggregation buckets (for testing/monitoring).
-func (w *WindowedAggregator) BucketCount() int {
- w.mu.RLock()
- defer w.mu.RUnlock()
-
- return len(w.counters)
-}
diff --git a/pkg/licensing/metering/aggregator_test.go b/pkg/licensing/metering/aggregator_test.go
deleted file mode 100644
index ed1e046d7f..0000000000
--- a/pkg/licensing/metering/aggregator_test.go
+++ /dev/null
@@ -1,458 +0,0 @@
-package metering
-
-import (
- "errors"
- "fmt"
- "sync"
- "testing"
- "time"
-)
-
-func TestNewWindowedAggregator(t *testing.T) {
- agg := NewWindowedAggregator()
- if agg == nil {
- t.Fatal("expected non-nil aggregator")
- }
- if agg.BucketCount() != 0 {
- t.Errorf("new aggregator should have 0 buckets, got %d", agg.BucketCount())
- }
-}
-
-func TestRecord_BasicAggregation(t *testing.T) {
- agg := NewWindowedAggregator()
-
- // Record two events for the same tenant/type/key — they should aggregate.
- for i := 0; i < 5; i++ {
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "tenant-1",
- Key: "agent-abc",
- Value: 1,
- })
- if err != nil {
- t.Fatalf("unexpected error on record %d: %v", i, err)
- }
- }
-
- if agg.BucketCount() != 1 {
- t.Errorf("expected 1 bucket, got %d", agg.BucketCount())
- }
-
- buckets := agg.Flush()
- if len(buckets) != 1 {
- t.Fatalf("expected 1 bucket after flush, got %d", len(buckets))
- }
- b := buckets[0]
- if b.TenantID != "tenant-1" {
- t.Errorf("expected tenant-1, got %s", b.TenantID)
- }
- if b.Type != EventAgentSeen {
- t.Errorf("expected event type %s, got %s", EventAgentSeen, b.Type)
- }
- if b.Key != "agent-abc" {
- t.Errorf("expected key agent-abc, got %s", b.Key)
- }
- if b.Count != 5 {
- t.Errorf("expected count 5, got %d", b.Count)
- }
- if b.TotalValue != 5 {
- t.Errorf("expected total value 5, got %d", b.TotalValue)
- }
-}
-
-func TestRecord_MultipleBuckets(t *testing.T) {
- agg := NewWindowedAggregator()
-
- // Different tenants, types, and keys should create distinct buckets.
- events := []Event{
- {Type: EventAgentSeen, TenantID: "t1", Key: "a1", Value: 1},
- {Type: EventAgentSeen, TenantID: "t1", Key: "a2", Value: 1},
- {Type: EventRelayBytes, TenantID: "t1", Key: "a1", Value: 1024},
- {Type: EventAgentSeen, TenantID: "t2", Key: "a1", Value: 1},
- }
- for _, e := range events {
- if err := agg.Record(e); err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- }
-
- if agg.BucketCount() != 4 {
- t.Errorf("expected 4 buckets, got %d", agg.BucketCount())
- }
-}
-
-func TestRecord_IdempotencyDedup(t *testing.T) {
- agg := NewWindowedAggregator()
-
- first := Event{
- Type: EventAgentSeen,
- TenantID: "t1",
- Key: "a1",
- Value: 1,
- IdempotencyKey: "idem-1",
- }
- if err := agg.Record(first); err != nil {
- t.Fatalf("first record failed: %v", err)
- }
-
- // Duplicate idempotency key should be rejected.
- err := agg.Record(first)
- if !errors.Is(err, ErrDuplicateEvent) {
- t.Errorf("expected ErrDuplicateEvent, got %v", err)
- }
-
- // Different idempotency key should succeed.
- second := first
- second.IdempotencyKey = "idem-2"
- if err := agg.Record(second); err != nil {
- t.Fatalf("second record failed: %v", err)
- }
-
- buckets := agg.Flush()
- if len(buckets) != 1 {
- t.Fatalf("expected 1 bucket, got %d", len(buckets))
- }
- if buckets[0].Count != 2 {
- t.Errorf("expected count 2 (deduped), got %d", buckets[0].Count)
- }
-}
-
-func TestRecord_EmptyIdempotencyKey_NeverDeduped(t *testing.T) {
- agg := NewWindowedAggregator()
-
- // Events without idempotency keys should never be deduped.
- for i := 0; i < 3; i++ {
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "t1",
- Key: "a1",
- Value: 1,
- }); err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- }
-
- buckets := agg.Flush()
- if len(buckets) != 1 {
- t.Fatalf("expected 1 bucket, got %d", len(buckets))
- }
- if buckets[0].Count != 3 {
- t.Errorf("expected count 3, got %d", buckets[0].Count)
- }
-}
-
-func TestRecord_CardinalityLimit(t *testing.T) {
- agg := NewWindowedAggregator()
-
- // Fill up to the cardinality limit for one tenant/event-type.
- for i := 0; i < MaxCardinalityPerTenant; i++ {
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "t1",
- Key: fmt.Sprintf("key-%d", i),
- Value: 1,
- })
- if err != nil {
- t.Fatalf("unexpected error at key %d: %v", i, err)
- }
- }
-
- // Next unique key should be rejected.
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "t1",
- Key: "one-too-many",
- Value: 1,
- })
- if !errors.Is(err, ErrCardinalityExceeded) {
- t.Errorf("expected ErrCardinalityExceeded, got %v", err)
- }
-
- // Existing key should still work (not a new bucket).
- err = agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "t1",
- Key: "key-0",
- Value: 1,
- })
- if err != nil {
- t.Errorf("existing key should succeed, got %v", err)
- }
-
- // Different tenant should not be affected.
- err = agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "t2",
- Key: "new-key",
- Value: 1,
- })
- if err != nil {
- t.Errorf("different tenant should succeed, got %v", err)
- }
-
- // Different event type for same tenant should not be affected.
- err = agg.Record(Event{
- Type: EventRelayBytes,
- TenantID: "t1",
- Key: "relay-key",
- Value: 1024,
- })
- if err != nil {
- t.Errorf("different event type should succeed, got %v", err)
- }
-}
-
-func TestRecord_IdempotencyKeyLimit(t *testing.T) {
- agg := NewWindowedAggregator()
-
- // Fill up idempotency key space. Spread across tenants to avoid hitting
- // MaxCardinalityPerTenant (1000) before MaxIdempotencyKeysPerWindow (10000).
- for i := 0; i < MaxIdempotencyKeysPerWindow; i++ {
- tenantID := fmt.Sprintf("t-%d", i/MaxCardinalityPerTenant)
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: tenantID,
- Key: fmt.Sprintf("key-%d", i%MaxCardinalityPerTenant),
- Value: 1,
- IdempotencyKey: fmt.Sprintf("idem-%d", i),
- })
- if err != nil {
- t.Fatalf("unexpected error at key %d (tenant %s): %v", i, tenantID, err)
- }
- }
-
- // Next event with an idempotency key should be rejected.
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "t1",
- Key: "overflow",
- Value: 1,
- IdempotencyKey: "idem-overflow",
- })
- if !errors.Is(err, ErrIdempotencyKeyLimitExceeded) {
- t.Errorf("expected ErrIdempotencyKeyLimitExceeded, got %v", err)
- }
-
- // Events without idempotency keys should still work.
- err = agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "t1",
- Key: "no-idem",
- Value: 1,
- })
- if err != nil {
- t.Errorf("event without idempotency key should succeed, got %v", err)
- }
-}
-
-func TestFlush_ResetsState(t *testing.T) {
- agg := NewWindowedAggregator()
-
- if err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "t1",
- Key: "a1",
- Value: 1,
- IdempotencyKey: "idem-1",
- }); err != nil {
- t.Fatal(err)
- }
-
- buckets := agg.Flush()
- if len(buckets) != 1 {
- t.Fatalf("expected 1 bucket, got %d", len(buckets))
- }
-
- // After flush:
- // - counters should be empty
- if agg.BucketCount() != 0 {
- t.Errorf("expected 0 buckets after flush, got %d", agg.BucketCount())
- }
- // - second flush should return empty
- buckets2 := agg.Flush()
- if len(buckets2) != 0 {
- t.Errorf("expected 0 buckets on second flush, got %d", len(buckets2))
- }
-
- // - idempotency keys should be reset (same key should work again)
- err := agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: "t1",
- Key: "a1",
- Value: 1,
- IdempotencyKey: "idem-1",
- })
- if err != nil {
- t.Errorf("idempotency key should be valid after flush, got %v", err)
- }
-}
-
-func TestFlush_WindowTimes(t *testing.T) {
- before := time.Now()
- agg := NewWindowedAggregator()
-
- if err := agg.Record(Event{Type: EventAgentSeen, TenantID: "t1", Key: "a1", Value: 1}); err != nil {
- t.Fatal(err)
- }
-
- buckets := agg.Flush()
- after := time.Now()
-
- if len(buckets) != 1 {
- t.Fatalf("expected 1 bucket, got %d", len(buckets))
- }
-
- b := buckets[0]
- if b.WindowStart.Before(before) {
- t.Errorf("window start %v should not be before test start %v", b.WindowStart, before)
- }
- if b.WindowEnd.After(after) {
- t.Errorf("window end %v should not be after test end %v", b.WindowEnd, after)
- }
- if b.WindowEnd.Before(b.WindowStart) {
- t.Errorf("window end %v should not be before window start %v", b.WindowEnd, b.WindowStart)
- }
-}
-
-func TestSnapshot_DoesNotResetState(t *testing.T) {
- agg := NewWindowedAggregator()
-
- if err := agg.Record(Event{Type: EventAgentSeen, TenantID: "t1", Key: "a1", Value: 1}); err != nil {
- t.Fatal(err)
- }
- if err := agg.Record(Event{Type: EventAgentSeen, TenantID: "t1", Key: "a1", Value: 1}); err != nil {
- t.Fatal(err)
- }
-
- snap1 := agg.Snapshot()
- if len(snap1) != 1 {
- t.Fatalf("expected 1 bucket in snapshot, got %d", len(snap1))
- }
- if snap1[0].Count != 2 {
- t.Errorf("expected count 2, got %d", snap1[0].Count)
- }
-
- // Snapshot should not reset; second snapshot should return same data.
- snap2 := agg.Snapshot()
- if len(snap2) != 1 {
- t.Fatalf("expected 1 bucket in second snapshot, got %d", len(snap2))
- }
- if snap2[0].Count != 2 {
- t.Errorf("expected count 2 in second snapshot, got %d", snap2[0].Count)
- }
-
- // BucketCount should still be 1.
- if agg.BucketCount() != 1 {
- t.Errorf("expected bucket count 1 after snapshot, got %d", agg.BucketCount())
- }
-}
-
-func TestSnapshot_NilAggregator(t *testing.T) {
- var agg *WindowedAggregator
- snap := agg.Snapshot()
- if snap == nil {
- t.Error("nil aggregator snapshot should return empty slice, not nil")
- }
- if len(snap) != 0 {
- t.Errorf("nil aggregator snapshot should be empty, got %d", len(snap))
- }
-}
-
-func TestRecord_ValueAggregation(t *testing.T) {
- agg := NewWindowedAggregator()
-
- values := []int64{100, 200, 300, 400}
- for _, v := range values {
- if err := agg.Record(Event{
- Type: EventRelayBytes,
- TenantID: "t1",
- Key: "org-1",
- Value: v,
- }); err != nil {
- t.Fatal(err)
- }
- }
-
- buckets := agg.Flush()
- if len(buckets) != 1 {
- t.Fatalf("expected 1 bucket, got %d", len(buckets))
- }
- if buckets[0].TotalValue != 1000 {
- t.Errorf("expected total value 1000, got %d", buckets[0].TotalValue)
- }
- if buckets[0].Count != 4 {
- t.Errorf("expected count 4, got %d", buckets[0].Count)
- }
-}
-
-func TestConcurrentRecord(t *testing.T) {
- agg := NewWindowedAggregator()
- const goroutines = 10
- const eventsPerGoroutine = 100
-
- var wg sync.WaitGroup
- wg.Add(goroutines)
- for g := 0; g < goroutines; g++ {
- go func(gID int) {
- defer wg.Done()
- for i := 0; i < eventsPerGoroutine; i++ {
- _ = agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: fmt.Sprintf("t-%d", gID),
- Key: fmt.Sprintf("key-%d", i%10), // 10 unique keys per goroutine
- Value: 1,
- })
- }
- }(g)
- }
- wg.Wait()
-
- buckets := agg.Flush()
- totalCount := int64(0)
- for _, b := range buckets {
- totalCount += b.Count
- }
- if totalCount != goroutines*eventsPerGoroutine {
- t.Errorf("expected total count %d, got %d", goroutines*eventsPerGoroutine, totalCount)
- }
-}
-
-func TestConcurrentRecordAndSnapshot(t *testing.T) {
- agg := NewWindowedAggregator()
- const goroutines = 5
- const iterations = 50
-
- var wg sync.WaitGroup
- wg.Add(goroutines * 2) // half writers, half readers
-
- for g := 0; g < goroutines; g++ {
- go func(gID int) {
- defer wg.Done()
- for i := 0; i < iterations; i++ {
- _ = agg.Record(Event{
- Type: EventAgentSeen,
- TenantID: fmt.Sprintf("t-%d", gID),
- Key: "k",
- Value: 1,
- })
- }
- }(g)
- }
-
- for g := 0; g < goroutines; g++ {
- go func() {
- defer wg.Done()
- for i := 0; i < iterations; i++ {
- _ = agg.Snapshot()
- }
- }()
- }
-
- wg.Wait()
-
- // No panics = success. Verify we can still flush.
- buckets := agg.Flush()
- if len(buckets) == 0 {
- t.Error("expected at least some buckets after concurrent operations")
- }
-}
diff --git a/pkg/licensing/metering/event.go b/pkg/licensing/metering/event.go
deleted file mode 100644
index ca959d3b46..0000000000
--- a/pkg/licensing/metering/event.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package metering
-
-import "time"
-
-// EventType represents a metering event category.
-type EventType string
-
-const (
- EventAgentSeen EventType = "agent_seen"
- EventRelayBytes EventType = "relay_bytes"
-)
-
-// Event represents a single metering event.
-type Event struct {
- // Type is the event category.
- Type EventType
-
- // TenantID identifies the tenant that generated this event.
- TenantID string
-
- // Key is the specific entity being metered (e.g., agent ID, org ID).
- Key string
-
- // Value is the numeric value for the event (e.g., bytes transferred).
- // For counter events (agent_seen), this is typically 1.
- Value int64
-
- // Timestamp is when the event occurred.
- Timestamp time.Time
-
- // IdempotencyKey prevents duplicate event recording.
- // Events with the same IdempotencyKey within a window are deduplicated.
- IdempotencyKey string
-}
-
-// AggregatedBucket represents the aggregated metering data for a flush window.
-type AggregatedBucket struct {
- // TenantID is the tenant this bucket belongs to.
- TenantID string
-
- // Type is the event type.
- Type EventType
-
- // Key is the specific entity.
- Key string
-
- // Count is the number of events in this bucket.
- Count int64
-
- // TotalValue is the sum of all event values in this bucket.
- TotalValue int64
-
- // WindowStart is the start of the aggregation window.
- WindowStart time.Time
-
- // WindowEnd is the end of the aggregation window.
- WindowEnd time.Time
-}
diff --git a/pkg/server/server.go b/pkg/server/server.go
index a046dc8135..68036f88f6 100644
--- a/pkg/server/server.go
+++ b/pkg/server/server.go
@@ -183,43 +183,6 @@ func Run(ctx context.Context, version string) error {
log.Warn().Err(err).Msg("Failed to ensure default organization owner membership")
}
- // Local-only upgrade events must be durable and tenant-aware (P0-6).
- // Renamed from conversion.db -> upgrade_metrics.db to reduce misleading telemetry optics.
- upgradeMetricsDB := filepath.Join(baseDataDir, "upgrade_metrics.db")
- legacyConversionDB := filepath.Join(baseDataDir, "conversion.db")
- if _, err := os.Stat(upgradeMetricsDB); os.IsNotExist(err) {
- if _, err := os.Stat(legacyConversionDB); err == nil {
- renameIfExists := func(from, to string) {
- if _, statErr := os.Stat(from); statErr != nil {
- return
- }
- if renameErr := os.Rename(from, to); renameErr != nil {
- log.Warn().Err(renameErr).Str("from", from).Str("to", to).Msg("Failed to migrate legacy local-only upgrade events DB artifact")
- }
- }
- renameIfExists(legacyConversionDB, upgradeMetricsDB)
- renameIfExists(legacyConversionDB+"-wal", upgradeMetricsDB+"-wal")
- renameIfExists(legacyConversionDB+"-shm", upgradeMetricsDB+"-shm")
- log.Info().Str("from", legacyConversionDB).Str("to", upgradeMetricsDB).Msg("Migrated legacy conversion DB to local-only upgrade events DB")
- }
- }
-
- conversionStore, err := pkglicensing.NewConversionStore(upgradeMetricsDB)
- if err != nil {
- return fmt.Errorf("failed to initialize local-only upgrade events store: %w", err)
- }
- conversionStoreClosed := false
- closeConversionStore := func() {
- if conversionStoreClosed {
- return
- }
- conversionStoreClosed = true
- if err := conversionStore.Close(); err != nil {
- log.Error().Err(err).Msg("Failed to close local-only upgrade events store")
- }
- }
- defer closeConversionStore()
-
// Always capture audit events to SQLite (defense in depth). Read/export endpoints are license-gated.
// For the default org, TenantLoggerManager routes to the global logger, so initialize it as SQLite too.
var globalCrypto audit.CryptoEncryptor
@@ -411,7 +374,7 @@ func Run(ctx context.Context, version string) error {
}
return nil
}
- router = api.NewRouter(cfg, reloadableMonitor.GetMonitor(), reloadableMonitor.GetMultiTenantMonitor(), wsHub, reloadFunc, version, conversionStore)
+ router = api.NewRouter(cfg, reloadableMonitor.GetMonitor(), reloadableMonitor.GetMultiTenantMonitor(), wsHub, reloadFunc, version)
// Inject resource store into monitor for WebSocket broadcasts
router.SetMonitor(reloadableMonitor.GetMonitor())
@@ -725,8 +688,6 @@ shutdown:
if err := audit.Close(); err != nil {
log.Error().Err(err).Msg("Failed to close audit logger")
}
- closeConversionStore()
-
log.Info().Msg("Server stopped")
return nil
}
diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.py
index e61dcf5cfb..1ef22fbd2b 100644
--- a/scripts/release_control/canonical_completion_guard_test.py
+++ b/scripts/release_control/canonical_completion_guard_test.py
@@ -3822,7 +3822,7 @@ index 1111111..2222222 100644
],
)
- def test_cloud_paid_conversion_pipeline_uses_specific_guardrails(self):
+ def test_cloud_paid_conversion_pipeline_stays_retired_without_policy_coverage(self):
rule = next(rule for rule in load_subsystem_rules() if rule["id"] == "cloud-paid")
requirements = build_verification_requirements(
rule,
@@ -3832,23 +3832,16 @@ index 1111111..2222222 100644
requirements,
[
{
- "id": "conversion-telemetry-pipeline",
- "label": "conversion telemetry pipeline proof",
+ "id": "missing-path-policy-coverage",
+ "label": "registry path policy coverage",
"touched_runtime_files": [
"pkg/licensing/conversion_store.go",
"pkg/licensing/metering/aggregator.go",
],
"allow_same_subsystem_tests": False,
"test_prefixes": [],
- "exact_files": [
- "pkg/licensing/conversion_api_helpers_test.go",
- "pkg/licensing/conversion_config_test.go",
- "pkg/licensing/conversion_events_test.go",
- "pkg/licensing/conversion_metrics_test.go",
- "pkg/licensing/conversion_quality_test.go",
- "pkg/licensing/conversion_recorder_test.go",
- "pkg/licensing/conversion_store_queryplan_test.go",
- ],
+ "exact_files": [],
+ "path_policy_gap": True,
}
],
)