Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cyclotron): Add metrics everywhere #25193

Draft
wants to merge 7 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion plugin-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,6 @@
},
"cyclotron": {
"//This is a short term workaround to ensure that cyclotron changes trigger a rebuild": true,
"version": "0.1.6"
"version": "0.1.7"
}
}
66 changes: 65 additions & 1 deletion plugin-server/src/cdp/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// NOTE: PostIngestionEvent is our context event - it should never be sent directly to an output, but rather transformed into a lightweight schema

import { CyclotronJob, CyclotronJobUpdate } from '@posthog/cyclotron'
import { CyclotronJob, CyclotronJobUpdate, getMetricsReport } from '@posthog/cyclotron'
import { captureException } from '@sentry/node'
import { DateTime } from 'luxon'
import { Counter, exponentialBuckets, Gauge, Histogram } from 'prom-client'
import RE2 from 're2'
import { gunzip, gzip } from 'zlib'

Expand Down Expand Up @@ -378,3 +379,66 @@ export function cyclotronJobToInvocation(job: CyclotronJob, hogFunction: HogFunc
timings: parsedState.timings,
}
}

const CYCLOTRON_GAUGES: Map<string, Gauge> = new Map()
const CYCLOTRON_COUNTERS: Map<string, Counter> = new Map()
const CYCLOTRON_HISTOGRAMS: Map<string, Histogram> = new Map()
const CYCLOTRON_HISTOGRAM_BOUNDS: number[] = exponentialBuckets(0.5, 2, 11) // 0.5 -> 512

export function emitCyclotronMetrics() {
oliverb123 marked this conversation as resolved.
Show resolved Hide resolved
const report = getMetricsReport()
for (const measurement of report.measurements) {
const name = measurement.name
const type = measurement.type

// The TS library seem to demand you declare labels up-front (for some reason?),
// but we have know good way of knowing the set of labels used up-front, so
// idk what to do here really - recreate the metric each time? That seems...
Copy link
Contributor

Choose a reason for hiding this comment

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

this would need to be tested but it could be that the labels are just for typing so if you just cast the label setting as any it might JustWork. Checked the lib source and it wasn't obvious either way if it would work though...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Rip... I'm gonna have to think about it a bit more than that it seems. It's easy to handle this with counter and gauges (I can just delete and recreate), but histograms are a bit trickier.

error: "Error: Added label \"outcome\" is not included in initial labelset: []
    at validateLabel (/Users/olly/Documents/work/posthog/plugin-server/node_modules/.pnpm/[email protected]/node_modules/prom-client/lib/validation.js:20:10)
    at Counter.inc (/Users/olly/Documents/work/posthog/plugin-server/node_modules/.pnpm/[email protected]/node_modules/prom-client/lib/counter.js:23:4)
    at emitCyclotronMetrics (/Users/olly/Documents/work/posthog/plugin-server/src/cdp/utils.ts:408:21)
    at CdpProcessedEventsConsumer.processBatch (/Users/olly/Documents/work/posthog/plugin-server/src/cdp/cdp-consumers.ts:408:29)
    at CdpProcessedEventsConsumer._handleKafkaBatch (/Users/olly/Documents/work/posthog/plugin-server/src/cdp/cdp-consumers.ts:595:20)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at func (/Users/olly/Documents/work/posthog/plugin-server/src/cdp/cdp-consumers.ts:338:25)
    at runInstrumentedFunction (/Users/olly/Documents/work/posthog/plugin-server/src/main/utils.ts:48:24)
    at eachBatch (/Users/olly/Documents/work/posthog/plugin-server/src/cdp/cdp-consumers.ts:334:24)
    at startConsuming (/Users/olly/Documents/work/posthog/plugin-server/src/kafka/batch-consumer.ts:305:17)
    at Object.join (/Users/olly/Documents/work/posthog/plugin-server/src/kafka/batch-consumer.ts:385:13)"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Found the ever-classic 5 year old issue 🙃 siimon/prom-client#298

// not good, maybe not feasible for histograms. Ingoring this problem for now,
// will return to it later (maybe get some help)
// let labels = measurement.labels

if (type === 'counter') {
const value = measurement.value as number
let counter = CYCLOTRON_COUNTERS.get(name)
if (!counter) {
counter = new Counter({
name,
help: name,
})
CYCLOTRON_COUNTERS.set(name, counter)
}
counter.reset()
counter.inc(value)
}

if (type === 'gauge') {
const value = measurement.value as number
let gauge = CYCLOTRON_GAUGES.get(name)
if (!gauge) {
gauge = new Gauge({
name,
help: name,
})
CYCLOTRON_GAUGES.set(name, gauge)
}
gauge.set(value)
}

if (type === 'histogram') {
const value = measurement.value as number[]
let histogram = CYCLOTRON_HISTOGRAMS.get(name)
if (!histogram) {
histogram = new Histogram({
name,
help: name,
buckets: CYCLOTRON_HISTOGRAM_BOUNDS,
})
CYCLOTRON_HISTOGRAMS.set(name, histogram)
}
for (let i = 0; i < value.length; i++) {
histogram.observe(value[i])
}
}
}
}
88 changes: 68 additions & 20 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,5 @@ url = { version = "2.5.0 " }
uuid = { version = "1.6.1", features = ["v7", "serde"] }
neon = "1"
quick_cache = "0.6.5"
ahash = "0.8.11"
ahash = "0.8.11"
metrics-util = "0.17.0"
3 changes: 2 additions & 1 deletion rust/common/metrics/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ workspace = true
axum = { workspace = true }
metrics-exporter-prometheus = { workspace = true }
tokio = { workspace = true }
metrics = { workspace = true }
metrics = { workspace = true }
uuid = { workspace = true }
10 changes: 7 additions & 3 deletions rust/common/metrics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ pub async fn serve(router: Router, bind: &str) -> Result<(), std::io::Error> {
}

/// Add the prometheus endpoint and middleware to a router, should be called last.
pub fn setup_metrics_routes(router: Router) -> Router {
let recorder_handle = setup_metrics_recorder();
pub fn setup_metrics_routes(router: Router, service: &str, process: Option<&str>) -> Router {
let recorder_handle = setup_metrics_recorder(service, process);

router
.route(
Expand All @@ -28,12 +28,16 @@ pub fn setup_metrics_routes(router: Router) -> Router {
.layer(axum::middleware::from_fn(track_metrics))
}

pub fn setup_metrics_recorder() -> PrometheusHandle {
pub fn setup_metrics_recorder(service: &str, process: Option<&str>) -> PrometheusHandle {
let default_process = uuid::Uuid::now_v7().to_string();
let process = process.unwrap_or(&default_process);
const BUCKETS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 50.0, 100.0, 250.0,
];

PrometheusBuilder::new()
.add_global_label("service", service)
.add_global_label("process", process)
.set_buckets(BUCKETS)
.unwrap()
.install_recorder()
Expand Down
13 changes: 0 additions & 13 deletions rust/common/serve_metrics/Cargo.toml

This file was deleted.

Loading
Loading