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.

fix(session-replay): stop low-diversity image fetch churn (#90738)

Robbie47093432143a
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 f7f0c15bfdfd..b5e9d1cef67a 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
@@ -101,7 +101,7 @@ The lane uses bounded labels for all signals. The dashboards group failures by a
| Kafka republishing consumes a large part of the poll interval. | Total republish flush duration and per-topic delivery time increase. Records and registrable-domain keys per topic show whether the cause is volume, redirect fan-out, or delivery latency. A finalization-deadline counter records batches that stop before all records start. | Fetch dashboard: **Republish messages and registrable domains per batch**, **Republish batch duration**, **Store health and delivery failures**, and **Poll batch duration**. | Check Kafka producer latency and target-domain fan-out. Keep the active batch below Kafka's poll limit. |
| The fetch lane is alive but the input is empty. | Polls increase, consumer members remain present, and batch utilization is zero. | Fetch dashboard: lane liveness and poll batch utilization. | Check the version 2 mirror producer and the input-topic production rate. |
| Poll batches contain few distinct origins or registrable domains, or the pod reaches request capacity. | Distinct counts, top 1, 5, and 10 URL shares, effective counts, immediately schedulable slots, scheduler waits, requests in flight, deadline deferrals, and `not_ready` republishes. | Fetch dashboard: batch diversity, request capacity, scheduler waits, origin policy, registrable-domain state, request outcomes, and republishes. | Increase batch size only when low diversity coincides with low request use, scoped scheduler wait, and sufficient Kafka poll margin. Scale pods for pod saturation. |
-| A dominant origin leaves too little diversity to use pod request capacity. | Low-origin-diversity pass count, origins, canonical URL jobs, and request slots at mode entry, and `ml_image_fetch_republished_total{reason="low_origin_diversity",topic="frontier"}`. | Fetch dashboard: batch diversity, low-origin-diversity deferrals, request capacity, and Kafka lag. | Tune the request-slot and tail thresholds only after comparing them with in-flight use and lag. The fixed progress allowance must remain positive. |
+| One frontier partition accumulates lag. | Per-partition input, fetchable, HTTP request, completion, republish, scheduler-wait, top-share, and effective-count metrics. | Fetch dashboard: partition flow, outcomes, scheduler waits, and concentration. | Separate high input volume from store filtering, HTTP work, politeness waits, and republish churn before changing capacity. |
| A registrable domain repeatedly fails, or an origin refuses access. | Request outcomes, bounded retry causes, registrable-domain block state, origin-policy decisions, and terminal refusal reasons change. | Fetch dashboard: request outcomes, retry causes, policy and budget decisions, and refused URLs. | Check the origin policy and response status. Do not override an opt-out signal. |
| Retry release cannot return work to the frontier. | `ml_image_fetch_retry_released_total{outcome="failed"}` and a durable consumer-loop error log. | Fetch dashboard: delivery failures. Loki alert: `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the frontier producer and Kafka connectivity. |
| Retry input is invalid. | `ml_image_fetch_retry_released_total` increases with a `malformed` or `invalid_timestamp` outcome. Missing content is committed and dropped. An invalid timestamp leaves the offset uncommitted and writes a durable consumer-loop error log. | Fetch dashboard: delivery failures. Alerts: `IngestionSessionReplayImageFetchRetryInputRejected` for missing content and `IngestionSessionReplayImageFetchConsumerLoopFailed` for an invalid timestamp. | Check the retry producer and the delay topic's `LogAppendTime` configuration. |
@@ -134,10 +134,8 @@ The pass-budget alert is inactive in dry-run mode. Delay-topic lag has no alert
- Deprecated topics remain protected and unused. Their cleanup is not required for this rollout.
- Current public documentation already describes the collector-side image limits. No separate documentation repository change is required.
- A cross-registrable-domain configuration redirect fails closed. This rule prevents a source Kafka partition from creating request state for another partition's registrable domain.
-- Low-origin-diversity thresholds count canonical URL jobs, not Kafka records. One Kafka record can contain from 1 to 1,000 jobs, so record count does not measure the remaining request work.
-- The 8-origin, 50-job, and 8-job progress defaults are initial operational values. Bounded metrics expose how often they defer work without adding origin or registrable-domain labels.
- Deduplication uses the global canonical ref. Redirect targets keep separate original refs because their terminal results must complete the replay URLs that created those refs.
-- An older consumer ignores and can remove the optional diversity-deferral marker when it republishes a job during a rolling deployment. This can add one extra deferral during the deployment window, but it does not reject or lose the job.
+- The parser accepts and removes the legacy diversity-deferral marker so that existing topic records drain during a rolling deployment.
## Delta from the original requirements
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 5a10d9ff6803..1087e6a740da 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
@@ -295,9 +295,7 @@ Removing an eligible entry cannot permit an earlier request.
**5.18** The queue selects the registrable domain that is furthest below its concurrency target. It uses the waiting job count and then insertion order as tie-breakers. It applies the same rule to origins within the selected registrable domain. The pod and registrable-domain limits still apply.
-**5.19** The queue calculates remaining request capacity from active and waiting jobs. It applies the configured registrable-domain and pod limits. The defaults are 6 and 300. If fewer than 48 request slots remain, low-origin-diversity mode can start. More than 50 canonical URL jobs must still be eligible for a diversity deferral. The pass processes 8 more jobs for forward progress. It then republishes each eligible job in the waiting tail to the frontier without reducing the hop budget. Low-origin-diversity mode remains active for the rest of that pass.
-
-This rule lets later Kafka records add domain and origin diversity when the current pass cannot use enough pod capacity. A job can receive this zero-wait diversity deferral once. A previously deferred job proceeds normally, subject to the pass deadline. This bound prevents a persistent dominant origin or one long run from creating a fast republish cycle without progress.
+**5.19** The queue continues processing eligible jobs when few origins or registrable domains remain. The scheduler still applies crawl delay, request rate, connection, breaker, registrable-domain, pod, and pass-deadline limits. The lane does not republish a job only to seek more origin diversity in a later Kafka batch.
**5.20** Each worker creates one Kafka group member for each configured target partition. Group assignments do not overlap, so ready group members supply batches from different partitions. The worker joins their batches into one fetch pass. The target must be from one to four and defaults to two. The worker starts the fetch pass when all target batches arrive or the join window ends. If fewer batches arrive, the worker processes the available batches. A later group can run concurrently instead of waiting behind a full pass. Shared request limits still bound total network concurrency. The worker divides the existing Kafka prefetch memory budget across its group members.
@@ -416,7 +414,7 @@ A terminal refusal has no destination Kafka record, so it starts at step 2. A de
}
```
-`v` is the integer `2`. The parser also accepts the two version `1` shapes that preceded this schema, so records already in a topic drain across an upgrade. `jobs` contains 1 to 1,000 entries, and the decoded JSON record cannot exceed 512 KiB. `originalRef` is the ref calculated for the URL first seen in the replay. `currentUrl` is the next URL to request after any redirects. `remainingHops`, `notBeforeMs`, `firstSeenAtMs`, `fetchCount`, and `republishCount` are non-negative safe integers. `firstSeenAtMs` is the Unix time when the producer first collected the URL. `fetchCount` counts image HTTP requests, and `republishCount` counts frontier and delay-topic republishes. `lastRepublishReason` is `null`, `redirect`, `retry`, `not_ready`, `pass_deadline`, `origin_map_full`, or `registrable_domain_map_full`. The optional boolean `lowOriginDiversityDeferred` records that the job has already received its one zero-wait diversity deferral.
+`v` is the integer `2`. The parser also accepts the two version `1` shapes that preceded this schema, so records already in a topic drain across an upgrade. `jobs` contains 1 to 1,000 entries, and the decoded JSON record cannot exceed 512 KiB. `originalRef` is the ref calculated for the URL first seen in the replay. `currentUrl` is the next URL to request after any redirects. `remainingHops`, `notBeforeMs`, `firstSeenAtMs`, `fetchCount`, and `republishCount` are non-negative safe integers. `firstSeenAtMs` is the Unix time when the producer first collected the URL. `fetchCount` counts image HTTP requests, and `republishCount` counts frontier and delay-topic republishes. `lastRepublishReason` is `null`, `redirect`, `retry`, `not_ready`, `pass_deadline`, `origin_map_full`, or `registrable_domain_map_full`. The parser accepts and removes the legacy optional `lowOriginDiversityDeferred` field.
The parser ignores unknown fields so that a producer can add optional data without breaking an older consumer. It rejects a missing field, an invalid field type or value, an unsupported version, or a record whose jobs do not all match the Kafka key. It derives the current origin and registrable domain from `currentUrl` with the shared URL-policy implementation. It uses `originalRef` as the crawl-history key so that a redirect result completes the URL that the recording referenced.
@@ -425,7 +423,7 @@ The parser ignores unknown fields so that a producer can add optional data witho
**10.6** A systematic error like not being able to reach Kafka or DynamoDB should throw. We should not drop messages in
that scenario.
-**10.7** A redirect, pass-deadline deferral, and low-origin-diversity deferral have no required wait. The lane publishes them to the frontier with `notBeforeMs` set to `0`. A retry, an early `notBeforeMs`, or a full runtime-state map uses the smallest delay topic that satisfies its required wait.
+**10.7** A redirect or pass-deadline deferral has no required wait. The lane publishes it to the frontier with `notBeforeMs` set to `0`. A retry, an early `notBeforeMs`, or a full runtime-state map uses the smallest delay topic that satisfies its required wait.
**10.8** Before Kafka delivery, the lane groups republished jobs by destination topic and the current URL's registrable domain. It packs each group into records of no more than 1,000 jobs and no more than 512 KiB. It sends records up to the configured pending-publish limit and waits for every started delivery acknowledgement. After one delivery fails, it starts no more records from that batch. It also stops starting deliveries 200 seconds after the poll batch began. This leaves time for in-flight delivery callbacks, the final crawl-history write, and offset handling before Kafka's 300-second poll limit. A record contains only one registrable domain and uses that registrable domain as its Kafka key.
@@ -455,17 +453,19 @@ A fetch batch can publish more frontier records than it consumed. This can occur
**11.5** The provider domain is the effective top-level domain plus one when only the ICANN section is active. For example, it is `posthog.com` for `app.posthog.com` and `vercel.app` for `myapp.vercel.app`. This document does not use the ambiguous term `root domain`.
-**11.6** Every metric label defined by this lane uses a fixed set of values. HTTP responses use `2xx`, `3xx`, `4xx`, `5xx`, or `other`. Republish destination classes use `frontier` or `delay`. Republish topic classes use `frontier`, `retry_1m`, `retry_10m`, or `retry_1h`. Image scrub sources use `inline` or `url`. Unexpected scrub source formats use `other`. No label defined by this lane contains a configured Kafka topic name, registrable domain, provider domain, origin, host, URL, image ref, team, project, exception message, or other external value.
+**11.6** Every metric label defined by this lane uses a fixed set of values or the bounded integer partition set of the frontier topic. HTTP responses use `2xx`, `3xx`, `4xx`, `5xx`, or `other`. Republish destination classes use `frontier` or `delay`. Republish topic classes use `frontier`, `retry_1m`, `retry_10m`, or `retry_1h`. Image scrub sources use `inline` or `url`. Unexpected scrub source formats use `other`. No label defined by this lane contains a configured Kafka topic name, registrable domain, provider domain, origin, host, URL, image ref, team, project, exception message, or other external value.
**11.7** The lane counts republished URLs by reason and bounded destination class. For each used topic class in a fetch batch, it observes the number of Kafka record delivery attempts, the number of attempted registrable-domain keys, and the wall time from topic-class scheduling until all started delivery attempts settle. It also observes total republish flush wall time and counts batches that reached the republish finalization deadline.
It counts transient retry causes as `timeout`, `error`, `rate_limited`, or `server_error`. It also counts republish failures, crawl-history keys affected by failed operations, and retry records by outcome.
-**11.8** The lane observes completed poll batch duration, active batch age, distinct origins and registrable domains per poll batch, crawl-history operation duration, scheduler waits by `origin_crawl_delay`, `registrable_domain_rate`, or `request_capacity`, and URL age at ingestion. For deduplicated canonical URL jobs, it observes the URL share held by the top 1, 5, and 10 origins and registrable domains. It also observes the inverse Simpson effective count for both scopes. At fetch-pass start, it observes the request slots that the queue can use immediately and their ratio to the pod request limit. It counts passes that enter low-origin-diversity mode and observes the origins, canonical URL jobs, and request slots that remain at entry. The pass-budget saturation ratio is `pass_deadline` republishes divided by completed URLs plus all republishes.
+**11.8** The lane observes completed poll batch duration, active batch age, distinct origins and registrable domains per poll batch, crawl-history operation duration, scheduler waits by `origin_crawl_delay`, `registrable_domain_rate`, or `request_capacity`, and URL age at ingestion. For deduplicated canonical URL jobs, it observes the URL share held by the top 1, 5, and 10 origins and registrable domains. It also observes the inverse Simpson effective count for both scopes. At fetch-pass start, it observes the request slots that the queue can use immediately and their ratio to the pod request limit. The pass-budget saturation ratio is `pass_deadline` republishes divided by completed URLs plus all republishes.
+
+**11.9** Partition metrics count valid Kafka records and URL jobs at the parsed, accepted, unique, fetchable, not-ready, and store-deduplicated stages. They count durable completed and republished outcomes. They also observe image request outcomes, image scheduler waits, the largest origin and registrable-domain share, and the effective count for each source partition. These metrics do not label configuration requests because one configuration request can serve jobs from more than one partition.
-**11.9** Alerts use frontier-topic lag, pass-budget saturation, active batch age, delivery failures, and invalid frontier or retry input. Durable log alerts cover one-shot failures that can stop a pod before Prometheus scrapes its counters. Requirement 16.6 still prohibits alerts on delay-topic lag.
+**11.10** Alerts use frontier-topic lag, pass-budget saturation, active batch age, delivery failures, and invalid frontier or retry input. Durable log alerts cover one-shot failures that can stop a pod before Prometheus scrapes its counters. Requirement 16.6 still prohibits alerts on delay-topic lag.
-**11.10** 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.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.
### 12. Conditional requests
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 6f983e6088c9..0991e17a9516 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
@@ -54,12 +54,19 @@ describe('frontier record', () => {
expect(parsed).toEqual({ ok: true, candidates: [candidate()], urlCount: 1, rejected: [] })
})
- it('round trips the optional low-origin-diversity marker', () => {
- const marked = candidate({ lowOriginDiversityDeferred: true })
+ it('does not persist source partition attribution', () => {
+ const parsed = parseCollectedUrlsRecord(
+ serializeFrontierRecord([candidate({ sourcePartitions: [7] })]),
+ 'example.com'
+ )
+
+ expect(parsed).toEqual({ ok: true, candidates: [candidate()], urlCount: 1, rejected: [] })
+ })
- expect(parseCollectedUrlsRecord(serializeFrontierRecord([marked]), 'example.com')).toEqual({
+ it('accepts and removes the legacy low-origin-diversity marker', () => {
+ expect(parseCollectedUrlsRecord(record({ lowOriginDiversityDeferred: true }), 'example.com')).toEqual({
ok: true,
- candidates: [marked],
+ candidates: [candidate()],
urlCount: 1,
rejected: [],
})
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 c184c70aa402..d147e1652b89 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
@@ -21,7 +21,7 @@ export type StoredRepublishReason =
| 'pass_deadline'
| 'origin_map_full'
| 'registrable_domain_map_full'
-export type RepublishReason = StoredRepublishReason | 'low_origin_diversity'
+export type RepublishReason = StoredRepublishReason
export interface FetchCandidate {
originalRef: string
@@ -35,7 +35,7 @@ export interface FetchCandidate {
fetchCount: number
republishCount: number
lastRepublishReason: StoredRepublishReason | null
- lowOriginDiversityDeferred?: boolean
+ sourcePartitions?: readonly number[]
}
export interface FrontierRecord {
@@ -51,7 +51,6 @@ export interface FrontierRecord {
| 'fetchCount'
| 'republishCount'
| 'lastRepublishReason'
- | 'lowOriginDiversityDeferred'
>
>
}
@@ -241,7 +240,6 @@ function parseJob(
fetchCount,
republishCount,
lastRepublishReason,
- lowOriginDiversityDeferred: lowOriginDiversityDeferred === true ? true : undefined,
},
}
}
@@ -258,7 +256,6 @@ export function serializeFrontierRecord(candidates: FetchCandidate[]): Buffer {
fetchCount: candidate.fetchCount,
republishCount: candidate.republishCount,
lastRepublishReason: candidate.lastRepublishReason,
- lowOriginDiversityDeferred: candidate.lowOriginDiversityDeferred === true ? true : undefined,
})),
}
return Buffer.from(JSON.stringify(record))
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.test.ts
index e62553ccfcc6..e6565e585d38 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.test.ts
@@ -4,9 +4,6 @@ import { FetchCandidateQueue } from './fetch-candidate-queue'
const OPTIONS = {
maxConcurrentPerRegistrableDomain: 6,
maxInFlightRequests: 300,
- lowOriginDiversityMinimumRequestSlots: 48,
- lowOriginDiversityRepublishThreshold: 50,
- lowOriginDiversityProgress: 8,
}
function candidate(index: number): FetchCandidate {
@@ -89,8 +86,6 @@ describe('FetchCandidateQueue', () => {
{
...OPTIONS,
maxConcurrentPerRegistrableDomain: 1,
- lowOriginDiversityMinimumRequestSlots: 1,
- lowOriginDiversityRepublishThreshold: 100_000,
}
)
let drained = 0
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts
index 543cc9f12039..c79e8e10903e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts
@@ -1,17 +1,7 @@
import { FetchCandidate } from './collected-urls-record'
-export type FetchCandidateQueueAction = 'fetch' | 'republish_low_origin_diversity'
-
-export interface LowOriginDiversitySnapshot {
- origins: number
- candidates: number
- requestSlots: number
-}
-
export interface FetchCandidateLease {
candidate: FetchCandidate
- action: FetchCandidateQueueAction
- lowOriginDiversityStarted?: LowOriginDiversitySnapshot
release(): void
}
@@ -142,9 +132,6 @@ class IndexedPriorityQueue<T extends IndexedPriorityQueueItem> {
export interface FetchCandidateQueueOptions {
maxConcurrentPerRegistrableDomain: number
maxInFlightRequests: number
- lowOriginDiversityMinimumRequestSlots: number
- lowOriginDiversityRepublishThreshold: number
- lowOriginDiversityProgress: number
}
export interface DeduplicatedFetchCandidates {
@@ -171,19 +158,13 @@ export class FetchCandidateQueue {
private readonly domains = new Map<string, RegistrableDomainQueue>()
private readonly availableDomains = new IndexedPriorityQueue<RegistrableDomainQueue>(domainQueueHasPriority)
private waitingCandidates = 0
- private waitingCandidatesWithoutDiversityDeferral = 0
- private remainingOrigins = 0
- private lowOriginDiversityStarted = false
- private lowOriginDiversityProgressRemaining: number
private initialSchedulableSlots = 0
- private remainingSchedulableSlots = 0
private aborted = false
constructor(
candidates: FetchCandidate[],
private readonly options: FetchCandidateQueueOptions
) {
- this.lowOriginDiversityProgressRemaining = options.lowOriginDiversityProgress
const deduplicated = deduplicateFetchCandidates(candidates)
let domainSequence = 0
let originSequence = 0
@@ -216,16 +197,12 @@ export class FetchCandidateQueue {
heapIndex: -1,
}
domain.origins.set(candidate.origin, originQueue)
- this.remainingOrigins += 1
}
originQueue.candidates.push(candidate)
originQueue.initialCandidateCount += 1
domain.initialCandidateCount += 1
domain.waitingCandidateCount += 1
this.waitingCandidates += 1
- if (candidate.lowOriginDiversityDeferred !== true) {
- this.waitingCandidatesWithoutDiversityDeferral += 1
- }
}
allocateConcurrentTargets(
[...this.domains.values()],
@@ -247,17 +224,12 @@ export class FetchCandidateQueue {
)
this.refreshDomainSelection(domain)
}
- this.remainingSchedulableSlots = this.initialSchedulableSlots
}
public get candidateCount(): number {
return this.waitingCandidates
}
- public get originCount(): number {
- return this.remainingOrigins
- }
-
public get selectableRegistrableDomainCount(): number {
return this.availableDomains.size
}
@@ -286,63 +258,24 @@ export class FetchCandidateQueue {
if (!selected) {
return undefined
}
- const remainingRequestSlots = Math.min(this.remainingSchedulableSlots, this.options.maxInFlightRequests)
- const lowOriginDiversity =
- this.lowOriginDiversityStarted ||
- (remainingRequestSlots < this.options.lowOriginDiversityMinimumRequestSlots &&
- this.waitingCandidatesWithoutDiversityDeferral > this.options.lowOriginDiversityRepublishThreshold)
- const lowOriginDiversityStarted =
- lowOriginDiversity && !this.lowOriginDiversityStarted
- ? {
- origins: this.remainingOrigins,
- candidates: this.waitingCandidates,
- requestSlots: remainingRequestSlots,
- }
- : undefined
- if (lowOriginDiversityStarted) {
- this.lowOriginDiversityStarted = true
- }
const candidate = selected.origin.candidates[selected.origin.head++]!
selected.domain.waitingCandidateCount -= 1
this.refreshOriginSelection(selected.domain, selected.origin)
this.refreshDomainSelection(selected.domain)
- const candidateCanReceiveDiversityDeferral = candidate.lowOriginDiversityDeferred !== true
- const action: FetchCandidateQueueAction =
- lowOriginDiversity && this.lowOriginDiversityProgressRemaining <= 0 && candidateCanReceiveDiversityDeferral
- ? 'republish_low_origin_diversity'
- : 'fetch'
- if (lowOriginDiversity && action === 'fetch' && this.lowOriginDiversityProgressRemaining > 0) {
- this.lowOriginDiversityProgressRemaining -= 1
- }
this.waitingCandidates -= 1
- if (candidateCanReceiveDiversityDeferral) {
- this.waitingCandidatesWithoutDiversityDeferral -= 1
- }
let released = false
return {
candidate,
- action,
- lowOriginDiversityStarted,
release: () => {
if (released) {
return
}
released = true
- const requestSlotsBeforeRelease = Math.min(
- selected.domain.active + selected.domain.waitingCandidateCount,
- this.options.maxConcurrentPerRegistrableDomain
- )
selected.domain.active = Math.max(0, selected.domain.active - 1)
selected.origin.active = Math.max(0, selected.origin.active - 1)
- const requestSlotsAfterRelease = Math.min(
- selected.domain.active + selected.domain.waitingCandidateCount,
- this.options.maxConcurrentPerRegistrableDomain
- )
- this.remainingSchedulableSlots -= requestSlotsBeforeRelease - requestSlotsAfterRelease
if (originCandidateCount(selected.origin) === 0 && selected.origin.active === 0) {
selected.domain.origins.delete(selected.origin.origin)
- this.remainingOrigins -= 1
} else {
this.refreshOriginSelection(selected.domain, selected.origin)
}
@@ -471,6 +404,9 @@ export function mergeDuplicateFetchCandidates(left: FetchCandidate, right: Fetch
preferredRoute = right
}
const latestState = left.republishCount >= right.republishCount ? left : right
+ const sourcePartitions = [...new Set([...(left.sourcePartitions ?? []), ...(right.sourcePartitions ?? [])])].sort(
+ (leftPartition, rightPartition) => leftPartition - rightPartition
+ )
return {
...preferredRoute,
remainingHops: Math.min(left.remainingHops, right.remainingHops),
@@ -479,7 +415,6 @@ export function mergeDuplicateFetchCandidates(left: FetchCandidate, right: Fetch
fetchCount: Math.max(left.fetchCount, right.fetchCount),
republishCount: Math.max(left.republishCount, right.republishCount),
lastRepublishReason: latestState.lastRepublishReason,
- lowOriginDiversityDeferred:
- left.lowOriginDiversityDeferred === true || right.lowOriginDiversityDeferred === true ? true : undefined,
+ sourcePartitions: sourcePartitions.length > 0 ? sourcePartitions : undefined,
}
}
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 a3506465f04b..3d5a3650e9b1 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
@@ -12,9 +12,6 @@ const NOW_MS = 1_700_000_000_000
const OPTIONS: FetchRunnerOptions = {
maxConcurrentPerRegistrableDomain: 2,
maxInFlightRequests: 50,
- lowOriginDiversityMinimumRequestSlots: 1,
- lowOriginDiversityRepublishThreshold: 50,
- lowOriginDiversityProgress: 8,
batchBudgetMs: 20_000,
maxBytes: 20 * 1024 * 1024,
requestTimeoutMs: 10_000,
@@ -129,11 +126,12 @@ describe('FetchRunner', () => {
],
])
- await harness.runner.run([candidate()], stored)
+ await harness.runner.run([candidate({ sourcePartitions: [7, 42] })], stored)
expect(harness.fetch.mock.calls[0][1]).toMatchObject({
maxBytes: OPTIONS.maxBytes,
maxRedirects: OPTIONS.maxRedirects,
+ sourcePartitions: [7, 42],
cache,
tdmrepReservation: true,
})
@@ -297,13 +295,10 @@ describe('FetchRunner', () => {
])
})
- it('republishes a low-capacity tail across many origins after making bounded progress', async () => {
+ it('processes a low-capacity tail instead of republishing it for more diversity', async () => {
const harness = build({}, {}, 'queued', {
...OPTIONS,
maxInFlightRequests: 1,
- lowOriginDiversityMinimumRequestSlots: 5,
- lowOriginDiversityRepublishThreshold: 2,
- lowOriginDiversityProgress: 1,
})
const candidates = Array.from({ length: 4 }, (_, index) => {
const origin = `https://cdn-${index}.example.com`
@@ -317,42 +312,9 @@ describe('FetchRunner', () => {
const attempts = await harness.runner.run(candidates, new Map())
- expect(harness.fetch).toHaveBeenCalledTimes(1)
- expect(harness.republish).toHaveBeenCalledTimes(3)
- expect(harness.republish).toHaveBeenCalledWith(
- expect.any(Object),
- expect.any(Object),
- 'low_origin_diversity',
- 0
- )
- expect(attempts.filter((attempt) => attempt.outcome === 'low_origin_diversity')).toHaveLength(3)
- })
-
- it('does not apply a second low-origin-diversity deferral to the same jobs', async () => {
- const harness = build({}, {}, 'queued', {
- ...OPTIONS,
- maxInFlightRequests: 1,
- lowOriginDiversityMinimumRequestSlots: 5,
- lowOriginDiversityRepublishThreshold: 2,
- lowOriginDiversityProgress: 1,
- })
- const candidates = Array.from({ length: 4 }, (_, index) =>
- candidate({
- originalRef: `imageurl:${index.toString().padStart(22, '0')}`,
- currentUrl: `https://cdn.example.com/${index}.png`,
- lowOriginDiversityDeferred: true,
- })
- )
-
- await harness.runner.run(candidates, new Map())
-
expect(harness.fetch).toHaveBeenCalledTimes(4)
- expect(harness.republish).not.toHaveBeenCalledWith(
- expect.any(Object),
- expect.any(Object),
- 'low_origin_diversity',
- expect.any(Number)
- )
+ expect(harness.republish).not.toHaveBeenCalled()
+ expect(attempts).toHaveLength(4)
})
it('keeps the pod request limit across overlapping passes', async () => {
@@ -452,12 +414,6 @@ describe('FetchRunner', () => {
expect(harness.fetch).toHaveBeenCalledTimes(1)
})
- it('rejects fractional low-origin-diversity counts', () => {
- expect(() => build({}, {}, 'queued', { ...OPTIONS, lowOriginDiversityProgress: 1.5 })).toThrow(
- 'SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_PROGRESS must be a positive safe integer'
- )
- })
-
it('deduplicates canonical refs before queue scheduling', async () => {
const harness = build()
const duplicate = candidate({ republishCount: 1, lastRepublishReason: 'retry' })
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 c8c0c20c3a63..2a7ddc918605 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
@@ -29,7 +29,6 @@ export type ShedReason =
| 'connection_limit'
| 'origin_map_full'
| 'registrable_domain_map_full'
- | 'low_origin_diversity'
export const HOPS_EXHAUSTED = 'hops_exhausted'
export const DELAY_TOO_LONG = 'delay_too_long'
export type AttemptOutcome =
@@ -52,9 +51,6 @@ export interface FetchAttempt {
export interface FetchRunnerOptions {
maxConcurrentPerRegistrableDomain: number
maxInFlightRequests: number
- lowOriginDiversityMinimumRequestSlots: number
- lowOriginDiversityRepublishThreshold: number
- lowOriginDiversityProgress: number
batchBudgetMs: number
maxBytes: number
requestTimeoutMs: number
@@ -119,18 +115,6 @@ export class FetchRunner implements FetchPass {
'SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS',
options.maxInFlightRequests
)
- requirePositiveSafeInteger(
- 'SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_MINIMUM_REQUEST_SLOTS',
- options.lowOriginDiversityMinimumRequestSlots
- )
- requirePositiveSafeInteger(
- 'SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_REPUBLISH_THRESHOLD',
- options.lowOriginDiversityRepublishThreshold
- )
- requirePositiveSafeInteger(
- 'SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_PROGRESS',
- options.lowOriginDiversityProgress
- )
requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES', options.maxBytes)
requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS', options.requestTimeoutMs)
requirePositive('AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS', options.seenTtlSeconds)
@@ -218,13 +202,6 @@ export class FetchRunner implements FetchPass {
return
}
try {
- if (lease.lowOriginDiversityStarted) {
- ImageFetchRequestMetrics.observeLowOriginDiversity(
- lease.lowOriginDiversityStarted.origins,
- lease.lowOriginDiversityStarted.candidates,
- lease.lowOriginDiversityStarted.requestSlots
- )
- }
attempts.push(
await this.processLease(
lease,
@@ -259,16 +236,6 @@ export class FetchRunner implements FetchPass {
if (candidate.remainingHops === 0) {
return this.terminal(candidate, HOPS_EXHAUSTED, undefined, [])
}
- if (lease.action === 'republish_low_origin_diversity') {
- return await this.republish(
- republishBatch,
- candidate,
- 'low_origin_diversity',
- 'low_origin_diversity',
- 0,
- []
- )
- }
if (Date.now() > deadlineMs) {
return await this.republish(republishBatch, candidate, 'deadline', 'pass_deadline', 0, [])
}
@@ -360,6 +327,7 @@ 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),
@@ -368,7 +336,12 @@ export class FetchRunner implements FetchPass {
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),
+ 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) {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
index 55d7dc909da5..04d8ae8075a2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
@@ -108,20 +108,6 @@ describe('FrontierPublisher', () => {
})
})
- it('records low-diversity republishing without extending the persisted reason enum', async () => {
- const { batch, sent } = build()
- const republished = jest.spyOn(ImageFetchRequestMetrics, 'incRepublished').mockImplementation()
-
- await batch.republish(candidate(), candidate(), 'low_origin_diversity')
- await batch.flush()
-
- expect(republished).toHaveBeenCalledWith('low_origin_diversity', 'frontier')
- expect(parseCollectedUrlsRecord(sent[0].value, 'example.com')).toMatchObject({
- ok: true,
- candidates: [{ republishCount: 1, lastRepublishReason: null, lowOriginDiversityDeferred: true }],
- })
- })
-
it.each([
['an unspecified retry', 0, 'retry_1m', 60_000],
['a short retry', 30_000, 'retry_1m', 60_000],
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 ab652da18a00..941fb8a521a3 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
@@ -169,9 +169,7 @@ class BufferedRepublishBatch implements RepublishBatch {
remainingHops,
notBeforeMs: destination.delayMs > 0 ? Date.now() + destination.delayMs : 0,
republishCount: candidate.republishCount + 1,
- lastRepublishReason: reason === 'low_origin_diversity' ? candidate.lastRepublishReason : reason,
- lowOriginDiversityDeferred:
- reason === 'low_origin_diversity' ? true : candidate.lowOriginDiversityDeferred,
+ lastRepublishReason: reason,
},
reason,
destination,
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 988434a90097..d4c850298206 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
@@ -1,6 +1,7 @@
import { ResolutionError, SecureRequestError, StreamedResponse, fetchStreamed } from '~/common/utils/request'
import { HttpImageFetcher, ImageFetchOptions, RedirectPolicy } from './image-fetcher'
+import { ImageFetchRequestMetrics } from './metrics'
import { WebBotAuthRequestSigner } from './web-bot-auth'
jest.mock('~/common/utils/request', () => ({
@@ -53,6 +54,7 @@ describe('HttpImageFetcher', () => {
beforeEach(() => {
fetchStreamedMock.mockReset()
})
+ afterEach(() => jest.restoreAllMocks())
it('identifies every request as PostHogImageFetcherBot', async () => {
fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png'))
@@ -70,6 +72,15 @@ describe('HttpImageFetcher', () => {
)
})
+ it('attributes image requests to the source partition', async () => {
+ const observeRequest = jest.spyOn(ImageFetchRequestMetrics, 'observeRequest')
+ fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png'))
+
+ await fetcher().fetch('https://cdn.example.com/a.png', { ...OPTIONS, sourcePartitions: [7, 42] })
+
+ expect(observeRequest).toHaveBeenCalledWith('2xx', expect.any(Number), [7, 42])
+ })
+
it('returns the bytes of an image whose payload matches its declared type', async () => {
fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png; charset=binary'))
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 b3aea833d0f3..b696bfcefe85 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
@@ -60,6 +60,7 @@ export interface ImageFetchResult {
}
export interface ImageFetchOptions {
+ sourcePartitions?: readonly number[]
maxBytes: number
/** Covers the redirect chain as a whole, so a chain of slow hops cannot outlive one hop's budget. */
timeoutMs: number
@@ -136,7 +137,8 @@ export class HttpImageFetcher implements ImageFetcher {
Math.max(1, deadlineMs - Date.now()),
options.maxBytes,
currentCache,
- tdmrepReservation
+ tdmrepReservation,
+ options.sourcePartitions
)
)
} catch (error) {
@@ -202,7 +204,8 @@ export class HttpImageFetcher implements ImageFetcher {
timeoutMs: number,
maxBytes: number,
previousCache: HttpCacheMetadata | undefined,
- tdmrepReservation: boolean
+ tdmrepReservation: boolean,
+ sourcePartitions: readonly number[] | undefined
): Promise<HopResult> {
const requestTimeMs = Date.now()
const canonical = canonicalizeUrl(url)
@@ -273,7 +276,11 @@ export class HttpImageFetcher implements ImageFetcher {
return { kind: 'done', result: { outcome: 'ok', status, bytes, contentType, contentEncoding, cache } }
} finally {
if (canonical) {
- ImageFetchRequestMetrics.observeRequest(requestOutcome, (Date.now() - requestTimeMs) / 1000)
+ ImageFetchRequestMetrics.observeRequest(
+ requestOutcome,
+ (Date.now() - requestTimeMs) / 1000,
+ sourcePartitions
+ )
}
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.ts
index 29d3142a6294..00edce3edb79 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.ts
@@ -63,6 +63,86 @@ describe('image fetch metrics', () => {
])
})
+ it('records partition flow, outcomes, waits, and concentration with bounded labels', async () => {
+ ImageFetchConsumerMetrics.observePartitionRecord(7, 10, 9)
+ ImageFetchConsumerMetrics.incPartitionUrls(7, 'unique', 8)
+ ImageFetchConsumerMetrics.observePartitionBatchDiversity(7, [6, 2], [7, 1])
+ ImageFetchRequestMetrics.observeRequest('2xx', 0.25, [7, 42])
+ ImageFetchRequestMetrics.observeSchedulerWait('origin_crawl_delay', 1.5, [7, 42])
+ ImageFetchRequestMetrics.incPartitionAttempt(7, 'completed', 'ok')
+ ImageFetchRequestMetrics.incPartitionAttempt(7, 'republished', 'backoff')
+
+ const metrics = await register.getMetricsAsJSON()
+ const records = metrics.find((metric) => metric.name === 'ml_image_fetch_partition_records_total')
+ const urls = metrics.find((metric) => metric.name === 'ml_image_fetch_partition_urls_total')
+ const requests = metrics.find((metric) => metric.name === 'ml_image_fetch_partition_requests_total')
+ const waits = metrics.find((metric) => metric.name === 'ml_image_fetch_partition_scheduler_wait_seconds')
+ const attempts = metrics.find((metric) => metric.name === 'ml_image_fetch_partition_attempts_total')
+ const topShare = metrics.find((metric) => metric.name === 'ml_image_fetch_partition_top_share')
+ const effectiveCount = metrics.find((metric) => metric.name === 'ml_image_fetch_partition_effective_count')
+
+ expect(records?.values).toContainEqual(expect.objectContaining({ labels: { partition: '7' }, value: 1 }))
+ expect(urls?.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ labels: { partition: '7', stage: 'parsed' }, value: 10 }),
+ expect.objectContaining({ labels: { partition: '7', stage: 'accepted' }, value: 9 }),
+ expect.objectContaining({ labels: { partition: '7', stage: 'unique' }, value: 8 }),
+ ])
+ )
+ expect(requests?.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ labels: { partition: '7', outcome: '2xx' }, value: 1 }),
+ expect.objectContaining({ labels: { partition: '42', outcome: '2xx' }, value: 1 }),
+ ])
+ )
+ expect(waits?.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ labels: { partition: '7', scope: 'origin_crawl_delay' }, value: 1 }),
+ expect.objectContaining({ labels: { partition: '42', scope: 'origin_crawl_delay' }, value: 1 }),
+ ])
+ )
+ expect(attempts?.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ labels: { partition: '7', disposition: 'completed', outcome: 'ok' },
+ value: 1,
+ }),
+ expect.objectContaining({
+ labels: { partition: '7', disposition: 'republished', outcome: 'backoff' },
+ value: 1,
+ }),
+ ])
+ )
+ expect(topShare?.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ metricName: expect.stringMatching(/_sum$/),
+ labels: { partition: '7', scope: 'origin' },
+ value: 0.75,
+ }),
+ expect.objectContaining({
+ metricName: expect.stringMatching(/_sum$/),
+ labels: { partition: '7', scope: 'registrable_domain' },
+ value: 0.875,
+ }),
+ ])
+ )
+ expect(effectiveCount?.values).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ metricName: expect.stringMatching(/_sum$/),
+ labels: { partition: '7', scope: 'origin' },
+ value: 64 / 40,
+ }),
+ expect.objectContaining({
+ metricName: expect.stringMatching(/_sum$/),
+ labels: { partition: '7', scope: 'registrable_domain' },
+ value: 64 / 50,
+ }),
+ ])
+ )
+ })
+
it('records initial schedulable slots against the pod request limit', async () => {
ImageFetchRequestMetrics.observeBatchSchedulableCapacity(7, 10)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts
index b59d6cc9ef88..0688611d8eaf 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts
@@ -24,6 +24,8 @@ export type HttpRequestOutcome = '2xx' | '3xx' | '4xx' | '5xx' | 'other' | 'netw
export type RepublishDestination = 'frontier' | 'delay'
export type RepublishTopic = 'frontier' | 'retry_1m' | 'retry_10m' | 'retry_1h'
type BatchDiversityScope = 'origin' | 'registrable_domain'
+type PartitionUrlStage = 'parsed' | 'accepted' | 'unique' | 'fetchable' | 'not_ready' | 'store_deduped'
+type PartitionAttemptDisposition = 'completed' | 'republished'
type PolicyAndBudgetReason = FetchRefusalReason | RequestScheduleBlockReason | 'none'
const BATCH_DIVERSITY_TOP_COUNTS = [1, 5, 10] as const
@@ -89,6 +91,28 @@ export class ImageFetchConsumerMetrics {
labelNames: ['scope'],
buckets: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16_384, 32_768, 65_536],
})
+ private static readonly partitionRecords = new Counter({
+ name: 'ml_image_fetch_partition_records_total',
+ help: 'Valid Kafka records handled by source partition',
+ labelNames: ['partition'],
+ })
+ private static readonly partitionUrls = new Counter({
+ name: 'ml_image_fetch_partition_urls_total',
+ help: 'URL jobs attributed to a source partition and bounded processing stage. A shared deduplicated job counts once for each contributing partition',
+ labelNames: ['partition', 'stage'],
+ })
+ private static readonly partitionTopShare = new Histogram({
+ name: 'ml_image_fetch_partition_top_share',
+ help: 'Share of deduplicated URL jobs in one source partition held by its largest origin or registrable domain in a joined batch',
+ labelNames: ['partition', 'scope'],
+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 1],
+ })
+ private static readonly partitionEffectiveCount = new Histogram({
+ name: 'ml_image_fetch_partition_effective_count',
+ help: 'Inverse Simpson effective count of origins or registrable domains for one source partition in a joined batch',
+ labelNames: ['partition', 'scope'],
+ buckets: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16_384],
+ })
private static readonly urlsPerRecord = new Histogram({
name: 'ml_image_fetch_consumer_urls_per_record',
help: 'URLs carried by one Kafka record. The producer packs a record to a byte budget, so a distribution pinned at the top means the count bound rather than the byte budget is what split it',
@@ -181,6 +205,23 @@ export class ImageFetchConsumerMetrics {
public static observeRecord(urls: number): void {
this.urlsPerRecord.observe(urls)
}
+ public static observePartitionRecord(partition: number, urls: number, acceptedUrls: number): void {
+ const partitionLabel = String(partition)
+ this.partitionRecords.labels(partitionLabel).inc()
+ this.partitionUrls.labels(partitionLabel, 'parsed').inc(urls)
+ this.partitionUrls.labels(partitionLabel, 'accepted').inc(acceptedUrls)
+ }
+ public static incPartitionUrls(partition: number, stage: PartitionUrlStage, count: number): void {
+ this.partitionUrls.labels(String(partition), stage).inc(count)
+ }
+ public static observePartitionBatchDiversity(
+ partition: number,
+ originCounts: number[],
+ registrableDomainCounts: number[]
+ ): void {
+ this.observePartitionDistribution(partition, 'origin', originCounts)
+ this.observePartitionDistribution(partition, 'registrable_domain', registrableDomainCounts)
+ }
public static observeAge(ageSeconds: number): void {
this.ageSeconds.observe(ageSeconds)
}
@@ -196,6 +237,18 @@ export class ImageFetchConsumerMetrics {
}
this.batchEffectiveCount.labels(scope).observe((summary.total * summary.total) / summary.sumOfSquares)
}
+
+ private static observePartitionDistribution(partition: number, scope: BatchDiversityScope, counts: number[]): void {
+ const summary = summarizeBatchDistribution(counts)
+ if (!summary) {
+ return
+ }
+ const partitionLabel = String(partition)
+ this.partitionTopShare.labels(partitionLabel, scope).observe(summary.largestCounts[0] / summary.total)
+ this.partitionEffectiveCount
+ .labels(partitionLabel, scope)
+ .observe((summary.total * summary.total) / summary.sumOfSquares)
+ }
}
function summarizeBatchDistribution(
@@ -252,25 +305,6 @@ export class ImageFetchRequestMetrics {
help: 'Origin-policy and registrable-domain request-control decisions after block state is known',
labelNames: ['blocked', 'reason'],
})
- private static readonly lowOriginDiversityPasses = new Counter({
- name: 'ml_image_fetch_low_origin_diversity_passes_total',
- help: 'Fetch passes that entered low-diversity mode because too few request slots remained',
- })
- private static readonly lowOriginDiversityOrigins = new Histogram({
- name: 'ml_image_fetch_low_origin_diversity_origins',
- help: 'Origins remaining when a fetch pass entered low-diversity mode',
- buckets: [1, 2, 4, 8, 16, 32, 64],
- })
- private static readonly lowOriginDiversityCandidates = new Histogram({
- name: 'ml_image_fetch_low_origin_diversity_candidates',
- help: 'Canonical URL jobs remaining when a fetch pass entered low-diversity mode',
- buckets: [1, 8, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16_384, 32_768, 65_536],
- })
- private static readonly lowOriginDiversityRequestSlots = new Histogram({
- name: 'ml_image_fetch_low_origin_diversity_request_slots',
- help: 'Request slots remaining when a fetch pass entered low-diversity mode',
- buckets: [1, 2, 4, 8, 16, 32, 48, 64, 128, 256, 300],
- })
private static readonly batchSchedulableSlots = new Histogram({
name: 'ml_image_fetch_batch_schedulable_slots',
help: 'Request slots that the initial fetch queue can use after live pod and registrable-domain concurrency limits',
@@ -295,6 +329,22 @@ export class ImageFetchRequestMetrics {
labelNames: ['outcome'],
buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],
})
+ private static readonly partitionOutcomes = new Counter({
+ name: 'ml_image_fetch_partition_requests_total',
+ help: 'Completed image HTTP requests attributed to each source partition and status class or network failure',
+ labelNames: ['partition', 'outcome'],
+ })
+ private static readonly partitionDuration = new Histogram({
+ name: 'ml_image_fetch_partition_request_duration_seconds',
+ help: 'Time for one completed image HTTP request attributed to each source partition, including its response body',
+ labelNames: ['partition', 'outcome'],
+ buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],
+ })
+ private static readonly partitionAttempts = new Counter({
+ name: 'ml_image_fetch_partition_attempts_total',
+ help: 'URL jobs completed or republished after successful delivery and URL accounting, attributed to each source partition and outcome',
+ labelNames: ['partition', 'disposition', 'outcome'],
+ })
private static readonly retryCauses = new Counter({
name: 'ml_image_fetch_retry_causes_total',
help: 'Transient fetch outcomes that caused the URL to be scheduled for another attempt',
@@ -310,6 +360,12 @@ export class ImageFetchRequestMetrics {
labelNames: ['scope'],
buckets: [0, 0.1, 0.5, 1, 2, 5, 10, 20],
})
+ private static readonly partitionSchedulerWait = new Histogram({
+ name: 'ml_image_fetch_partition_scheduler_wait_seconds',
+ help: 'Time an image request waited, attributed to each source partition and politeness or capacity scope',
+ labelNames: ['partition', 'scope'],
+ buckets: [0, 0.1, 0.5, 1, 2, 5, 10, 20],
+ })
private static readonly responseBytes = new Histogram({
name: 'ml_image_fetch_response_bytes',
help: 'Size of a downloaded image. The tail against the configured byte limit says how much of the catalog the limit refuses',
@@ -374,9 +430,18 @@ export class ImageFetchRequestMetrics {
}
return 'other'
}
- public static observeRequest(outcome: HttpRequestOutcome, durationSeconds: number): void {
+ public static observeRequest(
+ outcome: HttpRequestOutcome,
+ durationSeconds: number,
+ sourcePartitions?: readonly number[]
+ ): void {
this.outcomes.labels(outcome).inc()
this.duration.labels(outcome).observe(durationSeconds)
+ for (const sourcePartition of new Set(sourcePartitions ?? [])) {
+ const partitionLabel = String(sourcePartition)
+ this.partitionOutcomes.labels(partitionLabel, outcome).inc()
+ this.partitionDuration.labels(partitionLabel, outcome).observe(durationSeconds)
+ }
}
public static incRetryCause(cause: TransientFetchOutcome): void {
this.retryCauses.labels(cause).inc()
@@ -399,19 +464,27 @@ export class ImageFetchRequestMetrics {
public static observePolicyAndBudgetDecision(blocked: boolean, reason: PolicyAndBudgetReason = 'none'): void {
this.policyAndBudgetDecisions.labels(blocked ? 'true' : 'false', reason).inc()
}
- public static observeLowOriginDiversity(origins: number, candidates: number, requestSlots: number): void {
- this.lowOriginDiversityPasses.inc()
- this.lowOriginDiversityOrigins.observe(origins)
- this.lowOriginDiversityCandidates.observe(candidates)
- this.lowOriginDiversityRequestSlots.observe(requestSlots)
- }
public static observeBatchSchedulableCapacity(slots: number, podRequestLimit: number): void {
const boundedSlots = Math.min(slots, podRequestLimit)
this.batchSchedulableSlots.observe(boundedSlots)
this.batchSchedulableCapacityRatio.observe(boundedSlots / podRequestLimit)
}
- public static observeSchedulerWait(scope: SchedulerWaitScope, waitSeconds: number): void {
+ public static observeSchedulerWait(
+ scope: SchedulerWaitScope,
+ waitSeconds: number,
+ sourcePartitions?: readonly number[]
+ ): void {
this.schedulerWait.labels(scope).observe(waitSeconds)
+ for (const sourcePartition of new Set(sourcePartitions ?? [])) {
+ this.partitionSchedulerWait.labels(String(sourcePartition), scope).observe(waitSeconds)
+ }
+ }
+ public static incPartitionAttempt(
+ partition: number,
+ disposition: PartitionAttemptDisposition,
+ outcome: AttemptOutcome
+ ): void {
+ this.partitionAttempts.labels(String(partition), disposition, outcome).inc()
}
public static observeBytes(bytes: number): void {
this.responseBytes.observe(bytes)
@@ -454,7 +527,7 @@ export class ImageFetchRequestMetrics {
*/
private static readonly republished = new Counter({
name: 'ml_image_fetch_republished_total',
- help: 'URLs published back to Kafka by bounded reason and destination class. "redirect" left the origin. "retry" hit a transient failure and waits in a delay topic. "not_ready" arrived before its wait ended. "low_origin_diversity" returns queued work to the frontier so a later batch can add origins',
+ help: 'URLs published back to Kafka by bounded reason and destination class. "redirect" left the origin. "retry" hit a transient failure and waits in a delay topic. "not_ready" arrived before its wait ended',
labelNames: ['reason', 'topic'],
})
private static readonly republishFailed = new Counter({
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 7f92e9f0dfa0..0e1c9fa7d983 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
@@ -32,10 +32,15 @@ describe('OriginRequestScheduler', () => {
const deadlineMs = Date.now() + 10_000
const requests = [0, 1, 2].map(() =>
- scheduler.runImage(ORIGIN, deadlineMs, () => {
- startedAtMs.push(Date.now())
- return Promise.resolve()
- })
+ scheduler.runImage(
+ ORIGIN,
+ deadlineMs,
+ () => {
+ startedAtMs.push(Date.now())
+ return Promise.resolve()
+ },
+ [7, 42]
+ )
)
await jest.runAllTimersAsync()
@@ -45,8 +50,8 @@ describe('OriginRequestScheduler', () => {
{ ran: true, value: undefined },
])
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)
- expect(observeSchedulerWait).toHaveBeenCalledWith('request_capacity', 0)
+ expect(observeSchedulerWait).toHaveBeenCalledWith('origin_crawl_delay', 1, [7, 42])
+ expect(observeSchedulerWait).toHaveBeenCalledWith('request_capacity', 0, [7, 42])
})
it('allows six concurrent same-origin requests when the request rate and crawl delay are disabled', async () => {
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 9b0175806477..108d8020685b 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
@@ -21,11 +21,16 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
}
public run<T>(url: URL, deadlineMs: number, request: () => Promise<T>): Promise<ScheduledRequest<T>> {
- return this.runScheduled(url, deadlineMs, true, request)
+ return this.runScheduled(url, deadlineMs, true, undefined, request)
}
- public runImage<T>(url: URL, deadlineMs: number, request: () => Promise<T>): Promise<ScheduledRequest<T>> {
- return this.runScheduled(url, deadlineMs, false, request)
+ public runImage<T>(
+ url: URL,
+ deadlineMs: number,
+ request: () => Promise<T>,
+ sourcePartitions?: readonly number[]
+ ): Promise<ScheduledRequest<T>> {
+ return this.runScheduled(url, deadlineMs, false, sourcePartitions, request)
}
public get running(): number {
@@ -36,6 +41,7 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
url: URL,
deadlineMs: number,
configurationRequest: boolean,
+ sourcePartitions: readonly number[] | undefined,
request: () => Promise<T>
): Promise<ScheduledRequest<T>> {
const origin = url.origin
@@ -53,7 +59,8 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
const checkedAtMs = Date.now()
ImageFetchRequestMetrics.observeSchedulerWait(
'request_capacity',
- Math.max(0, checkedAtMs - capacityWaitStartedAtMs) / 1000
+ Math.max(0, checkedAtMs - capacityWaitStartedAtMs) / 1000,
+ sourcePartitions
)
const grant = this.budget.take(
registrableDomain,
@@ -113,7 +120,11 @@ export class OriginRequestScheduler implements ConfigurationRequestScheduler {
if (Date.now() + scheduled.waitMs > deadlineMs) {
return { ran: false, reason: 'deadline', waitMs: scheduled.waitMs }
}
- ImageFetchRequestMetrics.observeSchedulerWait(scheduled.waitScope, scheduled.waitMs / 1000)
+ ImageFetchRequestMetrics.observeSchedulerWait(
+ scheduled.waitScope,
+ scheduled.waitMs / 1000,
+ sourcePartitions
+ )
await delay(scheduled.waitMs)
}
} finally {
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 47b802bf42fc..8ffdd82a4a64 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
@@ -28,14 +28,14 @@ function candidate(name: string, overrides: Partial<FetchCandidate> = {}): Fetch
}
}
-function message(candidates: FetchCandidate[], key = 'example.com'): Message {
+function message(candidates: FetchCandidate[], key = 'example.com', partition = 0): Message {
const value = serializeFrontierRecord(candidates)
return {
value,
key: Buffer.from(key),
size: value.length,
topic: 'session_replay_image_fetch',
- partition: 0,
+ partition,
offset: 0,
}
}
@@ -155,7 +155,10 @@ describe('UrlFetchConsumer', () => {
configurationCacheKey(candidate('a').origin, 'tdmrep'),
],
])
- expect(harness.run.mock.calls[0][0]).toEqual([candidate('a'), candidate('b')])
+ expect(harness.run.mock.calls[0][0]).toEqual([
+ candidate('a', { sourcePartitions: [0] }),
+ candidate('b', { sourcePartitions: [0] }),
+ ])
expect(harness.history.writes[0]).toHaveLength(2)
})
@@ -184,12 +187,77 @@ describe('UrlFetchConsumer', () => {
expect(observeBatchDiversity).toHaveBeenCalledWith([1, 1, 1], [2, 1])
})
+ it('attributes joined batch work and outcomes to each source partition', async () => {
+ const harness = build()
+ const observePartitionRecord = jest.spyOn(ImageFetchConsumerMetrics, 'observePartitionRecord')
+ const incPartitionUrls = jest.spyOn(ImageFetchConsumerMetrics, 'incPartitionUrls')
+ const observePartitionBatchDiversity = jest.spyOn(ImageFetchConsumerMetrics, 'observePartitionBatchDiversity')
+ const incPartitionAttempt = jest.spyOn(ImageFetchRequestMetrics, 'incPartitionAttempt')
+ const fromPartition7 = candidate('a')
+ const fromPartition42 = candidate('b', {
+ currentUrl: 'https://cdn.other.net/b.png',
+ host: 'cdn.other.net',
+ origin: 'https://cdn.other.net',
+ registrableDomain: 'other.net',
+ })
+
+ await harness.consumer.handleBatch(
+ [message([fromPartition7], 'example.com', 7), message([fromPartition42], 'other.net', 42)],
+ NOW_MS
+ )
+
+ expect(observePartitionRecord).toHaveBeenCalledWith(7, 1, 1)
+ expect(observePartitionRecord).toHaveBeenCalledWith(42, 1, 1)
+ expect(incPartitionUrls).toHaveBeenCalledWith(7, 'unique', 1)
+ expect(incPartitionUrls).toHaveBeenCalledWith(7, 'fetchable', 1)
+ expect(incPartitionUrls).toHaveBeenCalledWith(42, 'unique', 1)
+ expect(incPartitionUrls).toHaveBeenCalledWith(42, 'fetchable', 1)
+ expect(observePartitionBatchDiversity).toHaveBeenCalledWith(7, [1], [1])
+ expect(observePartitionBatchDiversity).toHaveBeenCalledWith(42, [1], [1])
+ expect(harness.run.mock.calls[0][0]).toEqual([
+ { ...fromPartition7, sourcePartitions: [7] },
+ { ...fromPartition42, sourcePartitions: [42] },
+ ])
+ expect(incPartitionAttempt).toHaveBeenCalledWith(7, 'completed', 'ok')
+ expect(incPartitionAttempt).toHaveBeenCalledWith(42, 'completed', 'ok')
+ })
+
+ it('keeps attribution when one ref arrives from different partitions', async () => {
+ const harness = build()
+ const incPartitionUrls = jest.spyOn(ImageFetchConsumerMetrics, 'incPartitionUrls')
+ const observePartitionBatchDiversity = jest.spyOn(ImageFetchConsumerMetrics, 'observePartitionBatchDiversity')
+ const incPartitionAttempt = jest.spyOn(ImageFetchRequestMetrics, 'incPartitionAttempt')
+ const fromPartition7 = candidate('a')
+ const fromPartition42 = candidate('a', {
+ currentUrl: 'https://cdn.other.net/a.png',
+ host: 'cdn.other.net',
+ origin: 'https://cdn.other.net',
+ registrableDomain: 'other.net',
+ remainingHops: 9,
+ republishCount: 1,
+ lastRepublishReason: 'redirect',
+ })
+
+ await harness.consumer.handleBatch(
+ [message([fromPartition7], 'example.com', 7), message([fromPartition42], 'other.net', 42)],
+ NOW_MS
+ )
+
+ expect(harness.run.mock.calls[0][0]).toEqual([{ ...fromPartition42, sourcePartitions: [7, 42] }])
+ for (const partition of [7, 42]) {
+ expect(incPartitionUrls).toHaveBeenCalledWith(partition, 'unique', 1)
+ expect(incPartitionUrls).toHaveBeenCalledWith(partition, 'fetchable', 1)
+ expect(observePartitionBatchDiversity).toHaveBeenCalledWith(partition, [1], [1])
+ expect(incPartitionAttempt).toHaveBeenCalledWith(partition, 'completed', 'ok')
+ }
+ })
+
it('deduplicates one global ref within the batch', async () => {
const harness = build()
await harness.consumer.handleBatch([message([candidate('a')]), message([candidate('a')])], NOW_MS)
- expect(harness.run.mock.calls[0][0]).toEqual([candidate('a')])
+ expect(harness.run.mock.calls[0][0]).toEqual([candidate('a', { sourcePartitions: [0] })])
})
it('keeps the most conservative durable state from duplicate jobs', async () => {
@@ -206,16 +274,7 @@ describe('UrlFetchConsumer', () => {
await harness.consumer.handleBatch([message([stale]), message([advanced])], NOW_MS)
- expect(harness.run.mock.calls[0][0]).toEqual([advanced])
- })
-
- it('keeps a low-origin-diversity marker from either duplicate job', async () => {
- const harness = build()
- const marked = candidate('a', { lowOriginDiversityDeferred: true })
-
- await harness.consumer.handleBatch([message([candidate('a')]), message([marked])], NOW_MS)
-
- expect(harness.run.mock.calls[0][0]).toEqual([marked])
+ expect(harness.run.mock.calls[0][0]).toEqual([{ ...advanced, sourcePartitions: [0] }])
})
it('keeps the latest not-before time from duplicate jobs', async () => {
@@ -251,7 +310,7 @@ describe('UrlFetchConsumer', () => {
await harness.consumer.handleBatch([message([candidate('a'), candidate('b')])], NOW_MS)
- expect(harness.run.mock.calls[0][0]).toEqual([candidate('b')])
+ expect(harness.run.mock.calls[0][0]).toEqual([candidate('b', { sourcePartitions: [0] })])
})
it('republishes a job that arrives before its durable not-before time', async () => {
@@ -262,7 +321,7 @@ describe('UrlFetchConsumer', () => {
expect(harness.run.mock.calls[0][0]).toEqual([])
expect(harness.republish).toHaveBeenCalledWith(
- early,
+ { ...early, sourcePartitions: [0] },
{
currentUrl: early.currentUrl,
host: early.host,
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 cc2da24aeba6..14e95976a070 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
@@ -71,6 +71,11 @@ export class UrlFetchConsumer {
continue
}
ImageFetchConsumerMetrics.observeRecord(parsed.urlCount)
+ ImageFetchConsumerMetrics.observePartitionRecord(
+ message.partition,
+ parsed.urlCount,
+ parsed.candidates.length
+ )
if (parsed.rejected.length > 0) {
rejectedRecords.push({
message,
@@ -78,12 +83,16 @@ export class UrlFetchConsumer {
})
}
for (const candidate of parsed.candidates) {
- const existing = candidatesByRef.get(candidate.originalRef)
+ const partitionCandidate = { ...candidate, sourcePartitions: [message.partition] }
+ const existing = candidatesByRef.get(partitionCandidate.originalRef)
if (existing) {
dedupedInBatch += 1
- candidatesByRef.set(candidate.originalRef, mergeDuplicateFetchCandidates(existing, candidate))
+ candidatesByRef.set(
+ partitionCandidate.originalRef,
+ mergeDuplicateFetchCandidates(existing, partitionCandidate)
+ )
} else {
- candidatesByRef.set(candidate.originalRef, candidate)
+ candidatesByRef.set(partitionCandidate.originalRef, partitionCandidate)
}
}
}
@@ -91,6 +100,8 @@ export class UrlFetchConsumer {
candidatesByRef.clear()
const origins = new Map<string, number>()
const registrableDomains = new Map<string, number>()
+ const partitionOrigins = new Map<number, Map<string, number>>()
+ const partitionRegistrableDomains = new Map<number, Map<string, number>>()
for (const candidate of candidates) {
ImageFetchConsumerMetrics.observeAge(Math.max(0, nowMs - candidate.firstSeenAtMs) / 1000)
origins.set(candidate.origin, (origins.get(candidate.origin) ?? 0) + 1)
@@ -98,11 +109,23 @@ export class UrlFetchConsumer {
candidate.registrableDomain,
(registrableDomains.get(candidate.registrableDomain) ?? 0) + 1
)
+ for (const sourcePartition of candidate.sourcePartitions ?? []) {
+ ImageFetchConsumerMetrics.incPartitionUrls(sourcePartition, 'unique', 1)
+ incrementNestedCount(partitionOrigins, sourcePartition, candidate.origin)
+ incrementNestedCount(partitionRegistrableDomains, sourcePartition, candidate.registrableDomain)
+ }
}
originCount = origins.size
registrableDomainCount = registrableDomains.size
originCandidateCounts = [...origins.values()]
registrableDomainCandidateCounts = [...registrableDomains.values()]
+ for (const [partition, partitionOriginCounts] of partitionOrigins) {
+ ImageFetchConsumerMetrics.observePartitionBatchDiversity(
+ partition,
+ [...partitionOriginCounts.values()],
+ [...(partitionRegistrableDomains.get(partition)?.values() ?? [])]
+ )
+ }
if (this.options.dryRun || candidates.length === 0) {
await this.parkRejectedRecords(rejectedRecords, drops)
@@ -124,12 +147,21 @@ export class UrlFetchConsumer {
const history = stored.get(candidate.originalRef)
if (history?.kind === 'url' && history.nextFetchAtMs > nowMs) {
ImageFetchConsumerMetrics.incDeduped('store', 1)
+ for (const sourcePartition of candidate.sourcePartitions ?? []) {
+ ImageFetchConsumerMetrics.incPartitionUrls(sourcePartition, 'store_deduped', 1)
+ }
continue
}
if (candidate.notBeforeMs > nowMs) {
notReady.push(candidate)
+ for (const sourcePartition of candidate.sourcePartitions ?? []) {
+ ImageFetchConsumerMetrics.incPartitionUrls(sourcePartition, 'not_ready', 1)
+ }
} else {
fetchable.push(candidate)
+ for (const sourcePartition of candidate.sourcePartitions ?? []) {
+ ImageFetchConsumerMetrics.incPartitionUrls(sourcePartition, 'fetchable', 1)
+ }
}
}
ImageFetchConsumerMetrics.incFetchable(fetchable.length)
@@ -157,6 +189,13 @@ export class UrlFetchConsumer {
throw new Error(`the image fetch lane could not account for ${lost} URLs`)
}
for (const attempt of attempts) {
+ for (const sourcePartition of attempt.candidate.sourcePartitions ?? []) {
+ ImageFetchRequestMetrics.incPartitionAttempt(
+ sourcePartition,
+ attempt.finished ? 'completed' : 'republished',
+ attempt.outcome
+ )
+ }
if (!attempt.finished && isTransientOutcome(attempt.outcome)) {
ImageFetchRequestMetrics.incRetryCause(attempt.outcome)
}
@@ -375,3 +414,12 @@ export class UrlFetchConsumer {
)
}
}
+
+function incrementNestedCount(counts: Map<number, Map<string, number>>, partition: number, key: string): void {
+ let partitionCounts = counts.get(partition)
+ if (!partitionCounts) {
+ partitionCounts = new Map<string, number>()
+ counts.set(partition, partitionCounts)
+ }
+ partitionCounts.set(key, (partitionCounts.get(key) ?? 0) + 1)
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 76ccab15744d..deea0a15a22a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -110,12 +110,6 @@ export type MlMirrorConfig = {
* scale with it too. Raise the pod's memory before you raise this.
*/
SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS: number
- /** Low-diversity mode starts when the remaining request capacity is lower than this value. */
- SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_MINIMUM_REQUEST_SLOTS: number
- /** Low-diversity mode starts only when more than this many undeferred canonical URL jobs remain. */
- SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_REPUBLISH_THRESHOLD: number
- /** Canonical URL jobs fetched in low-diversity mode before the remaining undeferred jobs return to Kafka. */
- SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_PROGRESS: number
/** Image bodies waiting for Kafka delivery. This must fit inside the producer byte queue. */
SESSION_RECORDING_ML_IMAGE_FETCH_MAX_PENDING_PUBLISHES: number
/**
@@ -244,9 +238,6 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST: 6,
SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN: 6,
SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS: 300,
- SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_MINIMUM_REQUEST_SLOTS: 48,
- SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_REPUBLISH_THRESHOLD: 50,
- SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_PROGRESS: 8,
SESSION_RECORDING_ML_IMAGE_FETCH_MAX_PENDING_PUBLISHES: 100,
SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS: 40_000,
SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES: 20 * 1024 * 1024,
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 c41fb2e91760..cf41bfd63ae4 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
@@ -132,11 +132,6 @@ export function buildFetchRunner(
maxConcurrentPerRegistrableDomain:
config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN,
maxInFlightRequests: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS,
- lowOriginDiversityMinimumRequestSlots:
- config.SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_MINIMUM_REQUEST_SLOTS,
- lowOriginDiversityRepublishThreshold:
- config.SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_REPUBLISH_THRESHOLD,
- lowOriginDiversityProgress: config.SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_PROGRESS,
batchBudgetMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS,
maxBytes: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES,
requestTimeoutMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS,