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.

feat(session-replay): add image fetch domain TopHog metrics (#91255)

Robbieb8e4c30c703e
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
index 1087e6a740da..e4fc9089e91f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
@@ -467,6 +467,18 @@ It counts transient retry causes as `timeout`, `error`, `rate_limited`, or `serv
**11.11** The mirror counts collected image ref occurrences by `css` or `html` source, canonical property name, and `inline` or `url` lane. It counts before per-message ref deduplication. Every property label comes from the fixed HTML attribute set in requirement 13.11 or the fixed CSS property allowlist in the anonymizer.
+**11.12** The fetch deployment writes three high-cardinality metrics to TopHog. It does not export registrable domains as Prometheus labels.
+
+`ml_image_fetch_attempts_by_registrable_domain` counts durable URL attempts by partition, registrable domain, completed or republished disposition, and outcome.
+
+`ml_image_fetch_block_events_by_registrable_domain` counts blocking observations by partition, registrable domain, and exact reason. Reasons distinguish concurrency, scheduler waits, configuration failures, response backoff, and deadlines.
+
+`ml_image_fetch_blocked_ms_by_registrable_domain` sums positive wait milliseconds spent or imposed for the same keys. Domain concurrency contributes events because it has no measured wait duration.
+
+The frontier retains an exact block reason across delay topics. Records created before this field existed use `unknown_backoff` when they return early.
+
+Each metric returns the top 20 domain-factor keys per flush and tracks at most 2,000 keys in pod memory.
+
### 12. Conditional requests
**12.1** The lane stores the request time, response time, `ETag`, `Last-Modified`, `Date`, `Age`, `Cache-Control`, and `Expires` metadata in the crawl history for that URL.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/block-reason.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/block-reason.ts
new file mode 100644
index 000000000000..3fa500061de1
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/block-reason.ts
@@ -0,0 +1,38 @@
+export type ImageFetchBlockReason =
+ | 'domain_concurrency'
+ | 'request_capacity'
+ | 'origin_crawl_delay'
+ | 'registrable_domain_rate'
+ | 'retry_after'
+ | 'transient_backoff'
+ | 'unknown_backoff'
+ | 'configuration_unreachable'
+ | 'configuration_deferred'
+ | 'breaker_open'
+ | 'connection_limit'
+ | 'origin_map_full'
+ | 'registrable_domain_map_full'
+ | 'pass_deadline'
+ | 'request_deadline'
+
+const IMAGE_FETCH_BLOCK_REASONS = new Set<ImageFetchBlockReason>([
+ 'domain_concurrency',
+ 'request_capacity',
+ 'origin_crawl_delay',
+ 'registrable_domain_rate',
+ 'retry_after',
+ 'transient_backoff',
+ 'unknown_backoff',
+ 'configuration_unreachable',
+ 'configuration_deferred',
+ 'breaker_open',
+ 'connection_limit',
+ 'origin_map_full',
+ 'registrable_domain_map_full',
+ 'pass_deadline',
+ 'request_deadline',
+])
+
+export function isImageFetchBlockReason(value: unknown): value is ImageFetchBlockReason {
+ return typeof value === 'string' && IMAGE_FETCH_BLOCK_REASONS.has(value as ImageFetchBlockReason)
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts
index 0991e17a9516..21af346ba912 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts
@@ -49,9 +49,10 @@ function record(overrides: Record<string, unknown> = {}): Buffer {
describe('frontier record', () => {
it('round trips the durable job state', () => {
- const parsed = parseCollectedUrlsRecord(serializeFrontierRecord([candidate()]), 'example.com')
+ const durableCandidate = candidate({ lastBlockReason: 'configuration_unreachable' })
+ const parsed = parseCollectedUrlsRecord(serializeFrontierRecord([durableCandidate]), 'example.com')
- expect(parsed).toEqual({ ok: true, candidates: [candidate()], urlCount: 1, rejected: [] })
+ expect(parsed).toEqual({ ok: true, candidates: [durableCandidate], urlCount: 1, rejected: [] })
})
it('does not persist source partition attribution', () => {
@@ -157,6 +158,7 @@ describe('frontier record', () => {
['fetchCount', 1.5],
['republishCount', Number.MAX_SAFE_INTEGER + 1],
['lastRepublishReason', 'unknown'],
+ ['lastBlockReason', 'unknown'],
])('drops an invalid %s', (field, value) => {
const parsed = parseCollectedUrlsRecord(record({ [field]: value }), 'example.com')
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
index d147e1652b89..343ff5efdf84 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
@@ -1,6 +1,7 @@
import { parseJSON } from '~/common/utils/json-parse'
import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
+import { ImageFetchBlockReason, isImageFetchBlockReason } from './block-reason'
import { canonicalizeUrl } from './politeness-key'
export const MAX_HOPS = 10
@@ -35,6 +36,7 @@ export interface FetchCandidate {
fetchCount: number
republishCount: number
lastRepublishReason: StoredRepublishReason | null
+ lastBlockReason?: ImageFetchBlockReason
sourcePartitions?: readonly number[]
}
@@ -51,6 +53,7 @@ export interface FrontierRecord {
| 'fetchCount'
| 'republishCount'
| 'lastRepublishReason'
+ | 'lastBlockReason'
>
>
}
@@ -199,6 +202,7 @@ function parseJob(
fetchCount,
republishCount,
lastRepublishReason,
+ lastBlockReason,
lowOriginDiversityDeferred,
} = job
if (
@@ -211,6 +215,7 @@ function parseJob(
!isNonNegativeSafeInteger(fetchCount) ||
!isNonNegativeSafeInteger(republishCount) ||
!isStoredRepublishReason(lastRepublishReason) ||
+ (lastBlockReason !== undefined && !isImageFetchBlockReason(lastBlockReason)) ||
(lowOriginDiversityDeferred !== undefined && typeof lowOriginDiversityDeferred !== 'boolean')
) {
return { ok: false, reason: 'bad_url' }
@@ -240,6 +245,7 @@ function parseJob(
fetchCount,
republishCount,
lastRepublishReason,
+ lastBlockReason,
},
}
}
@@ -256,6 +262,7 @@ export function serializeFrontierRecord(candidates: FetchCandidate[]): Buffer {
fetchCount: candidate.fetchCount,
republishCount: candidate.republishCount,
lastRepublishReason: candidate.lastRepublishReason,
+ lastBlockReason: candidate.lastBlockReason,
})),
}
return Buffer.from(JSON.stringify(record))
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
index 3d5a3650e9b1..3a97a0db014c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
@@ -1,3 +1,5 @@
+import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'
+
import { FetchCandidate, MAX_HOPS } from './collected-urls-record'
import { ConfigurationPolicyService, OriginPolicyDecision } from './configuration-policy'
import { ConfigurationCacheItem, CrawlHistoryItem, HttpCacheMetadata } from './crawl-history'
@@ -7,6 +9,7 @@ import { HostBudget } from './host-budget'
import { ImageFetchOptions, ImageFetchResult, ImageFetcher } from './image-fetcher'
import { ImageFetchRequestMetrics } from './metrics'
import { OriginRequestScheduler } from './origin-request-scheduler'
+import { ImageFetchTopHogMetrics } from './tophog-metrics'
const NOW_MS = 1_700_000_000_000
const OPTIONS: FetchRunnerOptions = {
@@ -44,6 +47,7 @@ interface Harness {
createPass: jest.Mock
republish: jest.Mock<Promise<RepublishResult>, any[]>
publishImage: jest.Mock<Promise<void>, any[]>
+ topHogRecords: Map<string, RecordedTopHogMetric[]>
}
function build(
@@ -87,15 +91,17 @@ function build(
maxTrackedOrigins: 20_000,
random: () => 0,
})
+ const recordingTopHog = createRecordingTopHog()
const runner = new FetchRunner(
{ fetch } as ImageFetcher,
budget,
scheduler,
{ createPass } as unknown as ConfigurationPolicyService,
options,
- { createRepublishBatch, publishImage } as unknown as FrontierPublisher
+ { createRepublishBatch, publishImage } as unknown as FrontierPublisher,
+ new ImageFetchTopHogMetrics(recordingTopHog.registry)
)
- return { runner, budget, fetch, check, createPass, republish, publishImage }
+ return { runner, budget, fetch, check, createPass, republish, publishImage, topHogRecords: recordingTopHog.records }
}
describe('FetchRunner', () => {
@@ -164,14 +170,16 @@ describe('FetchRunner', () => {
releaseFirst = () => resolve({ outcome: 'ok', redirects: 0, currentUrl: url })
})
)
+ const first = candidate({ sourcePartitions: [110] })
const sibling = candidate({
originalRef: `imageurl:${'b'.repeat(22)}`,
currentUrl: 'https://images.example.com/b.png',
host: 'images.example.com',
origin: 'https://images.example.com',
+ sourcePartitions: [110],
})
- const run = harness.runner.run([candidate(), sibling], new Map())
+ const run = harness.runner.run([first, sibling], new Map())
await Promise.resolve()
await Promise.resolve()
@@ -180,6 +188,12 @@ describe('FetchRunner', () => {
releaseFirst?.()
await run
expect(harness.fetch).toHaveBeenCalledTimes(2)
+ expect(harness.topHogRecords.get('ml_image_fetch_block_events_by_registrable_domain')).toEqual([
+ {
+ key: { registrable_domain: 'example.com', reason: 'domain_concurrency', partition: '110' },
+ value: 1,
+ },
+ ])
})
it('allocates sibling-origin workers by queue share', async () => {
@@ -228,11 +242,12 @@ describe('FetchRunner', () => {
maxInFlightRequests: 3,
})
const candidates = [
- candidate(),
+ candidate({ sourcePartitions: [110] }),
...Array.from({ length: 2 }, (_, index) =>
candidate({
originalRef: `imageurl:${String(index + 1).repeat(22)}`,
currentUrl: `https://cdn.example.com/image-${index}.png`,
+ sourcePartitions: [110],
})
),
...Array.from({ length: 2 }, (_, index) =>
@@ -242,6 +257,7 @@ describe('FetchRunner', () => {
host: `origin-${index}.other.net`,
origin: `https://origin-${index}.other.net`,
registrableDomain: 'other.net',
+ sourcePartitions: [42],
})
),
]
@@ -259,6 +275,12 @@ describe('FetchRunner', () => {
await harness.runner.run(candidates, new Map())
expect(observeCapacity).toHaveBeenCalledWith(3, 3)
+ expect(harness.topHogRecords.get('ml_image_fetch_block_events_by_registrable_domain')).toEqual([
+ {
+ key: { registrable_domain: 'example.com', reason: 'domain_concurrency', partition: '110' },
+ value: 2,
+ },
+ ])
harness.budget.releaseConnection('example.com', 'https://cdn.example.com')
})
@@ -449,7 +471,10 @@ describe('FetchRunner', () => {
const [attempt] = await harness.runner.run([candidate()], new Map())
expect(harness.republish).toHaveBeenCalledWith(
- candidate(),
+ expect.objectContaining({
+ originalRef: candidate().originalRef,
+ lastBlockReason: 'configuration_unreachable',
+ }),
{
currentUrl: candidate().currentUrl,
host: candidate().host,
@@ -459,7 +484,12 @@ describe('FetchRunner', () => {
'not_ready',
3_600_000
)
- expect(attempt).toMatchObject({ outcome: 'backoff', finished: false, lost: false })
+ expect(attempt).toMatchObject({
+ outcome: 'backoff',
+ finished: false,
+ lost: false,
+ block: { reason: 'configuration_unreachable', waitMs: 3_600_000 },
+ })
expect(attempt.history).toBeUndefined()
})
@@ -483,7 +513,11 @@ describe('FetchRunner', () => {
'retry',
120_000
)
- expect(attempt).toMatchObject({ outcome: 'server_error', finished: false })
+ expect(attempt).toMatchObject({
+ outcome: 'server_error',
+ finished: false,
+ block: { reason: 'retry_after', waitMs: 120_000 },
+ })
})
it('republishes an unfollowed redirect target with the original ref', async () => {
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 2a7ddc918605..8a4084685e0f 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
@@ -1,6 +1,7 @@
import { ConcurrencyController } from '~/common/utils/concurrencyController'
import { logger } from '~/common/utils/logger'
+import type { ImageFetchBlockReason } from './block-reason'
import { FetchCandidate, MAX_HOPS, RepublishReason } from './collected-urls-record'
import {
ConfigurationPolicyPass,
@@ -21,6 +22,7 @@ import {
import { ImageFetchRequestMetrics } from './metrics'
import { OriginRequestScheduler } from './origin-request-scheduler'
import { canonicalizeUrl } from './politeness-key'
+import { ImageFetchTopHogMetrics } from './tophog-metrics'
export type ShedReason =
| 'breaker_open'
@@ -44,6 +46,7 @@ export interface FetchAttempt {
outcome: AttemptOutcome
finished: boolean
lost: boolean
+ block?: { reason: ImageFetchBlockReason; waitMs: number }
history?: UrlCrawlHistoryItem
configurationUpdates: ConfigurationCacheItem[]
}
@@ -105,7 +108,8 @@ export class FetchRunner implements FetchPass {
private readonly scheduler: OriginRequestScheduler,
private readonly configurationPolicy: ConfigurationPolicyService,
private readonly options: FetchRunnerOptions,
- private readonly publisher: FrontierPublisher
+ private readonly publisher: FrontierPublisher,
+ private readonly topHogMetrics?: ImageFetchTopHogMetrics
) {
requirePositiveSafeInteger(
'SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN',
@@ -141,12 +145,15 @@ export class FetchRunner implements FetchPass {
}
}
const queue = new FetchCandidateQueue(candidates, this.options)
+ this.topHogMetrics?.recordConcurrencyLimitedUrls(candidates, (registrableDomain) =>
+ this.budget.availableConnections(registrableDomain, this.options.maxConcurrentPerRegistrableDomain)
+ )
const podRequestSlots = Math.max(0, this.options.maxInFlightRequests - this.candidateWork.running)
ImageFetchRequestMetrics.observeBatchSchedulableCapacity(
Math.min(
podRequestSlots,
queue.availableRequestSlotsAtStart((registrableDomain) =>
- this.budget.availableConnections(registrableDomain)
+ this.budget.availableConnections(registrableDomain, this.options.maxConcurrentPerRegistrableDomain)
)
),
this.options.maxInFlightRequests
@@ -237,7 +244,7 @@ export class FetchRunner implements FetchPass {
return this.terminal(candidate, HOPS_EXHAUSTED, undefined, [])
}
if (Date.now() > deadlineMs) {
- return await this.republish(republishBatch, candidate, 'deadline', 'pass_deadline', 0, [])
+ return await this.republish(republishBatch, candidate, 'deadline', 'pass_deadline', 0, [], 'pass_deadline')
}
return await this.candidateWork.run({
debugTag: candidate.registrableDomain,
@@ -247,7 +254,15 @@ export class FetchRunner implements FetchPass {
}
try {
if (Date.now() > deadlineMs) {
- return await this.republish(republishBatch, candidate, 'deadline', 'pass_deadline', 0, [])
+ return await this.republish(
+ republishBatch,
+ candidate,
+ 'deadline',
+ 'pass_deadline',
+ 0,
+ [],
+ 'pass_deadline'
+ )
}
return await this.fetchOne(
candidate,
@@ -291,7 +306,8 @@ export class FetchRunner implements FetchPass {
policy.reason,
policy.reason,
ONE_MINUTE_MS,
- configurationUpdates
+ configurationUpdates,
+ policy.reason
)
}
const waitMs = policy.reason === 'configuration_unreachable' ? CONFIGURATION_RETRY_MS : ONE_MINUTE_MS
@@ -301,7 +317,10 @@ export class FetchRunner implements FetchPass {
'backoff',
'not_ready',
waitMs,
- configurationUpdates
+ configurationUpdates,
+ policy.reason === 'configuration_unreachable'
+ ? 'configuration_unreachable'
+ : 'configuration_deferred'
)
}
return this.terminal(
@@ -320,7 +339,8 @@ export class FetchRunner implements FetchPass {
'origin_map_full',
'origin_map_full',
ONE_MINUTE_MS,
- configurationUpdates
+ configurationUpdates,
+ 'origin_map_full'
)
}
@@ -397,7 +417,12 @@ export class FetchRunner implements FetchPass {
reason,
republishReason,
waitMs,
- configurationUpdates
+ configurationUpdates,
+ stateFull
+ ? reason
+ : reason === 'configuration_unreachable'
+ ? 'configuration_unreachable'
+ : 'configuration_deferred'
)
}
return this.terminal(attemptedCandidate, reason, undefined, configurationUpdates, reason)
@@ -425,7 +450,15 @@ export class FetchRunner implements FetchPass {
reason,
republishReason,
waitMs,
- configurationUpdates
+ configurationUpdates,
+ result.schedulingBlockingReason ??
+ (republishReason === 'pass_deadline'
+ ? 'pass_deadline'
+ : reason === 'backoff'
+ ? 'unknown_backoff'
+ : reason === 'deadline'
+ ? 'request_deadline'
+ : reason)
)
}
@@ -443,7 +476,8 @@ export class FetchRunner implements FetchPass {
result.outcome,
'retry',
delayMs,
- configurationUpdates
+ configurationUpdates,
+ result.retryAfterMs === undefined ? 'transient_backoff' : 'retry_after'
)
return attempt
}
@@ -503,7 +537,8 @@ export class FetchRunner implements FetchPass {
outcome: AttemptOutcome,
reason: RepublishReason,
waitMs: number,
- configurationUpdates: ConfigurationCacheItem[]
+ configurationUpdates: ConfigurationCacheItem[],
+ blockingReason: ImageFetchBlockReason
): Promise<FetchAttempt> {
return await this.republishToTarget(
republishBatch,
@@ -517,7 +552,8 @@ export class FetchRunner implements FetchPass {
},
reason,
waitMs,
- configurationUpdates
+ configurationUpdates,
+ { reason: blockingReason, waitMs }
)
}
@@ -528,20 +564,26 @@ export class FetchRunner implements FetchPass {
target: Pick<FetchCandidate, 'currentUrl' | 'host' | 'origin' | 'registrableDomain'>,
reason: RepublishReason,
waitMs: number,
- configurationUpdates: ConfigurationCacheItem[]
+ configurationUpdates: ConfigurationCacheItem[],
+ block?: { reason: ImageFetchBlockReason; waitMs: number }
): Promise<FetchAttempt> {
if ((reason === 'redirect' || reason === 'retry') && candidate.remainingHops <= 1) {
return this.terminal(candidate, HOPS_EXHAUSTED, undefined, configurationUpdates)
}
- const result: RepublishResult = await republishBatch.republish(candidate, target, reason, waitMs)
+ const republishedCandidate: FetchCandidate = {
+ ...candidate,
+ lastBlockReason: block?.reason,
+ }
+ const result: RepublishResult = await republishBatch.republish(republishedCandidate, target, reason, waitMs)
if (result === 'refused_delay') {
return this.terminal(candidate, DELAY_TOO_LONG, undefined, configurationUpdates)
}
return {
- candidate,
+ candidate: republishedCandidate,
outcome,
finished: false,
lost: false,
+ block,
configurationUpdates,
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts
index 445a6f3859aa..c0c87cf8b024 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts
@@ -113,6 +113,7 @@ describe('HostBudget', () => {
expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 180_999, DEADLINE_MS)).toEqual({
granted: false,
reason: 'backoff',
+ backoffReason: 'retry_after',
waitMs: 1,
})
})
@@ -125,6 +126,7 @@ describe('HostBudget', () => {
expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 2_000, DEADLINE_MS)).toEqual({
granted: false,
reason: 'backoff',
+ backoffReason: 'retry_after',
waitMs: 179_000,
})
})
@@ -242,6 +244,7 @@ describe('HostBudget', () => {
granted: false,
reason: 'deadline',
waitMs: 600_000,
+ waitScope: 'origin_crawl_delay',
})
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts
index 035f9a5de6c6..03ceb6ca91ae 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts
@@ -1,3 +1,5 @@
+import type { ImageFetchBlockReason } from './block-reason'
+
export interface HostBudgetOptions {
requestsPerSecond: number
burst: number
@@ -17,6 +19,7 @@ export type BudgetBlockReason =
| 'origin_map_full'
| 'registrable_domain_map_full'
export type BudgetWaitScope = 'origin_crawl_delay' | 'registrable_domain_rate'
+export type HostBackoffReason = Extract<ImageFetchBlockReason, 'retry_after' | 'transient_backoff'>
export type BudgetGrant =
| {
granted: true
@@ -25,7 +28,13 @@ export type BudgetGrant =
halfOpenProbe: boolean
reservedStartAtMs: number | null
}
- | { granted: false; reason: BudgetBlockReason; waitMs: number }
+ | {
+ granted: false
+ reason: BudgetBlockReason
+ waitMs: number
+ backoffReason?: HostBackoffReason
+ waitScope?: BudgetWaitScope
+ }
const EVICTION_SCAN_LIMIT = 64
@@ -36,6 +45,7 @@ interface RegistrableDomainState {
lastRefillMs: number
consecutiveTransientFailures: number
blockedUntilMs: number
+ backoffReason: HostBackoffReason | null
breakerOpen: boolean
halfOpenProbeInFlight: boolean
}
@@ -89,10 +99,18 @@ export class HostBudget {
let halfOpenProbe = false
if (!ignoreImageDelay) {
if (registrableDomainState.blockedUntilMs > nowMs) {
+ if (registrableDomainState.breakerOpen) {
+ return {
+ granted: false,
+ reason: 'breaker_open',
+ waitMs: registrableDomainState.blockedUntilMs - nowMs,
+ }
+ }
return {
granted: false,
- reason: registrableDomainState.breakerOpen ? 'breaker_open' : 'backoff',
+ reason: 'backoff',
waitMs: registrableDomainState.blockedUntilMs - nowMs,
+ backoffReason: registrableDomainState.backoffReason ?? undefined,
}
}
if (registrableDomainState.breakerOpen) {
@@ -113,7 +131,7 @@ export class HostBudget {
const waitScope: BudgetWaitScope | null =
waitMs === 0 ? null : crawlWaitMs > tokenWaitMs ? 'origin_crawl_delay' : 'registrable_domain_rate'
if (nowMs + waitMs > deadlineMs) {
- return { granted: false, reason: 'deadline', waitMs }
+ return { granted: false, reason: 'deadline', waitMs, waitScope: waitScope ?? undefined }
}
if (waitMs > 0) {
return {
@@ -203,9 +221,9 @@ export class HostBudget {
return true
}
- public availableConnections(registrableDomain: string): number {
+ public availableConnections(registrableDomain: string, connectionLimit = this.options.maxConcurrent): number {
const inFlight = this.registrableDomains.get(registrableDomain)?.inFlight ?? 0
- return Math.max(0, this.options.maxConcurrent - inFlight)
+ return Math.max(0, Math.min(this.options.maxConcurrent, connectionLimit) - inFlight)
}
public releaseConnection(registrableDomain: string, origin: string): void {
@@ -260,7 +278,11 @@ export class HostBudget {
minimumDelayMs + Math.floor(this.random() * (maximumDelayMs - minimumDelayMs + 1))
)
const delayMs = Math.max(jitteredDelayMs, retryAfterMs ?? 0)
- state.blockedUntilMs = Math.max(state.blockedUntilMs, nowMs + delayMs)
+ const blockedUntilMs = nowMs + delayMs
+ if (blockedUntilMs >= state.blockedUntilMs) {
+ state.backoffReason = retryAfterMs === undefined ? 'transient_backoff' : 'retry_after'
+ }
+ state.blockedUntilMs = Math.max(state.blockedUntilMs, blockedUntilMs)
if (state.consecutiveTransientFailures >= this.options.breakerFailures) {
state.breakerOpen = true
state.halfOpenProbeInFlight = false
@@ -275,6 +297,9 @@ export class HostBudget {
}
state.consecutiveTransientFailures = 0
state.blockedUntilMs = Math.max(state.blockedUntilMs, nowMs)
+ if (state.blockedUntilMs <= nowMs) {
+ state.backoffReason = null
+ }
state.breakerOpen = false
state.halfOpenProbeInFlight = false
}
@@ -322,6 +347,7 @@ export class HostBudget {
lastRefillMs: nowMs,
consecutiveTransientFailures: 0,
blockedUntilMs: 0,
+ backoffReason: null,
breakerOpen: false,
halfOpenProbeInFlight: false,
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts
index d4c850298206..40d9bc7272e1 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts
@@ -350,7 +350,12 @@ describe('HttpImageFetcher', () => {
requestNumber += 1
return requestNumber === 1
? { ran: true as const, value: await request() }
- : { ran: false as const, reason: 'backoff' as const, waitMs: 90_000 }
+ : {
+ ran: false as const,
+ reason: 'backoff' as const,
+ blockingReason: 'retry_after' as const,
+ waitMs: 90_000,
+ }
},
})
@@ -359,6 +364,7 @@ describe('HttpImageFetcher', () => {
redirects: 1,
currentUrl: 'https://cdn.example.net/a.png',
schedulingReason: 'backoff',
+ schedulingBlockingReason: 'retry_after',
schedulingWaitMs: 90_000,
})
expect(fetchStreamedMock).toHaveBeenCalledTimes(1)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts
index b696bfcefe85..c3ff3968d99f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts
@@ -1,5 +1,6 @@
import { InvalidRequestError, ResolutionError, SecureRequestError, fetchStreamed } from '~/common/utils/request'
+import type { ImageFetchBlockReason } from './block-reason'
import { OriginPolicyReason, ResponseOptOutReason, responseOptOutReason } from './configuration-policy'
import { HttpCacheMetadata } from './crawl-history'
import { ImageFetchRequestMetrics } from './metrics'
@@ -53,6 +54,7 @@ export interface ImageFetchResult {
/** Set by a 429 or a 503 that named a period. The caller holds the registrable domain for that period. */
retryAfterMs?: number
schedulingReason?: RequestScheduleBlockReason
+ schedulingBlockingReason?: ImageFetchBlockReason
schedulingWaitMs?: number
policyTransient?: boolean
/** Where a redirect this lane did not follow points. The caller republishes it rather than fetching it. */
@@ -69,7 +71,15 @@ export interface ImageFetchOptions {
url: URL,
deadlineMs: number,
request: () => Promise<T>
- ) => Promise<{ ran: true; value: T } | { ran: false; reason: RequestScheduleBlockReason; waitMs: number }>
+ ) => Promise<
+ | { ran: true; value: T }
+ | {
+ ran: false
+ reason: RequestScheduleBlockReason
+ blockingReason: ImageFetchBlockReason
+ waitMs: number
+ }
+ >
checkRedirectPolicy: (url: string) => Promise<RedirectTargetPolicy>
isDifferentOrigin: (url: URL) => boolean
cache?: HttpCacheMetadata
@@ -129,7 +139,12 @@ export class HttpImageFetcher implements ImageFetcher {
}
let scheduled:
| { ran: true; value: HopResult }
- | { ran: false; reason: RequestScheduleBlockReason; waitMs: number }
+ | {
+ ran: false
+ reason: RequestScheduleBlockReason
+ blockingReason: ImageFetchBlockReason
+ waitMs: number
+ }
try {
scheduled = await options.scheduleRequest(new URL(target), deadlineMs, () =>
this.hop(
@@ -150,6 +165,7 @@ export class HttpImageFetcher implements ImageFetcher {
redirects,
currentUrl: target,
schedulingReason: scheduled.reason,
+ schedulingBlockingReason: scheduled.blockingReason,
schedulingWaitMs: scheduled.waitMs,
}
}
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 0e1c9fa7d983..f63c83a84510 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,6 +1,9 @@
+import { createRecordingTopHog } from '~/tests/helpers/tophog'
+
import { HostBudget, HostBudgetOptions } from './host-budget'
import { ImageFetchRequestMetrics } from './metrics'
import { OriginRequestScheduler } from './origin-request-scheduler'
+import { ImageFetchTopHogMetrics } from './tophog-metrics'
const OPTIONS: HostBudgetOptions = {
requestsPerSecond: 1,
@@ -26,7 +29,8 @@ describe('OriginRequestScheduler', () => {
it('keeps concurrent request start times at least one second apart', async () => {
const budget = new HostBudget(OPTIONS)
budget.setCrawlDelay(ORIGIN.origin, 1_000, Date.now())
- const scheduler = new OriginRequestScheduler(budget, 300)
+ const recordingTopHog = createRecordingTopHog()
+ const scheduler = new OriginRequestScheduler(budget, 300, new ImageFetchTopHogMetrics(recordingTopHog.registry))
const observeSchedulerWait = jest.spyOn(ImageFetchRequestMetrics, 'observeSchedulerWait')
const startedAtMs: number[] = []
const deadlineMs = Date.now() + 10_000
@@ -52,6 +56,35 @@ describe('OriginRequestScheduler', () => {
expect(startedAtMs).toEqual([1_700_000_000_000, 1_700_000_001_000, 1_700_000_002_000])
expect(observeSchedulerWait).toHaveBeenCalledWith('origin_crawl_delay', 1, [7, 42])
expect(observeSchedulerWait).toHaveBeenCalledWith('request_capacity', 0, [7, 42])
+ expect(recordingTopHog.records.get('ml_image_fetch_block_events_by_registrable_domain')).toEqual(
+ expect.arrayContaining([
+ {
+ key: {
+ registrable_domain: REGISTRABLE_DOMAIN,
+ reason: 'origin_crawl_delay',
+ partition: '7',
+ },
+ value: 1,
+ },
+ ])
+ )
+ expect(recordingTopHog.records.get('ml_image_fetch_blocked_ms_by_registrable_domain')).toEqual(
+ expect.arrayContaining([
+ {
+ key: {
+ registrable_domain: REGISTRABLE_DOMAIN,
+ reason: 'origin_crawl_delay',
+ partition: '7',
+ },
+ value: 1_000,
+ },
+ ])
+ )
+ expect(
+ recordingTopHog.records
+ .get('ml_image_fetch_block_events_by_registrable_domain')
+ ?.some(({ key }) => key.reason === 'request_capacity')
+ ).toBe(false)
})
it('allows six concurrent same-origin requests when the request rate and crawl delay are disabled', async () => {
@@ -71,7 +104,12 @@ describe('OriginRequestScheduler', () => {
)
)
- await expect(requests[6]).resolves.toEqual({ ran: false, reason: 'connection_limit', waitMs: 0 })
+ await expect(requests[6]).resolves.toEqual({
+ ran: false,
+ reason: 'connection_limit',
+ blockingReason: 'connection_limit',
+ waitMs: 0,
+ })
expect(releases).toHaveLength(6)
releases.forEach((release) => release())
await expect(Promise.all(requests.slice(0, 6))).resolves.toEqual(
@@ -99,6 +137,7 @@ describe('OriginRequestScheduler', () => {
await expect(scheduler.runImage(ORIGIN, Date.now() + 10_000, () => Promise.resolve())).resolves.toEqual({
ran: false,
reason: 'breaker_open',
+ blockingReason: 'breaker_open',
waitMs: OPTIONS.breakerCooldownMs,
})
expect(finishProbe).toBeDefined()
@@ -106,6 +145,19 @@ describe('OriginRequestScheduler', () => {
await expect(probe).resolves.toEqual({ ran: true, value: undefined })
})
+ it('preserves the response backoff reason', async () => {
+ const budget = new HostBudget(OPTIONS)
+ budget.recordTransientFailure(REGISTRABLE_DOMAIN, Date.now(), 120_000)
+ const scheduler = new OriginRequestScheduler(budget, 300)
+
+ await expect(scheduler.runImage(ORIGIN, Date.now() + 10_000, () => Promise.resolve())).resolves.toEqual({
+ ran: false,
+ reason: 'backoff',
+ blockingReason: 'retry_after',
+ waitMs: 120_000,
+ })
+ })
+
it('returns a queued request to the caller when its pass deadline expires', async () => {
const scheduler = new OriginRequestScheduler(new HostBudget(OPTIONS), 1)
let releaseFirst: (() => void) | undefined
@@ -124,7 +176,12 @@ describe('OriginRequestScheduler', () => {
releaseFirst?.()
await expect(first).resolves.toEqual({ ran: true, value: undefined })
- await expect(second).resolves.toEqual({ ran: false, reason: 'deadline', waitMs: 0 })
+ await expect(second).resolves.toEqual({
+ ran: false,
+ reason: 'deadline',
+ blockingReason: 'request_deadline',
+ waitMs: 0,
+ })
})
it('checks the registrable-domain token bucket after a pod-capacity wait', async () => {
@@ -168,6 +225,7 @@ describe('OriginRequestScheduler', () => {
await expect(scheduler.runImage(ORIGIN, Date.now() + 20_000, () => Promise.resolve())).resolves.toEqual({
ran: false,
reason: 'deadline',
+ blockingReason: 'origin_crawl_delay',
waitMs: 600_000,
})
})
@@ -187,7 +245,12 @@ describe('OriginRequestScheduler', () => {
await Promise.resolve()
await expect(
scheduler.runImage(new URL('https://b.example.com/image.png'), Date.now() + 10_000, () => Promise.resolve())
- ).resolves.toEqual({ ran: false, reason: 'connection_limit', waitMs: 0 })
+ ).resolves.toEqual({
+ ran: false,
+ reason: 'connection_limit',
+ blockingReason: 'connection_limit',
+ waitMs: 0,
+ })
releaseFirst?.()
await expect(first).resolves.toEqual({ ran: true, value: undefined })
@@ -208,7 +271,12 @@ describe('OriginRequestScheduler', () => {
await Promise.resolve()
await expect(
scheduler.runImage(new URL('https://b.example.com/image.png'), Date.now() + 10_000, () => Promise.resolve())
- ).resolves.toEqual({ ran: false, reason: 'connection_limit', waitMs: 0 })
+ ).resolves.toEqual({
+ ran: false,
+ reason: 'connection_limit',
+ blockingReason: 'connection_limit',
+ waitMs: 0,
+ })
expect(releaseConfiguration).toBeDefined()
releaseConfiguration?.()
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 108d8020685b..5ec55d54521c 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
@@ -1,21 +1,39 @@
import { ConcurrencyController } from '~/common/utils/concurrencyController'
import { delay } from '~/common/utils/utils'
+import type { ImageFetchBlockReason } from './block-reason'
import { ConfigurationRequestScheduler } from './configuration-policy'
-import { BudgetBlockReason, HostBudget } from './host-budget'
-import { ImageFetchRequestMetrics } from './metrics'
+import { BudgetBlockReason, BudgetGrant, HostBudget } from './host-budget'
+import { ImageFetchRequestMetrics, SchedulerWaitScope } from './metrics'
import { politenessKey } from './politeness-key'
+import { ImageFetchTopHogMetrics } from './tophog-metrics'
export type ScheduledRequest<T> =
| { ran: true; value: T }
- | { ran: false; reason: BudgetBlockReason | 'connection_limit'; waitMs: number }
+ | {
+ ran: false
+ reason: BudgetBlockReason | 'connection_limit'
+ blockingReason: ImageFetchBlockReason
+ waitMs: number
+ }
+
+function blockingReasonForStoppedGrant(grant: Extract<BudgetGrant, { granted: false }>): ImageFetchBlockReason {
+ if (grant.reason === 'backoff') {
+ return grant.backoffReason ?? 'unknown_backoff'
+ }
+ if (grant.reason === 'deadline') {
+ return grant.waitScope ?? 'request_deadline'
+ }
+ return grant.reason
+}
export class OriginRequestScheduler implements ConfigurationRequestScheduler {
private readonly inFlight: ConcurrencyController
constructor(
private readonly budget: HostBudget,
- maxInFlightRequests: number
+ maxInFlightRequests: number,
+ private readonly topHogMetrics?: ImageFetchTopHogMetrics
) {
this.inFlight = new ConcurrencyController(maxInFlightRequests)
}
@@ -48,7 +66,7 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
const registrableDomain = politenessKey(url.hostname)
const nowMs = Date.now()
if (!this.budget.requestScheduled(origin, nowMs)) {
- return { ran: false, reason: 'origin_map_full', waitMs: 0 }
+ return { ran: false, reason: 'origin_map_full', blockingReason: 'origin_map_full', waitMs: 0 }
}
try {
for (;;) {
@@ -57,9 +75,11 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
debugTag: registrableDomain,
fn: async () => {
const checkedAtMs = Date.now()
- ImageFetchRequestMetrics.observeSchedulerWait(
+ this.recordSchedulerWait(
'request_capacity',
- Math.max(0, checkedAtMs - capacityWaitStartedAtMs) / 1000,
+ Math.max(0, checkedAtMs - capacityWaitStartedAtMs),
+ registrableDomain,
+ configurationRequest,
sourcePartitions
)
const grant = this.budget.take(
@@ -73,6 +93,7 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
return {
kind: 'stopped',
reason: grant.reason,
+ blockingReason: blockingReasonForStoppedGrant(grant),
waitMs: grant.waitMs,
} as const
}
@@ -91,7 +112,12 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
grant.reservedStartAtMs,
grant.halfOpenProbe
)
- return { kind: 'stopped', reason: 'connection_limit' as const, waitMs: 0 } as const
+ return {
+ kind: 'stopped',
+ reason: 'connection_limit' as const,
+ blockingReason: 'connection_limit' as const,
+ waitMs: 0,
+ } as const
}
try {
this.budget.markRequestStarted(
@@ -114,15 +140,23 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
return {
ran: false,
reason: scheduled.reason,
+ blockingReason: scheduled.blockingReason,
waitMs: scheduled.waitMs,
}
}
if (Date.now() + scheduled.waitMs > deadlineMs) {
- return { ran: false, reason: 'deadline', waitMs: scheduled.waitMs }
+ return {
+ ran: false,
+ reason: 'deadline',
+ blockingReason: scheduled.waitScope,
+ waitMs: scheduled.waitMs,
+ }
}
- ImageFetchRequestMetrics.observeSchedulerWait(
+ this.recordSchedulerWait(
scheduled.waitScope,
- scheduled.waitMs / 1000,
+ scheduled.waitMs,
+ registrableDomain,
+ configurationRequest,
sourcePartitions
)
await delay(scheduled.waitMs)
@@ -131,4 +165,17 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
this.budget.requestFinished(origin)
}
}
+
+ private recordSchedulerWait(
+ scope: SchedulerWaitScope,
+ waitMs: number,
+ registrableDomain: string,
+ configurationRequest: boolean,
+ sourcePartitions: readonly number[] | undefined
+ ): void {
+ ImageFetchRequestMetrics.observeSchedulerWait(scope, waitMs / 1000, sourcePartitions)
+ if (!configurationRequest) {
+ this.topHogMetrics?.recordSchedulerWait(registrableDomain, sourcePartitions, scope, waitMs)
+ }
+ }
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/tophog-metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/tophog-metrics.ts
new file mode 100644
index 000000000000..ea7a4a44f68e
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/tophog-metrics.ts
@@ -0,0 +1,126 @@
+import type { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
+
+import type { ImageFetchBlockReason } from './block-reason'
+import type { FetchCandidate } from './collected-urls-record'
+import { deduplicateFetchCandidates } from './fetch-candidate-queue'
+import type { FetchAttempt } from './fetch-runner'
+import type { SchedulerWaitScope } from './metrics'
+
+const TOP_DOMAIN_FACTORS = 20
+const MAX_TRACKED_DOMAIN_FACTORS = 2_000
+
+type Recorder = { record(key: Record<string, string>, value: number): void }
+
+export class ImageFetchTopHogMetrics {
+ private readonly attempts: Recorder
+ private readonly blockEvents: Recorder
+ private readonly blockedMs: Recorder
+
+ constructor(topHog: TopHogRegistry) {
+ this.attempts = topHog.registerSum('ml_image_fetch_attempts_by_registrable_domain', {
+ topN: TOP_DOMAIN_FACTORS,
+ maxKeys: MAX_TRACKED_DOMAIN_FACTORS,
+ })
+ this.blockEvents = topHog.registerSum('ml_image_fetch_block_events_by_registrable_domain', {
+ topN: TOP_DOMAIN_FACTORS,
+ maxKeys: MAX_TRACKED_DOMAIN_FACTORS,
+ })
+ this.blockedMs = topHog.registerSum('ml_image_fetch_blocked_ms_by_registrable_domain', {
+ topN: TOP_DOMAIN_FACTORS,
+ maxKeys: MAX_TRACKED_DOMAIN_FACTORS,
+ })
+ }
+
+ public recordAttempt(attempt: FetchAttempt): void {
+ this.recordForSourcePartitions(
+ this.attempts,
+ attempt.candidate.sourcePartitions,
+ {
+ registrable_domain: attempt.candidate.registrableDomain,
+ disposition: attempt.finished ? 'completed' : 'republished',
+ outcome: attempt.outcome,
+ },
+ 1
+ )
+ if (attempt.block) {
+ this.recordBlock(
+ attempt.candidate.registrableDomain,
+ attempt.candidate.sourcePartitions,
+ attempt.block.reason,
+ 1,
+ attempt.block.waitMs
+ )
+ }
+ }
+
+ public recordConcurrencyLimitedUrls(
+ candidates: FetchCandidate[],
+ availableConnections: (registrableDomain: string) => number
+ ): void {
+ const candidatesByRegistrableDomain = new Map<
+ string,
+ { candidateCount: number; sourcePartitions: Set<number> }
+ >()
+ for (const candidate of deduplicateFetchCandidates(candidates).candidates) {
+ const domainCandidates = candidatesByRegistrableDomain.get(candidate.registrableDomain) ?? {
+ candidateCount: 0,
+ sourcePartitions: new Set<number>(),
+ }
+ domainCandidates.candidateCount += 1
+ for (const sourcePartition of candidate.sourcePartitions ?? []) {
+ domainCandidates.sourcePartitions.add(sourcePartition)
+ }
+ candidatesByRegistrableDomain.set(candidate.registrableDomain, domainCandidates)
+ }
+ for (const [registrableDomain, domainCandidates] of candidatesByRegistrableDomain) {
+ const limitedUrls = Math.max(0, domainCandidates.candidateCount - availableConnections(registrableDomain))
+ if (limitedUrls > 0) {
+ this.recordBlock(
+ registrableDomain,
+ [...domainCandidates.sourcePartitions],
+ 'domain_concurrency',
+ limitedUrls,
+ 0
+ )
+ }
+ }
+ }
+
+ public recordSchedulerWait(
+ registrableDomain: string,
+ sourcePartitions: readonly number[] | undefined,
+ scope: SchedulerWaitScope,
+ waitMs: number
+ ): void {
+ if (waitMs <= 0) {
+ return
+ }
+ this.recordBlock(registrableDomain, sourcePartitions, scope, 1, waitMs)
+ }
+
+ private recordBlock(
+ registrableDomain: string,
+ sourcePartitions: readonly number[] | undefined,
+ reason: ImageFetchBlockReason,
+ eventCount: number,
+ waitMs: number
+ ): void {
+ const key = { registrable_domain: registrableDomain, reason }
+ this.recordForSourcePartitions(this.blockEvents, sourcePartitions, key, eventCount)
+ if (waitMs > 0) {
+ this.recordForSourcePartitions(this.blockedMs, sourcePartitions, key, waitMs)
+ }
+ }
+
+ private recordForSourcePartitions(
+ recorder: Recorder,
+ sourcePartitions: readonly number[] | undefined,
+ key: Record<string, string>,
+ value: number
+ ): void {
+ const partitions = sourcePartitions?.length ? new Set(sourcePartitions) : new Set(['unattributed'])
+ for (const partition of partitions) {
+ recorder.record({ ...key, partition: String(partition) }, value)
+ }
+ }
+}
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 8ffdd82a4a64..77172d1e0cc1 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,11 +1,14 @@
import { Message } from 'node-rdkafka'
+import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'
+
import { FetchCandidate, MAX_HOPS, serializeFrontierRecord } from './collected-urls-record'
import { CrawlHistoryItem, CrawlHistoryStore, configurationCacheKey } from './crawl-history'
import { AttemptOutcome, DELAY_TOO_LONG, FetchAttempt, FetchPass, HOPS_EXHAUSTED } from './fetch-runner'
import { FrontierDeadLetterSink } from './frontier-dead-letter-sink'
import { FrontierPublisher, RepublishFlushResult, RepublishResult } from './frontier-publisher'
import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'
+import { ImageFetchTopHogMetrics } from './tophog-metrics'
import { UrlFetchConsumer } from './url-fetch-consumer'
const NOW_MS = 1_700_000_000_000
@@ -93,6 +96,7 @@ interface Harness {
republish: jest.Mock<Promise<RepublishResult>, any[]>
flush: jest.Mock<Promise<RepublishFlushResult>, []>
park: jest.Mock<Promise<void>, any[]>
+ topHogRecords: Map<string, RecordedTopHogMetric[]>
}
function build(dryRun = false, deadLettersEnabled = true): Harness {
@@ -103,14 +107,17 @@ function build(dryRun = false, deadLettersEnabled = true): Harness {
const republish = jest.fn(() => Promise.resolve('queued' as const))
const flush = jest.fn(() => Promise.resolve({ failedUrls: 0 }))
const park = jest.fn(() => Promise.resolve())
+ const recordingTopHog = createRecordingTopHog()
+ const topHogMetrics = new ImageFetchTopHogMetrics(recordingTopHog.registry)
const consumer = new UrlFetchConsumer(
history,
{ createRepublishBatch: () => ({ republish, flush }) } as unknown as FrontierPublisher,
{ seenTtlSeconds: 30 * 24 * 60 * 60, dryRun },
dryRun ? undefined : ({ run } as FetchPass),
- deadLettersEnabled ? ({ park } as FrontierDeadLetterSink) : null
+ deadLettersEnabled ? ({ park } as FrontierDeadLetterSink) : null,
+ topHogMetrics
)
- return { consumer, history, run, republish, flush, park }
+ return { consumer, history, run, republish, flush, park, topHogRecords: recordingTopHog.records }
}
describe('UrlFetchConsumer', () => {
@@ -218,6 +225,26 @@ describe('UrlFetchConsumer', () => {
{ ...fromPartition7, sourcePartitions: [7] },
{ ...fromPartition42, sourcePartitions: [42] },
])
+ expect(harness.topHogRecords.get('ml_image_fetch_attempts_by_registrable_domain')).toEqual([
+ {
+ key: {
+ registrable_domain: 'example.com',
+ disposition: 'completed',
+ outcome: 'ok',
+ partition: '7',
+ },
+ value: 1,
+ },
+ {
+ key: {
+ registrable_domain: 'other.net',
+ disposition: 'completed',
+ outcome: 'ok',
+ partition: '42',
+ },
+ value: 1,
+ },
+ ])
expect(incPartitionAttempt).toHaveBeenCalledWith(7, 'completed', 'ok')
expect(incPartitionAttempt).toHaveBeenCalledWith(42, 'completed', 'ok')
})
@@ -315,13 +342,16 @@ describe('UrlFetchConsumer', () => {
it('republishes a job that arrives before its durable not-before time', async () => {
const harness = build()
- const early = candidate('a', { notBeforeMs: NOW_MS + 30_000 })
+ const early = candidate('a', {
+ notBeforeMs: NOW_MS + 30_000,
+ lastBlockReason: 'configuration_unreachable',
+ })
await harness.consumer.handleBatch([message([early])], NOW_MS)
expect(harness.run.mock.calls[0][0]).toEqual([])
expect(harness.republish).toHaveBeenCalledWith(
- { ...early, sourcePartitions: [0] },
+ { ...early, sourcePartitions: [0], lastBlockReason: 'configuration_unreachable' },
{
currentUrl: early.currentUrl,
host: early.host,
@@ -332,6 +362,37 @@ describe('UrlFetchConsumer', () => {
30_000
)
expect(harness.history.writes).toEqual([])
+ expect(harness.topHogRecords.get('ml_image_fetch_attempts_by_registrable_domain')).toEqual([
+ {
+ key: {
+ registrable_domain: 'example.com',
+ disposition: 'republished',
+ outcome: 'backoff',
+ partition: '0',
+ },
+ value: 1,
+ },
+ ])
+ expect(harness.topHogRecords.get('ml_image_fetch_block_events_by_registrable_domain')).toEqual([
+ {
+ key: {
+ registrable_domain: 'example.com',
+ reason: 'configuration_unreachable',
+ partition: '0',
+ },
+ value: 1,
+ },
+ ])
+ expect(harness.topHogRecords.get('ml_image_fetch_blocked_ms_by_registrable_domain')).toEqual([
+ {
+ key: {
+ registrable_domain: 'example.com',
+ reason: 'configuration_unreachable',
+ partition: '0',
+ },
+ value: 30_000,
+ },
+ ])
})
it('records a terminal refusal when the remaining delay is over one hour', async () => {
@@ -564,19 +625,31 @@ describe('UrlFetchConsumer', () => {
it('throws when the fetch pass reports a lost URL', async () => {
const harness = build()
harness.run.mockImplementation((candidates) =>
- Promise.resolve(
- candidates.map((item) => ({
- candidate: item,
+ Promise.resolve([
+ {
+ candidate: candidates[0],
outcome: 'timeout',
finished: false,
lost: true,
configurationUpdates: [],
- }))
- )
+ },
+ terminal(candidates[1]),
+ ])
)
- await expect(harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)).rejects.toThrow(
+ await expect(harness.consumer.handleBatch([message([candidate('a'), candidate('b')])], NOW_MS)).rejects.toThrow(
'account for 1 URLs'
)
+ expect(harness.topHogRecords.get('ml_image_fetch_attempts_by_registrable_domain')).toEqual([
+ {
+ key: {
+ registrable_domain: 'example.com',
+ disposition: 'completed',
+ outcome: 'ok',
+ partition: '0',
+ },
+ value: 1,
+ },
+ ])
})
})
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 14e95976a070..fa744dece5f2 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
@@ -17,6 +17,7 @@ import {
import { FrontierDeadLetterReason, FrontierDeadLetterSink } from './frontier-dead-letter-sink'
import { FrontierPublisher, RepublishBatch } from './frontier-publisher'
import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'
+import { ImageFetchTopHogMetrics } from './tophog-metrics'
const ONE_HOUR_MS = 60 * 60 * 1000
const REPUBLISH_DEADLINE_FROM_BATCH_START_MS = 200_000
@@ -39,7 +40,8 @@ export class UrlFetchConsumer {
private readonly publisher: FrontierPublisher,
private readonly options: UrlFetchConsumerOptions,
private readonly runner?: FetchPass,
- private readonly deadLetters: FrontierDeadLetterSink | null = null
+ private readonly deadLetters: FrontierDeadLetterSink | null = null,
+ private readonly topHogMetrics?: ImageFetchTopHogMetrics
) {
if (!Number.isInteger(options.seenTtlSeconds) || options.seenTtlSeconds < 60 * 60) {
throw new Error('AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS must be at least 3600')
@@ -184,11 +186,10 @@ export class UrlFetchConsumer {
await this.runCrawlHistoryOperation('write', updates.length, () => this.crawlHistory.write(updates))
}
const republishResult = await republishBatch.flush()
- const lost = attempts.filter((attempt) => attempt.lost).length + republishResult.failedUrls
- if (lost > 0) {
- throw new Error(`the image fetch lane could not account for ${lost} URLs`)
- }
for (const attempt of attempts) {
+ if (attempt.lost || (!attempt.finished && republishResult.failedUrls > 0)) {
+ continue
+ }
for (const sourcePartition of attempt.candidate.sourcePartitions ?? []) {
ImageFetchRequestMetrics.incPartitionAttempt(
sourcePartition,
@@ -196,10 +197,15 @@ export class UrlFetchConsumer {
attempt.outcome
)
}
+ this.topHogMetrics?.recordAttempt(attempt)
if (!attempt.finished && isTransientOutcome(attempt.outcome)) {
ImageFetchRequestMetrics.incRetryCause(attempt.outcome)
}
}
+ const lost = attempts.filter((attempt) => attempt.lost).length + republishResult.failedUrls
+ if (lost > 0) {
+ throw new Error(`the image fetch lane could not account for ${lost} URLs`)
+ }
await this.parkRejectedRecords(rejectedRecords, drops)
} finally {
ImageFetchConsumerMetrics.finishBatch(activeBatchId)
@@ -338,8 +344,10 @@ export class UrlFetchConsumer {
return this.terminalAttempt(candidate, HOPS_EXHAUSTED, nowMs)
}
const waitMs = candidate.notBeforeMs - nowMs
+ const blockingReason = candidate.lastBlockReason ?? 'unknown_backoff'
+ const republishedCandidate: FetchCandidate = { ...candidate, lastBlockReason: blockingReason }
const result = await republishBatch.republish(
- candidate,
+ republishedCandidate,
{
currentUrl: candidate.currentUrl,
host: candidate.host,
@@ -353,10 +361,11 @@ export class UrlFetchConsumer {
return this.terminalAttempt(candidate, DELAY_TOO_LONG, nowMs)
}
return {
- candidate,
+ candidate: republishedCandidate,
outcome: 'backoff',
finished: false,
lost: false,
+ block: { reason: blockingReason, waitMs },
configurationUpdates: [],
}
}
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
index cf41bfd63ae4..4522f97d1146 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
@@ -13,6 +13,7 @@ import { KafkaConsumerV2, KafkaConsumerV2Config, RdKafkaConsumerOverrides } from
import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
import { logger } from '~/common/utils/logger'
+import { TopHog } from '~/ingestion/framework/tophog/tophog'
import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'
import {
ConfigurationPolicyService,
@@ -30,9 +31,11 @@ import {
import { HttpImageFetcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'
import { OriginRequestScheduler } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler'
import { assertUrlPolicyLoaded } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key'
+import { ImageFetchTopHogMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/tophog-metrics'
import { UrlFetchConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer'
import { createWebBotAuthRequestSigner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth'
import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
+import { createOutputsRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/registry'
import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
import { HealthCheckResultOk } from '~/types'
@@ -94,7 +97,8 @@ export function buildFrontierPublisher(
export function buildFetchRunner(
config: IngestionSessionReplayMlMirrorServerConfig,
- publisher: FrontierPublisher
+ publisher: FrontierPublisher,
+ topHogMetrics: ImageFetchTopHogMetrics
): FetchRunner {
const webBotAuthSigner = createWebBotAuthRequestSigner(config.WEB_BOT_AUTH_PRIVATE_KEYS)
const budget = new HostBudget({
@@ -107,7 +111,11 @@ export function buildFetchRunner(
maxTrackedRegistrableDomains: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_REGISTRABLE_DOMAINS,
maxTrackedOrigins: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_ORIGINS,
})
- const scheduler = new OriginRequestScheduler(budget, config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS)
+ const scheduler = new OriginRequestScheduler(
+ budget,
+ config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS,
+ topHogMetrics
+ )
const configurationPolicy = new ConfigurationPolicyService(
new HttpConfigurationFetcher(
webBotAuthSigner,
@@ -138,7 +146,8 @@ export function buildFetchRunner(
maxRedirects: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_REDIRECTS,
seenTtlSeconds: config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS,
},
- publisher
+ publisher,
+ topHogMetrics
)
}
@@ -180,6 +189,7 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
private config: IngestionSessionReplayMlMirrorServerConfig
private crawlHistoryClient?: DynamoDBClient
private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
+ private topHog?: TopHog
constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
this.config = buildMlMirrorServerConfig(config)
@@ -233,6 +243,14 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
// Built even in dry run, so the wiring is exercised by every start rather than only by the
// one that clears the flag.
this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)
+ const outputs = createOutputsRegistry().build(this.producerRegistry, this.config)
+ this.topHog = new TopHog({
+ outputs,
+ pipeline: this.config.INGESTION_PIPELINE ?? 'unknown',
+ lane: this.config.INGESTION_LANE ?? 'unknown',
+ })
+ this.topHog.start()
+ const topHogMetrics = new ImageFetchTopHogMetrics(this.topHog)
const producer = this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER)
const publisher = buildFrontierPublisher(
producer,
@@ -250,8 +268,9 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
seenTtlSeconds: this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS,
dryRun,
},
- buildFetchRunner(this.config, publisher),
- deadLetters
+ buildFetchRunner(this.config, publisher, topHogMetrics),
+ deadLetters,
+ topHogMetrics
)
logger.info('🌐', 'ml_image_fetch_started', { dryRun })
@@ -290,7 +309,11 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
redisPools: [],
additionalCleanup: async () => {
this.crawlHistoryClient?.destroy()
- await this.producerRegistry?.disconnectAll()
+ try {
+ await this.topHog?.stop()
+ } finally {
+ await this.producerRegistry?.disconnectAll()
+ }
},
}
}