Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(ai-research): measure image fetch stages and waits (#99234)

Robbie3a74dfb6c201
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
index 8cf4db02e3f9..db7c4c3cd0ae 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
@@ -84,6 +84,24 @@ Batch-diversity histograms record the top 1, 5, and 10 URL shares and the invers
Republish batch metrics use the fixed topic classes `frontier`, `retry_1m`, `retry_10m`, and `retry_1h`. They expose Kafka record count, registrable-domain key count, per-topic delivery time, and total republish flush time. They do not use a configured topic name or a domain as a label.
+Processing-stage metrics expose the active count, oldest active age, and elapsed time of finished operations, including failures.
+Consumer stages separate the join window from waiting for the combined batch to finish.
+Batch stages separate parsing, history reads, filtering, fetching, republish preparation, history writes, republish flushes, final accounting, and dead-letter delivery.
+Candidate stages separate admission to the pod-wide controller, work that holds a slot, policy checks, and image fetching.
+The queued-candidate gauge counts work before selection; it excludes candidates waiting for admission or already running.
+Request stages distinguish configuration and image HTTP work from capacity, crawl-delay, and domain-rate waits.
+Image publication separates admission from Kafka delivery.
+Stage timers use a monotonic clock and record actual elapsed time, including scheduler delays.
+Nested stages overlap: candidate work includes policy and publication, and candidate fetch includes scheduler waits and redirect policy checks.
+Do not sum nested stages or subtract their percentiles to estimate batch time.
+
+Configuration lookup counters distinguish cached results, callers that share an existing request, and callers that start a new request.
+Their outcome describes the cache entry or fetched result before any stale-cache fallback.
+Configuration fetch counters count each redirect chain once, with a fixed failure category.
+A timeout category means the request deadline elapsed before an exception reached the fetcher; other exceptions use `request_error`.
+These counters do not count individual redirect hops, and shared or cached results can produce multiple policy decisions.
+No new metric uses a URL, hostname, domain, error message, or batch identifier as a label.
+
The Grafana dashboard uses these runtime metrics. Its frontier health panels exclude the delay topics so they do not double-count retry traffic.
The Helm deployment defines fetch, scrub, and three retry consumers. Fetch and retry synchronization remains manual until their dependencies exist.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts
index 7cd413b64cb7..3af346ed1042 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts
@@ -1,3 +1,5 @@
+import { register } from 'prom-client'
+
import { StreamedResponse, fetchStreamed } from '~/common/utils/request'
import {
@@ -200,6 +202,7 @@ describe('response opt-out policy', () => {
})
describe('ConfigurationPolicyService', () => {
+ beforeEach(() => register.resetMetrics())
it('checks both files before it allows an image request', async () => {
const { policy, fetch } = service()
@@ -219,6 +222,36 @@ describe('ConfigurationPolicyService', () => {
await expect(policy.check(`${ORIGIN}/image.png`, cache, NOW_MS)).resolves.toMatchObject({ allowed: true })
expect(fetch).not.toHaveBeenCalled()
+ const lookups = await register.getSingleMetric('ml_image_fetch_configuration_lookups_total')!.get()
+ expect(lookups.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ labels: { file: 'robots', source: 'cache', outcome: 'absent' }, value: 1 }),
+ expect.objectContaining({ labels: { file: 'tdmrep', source: 'cache', outcome: 'absent' }, value: 1 }),
+ ])
+ )
+ })
+
+ it('counts shared configuration requests separately from new requests', async () => {
+ let resolve!: (result: ConfigurationFetchResult) => void
+ const pending = new Promise<ConfigurationFetchResult>((done) => {
+ resolve = done
+ })
+ const fetch = jest.fn(() => pending)
+ const policy = new ConfigurationPolicyService({ fetch } as unknown as HttpConfigurationFetcher)
+ const first = policy.check(`${ORIGIN}/first.png`, new Map(), NOW_MS)
+ const second = policy.check(`${ORIGIN}/second.png`, new Map(), NOW_MS)
+ expect(fetch).toHaveBeenCalledTimes(2)
+ resolve({ outcome: 'unreachable' })
+ await Promise.all([first, second])
+ const lookups = await register.getSingleMetric('ml_image_fetch_configuration_lookups_total')!.get()
+ for (const file of ['robots', 'tdmrep']) {
+ expect(lookups.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ labels: { file, source: 'network', outcome: 'unreachable' }, value: 1 }),
+ expect.objectContaining({ labels: { file, source: 'shared', outcome: 'unreachable' }, value: 1 }),
+ ])
+ )
+ }
})
it('parses each cached policy revision once in a fetch pass', async () => {
@@ -340,20 +373,25 @@ describe('ConfigurationPolicyService', () => {
describe('HttpConfigurationFetcher', () => {
beforeEach(() => {
fetchStreamedMock.mockReset()
+ register.resetMetrics()
})
it.each([
- [404, 'absent'],
- [410, 'absent'],
- [401, 'refused'],
- [403, 'refused'],
- [429, 'unreachable'],
- [500, 'unreachable'],
- [204, 'unreachable'],
- ])('maps HTTP %s to %s', async (status, outcome) => {
+ [404, 'absent', 'absent'],
+ [410, 'absent', 'absent'],
+ [401, 'refused', 'refused'],
+ [403, 'refused', 'refused'],
+ [429, 'unreachable', 'http_429'],
+ [500, 'unreachable', 'http_5xx'],
+ [204, 'unreachable', 'unexpected_status'],
+ ])('maps HTTP %s to %s', async (status, outcome, reason) => {
fetchStreamedMock.mockResolvedValue(response(status))
await expect(httpFetcher().fetch(ORIGIN, 'robots')).resolves.toMatchObject({ outcome })
+ const fetches = await register.getSingleMetric('ml_image_fetch_configuration_fetches_total')!.get()
+ expect(fetches.values).toEqual([
+ expect.objectContaining({ labels: { file: 'robots', outcome, reason }, value: 1 }),
+ ])
})
it('uses the retained prefix when robots.txt exceeds its byte limit', async () => {
@@ -388,6 +426,19 @@ describe('HttpConfigurationFetcher', () => {
await expect(httpFetcher().fetch(ORIGIN, 'tdmrep')).resolves.toMatchObject({ outcome: 'unreachable' })
await expect(httpFetcher().fetch(ORIGIN, 'tdmrep')).resolves.toMatchObject({ outcome: 'unreachable' })
+ const fetches = await register.getSingleMetric('ml_image_fetch_configuration_fetches_total')!.get()
+ expect(fetches.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ labels: { file: 'tdmrep', outcome: 'unreachable', reason: 'body_limit' },
+ value: 1,
+ }),
+ expect.objectContaining({
+ labels: { file: 'tdmrep', outcome: 'unreachable', reason: 'invalid_document' },
+ value: 1,
+ }),
+ ])
+ )
})
it('treats repeated Location field lines as unreachable', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts
index 9e94f19b9e54..337a719fe22a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts
@@ -7,6 +7,7 @@ import { fetchStreamed } from '~/common/utils/request'
import { ConfigurationCacheItem, ConfigurationFile, HttpCacheMetadata, configurationCacheKey } from './crawl-history'
import { ImageFetchRequestMetrics } from './metrics'
import { canonicalizeUrl, politenessKey } from './politeness-key'
+import { ConfigurationFetchReason, ImageFetchProcessingMetrics } from './processing-metrics'
import { WebBotAuthRequestSigner } from './web-bot-auth'
import { wildcardPatternMatchesPathname } from './wildcard-pattern'
@@ -54,7 +55,7 @@ export interface ConfigurationRequestScheduler {
type ConfigurationHop =
| { kind: 'redirect'; location: string; cache: HttpCacheMetadata }
- | { kind: 'done'; result: ConfigurationFetchResult }
+ | { kind: 'done'; result: ConfigurationFetchResult; reason?: ConfigurationFetchReason }
export class HttpConfigurationFetcher {
constructor(
@@ -64,13 +65,23 @@ export class HttpConfigurationFetcher {
) {}
public async fetch(origin: string, file: ConfigurationFile): Promise<ConfigurationFetchResult> {
+ return await ImageFetchProcessingMetrics.measure('configuration_fetch', () =>
+ this.fetchConfiguration(origin, file)
+ )
+ }
+
+ private async fetchConfiguration(origin: string, file: ConfigurationFile): Promise<ConfigurationFetchResult> {
+ const complete = (
+ result: ConfigurationFetchResult,
+ reason: ConfigurationFetchReason = result.outcome
+ ): ConfigurationFetchResult => ImageFetchProcessingMetrics.observeConfigurationFetch(file, result, reason)
const deadlineMs = Date.now() + this.timeoutMs
let target = new URL(file === 'robots' ? '/robots.txt' : '/.well-known/tdmrep.json', origin)
const registrableDomain = politenessKey(target.hostname)
for (let redirects = 0; ; redirects++) {
const canonical = canonicalizeUrl(target.toString())
if (!canonical) {
- return { outcome: 'refused' }
+ return complete({ outcome: 'refused' }, 'invalid_url')
}
target = new URL(canonical.fetch)
let scheduled:
@@ -79,26 +90,26 @@ export class HttpConfigurationFetcher {
try {
scheduled = await this.scheduler.run(target, deadlineMs, () => this.hop(target, file, deadlineMs))
} catch {
- return { outcome: 'unreachable' }
+ return complete({ outcome: 'unreachable' }, Date.now() >= deadlineMs ? 'timeout' : 'request_error')
}
if (!scheduled.ran) {
- return { outcome: 'deferred', reason: scheduled.reason }
+ return complete({ outcome: 'deferred', reason: scheduled.reason })
}
const hop = scheduled.value
if (hop.kind === 'done') {
- return hop.result
+ return complete(hop.result, hop.reason)
}
if (redirects >= CONFIG_REDIRECT_LIMIT) {
- return { outcome: 'unreachable', cache: hop.cache }
+ return complete({ outcome: 'unreachable', cache: hop.cache }, 'redirect_limit')
}
try {
const redirectTarget = new URL(hop.location, target)
if (politenessKey(redirectTarget.hostname) !== registrableDomain) {
- return { outcome: 'unreachable', cache: hop.cache }
+ return complete({ outcome: 'unreachable', cache: hop.cache }, 'cross_domain_redirect')
}
target = redirectTarget
} catch {
- return { outcome: 'unreachable', cache: hop.cache }
+ return complete({ outcome: 'unreachable', cache: hop.cache }, 'invalid_redirect')
}
}
}
@@ -141,7 +152,7 @@ export class HttpConfigurationFetcher {
return complete(
location
? { kind: 'redirect', location, cache }
- : { kind: 'done', result: { outcome: 'unreachable', cache } }
+ : { kind: 'done', result: { outcome: 'unreachable', cache }, reason: 'missing_location' }
)
}
if (response.status === 404 || response.status === 410) {
@@ -150,7 +161,11 @@ export class HttpConfigurationFetcher {
}
if (response.status === 429 || response.status >= 500) {
response.discard()
- return complete({ kind: 'done', result: { outcome: 'unreachable', cache } })
+ return complete({
+ kind: 'done',
+ result: { outcome: 'unreachable', cache },
+ reason: response.status === 429 ? 'http_429' : 'http_5xx',
+ })
}
if (response.status >= 400 && response.status < 500) {
response.discard()
@@ -158,20 +173,20 @@ export class HttpConfigurationFetcher {
}
if (response.status !== 200) {
response.discard()
- return complete({ kind: 'done', result: { outcome: 'unreachable', cache } })
+ return complete({ kind: 'done', result: { outcome: 'unreachable', cache }, reason: 'unexpected_status' })
}
const body = await response.read(CONFIG_BODY_LIMIT)
if (body.overLimit && file === 'tdmrep') {
- return complete({ kind: 'done', result: { outcome: 'unreachable', cache } })
+ return complete({ kind: 'done', result: { outcome: 'unreachable', cache }, reason: 'body_limit' })
}
let text: string
try {
text = new TextDecoder('utf-8', { fatal: true }).decode(body.bytes, { stream: body.overLimit })
} catch {
- return complete({ kind: 'done', result: { outcome: 'unreachable', cache } })
+ return complete({ kind: 'done', result: { outcome: 'unreachable', cache }, reason: 'invalid_utf8' })
}
if (file === 'tdmrep' && !isValidTdmrepDocument(text)) {
- return complete({ kind: 'done', result: { outcome: 'unreachable', cache } })
+ return complete({ kind: 'done', result: { outcome: 'unreachable', cache }, reason: 'invalid_document' })
}
return complete({ kind: 'done', result: { outcome: 'available', body: text, cache } })
}
@@ -316,18 +331,25 @@ export class ConfigurationPolicyService {
previous = undefined
}
if (previous && previous.refreshAtMs > nowMs) {
+ ImageFetchProcessingMetrics.observeConfigurationLookup(file, 'cache', previous.status)
return { item: previous, updates: [] }
}
if (previous?.status === 'unreachable' && previous.retryAtMs > nowMs) {
+ ImageFetchProcessingMetrics.observeConfigurationLookup(file, 'cache', previous.status)
return { item: previous, updates: [] }
}
const key = configurationCacheKey(origin, file)
let request = this.inFlight.get(key)
+ const source = request ? 'shared' : 'network'
if (!request) {
request = this.fetcher.fetch(origin, file).finally(() => this.inFlight.delete(key))
this.inFlight.set(key, request)
}
- const fetched = await request
+ const fetched = await request.catch((error) => {
+ ImageFetchProcessingMetrics.observeConfigurationLookup(file, source, 'error')
+ throw error
+ })
+ ImageFetchProcessingMetrics.observeConfigurationLookup(file, source, fetched.outcome)
if (fetched.outcome === 'deferred') {
return {
item: previous ?? unreachableItem(origin, file, nowMs),
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts
index 8a4084685e0f..f312969e67c5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts
@@ -22,6 +22,7 @@ import {
import { ImageFetchRequestMetrics } from './metrics'
import { OriginRequestScheduler } from './origin-request-scheduler'
import { canonicalizeUrl } from './politeness-key'
+import { ImageFetchProcessingMetrics } from './processing-metrics'
import { ImageFetchTopHogMetrics } from './tophog-metrics'
export type ShedReason =
@@ -159,6 +160,7 @@ export class FetchRunner implements FetchPass {
this.options.maxInFlightRequests
)
const attempts: FetchAttempt[] = []
+ const stopTrackingQueue = ImageFetchProcessingMetrics.trackQueue(queue)
const workers = Array.from(
{ length: Math.min(this.options.maxInFlightRequests, queue.schedulableSlotsAtStart) },
() =>
@@ -173,7 +175,7 @@ export class FetchRunner implements FetchPass {
passState
)
)
- const settledWorkers = await Promise.allSettled(workers)
+ const settledWorkers = await Promise.allSettled(workers).finally(stopTrackingQueue)
if (passState.failure) {
throw passState.failure.error
}
@@ -246,38 +248,43 @@ export class FetchRunner implements FetchPass {
if (Date.now() > deadlineMs) {
return await this.republish(republishBatch, candidate, 'deadline', 'pass_deadline', 0, [], 'pass_deadline')
}
- return await this.candidateWork.run({
- debugTag: candidate.registrableDomain,
- fn: async () => {
- if (passState.failure) {
- throw passState.failure.error
- }
- try {
- if (Date.now() > deadlineMs) {
- return await this.republish(
- republishBatch,
+ return await ImageFetchProcessingMetrics.runLimited(
+ this.candidateWork,
+ 'candidate_admission',
+ 'candidate_work',
+ {
+ debugTag: candidate.registrableDomain,
+ fn: async () => {
+ if (passState.failure) {
+ throw passState.failure.error
+ }
+ try {
+ if (Date.now() > deadlineMs) {
+ return await this.republish(
+ republishBatch,
+ candidate,
+ 'deadline',
+ 'pass_deadline',
+ 0,
+ [],
+ 'pass_deadline'
+ )
+ }
+ return await this.fetchOne(
candidate,
- 'deadline',
- 'pass_deadline',
- 0,
- [],
- 'pass_deadline'
+ stored,
+ configurationItems,
+ configurationPolicy,
+ deadlineMs,
+ republishBatch
)
+ } catch (error) {
+ passState.failure ??= { error }
+ throw error
}
- return await this.fetchOne(
- candidate,
- stored,
- configurationItems,
- configurationPolicy,
- deadlineMs,
- republishBatch
- )
- } catch (error) {
- passState.failure ??= { error }
- throw error
- }
- },
- })
+ },
+ }
+ )
}
private async fetchOne(
@@ -291,7 +298,9 @@ export class FetchRunner implements FetchPass {
if (candidate.remainingHops === 0) {
return this.terminal(candidate, HOPS_EXHAUSTED, undefined, [])
}
- const policy = await configurationPolicy.check(candidate.currentUrl, configurationItems, Date.now())
+ const policy = await ImageFetchProcessingMetrics.measure('candidate_policy', () =>
+ configurationPolicy.check(candidate.currentUrl, configurationItems, Date.now())
+ )
const configurationUpdates = [...policy.updates]
for (const update of policy.updates) {
configurationItems.set(update.key, update)
@@ -346,42 +355,46 @@ export class FetchRunner implements FetchPass {
const previous = stored.get(candidate.originalRef)
const previousUrl = previous?.kind === 'url' ? previous : undefined
- const result = await this.fetcher.fetch(candidate.currentUrl, {
- sourcePartitions: candidate.sourcePartitions,
- maxBytes: this.options.maxBytes,
- timeoutMs: this.options.requestTimeoutMs,
- maxRedirects: Math.min(this.options.maxRedirects, candidate.remainingHops),
- cache: previousUrl?.cache,
- tdmrepReservation: policy.tdmrepReservation,
- onRedirectResponse: () => this.budget.recordCompletedResponse(candidate.registrableDomain, Date.now()),
- isDifferentOrigin: (url) => url.origin !== candidate.origin,
- scheduleRequest: (url, requestDeadlineMs, request) =>
- this.scheduler.runImage(
- url,
- Math.min(deadlineMs, requestDeadlineMs),
- request,
- candidate.sourcePartitions
- ),
- checkRedirectPolicy: async (url) => {
- const redirectPolicy = await configurationPolicy.check(url, configurationItems, Date.now())
- for (const update of redirectPolicy.updates) {
- configurationItems.set(update.key, update)
- configurationUpdates.push(update)
- }
- if (!redirectPolicy.allowed) {
- return {
- allowed: false,
- transient: redirectPolicy.transient,
- reason: redirectPolicy.reason ?? 'configuration_refused',
+ const result = await ImageFetchProcessingMetrics.measure('candidate_fetch', () =>
+ this.fetcher.fetch(candidate.currentUrl, {
+ sourcePartitions: candidate.sourcePartitions,
+ maxBytes: this.options.maxBytes,
+ timeoutMs: this.options.requestTimeoutMs,
+ maxRedirects: Math.min(this.options.maxRedirects, candidate.remainingHops),
+ cache: previousUrl?.cache,
+ tdmrepReservation: policy.tdmrepReservation,
+ onRedirectResponse: () => this.budget.recordCompletedResponse(candidate.registrableDomain, Date.now()),
+ isDifferentOrigin: (url) => url.origin !== candidate.origin,
+ scheduleRequest: (url, requestDeadlineMs, request) =>
+ this.scheduler.runImage(
+ url,
+ Math.min(deadlineMs, requestDeadlineMs),
+ request,
+ candidate.sourcePartitions
+ ),
+ checkRedirectPolicy: async (url) => {
+ const redirectPolicy = await ImageFetchProcessingMetrics.measure('candidate_policy', () =>
+ configurationPolicy.check(url, configurationItems, Date.now())
+ )
+ for (const update of redirectPolicy.updates) {
+ configurationItems.set(update.key, update)
+ configurationUpdates.push(update)
}
- }
- const origin = new URL(url).origin
- if (!this.budget.setCrawlDelay(origin, redirectPolicy.crawlDelayMs, Date.now())) {
- return { allowed: false, transient: true, reason: 'origin_map_full' }
- }
- return { allowed: true, tdmrepReservation: redirectPolicy.tdmrepReservation }
- },
- })
+ if (!redirectPolicy.allowed) {
+ return {
+ allowed: false,
+ transient: redirectPolicy.transient,
+ reason: redirectPolicy.reason ?? 'configuration_refused',
+ }
+ }
+ const origin = new URL(url).origin
+ if (!this.budget.setCrawlDelay(origin, redirectPolicy.crawlDelayMs, Date.now())) {
+ return { allowed: false, transient: true, reason: 'origin_map_full' }
+ }
+ return { allowed: true, tdmrepReservation: redirectPolicy.tdmrepReservation }
+ },
+ })
+ )
ImageFetchRequestMetrics.observeRedirectCount(result.redirects)
if (result.bytes) {
ImageFetchRequestMetrics.observeBytes(result.bytes.length)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
index 941fb8a521a3..b3e55f1c4a8e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
@@ -12,6 +12,7 @@ import {
} from './collected-urls-record'
import type { ImageFetchResult } from './image-fetcher'
import { ImageFetchRequestMetrics, RepublishTopic } from './metrics'
+import { ImageFetchProcessingMetrics } from './processing-metrics'
export interface DelayTier {
topic: string
@@ -117,16 +118,21 @@ export class FrontierPublisher {
if (result.contentEncoding) {
headers['content-encoding'] = result.contentEncoding
}
- await this.imagePublishes.run({
- debugTag: candidate.registrableDomain,
- fn: () =>
- this.producer.produce({
- topic: this.options.scrubTopic,
- key: Buffer.from(candidate.originalRef),
- value: bytes,
- headers,
- }),
- })
+ await ImageFetchProcessingMetrics.runLimited(
+ this.imagePublishes,
+ 'image_publish_admission',
+ 'image_publish_delivery',
+ {
+ debugTag: candidate.registrableDomain,
+ fn: () =>
+ this.producer.produce({
+ topic: this.options.scrubTopic,
+ key: Buffer.from(candidate.originalRef),
+ value: bytes,
+ headers,
+ }),
+ }
+ )
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts
index 40e01c5fb5ef..a9515e429efc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts
@@ -1,4 +1,5 @@
import { Message } from 'node-rdkafka'
+import { register } from 'prom-client'
import { IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS, ImageFetchBatchJoiner } from './image-fetch-batch-joiner'
@@ -23,7 +24,10 @@ function deferred(): { promise: Promise<void>; resolve: () => void; reject: (err
}
describe('ImageFetchBatchJoiner', () => {
- beforeEach(() => jest.useFakeTimers())
+ beforeEach(() => {
+ jest.useFakeTimers()
+ register.resetMetrics()
+ })
afterEach(() => jest.useRealTimers())
it.each([2, 16])('joins batches from %i consumers before processing', async (consumerCount) => {
@@ -64,10 +68,23 @@ describe('ImageFetchBatchJoiner', () => {
const first = joiner.handleBatch([message(0)])
await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)
const second = joiner.handleBatch([message(1)])
+ const active = register.getSingleMetric('ml_image_fetch_stage_active')!
+ expect((await active.get()).values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ labels: { stage: 'consumer_join' }, value: 1 }),
+ expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 1 }),
+ ])
+ )
pass.reject(error)
await expect(first).rejects.toBe(error)
await expect(second).rejects.toBe(error)
+ expect((await active.get()).values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ labels: { stage: 'consumer_join' }, value: 0 }),
+ expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 0 }),
+ ])
+ )
})
it('does not hold a later partial batch behind active processing', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.ts
index 9f89c1a861ab..6b6889dc274c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.ts
@@ -1,5 +1,7 @@
import { Message } from 'node-rdkafka'
+import { ImageFetchProcessingMetrics, ProcessingStageTimer } from './processing-metrics'
+
export const IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS = 500
export const MAX_IMAGE_FETCH_BATCHES_PER_PASS = 16
@@ -8,6 +10,7 @@ type BatchProcessor = (messages: Message[]) => Promise<void>
type BatchWaiter = {
resolve: () => void
reject: (error: unknown) => void
+ timer: ProcessingStageTimer
}
type PendingBatchGroup = {
@@ -49,7 +52,7 @@ export class ImageFetchBatchJoiner {
return new Promise<void>((resolve, reject) => {
const group = this.pendingGroup ?? this.createPendingGroup()
group.batches.push(messages)
- group.waiters.push({ resolve, reject })
+ group.waiters.push({ resolve, reject, timer: ImageFetchProcessingMetrics.start('consumer_join') })
if (group.batches.length >= this.targetBatchCount) {
this.dispatch(group)
}
@@ -72,6 +75,10 @@ export class ImageFetchBatchJoiner {
clearTimeout(group.timeout)
}
+ ImageFetchProcessingMetrics.joinedBatches.observe(group.batches.length)
+ for (const { timer } of group.waiters) {
+ timer.move('consumer_process')
+ }
const processing = (async () => {
if (this.failed) {
throw this.failure
@@ -82,7 +89,7 @@ export class ImageFetchBatchJoiner {
this.fail(error)
throw error
}
- })()
+ })().finally(() => group.waiters.forEach(({ timer }) => timer.finish()))
void processing.then(
() => group.waiters.forEach(({ resolve }) => resolve()),
(error) => group.waiters.forEach(({ reject }) => reject(error))
@@ -103,7 +110,8 @@ export class ImageFetchBatchJoiner {
if (pendingGroup.timeout) {
clearTimeout(pendingGroup.timeout)
}
- for (const { reject } of pendingGroup.waiters) {
+ for (const { reject, timer } of pendingGroup.waiters) {
+ timer.finish()
reject(this.failure)
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.test.ts
index f63c83a84510..cbfa00fe6a43 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.test.ts
@@ -1,3 +1,5 @@
+import { register } from 'prom-client'
+
import { createRecordingTopHog } from '~/tests/helpers/tophog'
import { HostBudget, HostBudgetOptions } from './host-budget'
@@ -27,6 +29,7 @@ describe('OriginRequestScheduler', () => {
})
it('keeps concurrent request start times at least one second apart', async () => {
+ register.resetMetrics()
const budget = new HostBudget(OPTIONS)
budget.setCrawlDelay(ORIGIN.origin, 1_000, Date.now())
const recordingTopHog = createRecordingTopHog()
@@ -46,7 +49,26 @@ describe('OriginRequestScheduler', () => {
[7, 42]
)
)
+ await jest.advanceTimersByTimeAsync(0)
+ const active = register.getSingleMetric('ml_image_fetch_stage_active')!
+ expect((await active.get()).values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ labels: { stage: 'image_origin_crawl_delay' }, value: 2 }),
+ expect.objectContaining({ labels: { stage: 'image_http' }, value: 0 }),
+ ])
+ )
await jest.runAllTimersAsync()
+ expect((await active.get()).values.every(({ value }) => value === 0)).toBe(true)
+ const durations = await register.getSingleMetric('ml_image_fetch_stage_duration_seconds')!.get()
+ expect(durations.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ metricName: 'ml_image_fetch_stage_duration_seconds_sum',
+ labels: { stage: 'image_origin_crawl_delay' },
+ value: 3,
+ }),
+ ])
+ )
expect(await Promise.all(requests)).toEqual([
{ ran: true, value: undefined },
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.ts
index 5ec55d54521c..d7be78697dee 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.ts
@@ -6,6 +6,7 @@ import { ConfigurationRequestScheduler } from './configuration-policy'
import { BudgetBlockReason, BudgetGrant, HostBudget } from './host-budget'
import { ImageFetchRequestMetrics, SchedulerWaitScope } from './metrics'
import { politenessKey } from './politeness-key'
+import { ImageFetchProcessingMetrics } from './processing-metrics'
import { ImageFetchTopHogMetrics } from './tophog-metrics'
export type ScheduledRequest<T> =
@@ -62,6 +63,7 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
sourcePartitions: readonly number[] | undefined,
request: () => Promise<T>
): Promise<ScheduledRequest<T>> {
+ const requestKind = configurationRequest ? 'configuration' : 'image'
const origin = url.origin
const registrableDomain = politenessKey(url.hostname)
const nowMs = Date.now()
@@ -71,68 +73,75 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
try {
for (;;) {
const capacityWaitStartedAtMs = Date.now()
- const scheduled = await this.inFlight.run({
- debugTag: registrableDomain,
- fn: async () => {
- const checkedAtMs = Date.now()
- this.recordSchedulerWait(
- 'request_capacity',
- Math.max(0, checkedAtMs - capacityWaitStartedAtMs),
- registrableDomain,
- configurationRequest,
- sourcePartitions
- )
- const grant = this.budget.take(
- registrableDomain,
- origin,
- checkedAtMs,
- deadlineMs,
- configurationRequest
- )
- if (!grant.granted) {
- return {
- kind: 'stopped',
- reason: grant.reason,
- blockingReason: blockingReasonForStoppedGrant(grant),
- waitMs: grant.waitMs,
- } as const
- }
- if (grant.waitMs > 0) {
- return {
- kind: 'wait',
- waitMs: grant.waitMs,
- waitScope: grant.waitScope ?? 'registrable_domain_rate',
- } as const
- }
- if (!this.budget.acquireConnection(registrableDomain, origin)) {
- this.budget.returnGrant(
+ const capacityWait = ImageFetchProcessingMetrics.start(`${requestKind}_request_capacity`)
+ const scheduled = await this.inFlight
+ .run({
+ debugTag: registrableDomain,
+ fn: async () => {
+ capacityWait.finish()
+ const checkedAtMs = Date.now()
+ this.recordSchedulerWait(
+ 'request_capacity',
+ Math.max(0, checkedAtMs - capacityWaitStartedAtMs),
registrableDomain,
- origin,
- checkedAtMs,
- grant.reservedStartAtMs,
- grant.halfOpenProbe
+ configurationRequest,
+ sourcePartitions
)
- return {
- kind: 'stopped',
- reason: 'connection_limit' as const,
- blockingReason: 'connection_limit' as const,
- waitMs: 0,
- } as const
- }
- try {
- this.budget.markRequestStarted(
+ const grant = this.budget.take(
registrableDomain,
origin,
- Date.now(),
- grant.reservedStartAtMs,
- configurationRequest ? 'configuration' : 'image'
+ checkedAtMs,
+ deadlineMs,
+ configurationRequest
)
- return { kind: 'ran', value: await request() } as const
- } finally {
- this.budget.releaseConnection(registrableDomain, origin)
- }
- },
- })
+ if (!grant.granted) {
+ return {
+ kind: 'stopped',
+ reason: grant.reason,
+ blockingReason: blockingReasonForStoppedGrant(grant),
+ waitMs: grant.waitMs,
+ } as const
+ }
+ if (grant.waitMs > 0) {
+ return {
+ kind: 'wait',
+ waitMs: grant.waitMs,
+ waitScope: grant.waitScope ?? 'registrable_domain_rate',
+ } as const
+ }
+ if (!this.budget.acquireConnection(registrableDomain, origin)) {
+ this.budget.returnGrant(
+ registrableDomain,
+ origin,
+ checkedAtMs,
+ grant.reservedStartAtMs,
+ grant.halfOpenProbe
+ )
+ return {
+ kind: 'stopped',
+ reason: 'connection_limit' as const,
+ blockingReason: 'connection_limit' as const,
+ waitMs: 0,
+ } as const
+ }
+ try {
+ this.budget.markRequestStarted(
+ registrableDomain,
+ origin,
+ Date.now(),
+ grant.reservedStartAtMs,
+ configurationRequest ? 'configuration' : 'image'
+ )
+ return {
+ kind: 'ran',
+ value: await ImageFetchProcessingMetrics.measure(`${requestKind}_http`, request),
+ } as const
+ } finally {
+ this.budget.releaseConnection(registrableDomain, origin)
+ }
+ },
+ })
+ .finally(() => capacityWait.finish())
if (scheduled.kind === 'ran') {
return { ran: true, value: scheduled.value }
}
@@ -159,7 +168,9 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
configurationRequest,
sourcePartitions
)
- await delay(scheduled.waitMs)
+ await ImageFetchProcessingMetrics.measure(`${requestKind}_${scheduled.waitScope}`, () =>
+ delay(scheduled.waitMs)
+ )
}
} finally {
this.budget.requestFinished(origin)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.test.ts
new file mode 100644
index 000000000000..8c787581fa39
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.test.ts
@@ -0,0 +1,89 @@
+import { register } from 'prom-client'
+
+import { ConcurrencyController } from '~/common/utils/concurrencyController'
+
+import { ImageFetchProcessingMetrics } from './processing-metrics'
+
+async function sample(name: string, stage: string): Promise<number | undefined> {
+ const metric = await register.getSingleMetric(name)!.get()
+ return metric.values.find((value) => value.labels.stage === stage)?.value
+}
+
+describe('ImageFetchProcessingMetrics', () => {
+ beforeEach(() => register.resetMetrics())
+ afterEach(() => jest.restoreAllMocks())
+
+ it('keeps the oldest overlapping operation visible and removes finished stages', async () => {
+ const clock = jest.spyOn(performance, 'now').mockReturnValue(1000)
+ const first = ImageFetchProcessingMetrics.start('batch_fetch')
+ clock.mockReturnValue(2000)
+ const second = ImageFetchProcessingMetrics.start('batch_fetch')
+ clock.mockReturnValue(5000)
+ expect(await sample('ml_image_fetch_stage_active', 'batch_fetch')).toBe(2)
+ expect(await sample('ml_image_fetch_stage_oldest_seconds', 'batch_fetch')).toBe(4)
+ first.move('batch_history_write')
+ expect(await sample('ml_image_fetch_stage_oldest_seconds', 'batch_fetch')).toBe(3)
+ second.finish()
+ second.finish()
+ first.finish()
+ expect(await sample('ml_image_fetch_stage_active', 'batch_fetch')).toBe(0)
+ expect(await sample('ml_image_fetch_stage_oldest_seconds', 'batch_fetch')).toBe(0)
+ const duration = await register.getSingleMetric('ml_image_fetch_stage_duration_seconds')!.get()
+ expect(duration.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ metricName: 'ml_image_fetch_stage_duration_seconds_count',
+ labels: { stage: 'batch_fetch' },
+ value: 2,
+ }),
+ expect.objectContaining({
+ metricName: 'ml_image_fetch_stage_duration_seconds_sum',
+ labels: { stage: 'batch_fetch' },
+ value: 7,
+ }),
+ ])
+ )
+ })
+
+ it('separates admission from running work and cleans up a rejected operation', async () => {
+ const controller = new ConcurrencyController(1)
+ let release!: () => void
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ const first = ImageFetchProcessingMetrics.runLimited(controller, 'candidate_admission', 'candidate_work', {
+ debugTag: 'example.com',
+ fn: () => blocked,
+ })
+ const error = new Error('synthetic failure')
+ const second = ImageFetchProcessingMetrics.runLimited(controller, 'candidate_admission', 'candidate_work', {
+ debugTag: 'example.org',
+ fn: () => Promise.reject(error),
+ })
+ const rejected = expect(second).rejects.toBe(error)
+ expect(await sample('ml_image_fetch_stage_active', 'candidate_admission')).toBe(1)
+ expect(await sample('ml_image_fetch_stage_active', 'candidate_work')).toBe(1)
+ release()
+ await first
+ await rejected
+ expect(await sample('ml_image_fetch_stage_active', 'candidate_admission')).toBe(0)
+ expect(await sample('ml_image_fetch_stage_active', 'candidate_work')).toBe(0)
+ await expect(ImageFetchProcessingMetrics.measure('candidate_policy', () => Promise.reject(error))).rejects.toBe(
+ error
+ )
+ expect(await sample('ml_image_fetch_stage_active', 'candidate_policy')).toBe(0)
+ })
+
+ it('collects live queue depths across passes and stops retaining finished queues', async () => {
+ const queue = { candidateCount: 4 }
+ const stopFirst = ImageFetchProcessingMetrics.trackQueue(queue)
+ const stopSecond = ImageFetchProcessingMetrics.trackQueue({ candidateCount: 2 })
+ const metric = register.getSingleMetric('ml_image_fetch_candidates_queued')!
+ expect((await metric.get()).values[0].value).toBe(6)
+ queue.candidateCount = 1
+ expect((await metric.get()).values[0].value).toBe(3)
+ stopFirst()
+ stopSecond()
+ expect((await metric.get()).values[0].value).toBe(0)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.ts
new file mode 100644
index 000000000000..0f7827ba7a78
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics.ts
@@ -0,0 +1,208 @@
+import { Counter, Gauge, Histogram } from 'prom-client'
+
+import { ConcurrencyController } from '~/common/utils/concurrencyController'
+
+import type { ConfigurationFetchResult } from './configuration-policy'
+import type { ConfigurationFile } from './crawl-history'
+
+export type ProcessingStage =
+ | 'batch_parse'
+ | 'batch_filter'
+ | 'batch_history_read'
+ | 'batch_fetch'
+ | 'batch_prepare_republish'
+ | 'batch_history_write'
+ | 'batch_republish_flush'
+ | 'batch_finalize'
+ | 'batch_dead_letter'
+ | 'consumer_join'
+ | 'consumer_process'
+ | 'candidate_admission'
+ | 'candidate_work'
+ | 'candidate_policy'
+ | 'candidate_fetch'
+ | 'image_publish_admission'
+ | 'image_publish_delivery'
+ | 'configuration_fetch'
+ | `configuration_${'request_capacity' | 'origin_crawl_delay' | 'registrable_domain_rate' | 'http'}`
+ | `image_${'request_capacity' | 'origin_crawl_delay' | 'registrable_domain_rate' | 'http'}`
+
+export type ConfigurationFetchReason =
+ | ConfigurationFetchResult['outcome']
+ | 'invalid_url'
+ | 'request_error'
+ | 'timeout'
+ | 'redirect_limit'
+ | 'cross_domain_redirect'
+ | 'invalid_redirect'
+ | 'missing_location'
+ | 'http_429'
+ | 'http_5xx'
+ | 'unexpected_status'
+ | 'body_limit'
+ | 'invalid_utf8'
+ | 'invalid_document'
+
+export class ImageFetchProcessingMetrics {
+ private static readonly active = new Map<ProcessingStage, Map<symbol, number>>()
+ private static readonly queues = new Set<{ readonly candidateCount: number }>()
+
+ private static readonly activeGauge = new Gauge({
+ name: 'ml_image_fetch_stage_active',
+ help: 'Active operations by stage; nested stages overlap and must not be summed together',
+ labelNames: ['stage'],
+ collect() {
+ for (const [stage, operations] of ImageFetchProcessingMetrics.active) {
+ this.set({ stage }, operations.size)
+ }
+ },
+ })
+
+ private static readonly oldestGauge = new Gauge({
+ name: 'ml_image_fetch_stage_oldest_seconds',
+ help: 'Age of the oldest active operation in each stage, or zero when idle',
+ labelNames: ['stage'],
+ collect() {
+ const now = performance.now()
+ for (const [stage, operations] of ImageFetchProcessingMetrics.active) {
+ const first = operations.values().next().value
+ this.set({ stage }, first === undefined ? 0 : Math.max(0, now - first) / 1000)
+ }
+ },
+ })
+
+ private static readonly queuedCandidates = new Gauge({
+ name: 'ml_image_fetch_candidates_queued',
+ help: 'Candidates waiting for selection from all active passes, before candidate admission',
+ collect() {
+ let count = 0
+ for (const queue of ImageFetchProcessingMetrics.queues) {
+ count += queue.candidateCount
+ }
+ this.set(count)
+ },
+ })
+
+ private static readonly duration = new Histogram({
+ name: 'ml_image_fetch_stage_duration_seconds',
+ help: 'Elapsed time of finished stage visits, including failed operations; nested stages overlap',
+ labelNames: ['stage'],
+ buckets: [0.001, 0.01, 0.1, 0.5, 1, 5, 10, 30, 60, 120, 240, 600],
+ })
+
+ public static readonly joinedBatches = new Histogram({
+ name: 'ml_image_fetch_joined_batches',
+ help: 'Consumer batches in each dispatched fetch group',
+ buckets: [1, 2, 4, 8, 12, 16],
+ })
+
+ private static readonly configurationLookups = new Counter({
+ name: 'ml_image_fetch_configuration_lookups_total',
+ help: 'Configuration lookups by source and observed status; shared requests count once per caller',
+ labelNames: ['file', 'source', 'outcome'],
+ })
+
+ private static readonly configurationFetches = new Counter({
+ name: 'ml_image_fetch_configuration_fetches_total',
+ help: 'Completed configuration fetches, once per redirect chain, by final outcome and reason',
+ labelNames: ['file', 'outcome', 'reason'],
+ })
+
+ public static start(stage: ProcessingStage): ProcessingStageTimer {
+ return new ProcessingStageTimer(stage)
+ }
+
+ public static enter(stage: ProcessingStage): symbol {
+ let operations = this.active.get(stage)
+ if (!operations) {
+ operations = new Map()
+ this.active.set(stage, operations)
+ }
+ const id = Symbol()
+ operations.set(id, performance.now())
+ return id
+ }
+
+ public static leave(stage: ProcessingStage, id: symbol): void {
+ const operations = this.active.get(stage)
+ const started = operations?.get(id)
+ if (started !== undefined) {
+ operations!.delete(id)
+ this.duration.observe({ stage }, Math.max(0, performance.now() - started) / 1000)
+ }
+ }
+
+ public static async measure<T>(stage: ProcessingStage, operation: () => Promise<T>): Promise<T> {
+ const timer = this.start(stage)
+ try {
+ return await operation()
+ } finally {
+ timer.finish()
+ }
+ }
+
+ public static async runLimited<T>(
+ controller: ConcurrencyController,
+ waitingStage: ProcessingStage,
+ runningStage: ProcessingStage,
+ options: { debugTag: string; fn: () => Promise<T> }
+ ): Promise<T> {
+ const timer = this.start(waitingStage)
+ try {
+ return await controller.run({
+ ...options,
+ fn: () => {
+ timer.move(runningStage)
+ return options.fn()
+ },
+ })
+ } finally {
+ timer.finish()
+ }
+ }
+
+ public static trackQueue(queue: { readonly candidateCount: number }): () => void {
+ this.queues.add(queue)
+ return () => {
+ this.queues.delete(queue)
+ }
+ }
+
+ public static observeConfigurationLookup(
+ file: ConfigurationFile,
+ source: 'cache' | 'shared' | 'network',
+ outcome: ConfigurationFetchResult['outcome'] | 'error'
+ ): void {
+ this.configurationLookups.inc({ file, source, outcome })
+ }
+
+ public static observeConfigurationFetch(
+ file: ConfigurationFile,
+ result: ConfigurationFetchResult,
+ reason: ConfigurationFetchReason
+ ): ConfigurationFetchResult {
+ this.configurationFetches.inc({ file, outcome: result.outcome, reason })
+ return result
+ }
+}
+
+export class ProcessingStageTimer {
+ private id: symbol | undefined
+
+ constructor(private stage: ProcessingStage) {
+ this.id = ImageFetchProcessingMetrics.enter(stage)
+ }
+
+ public move(stage: ProcessingStage): void {
+ this.finish()
+ this.stage = stage
+ this.id = ImageFetchProcessingMetrics.enter(stage)
+ }
+
+ public finish(): void {
+ if (this.id !== undefined) {
+ ImageFetchProcessingMetrics.leave(this.stage, this.id)
+ this.id = undefined
+ }
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
index 77b85bc93927..decf4c86223a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
@@ -1,4 +1,5 @@
import { Message } from 'node-rdkafka'
+import { register } from 'prom-client'
import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'
@@ -630,6 +631,7 @@ describe('UrlFetchConsumer', () => {
})
it('throws when the bulk read fails', async () => {
+ register.resetMetrics()
const harness = build()
harness.history.readError = new Error('read failed')
const observeBatch = jest.spyOn(ImageFetchConsumerMetrics, 'observeBatch')
@@ -642,6 +644,18 @@ describe('UrlFetchConsumer', () => {
expect(observeStoreDuration).toHaveBeenCalledWith('read', 'error', expect.any(Number))
expect(startBatch).toHaveBeenCalledTimes(1)
expect(finishBatch).toHaveBeenCalledTimes(1)
+ const active = await register.getSingleMetric('ml_image_fetch_stage_active')!.get()
+ expect(active.values.every(({ value }) => value === 0)).toBe(true)
+ const durations = await register.getSingleMetric('ml_image_fetch_stage_duration_seconds')!.get()
+ expect(durations.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ metricName: 'ml_image_fetch_stage_duration_seconds_count',
+ labels: { stage: 'batch_history_read' },
+ value: 1,
+ }),
+ ])
+ )
})
it('throws when the final bulk write fails', async () => {
@@ -653,6 +667,7 @@ describe('UrlFetchConsumer', () => {
})
it('writes durable state before it flushes buffered republishes', async () => {
+ register.resetMetrics()
const harness = build()
const order: string[] = []
harness.run.mockImplementation((candidates) => {
@@ -672,6 +687,23 @@ describe('UrlFetchConsumer', () => {
await harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)
expect(order).toEqual(['published', 'history', 'republished'])
+ const durations = await register.getSingleMetric('ml_image_fetch_stage_duration_seconds')!.get()
+ const completedStages = durations.values.map(({ labels }) => labels.stage)
+ expect(completedStages).toEqual(
+ expect.arrayContaining([
+ 'batch_parse',
+ 'batch_history_read',
+ 'batch_filter',
+ 'batch_fetch',
+ 'batch_prepare_republish',
+ 'batch_history_write',
+ 'batch_republish_flush',
+ 'batch_finalize',
+ 'batch_dead_letter',
+ ])
+ )
+ const active = await register.getSingleMetric('ml_image_fetch_stage_active')!.get()
+ expect(active.values.every(({ value }) => value === 0)).toBe(true)
})
it('throws when the fetch pass reports a lost URL', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
index 8bc5dd175fe5..2f993bed6b6f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
@@ -23,6 +23,7 @@ import {
import { FrontierDeadLetterReason, FrontierDeadLetterSink } from './frontier-dead-letter-sink'
import { FrontierPublisher, RepublishBatch } from './frontier-publisher'
import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'
+import { ImageFetchProcessingMetrics } from './processing-metrics'
import { ImageFetchTopHogMetrics } from './tophog-metrics'
const ONE_HOUR_MS = 60 * 60 * 1000
@@ -71,6 +72,7 @@ export class UrlFetchConsumer {
let originCandidateCounts: number[] = []
let registrableDomainCandidateCounts: number[] = []
const activeBatchId = ImageFetchConsumerMetrics.startBatch()
+ const stage = ImageFetchProcessingMetrics.start('batch_parse')
try {
for (const message of messages) {
@@ -140,6 +142,7 @@ export class UrlFetchConsumer {
}
if (this.options.dryRun || candidates.length === 0) {
+ stage.move('batch_dead_letter')
await this.parkRejectedRecords(rejectedRecords, drops)
this.countSkippedJobs(skips)
return
@@ -152,8 +155,10 @@ export class UrlFetchConsumer {
configurationCacheKey(origin, 'tdmrep'),
]),
]
+ stage.move('batch_history_read')
const stored = await this.runCrawlHistoryOperation('read', keys.length, () => this.crawlHistory.read(keys))
+ stage.move('batch_filter')
const fetchable: FetchCandidate[] = []
const notReady: FetchCandidate[] = []
for (const candidate of candidates) {
@@ -180,7 +185,9 @@ export class UrlFetchConsumer {
ImageFetchConsumerMetrics.incFetchable(fetchable.length)
const republishBatch = this.publisher.createRepublishBatch(republishDeadlineAtMonotonicMs)
+ stage.move('batch_fetch')
const attempts = await this.runner!.run(fetchable, stored, republishBatch)
+ stage.move('batch_prepare_republish')
attempts.push(
...(await Promise.all(
notReady.map((candidate) => this.republishNotReady(republishBatch, candidate, nowMs))
@@ -194,9 +201,12 @@ export class UrlFetchConsumer {
}
}
if (updates.length > 0) {
+ stage.move('batch_history_write')
await this.runCrawlHistoryOperation('write', updates.length, () => this.crawlHistory.write(updates))
}
+ stage.move('batch_republish_flush')
const republishResult = await republishBatch.flush()
+ stage.move('batch_finalize')
for (const attempt of attempts) {
if (attempt.lost || (!attempt.finished && republishResult.failedUrls > 0)) {
continue
@@ -217,9 +227,11 @@ export class UrlFetchConsumer {
if (lost > 0) {
throw new Error(`the image fetch lane could not account for ${lost} URLs`)
}
+ stage.move('batch_dead_letter')
await this.parkRejectedRecords(rejectedRecords, drops)
this.countSkippedJobs(skips)
} finally {
+ stage.finish()
ImageFetchConsumerMetrics.finishBatch(activeBatchId)
this.recordMetrics(
drops,