Skip to content

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

fix(ai-research-v4): stop limiting image fetch to one request per domain (#128345)

Nicholas Waltz2c86a55f4c89
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/config.ts
index 73dc8c8ed42c..07a034d16ef3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/config.ts
@@ -27,12 +27,6 @@ export type AiResearchV4Config = {
AI_RESEARCH_V4_IMAGE_FETCH_GROUP_ID: string
/** How long all key lookups of one batch may take. A job whose key is not read by then goes to a delay tier. */
AI_RESEARCH_V4_IMAGE_FETCH_KEY_BUDGET_MS: number
- /**
- * The share of the per registrable domain limits below that the v4 lane uses. The v3 lane's pods hold their own
- * budget, so a host sees both lanes.
- */
- AI_RESEARCH_V4_IMAGE_FETCH_HOST_BUDGET_SHARE: number
-
/** US-only, PEM, multiple keys allowed (comma-separated). */
AI_RESEARCH_V4_IMAGE_FETCH_WEB_BOT_AUTH_PRIVATE_KEYS: string
/** While true, the fetch lane parses input but sends no request and writes no crawl history. */
@@ -169,7 +163,6 @@ export function getDefaultAiResearchV4Config(): AiResearchV4Config {
AI_RESEARCH_V4_KMS_REQUESTS_PER_SECOND: 150,
AI_RESEARCH_V4_IMAGE_FETCH_GROUP_ID: 'ai-research-v4-image-fetch',
AI_RESEARCH_V4_IMAGE_FETCH_KEY_BUDGET_MS: 60_000,
- AI_RESEARCH_V4_IMAGE_FETCH_HOST_BUDGET_SHARE: 0.25,
AI_RESEARCH_V4_IMAGE_FETCH_WEB_BOT_AUTH_PRIVATE_KEYS: '',
AI_RESEARCH_V4_IMAGE_FETCH_DRY_RUN: true,
@@ -185,7 +178,7 @@ export function getDefaultAiResearchV4Config(): AiResearchV4Config {
AI_RESEARCH_V4_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS: 30 * 24 * 60 * 60,
AI_RESEARCH_V4_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND: 0,
AI_RESEARCH_V4_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST: 6,
- AI_RESEARCH_V4_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN: 6,
+ AI_RESEARCH_V4_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN: 7,
AI_RESEARCH_V4_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS: 300,
AI_RESEARCH_V4_IMAGE_FETCH_MAX_PENDING_PUBLISHES: 100,
AI_RESEARCH_V4_IMAGE_FETCH_REQUEST_BUDGET_MS: 40_000,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/lane.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/lane.ts
index 524fc9d5f742..20a501e11a97 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/lane.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/lane.ts
@@ -40,15 +40,3 @@ export interface HostLimits {
burst: number
maxConcurrent: number
}
-
-/** The v4 per registrable domain limits: a share of the configured limits, at least one request at a time. */
-export function v4HostLimits(limits: HostLimits, share: number): HostLimits {
- if (!(share > 0 && share <= 1)) {
- throw new Error(`AI_RESEARCH_V4_IMAGE_FETCH_HOST_BUDGET_SHARE must be in (0, 1], got ${share}`)
- }
- return {
- requestsPerSecond: limits.requestsPerSecond * share,
- burst: Math.max(1, Math.floor(limits.burst * share)),
- maxConcurrent: Math.max(1, Math.floor(limits.maxConcurrent * share)),
- }
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/tophog-metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/tophog-metrics.ts
index 981abe6029da..1df97090b2cb 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/tophog-metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/tophog-metrics.ts
@@ -15,6 +15,7 @@ export class ImageFetchTopHogMetrics {
private readonly attempts: Recorder
private readonly blockEvents: Recorder
private readonly blockedMs: Recorder
+ private readonly filteredUrls: Recorder
constructor(topHog: TopHogRegistry) {
this.attempts = topHog.registerSum('ai_research_v4_image_fetch_attempts_by_registrable_domain', {
@@ -29,6 +30,31 @@ export class ImageFetchTopHogMetrics {
topN: TOP_DOMAIN_FACTORS,
maxKeys: MAX_TRACKED_DOMAIN_FACTORS,
})
+ this.filteredUrls = topHog.registerSum('ai_research_v4_image_fetch_filtered_urls_by_registrable_domain', {
+ topN: TOP_DOMAIN_FACTORS,
+ maxKeys: MAX_TRACKED_DOMAIN_FACTORS,
+ })
+ }
+
+ /**
+ * The first pass of a URL shows what the recorder sends for a domain. The later passes show what the fetcher sends
+ * back to itself, so the two together separate new demand from republish churn. Only the `received` stage reads
+ * demand, because the later stages see a URL after duplicates merge, with the highest pass and one route.
+ */
+ public recordFilteredUrl(
+ candidate: FetchCandidate,
+ stage: 'received' | 'store_deduped' | 'not_ready' | 'fetchable'
+ ): void {
+ this.recordForSourcePartitions(
+ this.filteredUrls,
+ candidate.sourcePartitions,
+ {
+ registrable_domain: candidate.registrableDomain,
+ stage,
+ pass: candidate.republishCount === 0 ? 'first' : 'republished',
+ },
+ 1
+ )
}
public recordAttempt(attempt: FetchAttempt): void {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/url-fetch-consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/url-fetch-consumer.test.ts
index f08fb5efb6e8..352824baecf4 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/url-fetch-consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/url-fetch-consumer.test.ts
@@ -347,6 +347,55 @@ describe('UrlFetchConsumer', () => {
await harness.consumer.handleBatch([message([stored, fresh])], NOW_MS)
expect(harness.run.mock.calls[0][0]).toEqual([{ ...fresh, sourcePartitions: [0] }])
+ expect(harness.topHogRecords.get('ai_research_v4_image_fetch_filtered_urls_by_registrable_domain')).toEqual([
+ {
+ key: { registrable_domain: 'example.com', stage: 'received', pass: 'first', partition: '0' },
+ value: 1,
+ },
+ {
+ key: { registrable_domain: 'example.com', stage: 'received', pass: 'first', partition: '0' },
+ value: 1,
+ },
+ {
+ key: { registrable_domain: 'example.com', stage: 'store_deduped', pass: 'first', partition: '0' },
+ value: 1,
+ },
+ {
+ key: { registrable_domain: 'example.com', stage: 'fetchable', pass: 'first', partition: '0' },
+ value: 1,
+ },
+ ])
+ })
+
+ it('counts the demand of each job before duplicates in a batch merge', async () => {
+ const harness = build()
+ const fresh = candidate('a')
+ const redirectedRetry = candidate('a', {
+ currentUrl: 'https://cdn.other.net/a.png',
+ host: 'cdn.other.net',
+ origin: 'https://cdn.other.net',
+ registrableDomain: 'other.net',
+ remainingHops: 9,
+ republishCount: 1,
+ lastRepublishReason: 'redirect',
+ })
+
+ await harness.consumer.handleBatch(
+ [message([fresh], 'example.com', 7), message([redirectedRetry], 'other.net', 42)],
+ NOW_MS
+ )
+
+ const records = harness.topHogRecords.get('ai_research_v4_image_fetch_filtered_urls_by_registrable_domain')
+ expect(records?.filter(({ key }) => key.stage === 'received')).toEqual([
+ {
+ key: { registrable_domain: 'example.com', stage: 'received', pass: 'first', partition: '7' },
+ value: 1,
+ },
+ {
+ key: { registrable_domain: 'other.net', stage: 'received', pass: 'republished', partition: '42' },
+ value: 1,
+ },
+ ])
})
it('republishes a job that arrives before its durable not-before time', async () => {
@@ -354,11 +403,22 @@ describe('UrlFetchConsumer', () => {
const early = candidate('a', {
notBeforeMs: NOW_MS + 30_000,
lastBlockReason: 'configuration_unreachable',
+ republishCount: 1,
})
await harness.consumer.handleBatch([message([early])], NOW_MS)
expect(harness.run.mock.calls[0][0]).toEqual([])
+ expect(harness.topHogRecords.get('ai_research_v4_image_fetch_filtered_urls_by_registrable_domain')).toEqual([
+ {
+ key: { registrable_domain: 'example.com', stage: 'received', pass: 'republished', partition: '0' },
+ value: 1,
+ },
+ {
+ key: { registrable_domain: 'example.com', stage: 'not_ready', pass: 'republished', partition: '0' },
+ value: 1,
+ },
+ ])
expect(harness.republish).toHaveBeenCalledWith(
{ ...early, sourcePartitions: [0], lastBlockReason: 'configuration_unreachable' },
{
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/url-fetch-consumer.ts
index 910572be3114..023998593087 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/url-fetch-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/url-fetch-consumer.ts
@@ -113,6 +113,7 @@ export class UrlFetchConsumer {
}
for (const candidate of parsed.candidates) {
const partitionCandidate = { ...candidate, sourcePartitions: [message.partition] }
+ this.topHogMetrics?.recordFilteredUrl(partitionCandidate, 'received')
const existing = candidatesByRef.get(partitionCandidate.originalRef)
if (existing) {
dedupedInBatch += 1
@@ -191,6 +192,7 @@ export class UrlFetchConsumer {
}
if (job === 'drop') {
ImageFetchConsumerMetrics.incDeduped('store', 1)
+ this.topHogMetrics?.recordFilteredUrl(candidate, 'store_deduped')
for (const sourcePartition of candidate.sourcePartitions ?? []) {
ImageFetchConsumerMetrics.incPartitionUrls(sourcePartition, 'store_deduped', 1)
}
@@ -199,11 +201,13 @@ export class UrlFetchConsumer {
}
if (candidate.notBeforeMs > nowMs) {
notReady.push(candidate)
+ this.topHogMetrics?.recordFilteredUrl(candidate, 'not_ready')
for (const sourcePartition of candidate.sourcePartitions ?? []) {
ImageFetchConsumerMetrics.incPartitionUrls(sourcePartition, 'not_ready', 1)
}
} else {
fetchable.push(candidate)
+ this.topHogMetrics?.recordFilteredUrl(candidate, 'fetchable')
for (const sourcePartition of candidate.sourcePartitions ?? []) {
ImageFetchConsumerMetrics.incPartitionUrls(sourcePartition, 'fetchable', 1)
}
diff --git a/nodejs/src/servers/ai-research-v4-image-fetch-server.ts b/nodejs/src/servers/ai-research-v4-image-fetch-server.ts
index c4157e51579e..07a0d35997ea 100644
--- a/nodejs/src/servers/ai-research-v4-image-fetch-server.ts
+++ b/nodejs/src/servers/ai-research-v4-image-fetch-server.ts
@@ -38,7 +38,6 @@ import {
V4_IMAGE_FETCH_DELAY_TOPICS,
V4_IMAGE_FETCH_LANE,
assertOwnImageFetchGroup,
- v4HostLimits,
} from '~/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/lane'
import { OriginRequestScheduler } from '~/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/origin-request-scheduler'
import { createPoolWindowBatchHandler } from '~/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/pool-window-batch-handler'
@@ -124,16 +123,12 @@ export function buildFrontierPublisher(
})
}
-/** The lane's per registrable domain limits: the configured share of the configured limits. */
export function imageFetchHostLimits(config: AiResearchV4ServerConfig): HostLimits {
- return v4HostLimits(
- {
- requestsPerSecond: config.AI_RESEARCH_V4_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND,
- burst: config.AI_RESEARCH_V4_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST,
- maxConcurrent: config.AI_RESEARCH_V4_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN,
- },
- config.AI_RESEARCH_V4_IMAGE_FETCH_HOST_BUDGET_SHARE
- )
+ return {
+ requestsPerSecond: config.AI_RESEARCH_V4_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND,
+ burst: config.AI_RESEARCH_V4_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST,
+ maxConcurrent: config.AI_RESEARCH_V4_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN,
+ }
}
export function buildFetchRunner(
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index d3af6f456851..4fc6704a49fe 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -736,7 +736,7 @@ Some limits apply:
The recorder sends each remote image URL that the URL policy accepts to the `ai_research_v4_image_fetch` topic in the v3 job shape, keyed by registrable domain. The job carries the reference that replaces the URL in the block.
It collects URLs from image sources, the kept candidate of each `srcset`, SVG image links, CSS `url(...)` values and attribute mutations, and skips hidden or 1×1 images as v3 does. Unlike v3, it also collects CSS custom properties and relative CSS URLs, and fetches one `image-set()` candidate of a stored type.
The topics hold jobs for 24 hours, because jobs carry raw URLs.
-The v4 image fetcher is its own copy of the v3 fetcher under `ai-research/image-fetch-v4/`, with the v3 fetch policy, its own consumer groups, its own `AI_RESEARCH_V4_IMAGE_FETCH_*` settings and a share of the v3 per-host limits. It shares no code or table with v3.
+The v4 image fetcher is its own copy of the v3 fetcher under `ai-research/image-fetch-v4/`, with the v3 fetch policy, its own consumer groups and its own `AI_RESEARCH_V4_IMAGE_FETCH_*` settings. It shares no code or table with v3.
It applies the recorder's URL policy through `@posthog/ai-research-v4-native`, an addon over `replay_core_v4::url_policy`, so it canonicalizes a URL, groups it by registrable domain and refuses private hosts exactly as the recorder does.
It stores each image, sealed and unscrubbed, under `images/url/`, and it does not send images to the scrub lane. It parses the image URL reference, seals the frame and computes the response URL HMAC with `replay_core_v4::fetched_image` through the same addon.
It stores PNG, JPEG, GIF, WebP and SVG as fetched. It does not rasterize an SVG; redaction downstream of the dataset handles SVG text.
@@ -767,6 +767,29 @@ Each recorder pod sends a reference at most once per UTC day. When `AI_RESEARCH_
`replay_core_v4::fetch_history` holds the drop rule, the 7-day refresh interval and the row parser. The recorder calls it directly, and the fetcher calls it through `@posthog/ai-research-v4-native`.
+#### Limits per domain and frontier backlog
+
+The fetcher sends at most `AI_RESEARCH_V4_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN` requests at once to one registrable domain.
+The default is 7. An explicit robots.txt crawl delay and the back-off after a failure can lower the rate for a domain. `Retry-After` can also lower it.
+
+The topic key sends each registrable domain to one partition and one pod, so more pods do not drain one domain faster.
+A pass ends after `AI_RESEARCH_V4_IMAGE_FETCH_REQUEST_BUDGET_MS`. A URL that the pass does not reach goes back to the frontier as `pass_deadline`. A URL whose domain is in back-off goes to a delay topic as `not_ready`.
+A URL finishes as `url_too_old` when it reaches `AI_RESEARCH_V4_IMAGE_FETCH_MAX_URL_AGE_MS`.
+
+When one frontier partition holds most of the lag, find the cause before you change capacity:
+
+1. Read `ai_research_v4_image_fetch_partition_urls_total` for the partition. A high `store_deduped` rate means that the recorder sends jobs that the fetcher drops. Check that the recorder has `AI_RESEARCH_V4_IMAGE_FETCH_HISTORY_TABLE` and read `ai_research_v4_recorder_image_fetch_history_total`.
+2. Read the TopHog metrics by `registrable_domain`, which the staff query path in `/querying-tophog` shows:
+ - `ai_research_v4_image_fetch_filtered_urls_by_registrable_domain` with `stage=received` shows the demand. `pass=first` counts what the recorder sent, and `pass=republished` counts what the fetcher sent back to itself. The other stages count unique URLs after duplicates in a batch merge, so they do not separate the two passes.
+ - `ai_research_v4_image_fetch_attempts_by_registrable_domain` shows each outcome.
+ - `ai_research_v4_image_fetch_block_events_by_registrable_domain` and `ai_research_v4_image_fetch_blocked_ms_by_registrable_domain` show which limit holds the domain.
+3. Act on the limit that holds the domain:
+ - For `transient_backoff`, `retry_after` or `breaker_open`, the site fails or asks for less traffic. Do not raise the limit. The URLs wait, and those that stay blocked finish as `url_too_old`.
+ - For `pass_deadline` with `domain_concurrency`, the domain has more URLs than its limit can serve in a pass. Raise the limit per domain only for a host that can take the traffic.
+ - For `configuration_unreachable`, the fetcher cannot read robots.txt or tdmrep for the origin. It waits for one hour and tries again.
+
+`IngestionSessionReplayMlConsumerNotDraining` and `IngestionSessionReplayMlConsumerStalled` read the lag of the whole topic. The `AiResearchV4ImageFetch*` alerts in the charts repository cover late completions, rejected input and long batches. The v4 image fetch dashboard in Grafana shows the same signals.
+
### Web fonts
A renderer that has no network needs the page's fonts. rrweb keeps the `@font-face` rules of a page in its style text, but it does not record font files, so the v4 lane fetches them as it fetches images.