Skip to content

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

feat(session-replay): allow six requests per origin (#88401)

Robbief11431686b41
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 c650e54f0c98..c8c53f2c12f9 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
@@ -12,7 +12,7 @@ The mirror emits versioned frontier jobs. Each job carries the original ref, cur
The mirror can read crawl history after its local URL cache and before Kafka. It suppresses URLs whose next fetch time is still in the future. A timeout or store error publishes every candidate. The fetch consumer repeats the read because a completion can race with the mirror.
-Kafka uses the registrable domain as the frontier key. Rate, burst, active-request, transient back-off, and circuit-breaker state use that registrable domain. Policy caches and crawl delay use the full origin.
+Kafka uses the registrable domain as the frontier key. Token-bucket rate and burst settings use that key when enabled. Active-request, transient back-off, and circuit-breaker state also use that key. Policy caches and crawl delay use the full origin.
### Policy and network boundary
@@ -28,13 +28,13 @@ Web Bot Auth uses the shared PostHog key directory. The directory response has a
### Scheduling and retries
-Each registrable domain has one token bucket, active-request limit, transient-failure count, and circuit breaker. Each origin has its own crawl delay and configuration-request state. Each runtime map contains at most 20,000 entries.
+Each registrable domain has an optional token bucket, an active-request limit, a transient-failure count, and a circuit breaker. Each origin has its own crawl delay and configuration-request state. Each runtime map contains at most 20,000 entries. The default disables the token bucket. The default allows 6 active requests. An explicit robots.txt crawl delay still spaces requests to its origin.
A 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.
+The fetch pass deduplicates jobs by global canonical ref. It groups the remaining jobs by registrable domain and origin. Two indexed priority queues select work in logarithmic time. Each queue gets a capped proportional concurrency target. The scheduler selects the queue that is furthest below its target. It uses the waiting job count and insertion order as tie-breakers.
-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 queue tracks the remaining request slots from active and waiting jobs. It applies the configured registrable-domain and pod limits. When fewer than 48 slots remain, low-diversity mode can start. More than 50 waiting URL jobs must still be eligible for 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.
The frontier consumer uses cooperative rebalancing. Its revoke path drains active work before it releases assigned partitions.
@@ -97,7 +97,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 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 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. |
| 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. |
@@ -142,7 +142,7 @@ The implementation has four product-behavior or interface deltas from the origin
| ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Accept any number of supported content-coding layers. | Accept at most four layers. | This bound limits decompression work. A response with more than four layers is refused. Requirements 14.1 and 17.6 now state this bound. |
| Export top-N registrable and provider domains and exact HTTP response values. | Export no registrable-domain or provider-domain labels and group HTTP status by class. | The metrics system does not support high-cardinality labels. Fixed categories keep the number of time series bounded. Per-registrable-domain request share is not available in metrics. Requirements 11.2 and 11.6 now state this rule. |
-| Apply one crawl delay across a registrable domain. | Apply each crawl delay only to the origin that published it. | robots.txt answers for one origin. Sibling origins still share rate, burst, active-request, transient back-off, and circuit-breaker controls. Requirements 5.11, 5.12, 7.10, and 7.11 state the split. |
+| Apply one crawl delay across a registrable domain. | Apply each crawl delay only to the origin that published it. | robots.txt answers for one origin. Sibling origins still share any enabled rate and burst, plus active-request, transient back-off, and circuit-breaker controls. Requirements 5.11, 5.12, 7.10, and 7.11 state the split. |
| Follow a configuration redirect to any authority without Kafka republishing. | Follow it only inside the source registrable domain. | Cross-registrable-domain redirects could create a second pod-local budget outside the target Kafka owner. The lane treats the source configuration as unreachable and does not request the target. Requirements 3.5 and 5.4 state this bound. |
The implementation also has these rollout and repository-state deltas. They do not change steady-state fetch behavior.
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 aa88c54869de..2293835b0a53 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
@@ -227,7 +227,7 @@ key at `https://us.posthog.com/.well-known/http-message-signatures-directory`, a
**5.2** Requests in flight to one registrable domain never exceed the registrable-domain limit during steady-state ownership. A bounded exception applies during the Kafka rebalance window described below.
-**5.3** Requests to one registrable domain never exceed the rate its token bucket allows during steady-state ownership. The same bounded rebalance exception applies.
+**5.3** A positive configured request rate enables a token bucket for each registrable domain. The default zero value disables this rate limit and uses only the active-request limit. The same bounded rebalance exception applies when the token bucket is enabled.
**5.4** A redirect is not a way around any limit. Each image request counts against the registrable-domain budget of its target and the crawl delay of its target origin. The lane follows a configuration redirect only when its target has the same registrable domain. Each followed configuration request counts against that shared registrable-domain budget.
@@ -235,7 +235,7 @@ key at `https://us.posthog.com/.well-known/http-message-signatures-directory`, a
**5.6** There is no global handling of concurrent request limits. The Kafka topic is partitioned by registrable domain, using both the ICANN and private sections of the Public Suffix List. All origins under one registrable domain therefore go to one partition. One pod normally holds the shared registrable-domain request budget and the separate policy and crawl-delay state for each origin.
-**5.7** On partition revocation, the consumer stops starting work for the revoked partitions and drains their active batch before it unassigns them. If the drain exceeds Kafka's rebalance timeout, Kafka can assign the partition to a new pod while the old pod finishes its active requests. During this exceptional window, one old owner and one new owner can each apply the registrable-domain limit and token bucket. The pod limit still applies independently to each pod. The lane does not use a distributed lease to close this window.
+**5.7** On partition revocation, the consumer stops starting work for the revoked partitions and drains their active batch before it unassigns them. If the drain exceeds Kafka's rebalance timeout, Kafka can assign the partition to a new pod while the old pod finishes its active requests. During this exceptional window, one old owner and one new owner can each apply the registrable-domain limit and an enabled token bucket. The pod limit still applies independently to each pod. The lane does not use a distributed lease to close this window.
**5.8** In-flight concurrency limits apply to all external URL fetches (e.g. `robots.txt` files), not just images. It does not apply to internal services like DynamoDB or Kafka.
@@ -247,7 +247,7 @@ key at `https://us.posthog.com/.well-known/http-message-signatures-directory`, a
| ------------------------------------------ | ------------------------------------------------- | ---------- |
| Requests in flight | pod | 300 |
| Requests in flight per registrable domain | registrable domain | 6 |
-| Requests per second per registrable domain | registrable domain | 1, burst 5 |
+| Requests per second per registrable domain | registrable domain | disabled |
| Hop budget | one original URL, across every message it becomes | 10 |
| Redirects followed without republishing | one fetch | 3 |
| Response bytes, compressed | one response | 20 MiB |
@@ -262,14 +262,14 @@ key at `https://us.posthog.com/.well-known/http-message-signatures-directory`, a
| State | Key | Location |
| ------------------------------------------------------------------------ | -------------------- | ------------------------------------------------------------ |
-| Active requests, token bucket, back-off, and circuit breaker | Registrable domain | Memory on the pod that owns the Kafka partition |
+| Active requests, optional token bucket, back-off, and circuit breaker | Registrable domain | Memory on the pod that owns the Kafka partition |
| Crawl delay and scheduled request count | Origin | Memory on the pod that owns the registrable-domain partition |
| Configuration request coalescing lock | Origin and file type | Memory on the pod that owns the registrable-domain partition |
| robots.txt and tdmrep.json results | Origin and file type | DynamoDB, with an optional hot cache in pod memory |
| URL crawl history and HTTP cache metadata | Global canonical URL | DynamoDB |
| Original ref, current URL, remaining image hops, and earliest retry time | One URL job | Kafka record |
-**5.12** Request rate, burst, active-request count, transient back-off, `Retry-After`, and circuit-breaker state use the registrable domain as their key. Configuration policy and `Crawl-delay` use the origin as their key. No request-control state uses the provider domain as its key.
+**5.12** A configured request rate, burst, active-request count, transient back-off, `Retry-After`, and circuit-breaker state use the registrable domain as their key. Configuration policy and `Crawl-delay` use the origin as their key. No request-control state uses the provider domain as its key.
**5.13** The pod limits both its registrable-domain runtime map and its origin runtime map to 20,000 entries because both key sets are unbounded.
@@ -277,7 +277,7 @@ key at `https://us.posthog.com/.well-known/http-message-signatures-directory`, a
- The registrable domain has no active request or pending request grant.
- The registrable domain has no active back-off or breaker.
-- The registrable domain's token bucket is full.
+- The registrable domain's token bucket is disabled or full.
The pod can evict an origin entry only when all these conditions apply:
@@ -291,13 +291,13 @@ Removing an eligible entry cannot permit an earlier request.
**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.17** The pass queue groups jobs first by registrable domain and then by origin. It assigns capped proportional concurrency targets at both levels. It starts with each queue's share of the deduplicated pass and the available parent capacity. It caps the target at the queue's job count and the registrable-domain limit. It redistributes unused capacity until no eligible queue exceeds either cap.
-**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.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** 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.
+**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 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.
+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.
### 6. Smokescreen
@@ -331,7 +331,7 @@ This rule lets later Kafka records add origin diversity before one origin consum
**7.9** The lane respects every `Crawl-delay` field line in the selected robots.txt group for `PostHogImageFetcherBot`. It accepts a non-negative decimal number of seconds, ignores invalid values, and uses the greatest valid value.
-**7.10** `Crawl-delay` is the minimum interval between the start times of two image requests to the same origin. The 1-request-per-second interval applies across the registrable domain. A request must satisfy both limits.
+**7.10** `Crawl-delay` is the minimum interval between the start times of two image requests to the same origin. An origin without this field has no start-time interval. A positive configured request rate can also apply across the registrable domain. A request must satisfy every enabled limit.
**7.11** Back-off, `Retry-After`, and an open circuit breaker apply to every image URL queued for the registrable domain. `Crawl-delay` applies only to image URLs queued for the origin that published it. The lane uses the latest applicable not-before time.
@@ -459,7 +459,7 @@ A fetch batch can publish more frontier records than it consumed. This can occur
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 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.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.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/configuration-policy.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts
index 3f386c3f61a9..93ed3cd076e8 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts
@@ -90,8 +90,14 @@ describe('robots policy', () => {
allowed: false,
reason: 'robots_disallow',
})
- await expect(parseRobotsPolicy(body, `${ORIGIN}/private/public.png`)).resolves.toMatchObject({ allowed: true })
- await expect(parseRobotsPolicy(body, `${ORIGIN}/wildcard/image.png`)).resolves.toMatchObject({ allowed: true })
+ await expect(parseRobotsPolicy(body, `${ORIGIN}/private/public.png`)).resolves.toMatchObject({
+ allowed: true,
+ crawlDelayMs: 0,
+ })
+ await expect(parseRobotsPolicy(body, `${ORIGIN}/wildcard/image.png`)).resolves.toMatchObject({
+ allowed: true,
+ crawlDelayMs: 0,
+ })
})
it('uses the greatest valid crawl delay in every selected field line', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts
index a2552b53b638..99aca0db16f0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts
@@ -239,7 +239,7 @@ export class ConfigurationPolicyService {
allowed: false,
transient: false,
reason: 'robots_refused',
- crawlDelayMs: 1_000,
+ crawlDelayMs: 0,
tdmrepReservation: false,
updates,
}
@@ -249,7 +249,7 @@ export class ConfigurationPolicyService {
allowed: false,
transient: false,
reason: 'tdmrep_refused',
- crawlDelayMs: 1_000,
+ crawlDelayMs: 0,
tdmrepReservation: false,
updates,
}
@@ -277,7 +277,7 @@ export class ConfigurationPolicyService {
allowed: false,
transient: true,
reason: deferredReason,
- crawlDelayMs: 1_000,
+ crawlDelayMs: 0,
tdmrepReservation: false,
updates,
}
@@ -287,7 +287,7 @@ export class ConfigurationPolicyService {
allowed: false,
transient: true,
reason: 'configuration_unreachable',
- crawlDelayMs: 1_000,
+ crawlDelayMs: 0,
tdmrepReservation: false,
updates,
}
@@ -458,7 +458,7 @@ function selectedExtensionFields(
}
function defaultRobotsPolicy(): { allowed: true; crawlDelayMs: number } {
- return { allowed: true, crawlDelayMs: 1_000 }
+ return { allowed: true, crawlDelayMs: 0 }
}
export async function parseRobotsPolicy(
@@ -482,10 +482,10 @@ function evaluateRobotsPolicy(
url: string
): { allowed: boolean; crawlDelayMs: number; reason?: RobotsPolicyRefusalReason } {
if (!parsed.matcher.checkUrl(BOT_NAME, url).allowed) {
- return { allowed: false, crawlDelayMs: 1_000, reason: 'robots_disallow' }
+ return { allowed: false, crawlDelayMs: 0, reason: 'robots_disallow' }
}
const crawlDelayMs = Math.max(
- 1_000,
+ 0,
...parsed.fields
.filter((field) => field.name === 'crawl-delay')
.flatMap((field) => {
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 cf23332e9c1a..e62553ccfcc6 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
@@ -1,6 +1,14 @@
import { FetchCandidate, MAX_HOPS } from './collected-urls-record'
import { FetchCandidateQueue } from './fetch-candidate-queue'
+const OPTIONS = {
+ maxConcurrentPerRegistrableDomain: 6,
+ maxInFlightRequests: 300,
+ lowOriginDiversityMinimumRequestSlots: 48,
+ lowOriginDiversityRepublishThreshold: 50,
+ lowOriginDiversityProgress: 8,
+}
+
function candidate(index: number): FetchCandidate {
return {
originalRef: `ref-${index}`,
@@ -26,17 +34,36 @@ function dominantOriginCandidate(index: number): FetchCandidate {
}
}
+function domainCandidate(domainIndex: number, candidateIndex: number): FetchCandidate {
+ const index = domainIndex * 1_000 + candidateIndex
+ const registrableDomain = `domain-${domainIndex}.example`
+ return {
+ ...candidate(index),
+ currentUrl: `https://cdn.${registrableDomain}/${candidateIndex}.png`,
+ host: `cdn.${registrableDomain}`,
+ origin: `https://cdn.${registrableDomain}`,
+ registrableDomain,
+ }
+}
+
+function concurrentDomainCounts(queue: FetchCandidateQueue, count: number): Map<string, number> {
+ const counts = new Map<string, number>()
+ for (let index = 0; index < count; index++) {
+ const lease = queue.take()
+ expect(lease).toBeDefined()
+ if (lease) {
+ counts.set(lease.candidate.registrableDomain, (counts.get(lease.candidate.registrableDomain) ?? 0) + 1)
+ }
+ }
+ return counts
+}
+
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,
- }
+ OPTIONS
)
let drained = 0
@@ -60,10 +87,10 @@ describe('FetchCandidateQueue', () => {
candidate(dominantCandidateCount),
],
{
+ ...OPTIONS,
maxConcurrentPerRegistrableDomain: 1,
- minimumActiveOrigins: 1,
+ lowOriginDiversityMinimumRequestSlots: 1,
lowOriginDiversityRepublishThreshold: 100_000,
- lowOriginDiversityProgress: 8,
}
)
let drained = 0
@@ -82,4 +109,30 @@ describe('FetchCandidateQueue', () => {
expect(drained).toBe(dominantCandidateCount + 1)
expect(maximumSelectableDomains).toBe(1)
})
+
+ it.each([
+ {
+ name: 'gives 150 equal domains two requests each',
+ domainSizes: Array.from({ length: 150 }, () => 6),
+ expectedCounts: Array.from({ length: 150 }, () => 2),
+ },
+ {
+ name: 'gives smaller domains their proportional request share',
+ domainSizes: [...Array.from({ length: 50 }, () => 100), ...Array.from({ length: 50 }, () => 10)],
+ expectedCounts: [...Array.from({ length: 50 }, () => 5), ...Array.from({ length: 50 }, () => 1)],
+ },
+ ])('$name', ({ domainSizes, expectedCounts }) => {
+ const queue = new FetchCandidateQueue(
+ domainSizes.flatMap((size, domainIndex) =>
+ Array.from({ length: size }, (_, candidateIndex) => domainCandidate(domainIndex, candidateIndex))
+ ),
+ OPTIONS
+ )
+
+ const counts = concurrentDomainCounts(queue, OPTIONS.maxInFlightRequests)
+
+ expect(
+ Array.from({ length: domainSizes.length }, (_, index) => counts.get(`domain-${index}.example`) ?? 0)
+ ).toEqual(expectedCounts)
+ })
})
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 08ff4e2fed7d..543cc9f12039 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,5 +1,3 @@
-import FastPriorityQueue from 'fastpriorityqueue'
-
import { FetchCandidate } from './collected-urls-record'
export type FetchCandidateQueueAction = 'fetch' | 'republish_low_origin_diversity'
@@ -7,6 +5,7 @@ export type FetchCandidateQueueAction = 'fetch' | 'republish_low_origin_diversit
export interface LowOriginDiversitySnapshot {
origins: number
candidates: number
+ requestSlots: number
}
export interface FetchCandidateLease {
@@ -21,40 +20,54 @@ interface OriginQueue {
candidates: FetchCandidate[]
head: number
sequence: number
+ active: number
+ initialCandidateCount: number
+ targetConcurrent: number
+ heapIndex: number
}
interface RegistrableDomainQueue {
registrableDomain: string
origins: Map<string, OriginQueue>
- availableOrigins: FastPriorityQueue<OriginQueue>
+ availableOrigins: IndexedPriorityQueue<OriginQueue>
+ initialCandidateCount: number
+ waitingCandidateCount: number
+ targetConcurrent: number
+ sequence: number
active: number
heapIndex: number
}
-class AvailableDomainQueue {
- private readonly heap: RegistrableDomainQueue[] = []
+interface IndexedPriorityQueueItem {
+ heapIndex: number
+}
+
+class IndexedPriorityQueue<T extends IndexedPriorityQueueItem> {
+ private readonly heap: T[] = []
+
+ constructor(private readonly hasPriority: (left: T, right: T) => boolean) {}
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)
+ public addOrUpdate(item: T): void {
+ if (item.heapIndex < 0) {
+ item.heapIndex = this.heap.length
+ this.heap.push(item)
+ this.siftUp(item.heapIndex)
return
}
- this.rebalance(domain.heapIndex)
+ this.rebalance(item.heapIndex)
}
- public remove(domain: RegistrableDomainQueue): void {
- const index = domain.heapIndex
+ public remove(item: T): void {
+ const index = item.heapIndex
if (index < 0) {
return
}
const last = this.heap.pop()!
- domain.heapIndex = -1
+ item.heapIndex = -1
if (index === this.heap.length) {
return
}
@@ -63,17 +76,21 @@ class AvailableDomainQueue {
this.rebalance(index)
}
- public poll(): RegistrableDomainQueue | undefined {
- const domain = this.heap[0]
- if (domain) {
- this.remove(domain)
+ public peek(): T | undefined {
+ return this.heap[0]
+ }
+
+ public poll(): T | undefined {
+ const item = this.heap[0]
+ if (item) {
+ this.remove(item)
}
- return domain
+ return item
}
private rebalance(index: number): void {
const parentIndex = Math.floor((index - 1) / 2)
- if (index > 0 && domainQueueHasPriority(this.heap[index], this.heap[parentIndex])) {
+ if (index > 0 && this.hasPriority(this.heap[index], this.heap[parentIndex])) {
this.siftUp(index)
} else {
this.siftDown(index)
@@ -84,7 +101,7 @@ class AvailableDomainQueue {
let index = startIndex
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2)
- if (!domainQueueHasPriority(this.heap[index], this.heap[parentIndex])) {
+ if (!this.hasPriority(this.heap[index], this.heap[parentIndex])) {
return
}
this.swap(index, parentIndex)
@@ -101,10 +118,10 @@ class AvailableDomainQueue {
}
const rightIndex = leftIndex + 1
const childIndex =
- rightIndex < this.heap.length && domainQueueHasPriority(this.heap[rightIndex], this.heap[leftIndex])
+ rightIndex < this.heap.length && this.hasPriority(this.heap[rightIndex], this.heap[leftIndex])
? rightIndex
: leftIndex
- if (!domainQueueHasPriority(this.heap[childIndex], this.heap[index])) {
+ if (!this.hasPriority(this.heap[childIndex], this.heap[index])) {
return
}
this.swap(index, childIndex)
@@ -124,7 +141,8 @@ class AvailableDomainQueue {
export interface FetchCandidateQueueOptions {
maxConcurrentPerRegistrableDomain: number
- minimumActiveOrigins: number
+ maxInFlightRequests: number
+ lowOriginDiversityMinimumRequestSlots: number
lowOriginDiversityRepublishThreshold: number
lowOriginDiversityProgress: number
}
@@ -141,7 +159,7 @@ export function deduplicateFetchCandidates(candidates: FetchCandidate[]): Dedupl
const existing = candidatesByCanonicalRef.get(candidate.originalRef)
if (existing) {
duplicateCount += 1
- candidatesByCanonicalRef.set(candidate.originalRef, foldDuplicateCandidate(existing, candidate))
+ candidatesByCanonicalRef.set(candidate.originalRef, mergeDuplicateFetchCandidates(existing, candidate))
} else {
candidatesByCanonicalRef.set(candidate.originalRef, candidate)
}
@@ -151,13 +169,14 @@ export function deduplicateFetchCandidates(candidates: FetchCandidate[]): Dedupl
export class FetchCandidateQueue {
private readonly domains = new Map<string, RegistrableDomainQueue>()
- private readonly availableDomains = new AvailableDomainQueue()
+ 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(
@@ -166,14 +185,19 @@ export class FetchCandidateQueue {
) {
this.lowOriginDiversityProgressRemaining = options.lowOriginDiversityProgress
const deduplicated = deduplicateFetchCandidates(candidates)
- let sequence = 0
+ let domainSequence = 0
+ let originSequence = 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),
+ availableOrigins: new IndexedPriorityQueue<OriginQueue>(originQueueHasPriority),
+ initialCandidateCount: 0,
+ waitingCandidateCount: 0,
+ targetConcurrent: 0,
+ sequence: domainSequence++,
active: 0,
heapIndex: -1,
}
@@ -185,27 +209,45 @@ export class FetchCandidateQueue {
origin: candidate.origin,
candidates: [],
head: 0,
- sequence: sequence++,
+ sequence: originSequence++,
+ active: 0,
+ initialCandidateCount: 0,
+ targetConcurrent: 0,
+ 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()],
+ this.options.maxInFlightRequests,
+ this.options.maxConcurrentPerRegistrableDomain
+ )
for (const domain of this.domains.values()) {
- this.initialSchedulableSlots += Math.min(
- domain.origins.size,
+ allocateConcurrentTargets(
+ [...domain.origins.values()],
+ domain.targetConcurrent,
this.options.maxConcurrentPerRegistrableDomain
)
for (const origin of domain.origins.values()) {
- domain.availableOrigins.add(origin)
+ this.refreshOriginSelection(domain, origin)
}
+ this.initialSchedulableSlots += Math.min(
+ domain.initialCandidateCount,
+ this.options.maxConcurrentPerRegistrableDomain
+ )
this.refreshDomainSelection(domain)
}
+ this.remainingSchedulableSlots = this.initialSchedulableSlots
}
public get candidateCount(): number {
@@ -224,6 +266,14 @@ export class FetchCandidateQueue {
return this.initialSchedulableSlots
}
+ public availableRequestSlotsAtStart(availableConnections: (registrableDomain: string) => number): number {
+ let slots = 0
+ for (const domain of this.domains.values()) {
+ slots += Math.min(domain.initialCandidateCount, availableConnections(domain.registrableDomain))
+ }
+ return slots
+ }
+
public abort(): void {
this.aborted = true
}
@@ -232,22 +282,30 @@ export class FetchCandidateQueue {
if (this.aborted) {
return undefined
}
- const selected = this.takeLargestAvailableOrigin()
+ const selected = this.takeHighestPriorityOrigin()
if (!selected) {
return undefined
}
+ const remainingRequestSlots = Math.min(this.remainingSchedulableSlots, this.options.maxInFlightRequests)
const lowOriginDiversity =
this.lowOriginDiversityStarted ||
- (this.remainingOrigins < this.options.minimumActiveOrigins &&
+ (remainingRequestSlots < this.options.lowOriginDiversityMinimumRequestSlots &&
this.waitingCandidatesWithoutDiversityDeferral > this.options.lowOriginDiversityRepublishThreshold)
const lowOriginDiversityStarted =
lowOriginDiversity && !this.lowOriginDiversityStarted
- ? { origins: this.remainingOrigins, candidates: this.waitingCandidates }
+ ? {
+ 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
@@ -271,12 +329,22 @@ export class FetchCandidateQueue {
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)
- if (originCandidateCount(selected.origin) === 0) {
+ 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 {
- selected.domain.availableOrigins.add(selected.origin)
+ this.refreshOriginSelection(selected.domain, selected.origin)
}
if (selected.domain.origins.size === 0) {
this.availableDomains.remove(selected.domain)
@@ -288,7 +356,7 @@ export class FetchCandidateQueue {
}
}
- private takeLargestAvailableOrigin(): { domain: RegistrableDomainQueue; origin: OriginQueue } | undefined {
+ private takeHighestPriorityOrigin(): { domain: RegistrableDomainQueue; origin: OriginQueue } | undefined {
for (;;) {
const domain = this.availableDomains.poll()
if (!domain) {
@@ -302,11 +370,19 @@ export class FetchCandidateQueue {
continue
}
domain.active += 1
- this.refreshDomainSelection(domain)
+ origin.active += 1
return { domain, origin }
}
}
+ private refreshOriginSelection(domain: RegistrableDomainQueue, origin: OriginQueue): void {
+ if (originCandidateCount(origin) === 0 || origin.active >= this.options.maxConcurrentPerRegistrableDomain) {
+ domain.availableOrigins.remove(origin)
+ return
+ }
+ domain.availableOrigins.addOrUpdate(origin)
+ }
+
private refreshDomainSelection(domain: RegistrableDomainQueue): void {
const origin = domain.availableOrigins.peek()
if (!origin || domain.active >= this.options.maxConcurrentPerRegistrableDomain) {
@@ -318,9 +394,14 @@ export class FetchCandidateQueue {
}
function originQueueHasPriority(left: OriginQueue, right: OriginQueue): boolean {
+ const leftDistance = left.targetConcurrent - left.active
+ const rightDistance = right.targetConcurrent - right.active
return (
- originCandidateCount(left) > originCandidateCount(right) ||
- (originCandidateCount(left) === originCandidateCount(right) && left.sequence < right.sequence)
+ leftDistance > rightDistance ||
+ (leftDistance === rightDistance && originCandidateCount(left) > originCandidateCount(right)) ||
+ (leftDistance === rightDistance &&
+ originCandidateCount(left) === originCandidateCount(right) &&
+ left.sequence < right.sequence)
)
}
@@ -329,16 +410,56 @@ function originCandidateCount(origin: OriginQueue): number {
}
function domainQueueHasPriority(left: RegistrableDomainQueue, right: RegistrableDomainQueue): boolean {
- const leftOrigin = left.availableOrigins.peek()!
- const rightOrigin = right.availableOrigins.peek()!
+ const leftDistance = left.targetConcurrent - left.active
+ const rightDistance = right.targetConcurrent - right.active
return (
- originCandidateCount(leftOrigin) > originCandidateCount(rightOrigin) ||
- (originCandidateCount(leftOrigin) === originCandidateCount(rightOrigin) &&
- leftOrigin.sequence < rightOrigin.sequence)
+ leftDistance > rightDistance ||
+ (leftDistance === rightDistance && left.waitingCandidateCount > right.waitingCandidateCount) ||
+ (leftDistance === rightDistance &&
+ left.waitingCandidateCount === right.waitingCandidateCount &&
+ left.sequence < right.sequence)
)
}
-function foldDuplicateCandidate(left: FetchCandidate, right: FetchCandidate): FetchCandidate {
+interface ConcurrentTarget {
+ initialCandidateCount: number
+ targetConcurrent: number
+}
+
+function allocateConcurrentTargets<T extends ConcurrentTarget>(
+ queues: T[],
+ totalCapacity: number,
+ maximumPerQueue: number
+): void {
+ let remainingCapacity = Math.min(
+ totalCapacity,
+ queues.reduce((sum, queue) => sum + queue.initialCandidateCount, 0)
+ )
+ let remainingWeight = queues.reduce((sum, queue) => sum + queue.initialCandidateCount, 0)
+ let remainingQueues = queues
+
+ while (remainingQueues.length > 0 && remainingCapacity > 0 && remainingWeight > 0) {
+ const queuesAtLimit = remainingQueues.filter((queue) => {
+ const proportionalTarget = (remainingCapacity * queue.initialCandidateCount) / remainingWeight
+ return proportionalTarget >= Math.min(maximumPerQueue, queue.initialCandidateCount)
+ })
+ if (queuesAtLimit.length === 0) {
+ for (const queue of remainingQueues) {
+ queue.targetConcurrent = (remainingCapacity * queue.initialCandidateCount) / remainingWeight
+ }
+ return
+ }
+ const queuesAtLimitSet = new Set(queuesAtLimit)
+ for (const queue of queuesAtLimit) {
+ queue.targetConcurrent = Math.min(maximumPerQueue, queue.initialCandidateCount)
+ remainingCapacity -= queue.targetConcurrent
+ remainingWeight -= queue.initialCandidateCount
+ }
+ remainingQueues = remainingQueues.filter((queue) => !queuesAtLimitSet.has(queue))
+ }
+}
+
+export function mergeDuplicateFetchCandidates(left: FetchCandidate, right: FetchCandidate): FetchCandidate {
let preferredRoute = left
if (
right.remainingHops < left.remainingHops ||
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 5fe0a8d9e855..a3506465f04b 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,7 +12,7 @@ const NOW_MS = 1_700_000_000_000
const OPTIONS: FetchRunnerOptions = {
maxConcurrentPerRegistrableDomain: 2,
maxInFlightRequests: 50,
- minimumActiveOrigins: 1,
+ lowOriginDiversityMinimumRequestSlots: 1,
lowOriginDiversityRepublishThreshold: 50,
lowOriginDiversityProgress: 8,
batchBudgetMs: 20_000,
@@ -41,6 +41,7 @@ function candidate(overrides: Partial<FetchCandidate> = {}): FetchCandidate {
interface Harness {
runner: FetchRunner
+ budget: HostBudget
fetch: jest.Mock<Promise<ImageFetchResult>, [string, ImageFetchOptions]>
check: jest.Mock<Promise<OriginPolicyDecision>, [string, Map<string, ConfigurationCacheItem>, number]>
createPass: jest.Mock
@@ -97,7 +98,7 @@ function build(
options,
{ createRepublishBatch, publishImage } as unknown as FrontierPublisher
)
- return { runner, fetch, check, createPass, republish, publishImage }
+ return { runner, budget, fetch, check, createPass, republish, publishImage }
}
describe('FetchRunner', () => {
@@ -183,7 +184,7 @@ describe('FetchRunner', () => {
expect(harness.fetch).toHaveBeenCalledTimes(2)
})
- it('does not let one origin occupy every registrable-domain worker', async () => {
+ it('allocates sibling-origin workers by queue share', async () => {
const harness = build({}, {}, 'queued', { ...OPTIONS, maxConcurrentPerRegistrableDomain: 2 })
let releaseFirst: (() => void) | undefined
let releaseSecond: (() => void) | undefined
@@ -219,7 +220,7 @@ describe('FetchRunner', () => {
expect(harness.fetch).toHaveBeenCalledTimes(3)
})
- it('records initial capacity after origin and registrable-domain limits', async () => {
+ it('records initial capacity after live pod and registrable-domain limits', async () => {
const observeCapacity = jest
.spyOn(ImageFetchRequestMetrics, 'observeBatchSchedulableCapacity')
.mockImplementation()
@@ -233,9 +234,7 @@ describe('FetchRunner', () => {
...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`,
+ currentUrl: `https://cdn.example.com/image-${index}.png`,
})
),
...Array.from({ length: 2 }, (_, index) =>
@@ -248,13 +247,24 @@ describe('FetchRunner', () => {
})
),
]
+ const grant = harness.budget.take('example.com', 'https://cdn.example.com', NOW_MS, NOW_MS + 10_000, true)
+ expect(grant).toMatchObject({ granted: true, waitMs: 0 })
+ expect(harness.budget.acquireConnection('example.com', 'https://cdn.example.com')).toBe(true)
+ harness.budget.markRequestStarted(
+ 'example.com',
+ 'https://cdn.example.com',
+ NOW_MS,
+ grant.granted ? grant.reservedStartAtMs : null,
+ 'configuration'
+ )
await harness.runner.run(candidates, new Map())
- expect(observeCapacity).toHaveBeenCalledWith(4, 3)
+ expect(observeCapacity).toHaveBeenCalledWith(3, 3)
+ harness.budget.releaseConnection('example.com', 'https://cdn.example.com')
})
- it('starts the origin with the largest canonical URL queue first', async () => {
+ it('keeps one request slot on the largest origin queue', async () => {
const harness = build({}, {}, 'queued', {
...OPTIONS,
maxConcurrentPerRegistrableDomain: 1,
@@ -282,25 +292,28 @@ describe('FetchRunner', () => {
expect(harness.fetch.mock.calls.map(([url]) => url)).toEqual([
largeFirst.currentUrl,
- small.currentUrl,
largeSecond.currentUrl,
+ small.currentUrl,
])
})
- it('republishes a low-origin-diversity tail after making bounded progress', async () => {
+ it('republishes a low-capacity tail across many origins after making bounded progress', async () => {
const harness = build({}, {}, 'queued', {
...OPTIONS,
maxInFlightRequests: 1,
- minimumActiveOrigins: 2,
+ lowOriginDiversityMinimumRequestSlots: 5,
lowOriginDiversityRepublishThreshold: 2,
lowOriginDiversityProgress: 1,
})
- const candidates = Array.from({ length: 4 }, (_, index) =>
- candidate({
+ const candidates = Array.from({ length: 4 }, (_, index) => {
+ const origin = `https://cdn-${index}.example.com`
+ return candidate({
originalRef: `imageurl:${index.toString().padStart(22, '0')}`,
- currentUrl: `https://cdn.example.com/${index}.png`,
+ currentUrl: `${origin}/${index}.png`,
+ host: `cdn-${index}.example.com`,
+ origin,
})
- )
+ })
const attempts = await harness.runner.run(candidates, new Map())
@@ -319,7 +332,7 @@ describe('FetchRunner', () => {
const harness = build({}, {}, 'queued', {
...OPTIONS,
maxInFlightRequests: 1,
- minimumActiveOrigins: 2,
+ lowOriginDiversityMinimumRequestSlots: 5,
lowOriginDiversityRepublishThreshold: 2,
lowOriginDiversityProgress: 1,
})
@@ -343,6 +356,9 @@ describe('FetchRunner', () => {
})
it('keeps the pod request limit across overlapping passes', async () => {
+ const observeCapacity = jest
+ .spyOn(ImageFetchRequestMetrics, 'observeBatchSchedulableCapacity')
+ .mockImplementation()
const harness = build({}, {}, 'queued', { ...OPTIONS, maxInFlightRequests: 1 })
const releases: Array<() => void> = []
let signalSecondFetchStarted: () => void = () => undefined
@@ -372,6 +388,10 @@ describe('FetchRunner', () => {
await Promise.resolve()
expect(harness.fetch).toHaveBeenCalledTimes(1)
+ expect(observeCapacity.mock.calls).toEqual([
+ [1, 1],
+ [0, 1],
+ ])
releases[0]()
await secondFetchStarted
expect(harness.fetch).toHaveBeenCalledTimes(2)
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 cafadb714d45..c8c0c20c3a63 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
@@ -52,7 +52,7 @@ export interface FetchAttempt {
export interface FetchRunnerOptions {
maxConcurrentPerRegistrableDomain: number
maxInFlightRequests: number
- minimumActiveOrigins: number
+ lowOriginDiversityMinimumRequestSlots: number
lowOriginDiversityRepublishThreshold: number
lowOriginDiversityProgress: number
batchBudgetMs: number
@@ -120,8 +120,8 @@ export class FetchRunner implements FetchPass {
options.maxInFlightRequests
)
requirePositiveSafeInteger(
- 'SESSION_RECORDING_ML_IMAGE_FETCH_MINIMUM_ACTIVE_ORIGINS',
- options.minimumActiveOrigins
+ 'SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_MINIMUM_REQUEST_SLOTS',
+ options.lowOriginDiversityMinimumRequestSlots
)
requirePositiveSafeInteger(
'SESSION_RECORDING_ML_IMAGE_FETCH_LOW_ORIGIN_DIVERSITY_REPUBLISH_THRESHOLD',
@@ -157,22 +157,30 @@ export class FetchRunner implements FetchPass {
}
}
const queue = new FetchCandidateQueue(candidates, this.options)
+ const podRequestSlots = Math.max(0, this.options.maxInFlightRequests - this.candidateWork.running)
ImageFetchRequestMetrics.observeBatchSchedulableCapacity(
- queue.schedulableSlotsAtStart,
+ Math.min(
+ podRequestSlots,
+ queue.availableRequestSlotsAtStart((registrableDomain) =>
+ this.budget.availableConnections(registrableDomain)
+ )
+ ),
this.options.maxInFlightRequests
)
const attempts: FetchAttempt[] = []
- const workers = Array.from({ length: Math.min(this.options.maxInFlightRequests, queue.originCount) }, () =>
- this.runQueueWorker(
- queue,
- stored,
- configurationItems,
- configurationPolicy,
- deadlineMs,
- attempts,
- activeRepublishBatch,
- passState
- )
+ const workers = Array.from(
+ { length: Math.min(this.options.maxInFlightRequests, queue.schedulableSlotsAtStart) },
+ () =>
+ this.runQueueWorker(
+ queue,
+ stored,
+ configurationItems,
+ configurationPolicy,
+ deadlineMs,
+ attempts,
+ activeRepublishBatch,
+ passState
+ )
)
const settledWorkers = await Promise.allSettled(workers)
if (passState.failure) {
@@ -213,7 +221,8 @@ export class FetchRunner implements FetchPass {
if (lease.lowOriginDiversityStarted) {
ImageFetchRequestMetrics.observeLowOriginDiversity(
lease.lowOriginDiversityStarted.origins,
- lease.lowOriginDiversityStarted.candidates
+ lease.lowOriginDiversityStarted.candidates,
+ lease.lowOriginDiversityStarted.requestSlots
)
}
attempts.push(
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts
index 9d229055a4ae..445a6f3859aa 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts
@@ -22,6 +22,7 @@ function budget(overrides: Partial<HostBudgetOptions> = {}): HostBudget {
describe('HostBudget', () => {
it('does not reserve a token before a crawl-delay wait finishes', () => {
const host = budget({ burst: 5 })
+ host.setCrawlDelay(ORIGIN, 1_000, 1_000)
const first = host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)
expect(first).toEqual({
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts
index d6c613c537c2..035f9a5de6c6 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts
@@ -55,8 +55,17 @@ export class HostBudget {
constructor(private readonly options: HostBudgetOptions) {
for (const [name, value] of Object.entries(options)) {
- if (name !== 'random' && (!Number.isFinite(value) || (value as number) <= 0)) {
- throw new Error(`the image fetch request budget needs a positive ${name}, got ${value}`)
+ if (name === 'random') {
+ continue
+ }
+ const number = value as number
+ const invalid = !Number.isFinite(number) || (name === 'requestsPerSecond' ? number < 0 : number <= 0)
+ if (invalid) {
+ const validRange =
+ name === 'requestsPerSecond'
+ ? 'a finite number greater than or equal to zero'
+ : 'a finite number greater than zero'
+ throw new Error(`the image fetch request budget ${name} must be ${validRange}, got ${value}`)
}
}
this.random = options.random ?? Math.random
@@ -95,7 +104,7 @@ export class HostBudget {
}
this.refill(registrableDomainState, nowMs)
const tokenWaitMs =
- registrableDomainState.tokens >= 1
+ this.options.requestsPerSecond === 0 || registrableDomainState.tokens >= 1
? 0
: Math.ceil(((1 - registrableDomainState.tokens) / this.options.requestsPerSecond) * 1000)
const previousStartMs = originState.lastRequestStartedAtMs ?? Number.NEGATIVE_INFINITY
@@ -118,7 +127,9 @@ export class HostBudget {
if (halfOpenProbe) {
registrableDomainState.halfOpenProbeInFlight = true
}
- registrableDomainState.tokens -= 1
+ if (this.options.requestsPerSecond > 0) {
+ registrableDomainState.tokens -= 1
+ }
registrableDomainState.pendingGrants += 1
const reservedStartAtMs = ignoreImageDelay ? null : nowMs
if (reservedStartAtMs !== null) {
@@ -172,8 +183,10 @@ export class HostBudget {
return
}
registrableDomainState.pendingGrants = Math.max(0, registrableDomainState.pendingGrants - 1)
- this.refill(registrableDomainState, nowMs)
- registrableDomainState.tokens = Math.min(this.options.burst, registrableDomainState.tokens + 1)
+ if (this.options.requestsPerSecond > 0) {
+ this.refill(registrableDomainState, nowMs)
+ registrableDomainState.tokens = Math.min(this.options.burst, registrableDomainState.tokens + 1)
+ }
if (halfOpenProbe && registrableDomainState.breakerOpen) {
registrableDomainState.halfOpenProbeInFlight = false
}
@@ -190,6 +203,11 @@ export class HostBudget {
return true
}
+ public availableConnections(registrableDomain: string): number {
+ const inFlight = this.registrableDomains.get(registrableDomain)?.inFlight ?? 0
+ return Math.max(0, this.options.maxConcurrent - inFlight)
+ }
+
public releaseConnection(registrableDomain: string, origin: string): void {
const registrableDomainState = this.registrableDomains.get(registrableDomain)
if (registrableDomainState) {
@@ -222,7 +240,7 @@ export class HostBudget {
if (!state) {
return false
}
- state.crawlDelayMs = Math.max(1_000, crawlDelayMs)
+ state.crawlDelayMs = Math.max(0, crawlDelayMs)
return true
}
@@ -326,7 +344,7 @@ export class HostBudget {
pendingRequests: 0,
lastRequestStartedAtMs: null,
reservedStartTimesMs: [],
- crawlDelayMs: 1_000,
+ crawlDelayMs: 0,
}
this.origins.set(origin, state)
return state
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 e7c741ca2825..a88e99a2dfec 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
@@ -232,26 +232,31 @@ export class ImageFetchRequestMetrics {
})
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',
+ 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 started low-diversity republishing',
+ 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 started low-diversity republishing',
+ 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 immediately after origin and registrable-domain concurrency limits',
+ help: 'Request slots that the initial fetch queue can use after live pod 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',
+ help: 'Share of the pod request limit that the initial fetch queue can use after live concurrency limits',
buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 1],
})
/**
@@ -372,10 +377,11 @@ 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 {
+ 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)
@@ -426,7 +432,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',
+ 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',
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 14eed6b3a041..7f92e9f0dfa0 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
@@ -24,7 +24,9 @@ describe('OriginRequestScheduler', () => {
})
it('keeps concurrent request start times at least one second apart', async () => {
- const scheduler = new OriginRequestScheduler(new HostBudget(OPTIONS), 300)
+ const budget = new HostBudget(OPTIONS)
+ budget.setCrawlDelay(ORIGIN.origin, 1_000, Date.now())
+ const scheduler = new OriginRequestScheduler(budget, 300)
const observeSchedulerWait = jest.spyOn(ImageFetchRequestMetrics, 'observeSchedulerWait')
const startedAtMs: number[] = []
const deadlineMs = Date.now() + 10_000
@@ -47,6 +49,31 @@ describe('OriginRequestScheduler', () => {
expect(observeSchedulerWait).toHaveBeenCalledWith('request_capacity', 0)
})
+ it('allows six concurrent same-origin requests when the request rate and crawl delay are disabled', async () => {
+ const scheduler = new OriginRequestScheduler(
+ new HostBudget({ ...OPTIONS, requestsPerSecond: 0, burst: 6, maxConcurrent: 6 }),
+ 300
+ )
+ const releases: Array<() => void> = []
+ const requests = Array.from({ length: 7 }, () =>
+ scheduler.runImage(
+ ORIGIN,
+ Date.now() + 10_000,
+ () =>
+ new Promise<void>((resolve) => {
+ releases.push(resolve)
+ })
+ )
+ )
+
+ await expect(requests[6]).resolves.toEqual({ ran: false, reason: 'connection_limit', waitMs: 0 })
+ expect(releases).toHaveLength(6)
+ releases.forEach((release) => release())
+ await expect(Promise.all(requests.slice(0, 6))).resolves.toEqual(
+ Array.from({ length: 6 }, () => ({ ran: true, value: undefined }))
+ )
+ })
+
it('runs one half-open probe while later requests remain blocked', async () => {
const budget = new HostBudget(OPTIONS)
budget.recordTransientFailure(REGISTRABLE_DOMAIN, Date.now())
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 3ada72f36b25..8a0db2984734 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
@@ -390,9 +390,10 @@ describe('UrlFetchConsumer', () => {
harness.history.writeError = new Error('write failed')
await expect(harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)).rejects.toThrow('write failed')
+ expect(harness.flush).not.toHaveBeenCalled()
})
- it('keeps publish work before the final history write', async () => {
+ it('writes durable state before it flushes buffered republishes', async () => {
const harness = build()
const order: string[] = []
harness.run.mockImplementation((candidates) => {
@@ -404,10 +405,14 @@ describe('UrlFetchConsumer', () => {
order.push('history')
await write(items)
}
+ harness.flush.mockImplementation(() => {
+ order.push('republished')
+ return Promise.resolve({ failedUrls: 0 })
+ })
await harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)
- expect(order).toEqual(['published', 'history'])
+ expect(order).toEqual(['published', 'history', 'republished'])
})
it('throws when the fetch pass reports a lost URL', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
index face47729031..a73b22a62555 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,7 +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 { mergeDuplicateFetchCandidates } from './fetch-candidate-queue'
import {
AttemptOutcome,
DELAY_TOO_LONG,
@@ -44,7 +44,7 @@ export class UrlFetchConsumer {
const startedAt = process.hrtime.bigint()
const republishDeadlineAtMonotonicMs = performance.now() + REPUBLISH_DEADLINE_FROM_BATCH_START_MS
const drops = new Map<UrlDropReason, number>()
- const parsedCandidates: FetchCandidate[] = []
+ const candidatesByRef = new Map<string, FetchCandidate>()
let dedupedInBatch = 0
let originCount = 0
let registrableDomainCount = 0
@@ -63,11 +63,18 @@ export class UrlFetchConsumer {
for (const rejected of parsed.rejected) {
drops.set(rejected.reason, (drops.get(rejected.reason) ?? 0) + 1)
}
- parsedCandidates.push(...parsed.candidates)
+ for (const candidate of parsed.candidates) {
+ const existing = candidatesByRef.get(candidate.originalRef)
+ if (existing) {
+ dedupedInBatch += 1
+ candidatesByRef.set(candidate.originalRef, mergeDuplicateFetchCandidates(existing, candidate))
+ } else {
+ candidatesByRef.set(candidate.originalRef, candidate)
+ }
+ }
}
- const deduplicated = deduplicateFetchCandidates(parsedCandidates)
- const candidates = deduplicated.candidates
- dedupedInBatch = deduplicated.duplicateCount
+ const candidates = [...candidatesByRef.values()]
+ candidatesByRef.clear()
const origins = new Map<string, number>()
const registrableDomains = new Map<string, number>()
for (const candidate of candidates) {
@@ -119,7 +126,6 @@ export class UrlFetchConsumer {
notReady.map((candidate) => this.republishNotReady(republishBatch, candidate, nowMs))
))
)
- const republishResult = await republishBatch.flush()
const updates: CrawlHistoryItem[] = []
for (const attempt of attempts) {
updates.push(...attempt.configurationUpdates)
@@ -130,6 +136,7 @@ export class UrlFetchConsumer {
if (updates.length > 0) {
await this.runCrawlHistoryOperation('write', updates.length, () => this.crawlHistory.write(updates))
}
+ const republishResult = await republishBatch.flush()
const lost = attempts.filter((attempt) => attempt.lost).length + republishResult.failedUrls
if (lost > 0) {
throw new Error(`the image fetch lane could not account for ${lost} URLs`)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 6b5126189d67..b6681243a9f6 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -91,11 +91,11 @@ export type MlMirrorConfig = {
/** TTL on each DynamoDB crawl-history entry, which sets the recrawl interval. */
AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS: number
- /** Requests one registrable domain receives from one pod each second. */
+ /** Optional steady request rate for one registrable domain. Zero uses the concurrency limit only. */
SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND: number
- /** Tokens one idle registrable domain can retain. */
+ /** Tokens one idle registrable domain can retain when the steady request rate is enabled. */
SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST: number
- /** Also the worker count for one registrable domain. */
+ /** Also the worker count for one registrable domain or origin. */
SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN: number
/**
* Requests this pod holds open across every registrable domain at once.
@@ -108,10 +108,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
+ /** 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
- /** URL jobs the largest origin can advance before the low-diversity tail returns to Kafka. */
+ /** 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
@@ -235,11 +236,11 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: '',
AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS: 5_000,
AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS: 30 * 24 * 60 * 60,
- SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND: 1,
- SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST: 5,
+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND: 0,
+ 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_MINIMUM_ACTIVE_ORIGINS: 8,
+ 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,
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 d02b2fe48895..bd20e6b1f80a 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,7 +117,8 @@ 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,
+ 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,