: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(session-replay): schedule image fetches by origin (#88331)
Robbie878b7932624b
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.mdindex f03743b5d655..e5038a153d93 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@@ -30,6 +30,10 @@ Each registrable domain has one token bucket, active-request limit, transient-faA registrable domain remains in memory while it is active, blocked, or has a pending request grant. An origin remains in memory while it has an active or scheduled request, a reserved image-request start, or an unelapsed crawl delay. A full map defers untracked work without network access.+The fetch pass deduplicates jobs by global canonical ref. It groups the remaining jobs by registrable domain and origin. Two priority-queue levels select the largest available origin in logarithmic time, with stable ordering for equal counts. Only one job from an origin is active at one time.++When fewer than 8 origins and more than 50 waiting URL jobs have not received a diversity deferral, the pass processes 8 more jobs. It then republishes each eligible tail job to the frontier. The mode stays active for the rest of the pass. A durable optional marker limits this fast deferral to once per job. Previously deferred jobs proceed normally until the pass deadline, which guarantees progress for both a persistent dominant origin and one long run from one origin.+The frontier consumer uses cooperative rebalancing. Its revoke path drains active work before it releases assigned partitions.Retry jobs use 1-minute, 10-minute, and 1-hour Kafka topics. The topics use broker append timestamps.@@ -68,6 +72,8 @@ The ML data-preparation resolver reads URL images by global ref. It removes siblMetrics cover terminal outcomes, requests, origin policy, registrable-domain request state, retries, amplification, system time, and DynamoDB failures. Every metric label defined by this lane uses a fixed category.+Batch-diversity histograms record the top 1, 5, and 10 URL shares and the inverse Simpson effective count for origins and registrable domains. Fetch-pass histograms record immediately schedulable slots and their ratio to the pod request limit. These metrics use only fixed scope and top-count labels.+`ml_image_fetch_republished_total` keeps the `topic` label key for rolling compatibility. The only values emitted by the new code are `frontier` and `delay`.Republish batch metrics use the fixed topic classes `frontier`, `retry_1m`, `retry_10m`, and `retry_1h`. They expose Kafka record count, registrable-domain key count, per-topic delivery time, and total republish flush time. They do not use a configured topic name or a domain as a label.@@ -88,7 +94,8 @@ The lane uses bounded labels for all signals. The dashboards group failures by a| DynamoDB is slow, or a DynamoDB or Kafka request fails. | Crawl-history duration by operation and outcome, a store error, a republish failure, or a failed retry release. A durable consumer-loop error log covers a pod that exits before a metrics scrape. | Fetch dashboard: **Store health and delivery failures**. Loki alert: `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the failed or slow operation. Do not discard or manually commit the affected offsets. || 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 candidate origins and registrable domains per poll batch, scheduler wait time by `origin_crawl_delay`, `registrable_domain_rate`, or `request_capacity`, 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. |+| 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 and canonical URL jobs 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 origin and tail thresholds only after comparing them with in-flight use and lag. The fixed progress allowance must remain positive. || 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. |@@ -119,6 +126,10 @@ 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.## Delta from the original requirements@@ -144,7 +155,7 @@ The implementation also has these rollout and repository-state deltas. They do n## Deployment order-The Node.js image with grouped, bounded republish delivery must be active before the chart raises the poll batch to 15 records and the request budget to 40 seconds. The older per-URL publisher can spend too much of Kafka's poll interval finalizing the larger batch.+The Node.js image with grouped, bounded republish delivery must be active before the chart raises the poll batch to 50 records and the request budget to 40 seconds. The older per-URL publisher can spend too much of Kafka's poll interval finalizing the larger batch.1. Apply the Kafka topic sizes and broker timestamp settings from `posthog-cloud-infra`.2. Apply the DynamoDB table, workload permissions, Smokescreen, and required secrets.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.mdindex 801cc098f8c3..aa88c54869de 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@@ -289,6 +289,16 @@ Removing an eligible entry cannot permit an earlier request.**5.15** If either map is full and has no eligible entry, the pod does not make the request. It sends the job to the 1-minute delay topic. The record names `origin_map_full` or `registrable_domain_map_full` as the reason.+**5.16** Before scheduling a pass, the lane deduplicates jobs by global canonical URL ref. It keeps the most conservative hop, retry, and timing state for each ref.++**5.17** The pass queue groups jobs first by registrable domain and then by origin. At most one job from an origin can be active in this queue. The registrable-domain and pod request limits still apply.++**5.18** When capacity is available, the queue selects the available origin with the most waiting canonical URL jobs. If two origins have the same count, it selects the origin that entered the pass first.++**5.19** If fewer than 8 origins remain and more than 50 canonical URL jobs have not received a diversity deferral, the pass enters low-origin-diversity mode. It 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 origin diversity before one origin consumes most of a pod's 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.+### 6. Smokescreen**6.1** Smokescreen is the authoritative network boundary for outbound requests in production. It must refuse a connection to an IP address that is not globally routable.@@ -404,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`.+`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.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.@@ -413,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 inthat scenario.-**10.7** A redirect and a pass-deadline 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, 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.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.@@ -449,7 +459,7 @@ A fetch batch can publish more frontier records than it consumed. This can occurIt 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. 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. It counts passes that enter low-origin-diversity mode and observes the origins and canonical URL jobs that remain at entry. The pass-budget saturation ratio is `pass_deadline` republishes divided by completed URLs plus all republishes.**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.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.tsindex e812ca02aa84..6f983e6088c9 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,6 +54,24 @@ 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 })++ expect(parseCollectedUrlsRecord(serializeFrontierRecord([marked]), 'example.com')).toEqual({+ ok: true,+ candidates: [marked],+ urlCount: 1,+ rejected: [],+ })+ })++ it('drops a job with a non-boolean low-origin-diversity marker', () => {+ expect(parseCollectedUrlsRecord(record({ lowOriginDiversityDeferred: 'true' }), 'example.com')).toEqual({+ ok: false,+ reason: 'bad_url',+ })+ })+it.each([['missing value', null, 'example.com', 'malformed'],['missing key', record(), null, 'malformed'],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.tsindex 14fc80bd7f99..c184c70aa402 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@@ -14,13 +14,14 @@ export type UrlDropReason =| 'bad_url'| 'foreign_domain'| 'oversized_record'-export type RepublishReason =+export type StoredRepublishReason =| 'redirect'| 'retry'| 'not_ready'| 'pass_deadline'| 'origin_map_full'| 'registrable_domain_map_full'+export type RepublishReason = StoredRepublishReason | 'low_origin_diversity'export interface FetchCandidate {originalRef: string@@ -33,7 +34,8 @@ export interface FetchCandidate {firstSeenAtMs: numberfetchCount: numberrepublishCount: number- lastRepublishReason: RepublishReason | null+ lastRepublishReason: StoredRepublishReason | null+ lowOriginDiversityDeferred?: boolean}export interface FrontierRecord {@@ -49,6 +51,7 @@ export interface FrontierRecord {| 'fetchCount'| 'republishCount'| 'lastRepublishReason'+ | 'lowOriginDiversityDeferred'>>}@@ -71,7 +74,7 @@ function isNonNegativeSafeInteger(value: unknown): value is number {return Number.isSafeInteger(value) && (value as number) >= 0}-function isRepublishReason(value: unknown): value is RepublishReason | null {+function isStoredRepublishReason(value: unknown): value is StoredRepublishReason | null {return (value === null ||value === 'redirect' ||@@ -197,6 +200,7 @@ function parseJob(fetchCount,republishCount,lastRepublishReason,+ lowOriginDiversityDeferred,} = jobif (typeof originalRef !== 'string' ||@@ -207,7 +211,8 @@ function parseJob(!isNonNegativeSafeInteger(firstSeenAtMs) ||!isNonNegativeSafeInteger(fetchCount) ||!isNonNegativeSafeInteger(republishCount) ||- !isRepublishReason(lastRepublishReason)+ !isStoredRepublishReason(lastRepublishReason) ||+ (lowOriginDiversityDeferred !== undefined && typeof lowOriginDiversityDeferred !== 'boolean')) {return { ok: false, reason: 'bad_url' }}@@ -236,6 +241,7 @@ function parseJob(fetchCount,republishCount,lastRepublishReason,+ lowOriginDiversityDeferred: lowOriginDiversityDeferred === true ? true : undefined,},}}@@ -252,6 +258,7 @@ 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.tsnew file mode 100644index 000000000000..cf23332e9c1a--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.test.ts@@ -0,0 +1,85 @@+import { FetchCandidate, MAX_HOPS } from './collected-urls-record'+import { FetchCandidateQueue } from './fetch-candidate-queue'++function candidate(index: number): FetchCandidate {+ return {+ originalRef: `ref-${index}`,+ currentUrl: `https://origin-${index}.example.com/image.png`,+ host: `origin-${index}.example.com`,+ origin: `https://origin-${index}.example.com`,+ registrableDomain: 'example.com',+ remainingHops: MAX_HOPS,+ notBeforeMs: 0,+ firstSeenAtMs: 1_700_000_000_000,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,+ }+}++function dominantOriginCandidate(index: number): FetchCandidate {+ return {+ ...candidate(index),+ currentUrl: `https://dominant.example.com/${index}.png`,+ host: 'dominant.example.com',+ origin: 'https://dominant.example.com',+ }+}++describe('FetchCandidateQueue', () => {+ it('drains a maximum-sized diverse poll batch without scanning every remaining origin', () => {+ const candidateCount = 50_000+ const queue = new FetchCandidateQueue(+ Array.from({ length: candidateCount }, (_, index) => candidate(index)),+ {+ maxConcurrentPerRegistrableDomain: 6,+ minimumActiveOrigins: 8,+ lowOriginDiversityRepublishThreshold: 50,+ lowOriginDiversityProgress: 8,+ }+ )+ let drained = 0++ for (;;) {+ const lease = queue.take()+ if (!lease) {+ break+ }+ drained += 1+ lease.release()+ }++ expect(drained).toBe(candidateCount)+ })++ it('keeps one selectable domain entry during a long dominant-origin run', () => {+ const dominantCandidateCount = 50_000+ const queue = new FetchCandidateQueue(+ [+ ...Array.from({ length: dominantCandidateCount }, (_, index) => dominantOriginCandidate(index)),+ candidate(dominantCandidateCount),+ ],+ {+ maxConcurrentPerRegistrableDomain: 1,+ minimumActiveOrigins: 1,+ lowOriginDiversityRepublishThreshold: 100_000,+ lowOriginDiversityProgress: 8,+ }+ )+ let drained = 0+ let maximumSelectableDomains = 0++ for (;;) {+ const lease = queue.take()+ if (!lease) {+ break+ }+ drained += 1+ lease.release()+ maximumSelectableDomains = Math.max(maximumSelectableDomains, queue.selectableRegistrableDomainCount)+ }++ expect(drained).toBe(dominantCandidateCount + 1)+ expect(maximumSelectableDomains).toBe(1)+ })+})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.tsnew file mode 100644index 000000000000..08ff4e2fed7d--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts@@ -0,0 +1,364 @@+import FastPriorityQueue from 'fastpriorityqueue'++import { FetchCandidate } from './collected-urls-record'++export type FetchCandidateQueueAction = 'fetch' | 'republish_low_origin_diversity'++export interface LowOriginDiversitySnapshot {+ origins: number+ candidates: number+}++export interface FetchCandidateLease {+ candidate: FetchCandidate+ action: FetchCandidateQueueAction+ lowOriginDiversityStarted?: LowOriginDiversitySnapshot+ release(): void+}++interface OriginQueue {+ origin: string+ candidates: FetchCandidate[]+ head: number+ sequence: number+}++interface RegistrableDomainQueue {+ registrableDomain: string+ origins: Map<string, OriginQueue>+ availableOrigins: FastPriorityQueue<OriginQueue>+ active: number+ heapIndex: number+}++class AvailableDomainQueue {+ private readonly heap: RegistrableDomainQueue[] = []++ public get size(): number {+ return this.heap.length+ }++ public addOrUpdate(domain: RegistrableDomainQueue): void {+ if (domain.heapIndex < 0) {+ domain.heapIndex = this.heap.length+ this.heap.push(domain)+ this.siftUp(domain.heapIndex)+ return+ }+ this.rebalance(domain.heapIndex)+ }++ public remove(domain: RegistrableDomainQueue): void {+ const index = domain.heapIndex+ if (index < 0) {+ return+ }+ const last = this.heap.pop()!+ domain.heapIndex = -1+ if (index === this.heap.length) {+ return+ }+ this.heap[index] = last+ last.heapIndex = index+ this.rebalance(index)+ }++ public poll(): RegistrableDomainQueue | undefined {+ const domain = this.heap[0]+ if (domain) {+ this.remove(domain)+ }+ return domain+ }++ private rebalance(index: number): void {+ const parentIndex = Math.floor((index - 1) / 2)+ if (index > 0 && domainQueueHasPriority(this.heap[index], this.heap[parentIndex])) {+ this.siftUp(index)+ } else {+ this.siftDown(index)+ }+ }++ private siftUp(startIndex: number): void {+ let index = startIndex+ while (index > 0) {+ const parentIndex = Math.floor((index - 1) / 2)+ if (!domainQueueHasPriority(this.heap[index], this.heap[parentIndex])) {+ return+ }+ this.swap(index, parentIndex)+ index = parentIndex+ }+ }++ private siftDown(startIndex: number): void {+ let index = startIndex+ for (;;) {+ const leftIndex = index * 2 + 1+ if (leftIndex >= this.heap.length) {+ return+ }+ const rightIndex = leftIndex + 1+ const childIndex =+ rightIndex < this.heap.length && domainQueueHasPriority(this.heap[rightIndex], this.heap[leftIndex])+ ? rightIndex+ : leftIndex+ if (!domainQueueHasPriority(this.heap[childIndex], this.heap[index])) {+ return+ }+ this.swap(index, childIndex)+ index = childIndex+ }+ }++ private swap(leftIndex: number, rightIndex: number): void {+ const left = this.heap[leftIndex]+ const right = this.heap[rightIndex]+ this.heap[leftIndex] = right+ this.heap[rightIndex] = left+ left.heapIndex = rightIndex+ right.heapIndex = leftIndex+ }+}++export interface FetchCandidateQueueOptions {+ maxConcurrentPerRegistrableDomain: number+ minimumActiveOrigins: number+ lowOriginDiversityRepublishThreshold: number+ lowOriginDiversityProgress: number+}++export interface DeduplicatedFetchCandidates {+ candidates: FetchCandidate[]+ duplicateCount: number+}++export function deduplicateFetchCandidates(candidates: FetchCandidate[]): DeduplicatedFetchCandidates {+ const candidatesByCanonicalRef = new Map<string, FetchCandidate>()+ let duplicateCount = 0+ for (const candidate of candidates) {+ const existing = candidatesByCanonicalRef.get(candidate.originalRef)+ if (existing) {+ duplicateCount += 1+ candidatesByCanonicalRef.set(candidate.originalRef, foldDuplicateCandidate(existing, candidate))+ } else {+ candidatesByCanonicalRef.set(candidate.originalRef, candidate)+ }+ }+ return { candidates: [...candidatesByCanonicalRef.values()], duplicateCount }+}++export class FetchCandidateQueue {+ private readonly domains = new Map<string, RegistrableDomainQueue>()+ private readonly availableDomains = new AvailableDomainQueue()+ private waitingCandidates = 0+ private waitingCandidatesWithoutDiversityDeferral = 0+ private remainingOrigins = 0+ private lowOriginDiversityStarted = false+ private lowOriginDiversityProgressRemaining: number+ private initialSchedulableSlots = 0+ private aborted = false++ constructor(+ candidates: FetchCandidate[],+ private readonly options: FetchCandidateQueueOptions+ ) {+ this.lowOriginDiversityProgressRemaining = options.lowOriginDiversityProgress+ const deduplicated = deduplicateFetchCandidates(candidates)+ let sequence = 0+ for (const candidate of deduplicated.candidates) {+ let domain = this.domains.get(candidate.registrableDomain)+ if (!domain) {+ domain = {+ registrableDomain: candidate.registrableDomain,+ origins: new Map(),+ availableOrigins: new FastPriorityQueue<OriginQueue>(originQueueHasPriority),+ active: 0,+ heapIndex: -1,+ }+ this.domains.set(candidate.registrableDomain, domain)+ }+ let originQueue = domain.origins.get(candidate.origin)+ if (!originQueue) {+ originQueue = {+ origin: candidate.origin,+ candidates: [],+ head: 0,+ sequence: sequence++,+ }+ domain.origins.set(candidate.origin, originQueue)+ this.remainingOrigins += 1+ }+ originQueue.candidates.push(candidate)+ this.waitingCandidates += 1+ if (candidate.lowOriginDiversityDeferred !== true) {+ this.waitingCandidatesWithoutDiversityDeferral += 1+ }+ }+ for (const domain of this.domains.values()) {+ this.initialSchedulableSlots += Math.min(+ domain.origins.size,+ this.options.maxConcurrentPerRegistrableDomain+ )+ for (const origin of domain.origins.values()) {+ domain.availableOrigins.add(origin)+ }+ this.refreshDomainSelection(domain)+ }+ }++ public get candidateCount(): number {+ return this.waitingCandidates+ }++ public get originCount(): number {+ return this.remainingOrigins+ }++ public get selectableRegistrableDomainCount(): number {+ return this.availableDomains.size+ }++ public get schedulableSlotsAtStart(): number {+ return this.initialSchedulableSlots+ }++ public abort(): void {+ this.aborted = true+ }++ public take(): FetchCandidateLease | undefined {+ if (this.aborted) {+ return undefined+ }+ const selected = this.takeLargestAvailableOrigin()+ if (!selected) {+ return undefined+ }+ const lowOriginDiversity =+ this.lowOriginDiversityStarted ||+ (this.remainingOrigins < this.options.minimumActiveOrigins &&+ this.waitingCandidatesWithoutDiversityDeferral > this.options.lowOriginDiversityRepublishThreshold)+ const lowOriginDiversityStarted =+ lowOriginDiversity && !this.lowOriginDiversityStarted+ ? { origins: this.remainingOrigins, candidates: this.waitingCandidates }+ : undefined+ if (lowOriginDiversityStarted) {+ this.lowOriginDiversityStarted = true+ }+ const candidate = selected.origin.candidates[selected.origin.head++]!+ 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+ selected.domain.active = Math.max(0, selected.domain.active - 1)+ if (originCandidateCount(selected.origin) === 0) {+ selected.domain.origins.delete(selected.origin.origin)+ this.remainingOrigins -= 1+ } else {+ selected.domain.availableOrigins.add(selected.origin)+ }+ if (selected.domain.origins.size === 0) {+ this.availableDomains.remove(selected.domain)+ this.domains.delete(selected.domain.registrableDomain)+ } else {+ this.refreshDomainSelection(selected.domain)+ }+ },+ }+ }++ private takeLargestAvailableOrigin(): { domain: RegistrableDomainQueue; origin: OriginQueue } | undefined {+ for (;;) {+ const domain = this.availableDomains.poll()+ if (!domain) {+ return undefined+ }+ if (domain.active >= this.options.maxConcurrentPerRegistrableDomain) {+ continue+ }+ const origin = domain.availableOrigins.poll()+ if (!origin) {+ continue+ }+ domain.active += 1+ this.refreshDomainSelection(domain)+ return { domain, origin }+ }+ }++ private refreshDomainSelection(domain: RegistrableDomainQueue): void {+ const origin = domain.availableOrigins.peek()+ if (!origin || domain.active >= this.options.maxConcurrentPerRegistrableDomain) {+ this.availableDomains.remove(domain)+ return+ }+ this.availableDomains.addOrUpdate(domain)+ }+}++function originQueueHasPriority(left: OriginQueue, right: OriginQueue): boolean {+ return (+ originCandidateCount(left) > originCandidateCount(right) ||+ (originCandidateCount(left) === originCandidateCount(right) && left.sequence < right.sequence)+ )+}++function originCandidateCount(origin: OriginQueue): number {+ return origin.candidates.length - origin.head+}++function domainQueueHasPriority(left: RegistrableDomainQueue, right: RegistrableDomainQueue): boolean {+ const leftOrigin = left.availableOrigins.peek()!+ const rightOrigin = right.availableOrigins.peek()!+ return (+ originCandidateCount(leftOrigin) > originCandidateCount(rightOrigin) ||+ (originCandidateCount(leftOrigin) === originCandidateCount(rightOrigin) &&+ leftOrigin.sequence < rightOrigin.sequence)+ )+}++function foldDuplicateCandidate(left: FetchCandidate, right: FetchCandidate): FetchCandidate {+ let preferredRoute = left+ if (+ right.remainingHops < left.remainingHops ||+ (right.remainingHops === left.remainingHops && right.republishCount > left.republishCount) ||+ (right.remainingHops === left.remainingHops &&+ right.republishCount === left.republishCount &&+ right.fetchCount > left.fetchCount)+ ) {+ preferredRoute = right+ }+ const latestState = left.republishCount >= right.republishCount ? left : right+ return {+ ...preferredRoute,+ remainingHops: Math.min(left.remainingHops, right.remainingHops),+ notBeforeMs: Math.max(left.notBeforeMs, right.notBeforeMs),+ firstSeenAtMs: Math.min(left.firstSeenAtMs, right.firstSeenAtMs),+ 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,+ }+}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.tsindex c94829da5260..5fe0a8d9e855 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@@ -5,12 +5,16 @@ import { DELAY_TOO_LONG, FetchRunner, FetchRunnerOptions, HOPS_EXHAUSTED } fromimport { FrontierPublisher, RepublishResult } from './frontier-publisher'import { HostBudget } from './host-budget'import { ImageFetchOptions, ImageFetchResult, ImageFetcher } from './image-fetcher'+import { ImageFetchRequestMetrics } from './metrics'import { OriginRequestScheduler } from './origin-request-scheduler'const NOW_MS = 1_700_000_000_000const OPTIONS: FetchRunnerOptions = {maxConcurrentPerRegistrableDomain: 2,maxInFlightRequests: 50,+ minimumActiveOrigins: 1,+ lowOriginDiversityRepublishThreshold: 50,+ lowOriginDiversityProgress: 8,batchBudgetMs: 20_000,maxBytes: 20 * 1024 * 1024,requestTimeoutMs: 10_000,@@ -215,6 +219,236 @@ describe('FetchRunner', () => {expect(harness.fetch).toHaveBeenCalledTimes(3)})+ it('records initial capacity after origin and registrable-domain limits', async () => {+ const observeCapacity = jest+ .spyOn(ImageFetchRequestMetrics, 'observeBatchSchedulableCapacity')+ .mockImplementation()+ const harness = build({}, {}, 'queued', {+ ...OPTIONS,+ maxConcurrentPerRegistrableDomain: 2,+ maxInFlightRequests: 3,+ })+ const candidates = [+ candidate(),+ ...Array.from({ length: 2 }, (_, index) =>+ candidate({+ originalRef: `imageurl:${String(index + 1).repeat(22)}`,+ currentUrl: `https://sibling-${index}.example.com/image.png`,+ host: `sibling-${index}.example.com`,+ origin: `https://sibling-${index}.example.com`,+ })+ ),+ ...Array.from({ length: 2 }, (_, index) =>+ candidate({+ originalRef: `imageurl:${String(index + 3).repeat(22)}`,+ currentUrl: `https://origin-${index}.other.net/image.png`,+ host: `origin-${index}.other.net`,+ origin: `https://origin-${index}.other.net`,+ registrableDomain: 'other.net',+ })+ ),+ ]++ await harness.runner.run(candidates, new Map())++ expect(observeCapacity).toHaveBeenCalledWith(4, 3)+ })++ it('starts the origin with the largest canonical URL queue first', async () => {+ const harness = build({}, {}, 'queued', {+ ...OPTIONS,+ maxConcurrentPerRegistrableDomain: 1,+ maxInFlightRequests: 1,+ })+ const small = candidate({+ currentUrl: 'https://small.example.com/a.png',+ host: 'small.example.com',+ origin: 'https://small.example.com',+ })+ const largeFirst = candidate({+ originalRef: `imageurl:${'b'.repeat(22)}`,+ currentUrl: 'https://large.example.com/a.png',+ host: 'large.example.com',+ origin: 'https://large.example.com',+ })+ const largeSecond = candidate({+ originalRef: `imageurl:${'c'.repeat(22)}`,+ currentUrl: 'https://large.example.com/b.png',+ host: 'large.example.com',+ origin: 'https://large.example.com',+ })++ await harness.runner.run([small, largeFirst, largeSecond], new Map())++ expect(harness.fetch.mock.calls.map(([url]) => url)).toEqual([+ largeFirst.currentUrl,+ small.currentUrl,+ largeSecond.currentUrl,+ ])+ })++ it('republishes a low-origin-diversity tail after making bounded progress', async () => {+ const harness = build({}, {}, 'queued', {+ ...OPTIONS,+ maxInFlightRequests: 1,+ minimumActiveOrigins: 2,+ 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`,+ })+ )++ 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,+ minimumActiveOrigins: 2,+ 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)+ )+ })++ it('keeps the pod request limit across overlapping passes', async () => {+ const harness = build({}, {}, 'queued', { ...OPTIONS, maxInFlightRequests: 1 })+ const releases: Array<() => void> = []+ let signalSecondFetchStarted: () => void = () => undefined+ const secondFetchStarted = new Promise<void>((resolve) => {+ signalSecondFetchStarted = resolve+ })+ harness.fetch.mockImplementation(+ (url: string) =>+ new Promise<ImageFetchResult>((resolve) => {+ releases.push(() => resolve({ outcome: 'ok', redirects: 0, currentUrl: url }))+ if (releases.length === 2) {+ signalSecondFetchStarted()+ }+ })+ )+ const otherDomain = candidate({+ originalRef: `imageurl:${'b'.repeat(22)}`,+ currentUrl: 'https://cdn.other.net/b.png',+ host: 'cdn.other.net',+ origin: 'https://cdn.other.net',+ registrableDomain: 'other.net',+ })++ const firstRun = harness.runner.run([candidate()], new Map())+ const secondRun = harness.runner.run([otherDomain], new Map())+ await Promise.resolve()+ await Promise.resolve()++ expect(harness.fetch).toHaveBeenCalledTimes(1)+ releases[0]()+ await secondFetchStarted+ expect(harness.fetch).toHaveBeenCalledTimes(2)+ releases[1]()+ await Promise.all([firstRun, secondRun])+ })++ it('does not start a queued request after another worker aborts its pass', async () => {+ const harness = build({}, {}, 'queued', { ...OPTIONS, maxInFlightRequests: 2 })+ let releaseBlocker: () => void = () => undefined+ let signalBlockerStarted: () => void = () => undefined+ const blockerStarted = new Promise<void>((resolve) => {+ signalBlockerStarted = resolve+ })+ harness.fetch.mockImplementation((url: string) => {+ if (url.includes('blocker')) {+ signalBlockerStarted()+ return new Promise<ImageFetchResult>((resolve) => {+ releaseBlocker = () => resolve({ outcome: 'ok', redirects: 0, currentUrl: url })+ })+ }+ if (url.includes('failure')) {+ return Promise.reject(new Error('dependency unavailable'))+ }+ return Promise.resolve({ outcome: 'ok', redirects: 0, currentUrl: url })+ })+ const blocker = candidate({ currentUrl: 'https://blocker.example.com/a.png' })+ const failure = candidate({+ originalRef: `imageurl:${'b'.repeat(22)}`,+ currentUrl: 'https://failure.example.com/b.png',+ host: 'failure.example.com',+ origin: 'https://failure.example.com',+ })+ const mustNotStart = candidate({+ originalRef: `imageurl:${'c'.repeat(22)}`,+ currentUrl: 'https://queued.example.com/c.png',+ host: 'queued.example.com',+ origin: 'https://queued.example.com',+ })++ const blockingRun = harness.runner.run([blocker], new Map())+ await blockerStarted+ const failingRun = harness.runner.run([failure, mustNotStart], new Map())++ await expect(failingRun).rejects.toThrow('dependency unavailable')+ expect(harness.fetch.mock.calls.map(([url]) => url)).toEqual([blocker.currentUrl, failure.currentUrl])+ releaseBlocker()+ await blockingRun+ })++ it('stops taking queue work after a fatal candidate error', async () => {+ const harness = build({}, {}, 'queued', { ...OPTIONS, maxInFlightRequests: 1 })+ harness.fetch.mockRejectedValueOnce(new Error('dependency unavailable'))+ const second = candidate({ originalRef: `imageurl:${'b'.repeat(22)}` })++ await expect(harness.runner.run([candidate(), second], new Map())).rejects.toThrow('dependency unavailable')++ 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' })++ const attempts = await harness.runner.run([candidate(), duplicate], new Map())++ expect(harness.fetch).toHaveBeenCalledTimes(1)+ expect(attempts).toHaveLength(1)+ expect(attempts[0].candidate).toMatchObject({ republishCount: 1, lastRepublishReason: 'retry' })+ })+it('marks an image publish failure as lost after all candidate work settles', async () => {const harness = build({ bytes: Buffer.from('image'), contentType: 'image/png' })harness.publishImage.mockRejectedValue(new Error('queue full'))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.tsindex 0017d318fabf..cafadb714d45 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@@ -8,6 +8,7 @@ import {explicitFreshnessLifetimeMs,} from './configuration-policy'import { ConfigurationCacheItem, CrawlHistoryItem, HttpCacheMetadata, UrlCrawlHistoryItem } from './crawl-history'+import { FetchCandidateLease, FetchCandidateQueue } from './fetch-candidate-queue'import { FrontierPublisher, RepublishBatch, RepublishResult } from './frontier-publisher'import { HostBudget } from './host-budget'import {@@ -28,6 +29,7 @@ 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 =@@ -50,6 +52,9 @@ export interface FetchAttempt {export interface FetchRunnerOptions {maxConcurrentPerRegistrableDomain: numbermaxInFlightRequests: number+ minimumActiveOrigins: number+ lowOriginDiversityRepublishThreshold: number+ lowOriginDiversityProgress: numberbatchBudgetMs: numbermaxBytes: numberrequestTimeoutMs: number@@ -67,6 +72,12 @@ function requirePositive(name: string, value: number): void {}}+function requirePositiveSafeInteger(name: string, value: number): void {+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new Error(`${name} must be a positive safe integer, got ${value}`)+ }+}+export function isTransientOutcome(outcome: AttemptOutcome): outcome is TransientFetchOutcome {return TRANSIENT_OUTCOMES.has(outcome as TransientFetchOutcome)}@@ -85,6 +96,10 @@ export interface FetchPass {): Promise<FetchAttempt[]>}+interface FetchPassState {+ failure?: { error: unknown }+}+export class FetchRunner implements FetchPass {private readonly candidateWork: ConcurrencyController@@ -96,11 +111,26 @@ export class FetchRunner implements FetchPass {private readonly options: FetchRunnerOptions,private readonly publisher: FrontierPublisher) {- requirePositive(+ requirePositiveSafeInteger('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN',options.maxConcurrentPerRegistrableDomain)- requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS', options.maxInFlightRequests)+ requirePositiveSafeInteger(+ 'SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS',+ options.maxInFlightRequests+ )+ requirePositiveSafeInteger(+ 'SESSION_RECORDING_ML_IMAGE_FETCH_MINIMUM_ACTIVE_ORIGINS',+ options.minimumActiveOrigins+ )+ 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)@@ -119,40 +149,40 @@ export class FetchRunner implements FetchPass {const activeRepublishBatch = republishBatch ?? this.publisher.createRepublishBatch()const deadlineMs = Date.now() + this.options.batchBudgetMsconst configurationPolicy = this.configurationPolicy.createPass()+ const passState: FetchPassState = {}const configurationItems = new Map<string, ConfigurationCacheItem>()for (const [key, item] of stored) {if (item.kind === 'robots' || item.kind === 'tdmrep') {configurationItems.set(key, item)}}- const byRegistrableDomain = new Map<string, FetchCandidate[]>()- for (const candidate of candidates) {- const queue = byRegistrableDomain.get(candidate.registrableDomain)- if (queue) {- queue.push(candidate)- } else {- byRegistrableDomain.set(candidate.registrableDomain, [candidate])- }- }+ const queue = new FetchCandidateQueue(candidates, this.options)+ ImageFetchRequestMetrics.observeBatchSchedulableCapacity(+ queue.schedulableSlotsAtStart,+ this.options.maxInFlightRequests+ )const attempts: FetchAttempt[] = []- const registrableDomainRuns = [...byRegistrableDomain].map(([registrableDomain, queue]) =>- this.runRegistrableDomainQueue(- registrableDomain,+ const workers = Array.from({ length: Math.min(this.options.maxInFlightRequests, queue.originCount) }, () =>+ this.runQueueWorker(queue,stored,configurationItems,configurationPolicy,deadlineMs,attempts,- activeRepublishBatch+ activeRepublishBatch,+ passState))- const settledRegistrableDomains = await Promise.allSettled(registrableDomainRuns)- const failedRegistrableDomain = settledRegistrableDomains.find(+ const settledWorkers = await Promise.allSettled(workers)+ if (passState.failure) {+ throw passState.failure.error+ }+ const failedWorker = settledWorkers.find((settled): settled is PromiseRejectedResult => settled.status === 'rejected')- if (failedRegistrableDomain) {- throw failedRegistrableDomain.reason+ if (failedWorker) {+ throw failedWorker.reason}if (!republishBatch) {const result = await activeRepublishBatch.flush()@@ -164,74 +194,99 @@ export class FetchRunner implements FetchPass {return attempts}- private async runRegistrableDomainQueue(- registrableDomain: string,- queue: FetchCandidate[],+ private async runQueueWorker(+ queue: FetchCandidateQueue,stored: Map<string, CrawlHistoryItem>,configurationItems: Map<string, ConfigurationCacheItem>,configurationPolicy: ConfigurationPolicyPass,deadlineMs: number,attempts: FetchAttempt[],- republishBatch: RepublishBatch+ republishBatch: RepublishBatch,+ passState: FetchPassState): Promise<void> {- const byOrigin = new Map<string, FetchCandidate[]>()- for (const candidate of queue) {- const originQueue = byOrigin.get(candidate.origin)- if (originQueue) {- originQueue.push(candidate)- } else {- byOrigin.set(candidate.origin, [candidate])+ for (;;) {+ const lease = queue.take()+ if (!lease) {+ return}- }- const registrableDomainWork = new ConcurrencyController(this.options.maxConcurrentPerRegistrableDomain)- const runOriginQueue = async (originQueue: FetchCandidate[]): Promise<void> => {- for (const candidate of originQueue) {- if (candidate.remainingHops === 0) {- attempts.push(this.terminal(candidate, HOPS_EXHAUSTED, undefined, []))- continue- }- if (Date.now() > deadlineMs) {- attempts.push(await this.republish(republishBatch, candidate, 'deadline', 'pass_deadline', 0, []))- continue+ try {+ if (lease.lowOriginDiversityStarted) {+ ImageFetchRequestMetrics.observeLowOriginDiversity(+ lease.lowOriginDiversityStarted.origins,+ lease.lowOriginDiversityStarted.candidates+ )}attempts.push(- await registrableDomainWork.run({- debugTag: candidate.origin,- fn: () =>- this.candidateWork.run({- debugTag: registrableDomain,- fn: () => {- if (Date.now() > deadlineMs) {- return this.republish(- republishBatch,- candidate,- 'deadline',- 'pass_deadline',- 0,- []- )- }- return this.fetchOne(- candidate,- stored,- configurationItems,- configurationPolicy,- deadlineMs,- republishBatch- )- },- }),- })+ await this.processLease(+ lease,+ stored,+ configurationItems,+ configurationPolicy,+ deadlineMs,+ republishBatch,+ passState+ ))+ } catch (error) {+ passState.failure ??= { error }+ queue.abort()+ throw error+ } finally {+ lease.release()}}- const settledWorkers = await Promise.allSettled([...byOrigin.values()].map(runOriginQueue))- const failedWorker = settledWorkers.find(- (settled): settled is PromiseRejectedResult => settled.status === 'rejected'- )- if (failedWorker) {- throw failedWorker.reason+ }++ private async processLease(+ lease: FetchCandidateLease,+ stored: Map<string, CrawlHistoryItem>,+ configurationItems: Map<string, ConfigurationCacheItem>,+ configurationPolicy: ConfigurationPolicyPass,+ deadlineMs: number,+ republishBatch: RepublishBatch,+ passState: FetchPassState+ ): Promise<FetchAttempt> {+ const candidate = lease.candidate+ 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, [])}+ return await this.candidateWork.run({+ debugTag: candidate.registrableDomain,+ fn: async () => {+ if (passState.failure) {+ throw passState.failure.error+ }+ try {+ if (Date.now() > deadlineMs) {+ return await this.republish(republishBatch, candidate, 'deadline', 'pass_deadline', 0, [])+ }+ return await this.fetchOne(+ candidate,+ stored,+ configurationItems,+ configurationPolicy,+ deadlineMs,+ republishBatch+ )+ } catch (error) {+ passState.failure ??= { error }+ throw error+ }+ },+ })}private async fetchOne(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.tsindex 158fd56bb3a7..c51aa2db7650 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,6 +108,20 @@ 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.tsindex 9a20d6a85b31..fbdb072ea17b 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@@ -165,7 +165,9 @@ class BufferedRepublishBatch implements RepublishBatch {remainingHops,notBeforeMs: destination.delayMs > 0 ? Date.now() + destination.delayMs : 0,republishCount: candidate.republishCount + 1,- lastRepublishReason: reason,+ lastRepublishReason: reason === 'low_origin_diversity' ? candidate.lastRepublishReason : reason,+ lowOriginDiversityDeferred:+ reason === 'low_origin_diversity' ? true : candidate.lowOriginDiversityDeferred,},reason,destination,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.tsindex 3d94d3b74189..93f625f58c03 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@@ -1,8 +1,8 @@import { register } from 'prom-client'-import { ImageFetchRequestMetrics } from './metrics'+import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'-describe('ImageFetchRequestMetrics', () => {+describe('image fetch metrics', () => {beforeEach(() => register.resetMetrics())test.each([@@ -34,4 +34,46 @@ describe('ImageFetchRequestMetrics', () => {expect(causes).toEqual(['rate_limited', 'server_error', 'timeout', 'error'])})++ it('records bounded concentration and effective-count distributions', async () => {+ ImageFetchConsumerMetrics.observeBatchDiversity([6, 3, 1], [9, 1])++ const metrics = await register.getMetricsAsJSON()+ const topShare = metrics.find((metric) => metric.name === 'ml_image_fetch_batch_top_share')+ const effectiveCount = metrics.find((metric) => metric.name === 'ml_image_fetch_batch_effective_count')+ const topShareSums = topShare?.values.filter(+ (value) => 'metricName' in value && String(value.metricName).endsWith('_sum')+ )+ const effectiveCountSums = effectiveCount?.values.filter(+ (value) => 'metricName' in value && String(value.metricName).endsWith('_sum')+ )++ expect(topShareSums).toEqual([+ expect.objectContaining({ labels: { scope: 'origin', top_n: '1' }, value: 0.6 }),+ expect.objectContaining({ labels: { scope: 'origin', top_n: '5' }, value: 1 }),+ expect.objectContaining({ labels: { scope: 'origin', top_n: '10' }, value: 1 }),+ expect.objectContaining({ labels: { scope: 'registrable_domain', top_n: '1' }, value: 0.9 }),+ expect.objectContaining({ labels: { scope: 'registrable_domain', top_n: '5' }, value: 1 }),+ expect.objectContaining({ labels: { scope: 'registrable_domain', top_n: '10' }, value: 1 }),+ ])+ expect(effectiveCountSums).toEqual([+ expect.objectContaining({ labels: { scope: 'origin' }, value: 100 / 46 }),+ expect.objectContaining({ labels: { scope: 'registrable_domain' }, value: 100 / 82 }),+ ])+ })++ it('records initial schedulable slots against the pod request limit', async () => {+ ImageFetchRequestMetrics.observeBatchSchedulableCapacity(7, 10)++ const metrics = await register.getMetricsAsJSON()+ const slots = metrics.find((metric) => metric.name === 'ml_image_fetch_batch_schedulable_slots')+ const ratio = metrics.find((metric) => metric.name === 'ml_image_fetch_batch_schedulable_capacity_ratio')++ expect(slots?.values).toContainEqual(+ expect.objectContaining({ metricName: expect.stringMatching(/_sum$/), value: 7 })+ )+ expect(ratio?.values).toContainEqual(+ expect.objectContaining({ metricName: expect.stringMatching(/_sum$/), value: 0.7 })+ )+ })})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.tsindex 664f2de7e542..e7c741ca2825 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@@ -22,8 +22,11 @@ export type SchedulerWaitScope = 'origin_crawl_delay' | 'registrable_domain_rateexport type HttpRequestOutcome = '2xx' | '3xx' | '4xx' | '5xx' | 'other' | 'network_error'export type RepublishDestination = 'frontier' | 'delay'export type RepublishTopic = 'frontier' | 'retry_1m' | 'retry_10m' | 'retry_1h'+type BatchDiversityScope = 'origin' | 'registrable_domain'type PolicyAndBudgetReason = FetchRefusalReason | RequestScheduleBlockReason | 'none'+const BATCH_DIVERSITY_TOP_COUNTS = [1, 5, 10] as const+export class ImageFetchConsumerMetrics {private static readonly fetchable = new Counter({name: 'ml_image_fetch_consumer_fetchable_total',@@ -63,6 +66,18 @@ export class ImageFetchConsumerMetrics {help: 'Distinct registrable domains in one poll batch',buckets: [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16_384],})+ private static readonly batchTopShare = new Histogram({+ name: 'ml_image_fetch_batch_top_share',+ help: 'Share of deduplicated canonical URL jobs held by the largest fixed number of origins or registrable domains in one poll batch',+ labelNames: ['scope', 'top_n'],+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 1],+ })+ private static readonly batchEffectiveCount = new Histogram({+ name: 'ml_image_fetch_batch_effective_count',+ help: 'Inverse Simpson effective count of origins or registrable domains among deduplicated canonical URL jobs in one poll batch',+ 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 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',@@ -131,6 +146,10 @@ export class ImageFetchConsumerMetrics {this.registrableDomainsPerBatch.observe(registrableDomains)this.batchDuration.observe(durationSeconds)}+ public static observeBatchDiversity(originCounts: number[], registrableDomainCounts: number[]): void {+ this.observeBatchDistribution('origin', originCounts)+ this.observeBatchDistribution('registrable_domain', registrableDomainCounts)+ }public static startBatch(nowMs = performance.now()): void {this.activeBatchStartedAtMs = nowMs}@@ -143,6 +162,40 @@ export class ImageFetchConsumerMetrics {public static observeAge(ageSeconds: number): void {this.ageSeconds.observe(ageSeconds)}++ private static observeBatchDistribution(scope: BatchDiversityScope, counts: number[]): void {+ const summary = summarizeBatchDistribution(counts)+ if (!summary) {+ return+ }+ for (const topCount of BATCH_DIVERSITY_TOP_COUNTS) {+ const topTotal = summary.largestCounts.slice(0, topCount).reduce((total, count) => total + count, 0)+ this.batchTopShare.labels(scope, String(topCount)).observe(topTotal / summary.total)+ }+ this.batchEffectiveCount.labels(scope).observe((summary.total * summary.total) / summary.sumOfSquares)+ }+}++function summarizeBatchDistribution(+ counts: number[]+): { total: number; sumOfSquares: number; largestCounts: number[] } | undefined {+ let total = 0+ let sumOfSquares = 0+ const largestCounts: number[] = []+ for (const count of counts) {+ total += count+ sumOfSquares += count * count+ const insertionIndex = largestCounts.findIndex((existing) => count > existing)+ if (insertionIndex >= 0) {+ largestCounts.splice(insertionIndex, 0, count)+ } else if (largestCounts.length < BATCH_DIVERSITY_TOP_COUNTS.at(-1)!) {+ largestCounts.push(count)+ }+ if (largestCounts.length > BATCH_DIVERSITY_TOP_COUNTS.at(-1)!) {+ largestCounts.pop()+ }+ }+ return total > 0 ? { total, sumOfSquares, largestCounts } : undefined}/**@@ -177,6 +230,30 @@ 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 republished queued work because too few origins remained to use request capacity',+ })+ private static readonly lowOriginDiversityOrigins = new Histogram({+ name: 'ml_image_fetch_low_origin_diversity_origins',+ help: 'Origins remaining when a fetch pass started low-diversity republishing',+ 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 started low-diversity republishing',+ buckets: [1, 8, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16_384, 32_768, 65_536],+ })+ private static readonly batchSchedulableSlots = new Histogram({+ name: 'ml_image_fetch_batch_schedulable_slots',+ help: 'Request slots that the initial fetch queue can use immediately after origin and registrable-domain concurrency limits',+ buckets: [1, 2, 4, 8, 16, 32, 64, 128, 256, 300, 512, 1024],+ })+ private static readonly batchSchedulableCapacityRatio = new Histogram({+ name: 'ml_image_fetch_batch_schedulable_capacity_ratio',+ help: 'Share of the pod request limit that the initial fetch queue can use immediately',+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 1],+ })/*** `ok` against the sum is the yield of the lane.*/@@ -295,6 +372,16 @@ 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): void {+ this.lowOriginDiversityPasses.inc()+ this.lowOriginDiversityOrigins.observe(origins)+ this.lowOriginDiversityCandidates.observe(candidates)+ }+ 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 {this.schedulerWait.labels(scope).observe(waitSeconds)}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.tsindex 7ebfcdeb80aa..3ada72f36b25 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@@ -158,6 +158,7 @@ describe('UrlFetchConsumer', () => {it('records distinct origins and registrable domains for the poll batch', async () => {const harness = build()const observeBatch = jest.spyOn(ImageFetchConsumerMetrics, 'observeBatch')+ const observeBatchDiversity = jest.spyOn(ImageFetchConsumerMetrics, 'observeBatchDiversity')const otherExampleOrigin = candidate('b', {currentUrl: 'https://img.example.com/b.png',host: 'img.example.com',@@ -176,6 +177,7 @@ describe('UrlFetchConsumer', () => {)expect(observeBatch).toHaveBeenCalledWith(3, 2, expect.any(Number))+ expect(observeBatchDiversity).toHaveBeenCalledWith([1, 1, 1], [2, 1])})it('deduplicates one global ref within the batch', async () => {@@ -203,6 +205,15 @@ describe('UrlFetchConsumer', () => {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])+ })+it('keeps the latest not-before time from duplicate jobs', async () => {const harness = build()const stale = candidate('a')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.tsindex fb70bb28ddf8..face47729031 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@@ -4,6 +4,7 @@ import { logger } from '~/common/utils/logger'import { FetchCandidate, MAX_HOPS, UrlDropReason, parseCollectedUrlsRecord } from './collected-urls-record'import { CrawlHistoryItem, CrawlHistoryStore, UrlCrawlHistoryItem, configurationCacheKey } from './crawl-history'+import { deduplicateFetchCandidates } from './fetch-candidate-queue'import {AttemptOutcome,DELAY_TOO_LONG,@@ -43,10 +44,12 @@ export class UrlFetchConsumer {const startedAt = process.hrtime.bigint()const republishDeadlineAtMonotonicMs = performance.now() + REPUBLISH_DEADLINE_FROM_BATCH_START_MSconst drops = new Map<UrlDropReason, number>()- const candidatesByRef = new Map<string, FetchCandidate>()+ const parsedCandidates: FetchCandidate[] = []let dedupedInBatch = 0let originCount = 0let registrableDomainCount = 0+ let originCandidateCounts: number[] = []+ let registrableDomainCandidateCounts: number[] = []ImageFetchConsumerMetrics.startBatch()try {@@ -60,26 +63,25 @@ export class UrlFetchConsumer {for (const rejected of parsed.rejected) {drops.set(rejected.reason, (drops.get(rejected.reason) ?? 0) + 1)}- for (const candidate of parsed.candidates) {- const existing = candidatesByRef.get(candidate.originalRef)- if (existing) {- dedupedInBatch += 1- candidatesByRef.set(candidate.originalRef, foldDuplicateCandidate(existing, candidate))- continue- }- ImageFetchConsumerMetrics.observeAge(Math.max(0, nowMs - candidate.firstSeenAtMs) / 1000)- candidatesByRef.set(candidate.originalRef, candidate)- }+ parsedCandidates.push(...parsed.candidates)}- const candidates = [...candidatesByRef.values()]- const origins = new Set<string>()- const registrableDomains = new Set<string>()+ const deduplicated = deduplicateFetchCandidates(parsedCandidates)+ const candidates = deduplicated.candidates+ dedupedInBatch = deduplicated.duplicateCount+ const origins = new Map<string, number>()+ const registrableDomains = new Map<string, number>()for (const candidate of candidates) {- origins.add(candidate.origin)- registrableDomains.add(candidate.registrableDomain)+ ImageFetchConsumerMetrics.observeAge(Math.max(0, nowMs - candidate.firstSeenAtMs) / 1000)+ origins.set(candidate.origin, (origins.get(candidate.origin) ?? 0) + 1)+ registrableDomains.set(+ candidate.registrableDomain,+ (registrableDomains.get(candidate.registrableDomain) ?? 0) + 1+ )}originCount = origins.sizeregistrableDomainCount = registrableDomains.size+ originCandidateCounts = [...origins.values()]+ registrableDomainCandidateCounts = [...registrableDomains.values()]if (this.options.dryRun || candidates.length === 0) {return@@ -87,7 +89,7 @@ export class UrlFetchConsumer {const keys = [...candidates.map((candidate) => candidate.originalRef),- ...[...origins].flatMap((origin) => [+ ...[...origins.keys()].flatMap((origin) => [configurationCacheKey(origin, 'robots'),configurationCacheKey(origin, 'tdmrep'),]),@@ -139,7 +141,15 @@ export class UrlFetchConsumer {}} finally {ImageFetchConsumerMetrics.finishBatch()- this.recordMetrics(drops, dedupedInBatch, originCount, registrableDomainCount, startedAt)+ this.recordMetrics(+ drops,+ dedupedInBatch,+ originCount,+ registrableDomainCount,+ originCandidateCounts,+ registrableDomainCandidateCounts,+ startedAt+ )}}@@ -243,6 +253,8 @@ export class UrlFetchConsumer {dedupedInBatch: number,origins: number,registrableDomains: number,+ originCandidateCounts: number[],+ registrableDomainCandidateCounts: number[],startedAt: bigint): void {if (dedupedInBatch > 0) {@@ -251,6 +263,7 @@ export class UrlFetchConsumer {for (const [reason, count] of drops) {ImageFetchConsumerMetrics.incDropped(reason, count)}+ ImageFetchConsumerMetrics.observeBatchDiversity(originCandidateCounts, registrableDomainCandidateCounts)ImageFetchConsumerMetrics.observeBatch(origins,registrableDomains,@@ -258,26 +271,3 @@ export class UrlFetchConsumer {)}}--function foldDuplicateCandidate(left: FetchCandidate, right: FetchCandidate): FetchCandidate {- let preferredRoute = left- if (- right.remainingHops < left.remainingHops ||- (right.remainingHops === left.remainingHops && right.republishCount > left.republishCount) ||- (right.remainingHops === left.remainingHops &&- right.republishCount === left.republishCount &&- right.fetchCount > left.fetchCount)- ) {- preferredRoute = right- }- const latestState = left.republishCount >= right.republishCount ? left : right- return {- ...preferredRoute,- remainingHops: Math.min(left.remainingHops, right.remainingHops),- notBeforeMs: Math.max(left.notBeforeMs, right.notBeforeMs),- firstSeenAtMs: Math.min(left.firstSeenAtMs, right.firstSeenAtMs),- fetchCount: Math.max(left.fetchCount, right.fetchCount),- republishCount: Math.max(left.republishCount, right.republishCount),- lastRepublishReason: latestState.lastRepublishReason,- }-}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 644257188706..f0c49b1ccf75 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -100,6 +100,11 @@ 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+ /** A larger queued tail returns to Kafka when fewer origins remain available. */+ SESSION_RECORDING_ML_IMAGE_FETCH_MINIMUM_ACTIVE_ORIGINS: number+ SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_REPUBLISH_THRESHOLD: number+ /** URL jobs the largest origin can advance before the low-diversity tail returns 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/**@@ -224,6 +229,9 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST: 5,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_MINIMUM_ACTIVE_ORIGINS: 8,+ 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.tsindex 9edf15624a63..d02b2fe48895 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@@ -117,6 +117,10 @@ 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,+ minimumActiveOrigins: config.SESSION_RECORDING_ML_IMAGE_FETCH_MINIMUM_ACTIVE_ORIGINS,+ 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,