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): batch image fetch republishes (#88026)

Robbiefb74b7b189bc
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 bce4c6f17650..f03743b5d655 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
@@ -36,6 +36,10 @@ Retry jobs use 1-minute, 10-minute, and 1-hour Kafka topics. The topics use brok
Each delay consumer waits once for the latest record in its batch. It then republishes the complete batch to the frontier.
+The fetch consumer buffers republished jobs until the fetch pass ends. It groups them by destination topic and current registrable domain, then packs each group to the shared job-count and byte limits. Redirects and pass-deadline deferrals return to the frontier. Work with a positive required wait uses a delay topic. Kafka deliveries use the configured pending-publish limit. One failed delivery stops the batch from starting more records, which bounds partial-delivery amplification before the source offsets retry. A monotonic deadline stops new deliveries 200 seconds after the poll batch starts. The producer's 20-second message timeout and the crawl-history store's 50-second batch budget plus command timeout keep the worst-case finalization near 275 seconds, below Kafka's 300-second poll limit.
+
+One source-domain record can redirect to several target registrable domains. Such a batch can publish more frontier records than it consumed. The lane keeps each target domain as a separate Kafka key instead of delaying a zero-wait redirect.
+
### Durable completion
DynamoDB stores URL outcomes and configuration entries. Reads use 100-item batches and writes use 25-item batches. Large configuration bodies use immutable generation-specific chunks that publish before their manifest.
@@ -66,6 +70,8 @@ Metrics cover terminal outcomes, requests, origin policy, registrable-domain req
`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.
+
The Grafana dashboard uses these runtime metrics. Its frontier health panels exclude the delay topics so they do not double-count retry traffic.
The Helm deployment defines fetch, scrub, and three retry consumers. Fetch and retry synchronization remains manual until their dependencies exist.
@@ -74,26 +80,27 @@ The Helm deployment defines fetch, scrub, and three retry consumers. Fetch and r
The lane uses bounded labels for all signals. The dashboards group failures by a fixed operation, reason, outcome, stage, or destination.
-| Failure mode | Primary signal | Dashboard or alert | Response |
-| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
-| The 20-second pass budget is too short. | `ml_image_fetch_republished_total{reason="pass_deadline"}` divided by completed URLs plus all republishes | Fetch dashboard: **Pass deadline deferral rate**. Alert: `IngestionSessionReplayImageFetchPassDeadlineSaturated`. | Increase capacity first. Increase the pass budget only if active batch age keeps enough margin below Kafka's 300-second poll limit. |
-| A fetch batch approaches Kafka's 300-second poll limit. | Active batch age exceeds 180 seconds. Completed batch duration shows the recent distribution. | Fetch dashboard: **Poll batch duration**. Alert: `IngestionSessionReplayImageFetchBatchNearPollLimit`. | Check store latency and request scheduling. Scale the lane before changing the pass budget. |
-| The fetch lane cannot drain its frontier topic. | Frontier lag exceeds 1,000 records and stays flat or projects more than 10% growth in one hour. | Fetch dashboard: Kafka lag and drain time. Alert: `IngestionSessionReplayImageFetchNotDraining`. | Check consumer members, pod capacity, request waits, and deadline deferrals. |
-| 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. |
-| 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. |
-| One origin, one registrable domain, or the pod reaches request capacity. | Scheduler wait time by `origin_crawl_delay`, `registrable_domain_rate`, or `request_capacity`, requests in flight, deadline deferrals, and `not_ready` republishes increase. | Fetch dashboard: request capacity, scheduler waits, origin policy, registrable-domain state, request outcomes, and republishes. | Scale pods for pod saturation. Check the exact wait scope before changing an origin or registrable-domain control. |
-| 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. |
-| The fetch consumer rejects frontier input. | `ml_image_fetch_consumer_dropped_total` increases by a bounded reason. The consumer commits and drops those jobs. | Fetch dashboard: **URLs refused**. Alert: `IngestionSessionReplayImageFetchInputRejected`. | Check the mirror and fetch versions and the frontier record schema. |
-| A retry worker shuts down during a deliberate wait. | `ml_image_fetch_retry_released_total{outcome="abandoned"}` increases. The consumer does not commit that offset. | Fetch dashboard only. This expected shutdown outcome does not alert. | Check pod lifecycle only if the rate does not match a rollout or scale-down. |
-| The scrub sidecar is saturated or unreachable. | Scrub waits increase by `busy`, `timeout`, or `transport`. | Scrub dashboard: scrub waits and sidecar pressure. Alert: `IngestionSessionReplayImageScrubSidecarUnreachable`. | Scale for `busy`. Check CPU for `timeout`. Check pod health for `transport`. |
-| The scrub consumer rejects input. | `ml_mirror_image_scrub_consumer_invalid_key_total` increases. The consumer commits and drops the record. | Scrub dashboard: invalid-key events. Alert: `IngestionSessionReplayImageScrubInputRejected`. | Check the fetch and scrub versions, the content-ref format, and the scrub topic. |
-| One image blocks later offsets. | Stuck-image events increase, batch retired ratio falls, or batch duration approaches 300 seconds. | Scrub dashboard: batch progress, batch duration, and quarantine events. | Find the image ref in logs. Check if dead-letter publication succeeds. |
-| Scrub output cannot reach S3 or the dead-letter topic. | A write batch failure or dead-letter publication failure occurs. Durable error logs cover a pod that exits before a metrics scrape. | Scrub dashboard: consumer delivery failures. Loki alerts: `IngestionSessionReplayImageScrubConsumerLoopFailed` and `IngestionSessionReplayImageScrubDeadLetterPublishFailed`. | Check bucket access, topic configuration, and maximum Kafka message size. |
-| A dead-letter replay cannot recover an image. | The replay emits `image_scrub_replay_exhausted`. The process metric is also visible if a scrape catches the bounded replay run. | Scrub dashboard: quarantine events. Loki alert: `IngestionSessionReplayImageScrubReplayExhausted`. | Fix or accept the permanent sidecar refusal before Kafka retention removes the parked bytes. |
-| A scrub batch approaches Kafka's 300-second poll limit. | Active batch age exceeds 180 seconds. Completed batch duration shows the recent distribution. | Scrub dashboard: **Image and batch duration**. Alert: `IngestionSessionReplayImageScrubBatchNearPollLimit`. | Check the retired ratio, stuck images, waits, CPU, and memory. |
-| The scrub lane cannot drain. | Scrub frontier lag exceeds 1,000 records and stays flat or projects more than 10% growth in one hour. | Scrub dashboard: Kafka lag and drain time. Alert: `IngestionSessionReplayImageScrubNotDraining`. | Check waits, head-of-line blocking, CPU, memory, and consumer restarts. |
+| Failure mode | Primary signal | Dashboard or alert | Response |
+| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| The 40-second pass budget is too short. | `ml_image_fetch_republished_total{reason="pass_deadline"}` divided by completed URLs plus all republishes | Fetch dashboard: **Pass deadline deferral rate**. Alert: `IngestionSessionReplayImageFetchPassDeadlineSaturated`. | Increase capacity first. Increase the pass budget only if active batch age keeps enough margin below Kafka's 300-second poll limit. |
+| A fetch batch approaches Kafka's 300-second poll limit. | Active batch age exceeds 180 seconds. Completed batch duration shows the recent distribution. | Fetch dashboard: **Poll batch duration**. Alert: `IngestionSessionReplayImageFetchBatchNearPollLimit`. | Check store latency and request scheduling. Scale the lane before changing the pass budget. |
+| The fetch lane cannot drain its frontier topic. | Frontier lag exceeds 1,000 records and stays flat or projects more than 10% growth in one hour. | Fetch dashboard: Kafka lag and drain time. Alert: `IngestionSessionReplayImageFetchNotDraining`. | Check consumer members, pod capacity, request waits, and deadline deferrals. |
+| 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. |
+| 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. |
+| The fetch consumer rejects frontier input. | `ml_image_fetch_consumer_dropped_total` increases by a bounded reason. The consumer commits and drops those jobs. | Fetch dashboard: **URLs refused**. Alert: `IngestionSessionReplayImageFetchInputRejected`. | Check the mirror and fetch versions and the frontier record schema. |
+| A retry worker shuts down during a deliberate wait. | `ml_image_fetch_retry_released_total{outcome="abandoned"}` increases. The consumer does not commit that offset. | Fetch dashboard only. This expected shutdown outcome does not alert. | Check pod lifecycle only if the rate does not match a rollout or scale-down. |
+| The scrub sidecar is saturated or unreachable. | Scrub waits increase by `busy`, `timeout`, or `transport`. | Scrub dashboard: scrub waits and sidecar pressure. Alert: `IngestionSessionReplayImageScrubSidecarUnreachable`. | Scale for `busy`. Check CPU for `timeout`. Check pod health for `transport`. |
+| The scrub consumer rejects input. | `ml_mirror_image_scrub_consumer_invalid_key_total` increases. The consumer commits and drops the record. | Scrub dashboard: invalid-key events. Alert: `IngestionSessionReplayImageScrubInputRejected`. | Check the fetch and scrub versions, the content-ref format, and the scrub topic. |
+| One image blocks later offsets. | Stuck-image events increase, batch retired ratio falls, or batch duration approaches 300 seconds. | Scrub dashboard: batch progress, batch duration, and quarantine events. | Find the image ref in logs. Check if dead-letter publication succeeds. |
+| Scrub output cannot reach S3 or the dead-letter topic. | A write batch failure or dead-letter publication failure occurs. Durable error logs cover a pod that exits before a metrics scrape. | Scrub dashboard: consumer delivery failures. Loki alerts: `IngestionSessionReplayImageScrubConsumerLoopFailed` and `IngestionSessionReplayImageScrubDeadLetterPublishFailed`. | Check bucket access, topic configuration, and maximum Kafka message size. |
+| A dead-letter replay cannot recover an image. | The replay emits `image_scrub_replay_exhausted`. The process metric is also visible if a scrape catches the bounded replay run. | Scrub dashboard: quarantine events. Loki alert: `IngestionSessionReplayImageScrubReplayExhausted`. | Fix or accept the permanent sidecar refusal before Kafka retention removes the parked bytes. |
+| A scrub batch approaches Kafka's 300-second poll limit. | Active batch age exceeds 180 seconds. Completed batch duration shows the recent distribution. | Scrub dashboard: **Image and batch duration**. Alert: `IngestionSessionReplayImageScrubBatchNearPollLimit`. | Check the retired ratio, stuck images, waits, CPU, and memory. |
+| The scrub lane cannot drain. | Scrub frontier lag exceeds 1,000 records and stays flat or projects more than 10% growth in one hour. | Scrub dashboard: Kafka lag and drain time. Alert: `IngestionSessionReplayImageScrubNotDraining`. | Check waits, head-of-line blocking, CPU, memory, and consumer restarts. |
The pass-budget alert is inactive in dry-run mode. Delay-topic lag has no alert because queued delay records are expected. Generic Kubernetes alerts cover pod crash loops and unavailable replicas.
@@ -126,7 +133,7 @@ The implementation has four product-behavior or interface deltas from the origin
The implementation also has these rollout and repository-state deltas. They do not change steady-state fetch behavior.
-- The 20-second pass is shorter than the first retry delay. Therefore, retries use the durable delay topic and do not use an in-memory second pass.
+- The 40-second pass and its 50-second worst-case wall time are shorter than the first retry delay. Therefore, retries use the durable delay topic and do not use an in-memory second pass.
- Fetch and retry ApplicationSet synchronization stays manual until the cross-repository dependencies are active.
- The base charts change keeps `SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN` set to `true` and `SESSION_RECORDING_ML_URL_PRODUCER_ENABLED` set to `false`.
- The first activation charts change clears fetch dry-run only after every consumer and infrastructure dependency is active.
@@ -137,6 +144,8 @@ 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.
+
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.
3. Deploy the scrubber changes and the ML data-preparation resolver.
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 6b44c8321dd5..b5aa1b92f01d 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
@@ -250,8 +250,8 @@ key at `https://us.posthog.com/.well-known/http-message-signatures-directory`, a
| Redirects followed without republishing | one fetch | 3 |
| Response bytes, compressed | one response | 20 MiB |
| Request timeout | one URL, redirects included | 10 seconds |
-| Pass deadline | one pass | 20 seconds |
-| Pass wall time, worst case | one pass | 30 seconds |
+| Pass deadline | one pass | 40 seconds |
+| Pass wall time, worst case | one pass | 50 seconds |
| Registrable domains tracked | pod | 20,000 |
| Origins tracked | pod | 20,000 |
| Crawl history entry | one URL | 30 days |
@@ -376,7 +376,7 @@ built from a redirect target matches no recording.
**10.3** The consumer completes durable work in this order:
-1. It publishes any image or delayed retry to its destination Kafka topic and waits for the delivery acknowledgement.
+1. It publishes each image and every frontier or delay record to its destination Kafka topic and waits for the delivery acknowledgement.
2. It writes all required crawl-history changes to DynamoDB.
3. It returns from the batch so that the input fetch-topic offset can be stored.
@@ -386,7 +386,7 @@ A terminal refusal has no destination Kafka record, so it starts at step 2. A de
```json
{
- "v": 1,
+ "v": 2,
"jobs": [
{
"originalRef": "imageurl:<hash>",
@@ -402,7 +402,7 @@ A terminal refusal has no destination Kafka record, so it starts at step 2. A de
}
```
-`v` is the integer `1`. `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`. `jobs` contains 1 to 1,000 entries, and the decoded JSON record cannot exceed 512 KiB. `originalRef` is the ref calculated for the URL first seen in the replay. `currentUrl` is the next URL to request after any redirects. `remainingHops`, `notBeforeMs`, `firstSeenAtMs`, `fetchCount`, and `republishCount` are non-negative safe integers. `firstSeenAtMs` is the Unix time when the producer first collected the URL. `fetchCount` counts image HTTP requests, and `republishCount` counts frontier and delay-topic republishes. `lastRepublishReason` is `null`, `redirect`, `retry`, `not_ready`, `pass_deadline`, `origin_map_full`, or `registrable_domain_map_full`.
The parser 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.
@@ -411,6 +411,12 @@ The parser ignores unknown fields so that a producer can add optional data witho
**10.6** A systematic error like not being able to reach Kafka or DynamoDB should throw. We should not drop messages in
that scenario.
+**10.7** A redirect 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.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.
+
+A fetch batch can publish more frontier records than it consumed. This can occur when URLs from one source-domain record redirect to several target registrable domains. It can also occur when the added durable state makes a republished record reach a wire limit earlier than its input record. The lane must preserve those target-domain keys and wire limits. It must not send a zero-wait redirect to a delay topic only to keep the record count unchanged.
+
### 11. Metrics
**11.1** These metrics are tracked for each completed URL
@@ -435,11 +441,13 @@ that scenario.
**11.5** The provider domain is the effective top-level domain plus one when only the ICANN section is active. For example, it is `posthog.com` for `app.posthog.com` and `vercel.app` for `myapp.vercel.app`. This document does not use the ambiguous term `root domain`.
-**11.6** Every metric label defined by this lane uses a fixed set of values. HTTP responses use `2xx`, `3xx`, `4xx`, `5xx`, or `other`. Republish destinations use `frontier` or `delay`. Unexpected scrub source formats use `other`. No label defined by this lane contains a registrable domain, provider domain, origin, host, URL, image ref, team, project, Kafka topic, exception message, or other external value.
+**11.6** Every metric label defined by this lane uses a fixed set of values. HTTP responses use `2xx`, `3xx`, `4xx`, `5xx`, or `other`. Republish destination classes use `frontier` or `delay`. Republish topic classes use `frontier`, `retry_1m`, `retry_10m`, or `retry_1h`. Unexpected scrub source formats use `other`. No label defined by this lane contains a configured Kafka topic name, registrable domain, provider domain, origin, host, URL, image ref, team, project, exception message, or other external value.
+
+**11.7** The lane counts republished URLs by reason and bounded destination class. For each used topic class in a fetch batch, it observes the number of Kafka record delivery attempts, the number of attempted registrable-domain keys, and the wall time from topic-class scheduling until all started delivery attempts settle. It also observes total republish flush wall time and counts batches that reached the republish finalization deadline.
-**11.7** The lane counts republishes by reason and bounded destination class. 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.
+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, 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. 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/fetch-runner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
index a742f8e545c1..c94829da5260 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,7 +5,6 @@ import { DELAY_TOO_LONG, FetchRunner, FetchRunnerOptions, HOPS_EXHAUSTED } from
import { 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_000
@@ -48,7 +47,7 @@ interface Harness {
function build(
result: Partial<ImageFetchResult> = {},
policy: Partial<OriginPolicyDecision> = {},
- republishResult: RepublishResult = 'published',
+ republishResult: RepublishResult = 'queued',
options: FetchRunnerOptions = OPTIONS
): Harness {
const fetch = jest.fn((url: string, _options: ImageFetchOptions) =>
@@ -66,6 +65,7 @@ function build(
)
const createPass = jest.fn(() => ({ check }))
const republish = jest.fn(() => Promise.resolve(republishResult))
+ const createRepublishBatch = jest.fn(() => ({ republish, flush: () => Promise.resolve({ failedUrls: 0 }) }))
const publishImage = jest.fn(() => Promise.resolve())
const scheduler = {
runImage: async (_url: URL, _deadlineMs: number, request: () => Promise<ImageFetchResult>) => ({
@@ -91,7 +91,7 @@ function build(
scheduler,
{ createPass } as unknown as ConfigurationPolicyService,
options,
- { republish, publishImage } as unknown as FrontierPublisher
+ { createRepublishBatch, publishImage } as unknown as FrontierPublisher
)
return { runner, fetch, check, createPass, republish, publishImage }
}
@@ -153,7 +153,7 @@ describe('FetchRunner', () => {
})
it('uses one worker limit across sibling origins', async () => {
- const harness = build({}, {}, 'published', { ...OPTIONS, maxConcurrentPerRegistrableDomain: 1 })
+ const harness = build({}, {}, 'queued', { ...OPTIONS, maxConcurrentPerRegistrableDomain: 1 })
let releaseFirst: (() => void) | undefined
harness.fetch.mockImplementationOnce(
(url: string) =>
@@ -180,7 +180,7 @@ describe('FetchRunner', () => {
})
it('does not let one origin occupy every registrable-domain worker', async () => {
- const harness = build({}, {}, 'published', { ...OPTIONS, maxConcurrentPerRegistrableDomain: 2 })
+ const harness = build({}, {}, 'queued', { ...OPTIONS, maxConcurrentPerRegistrableDomain: 2 })
let releaseFirst: (() => void) | undefined
let releaseSecond: (() => void) | undefined
harness.fetch
@@ -261,8 +261,6 @@ describe('FetchRunner', () => {
currentUrl: 'https://cdn.example.com/final.png',
retryAfterMs: 120_000,
})
- const retryCause = jest.spyOn(ImageFetchRequestMetrics, 'incRetryCause').mockImplementation()
-
const [attempt] = await harness.runner.run([candidate()], new Map())
expect(harness.republish).toHaveBeenCalledWith(
@@ -275,7 +273,6 @@ describe('FetchRunner', () => {
'retry',
120_000
)
- expect(retryCause).toHaveBeenCalledWith('server_error')
expect(attempt).toMatchObject({ outcome: 'server_error', finished: false })
})
@@ -357,6 +354,14 @@ describe('FetchRunner', () => {
expect(harness.republish).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), 'not_ready', 600_000)
})
+ it('returns pass-deadline work directly to the frontier', async () => {
+ const harness = build({}, {}, 'queued', { ...OPTIONS, batchBudgetMs: -1 })
+
+ await harness.runner.run([candidate()], new Map())
+
+ expect(harness.republish).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), 'pass_deadline', 0)
+ })
+
it('finishes a retry when its last hop was the failed request', async () => {
const harness = build({ outcome: 'timeout' })
@@ -376,23 +381,10 @@ describe('FetchRunner', () => {
expect(attempt).toMatchObject({ outcome: HOPS_EXHAUSTED, finished: true })
})
- it('marks a failed republish as lost so the Kafka batch cannot commit', async () => {
- const harness = build({ outcome: 'timeout' }, {}, 'failed')
- const retryCause = jest.spyOn(ImageFetchRequestMetrics, 'incRetryCause').mockImplementation()
-
- const [attempt] = await harness.runner.run([candidate()], new Map())
-
- expect(retryCause).not.toHaveBeenCalled()
- expect(attempt).toMatchObject({ outcome: 'timeout', finished: false, lost: true })
- })
-
it('records a terminal refusal when no delay topic can hold the wait', async () => {
const harness = build({ outcome: 'timeout' }, {}, 'refused_delay')
- const retryCause = jest.spyOn(ImageFetchRequestMetrics, 'incRetryCause').mockImplementation()
-
const [attempt] = await harness.runner.run([candidate()], new Map())
- expect(retryCause).not.toHaveBeenCalled()
expect(attempt).toMatchObject({ outcome: DELAY_TOO_LONG, finished: true })
})
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 ab16743af35d..0017d318fabf 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,7 +8,7 @@ import {
explicitFreshnessLifetimeMs,
} from './configuration-policy'
import { ConfigurationCacheItem, CrawlHistoryItem, HttpCacheMetadata, UrlCrawlHistoryItem } from './crawl-history'
-import { FrontierPublisher, RepublishResult } from './frontier-publisher'
+import { FrontierPublisher, RepublishBatch, RepublishResult } from './frontier-publisher'
import { HostBudget } from './host-budget'
import {
FetchOutcome,
@@ -67,7 +67,7 @@ function requirePositive(name: string, value: number): void {
}
}
-function isTransientOutcome(outcome: FetchOutcome): outcome is TransientFetchOutcome {
+export function isTransientOutcome(outcome: AttemptOutcome): outcome is TransientFetchOutcome {
return TRANSIENT_OUTCOMES.has(outcome as TransientFetchOutcome)
}
@@ -78,7 +78,11 @@ function isRequestStateFull(
}
export interface FetchPass {
- run(candidates: FetchCandidate[], stored: Map<string, CrawlHistoryItem>): Promise<FetchAttempt[]>
+ run(
+ candidates: FetchCandidate[],
+ stored: Map<string, CrawlHistoryItem>,
+ republishBatch?: RepublishBatch
+ ): Promise<FetchAttempt[]>
}
export class FetchRunner implements FetchPass {
@@ -107,7 +111,12 @@ export class FetchRunner implements FetchPass {
ImageFetchRequestMetrics.trackBudget(budget, scheduler)
}
- public async run(candidates: FetchCandidate[], stored: Map<string, CrawlHistoryItem>): Promise<FetchAttempt[]> {
+ public async run(
+ candidates: FetchCandidate[],
+ stored: Map<string, CrawlHistoryItem>,
+ republishBatch?: RepublishBatch
+ ): Promise<FetchAttempt[]> {
+ const activeRepublishBatch = republishBatch ?? this.publisher.createRepublishBatch()
const deadlineMs = Date.now() + this.options.batchBudgetMs
const configurationPolicy = this.configurationPolicy.createPass()
const configurationItems = new Map<string, ConfigurationCacheItem>()
@@ -134,7 +143,8 @@ export class FetchRunner implements FetchPass {
configurationItems,
configurationPolicy,
deadlineMs,
- attempts
+ attempts,
+ activeRepublishBatch
)
)
const settledRegistrableDomains = await Promise.allSettled(registrableDomainRuns)
@@ -144,6 +154,12 @@ export class FetchRunner implements FetchPass {
if (failedRegistrableDomain) {
throw failedRegistrableDomain.reason
}
+ if (!republishBatch) {
+ const result = await activeRepublishBatch.flush()
+ if (result.failedUrls > 0) {
+ throw new Error(`the image fetch lane could not account for ${result.failedUrls} URLs`)
+ }
+ }
this.logFailures(attempts)
return attempts
}
@@ -155,7 +171,8 @@ export class FetchRunner implements FetchPass {
configurationItems: Map<string, ConfigurationCacheItem>,
configurationPolicy: ConfigurationPolicyPass,
deadlineMs: number,
- attempts: FetchAttempt[]
+ attempts: FetchAttempt[],
+ republishBatch: RepublishBatch
): Promise<void> {
const byOrigin = new Map<string, FetchCandidate[]>()
for (const candidate of queue) {
@@ -174,7 +191,7 @@ export class FetchRunner implements FetchPass {
continue
}
if (Date.now() > deadlineMs) {
- attempts.push(await this.republish(candidate, 'deadline', 'pass_deadline', ONE_MINUTE_MS, []))
+ attempts.push(await this.republish(republishBatch, candidate, 'deadline', 'pass_deadline', 0, []))
continue
}
attempts.push(
@@ -185,14 +202,22 @@ export class FetchRunner implements FetchPass {
debugTag: registrableDomain,
fn: () => {
if (Date.now() > deadlineMs) {
- return this.republish(candidate, 'deadline', 'pass_deadline', ONE_MINUTE_MS, [])
+ return this.republish(
+ republishBatch,
+ candidate,
+ 'deadline',
+ 'pass_deadline',
+ 0,
+ []
+ )
}
return this.fetchOne(
candidate,
stored,
configurationItems,
configurationPolicy,
- deadlineMs
+ deadlineMs,
+ republishBatch
)
},
}),
@@ -214,7 +239,8 @@ export class FetchRunner implements FetchPass {
stored: Map<string, CrawlHistoryItem>,
configurationItems: Map<string, ConfigurationCacheItem>,
configurationPolicy: ConfigurationPolicyPass,
- deadlineMs: number
+ deadlineMs: number,
+ republishBatch: RepublishBatch
): Promise<FetchAttempt> {
if (candidate.remainingHops === 0) {
return this.terminal(candidate, HOPS_EXHAUSTED, undefined, [])
@@ -229,6 +255,7 @@ export class FetchRunner implements FetchPass {
if (policy.transient) {
if (isRequestStateFull(policy.reason)) {
return await this.republish(
+ republishBatch,
candidate,
policy.reason,
policy.reason,
@@ -237,7 +264,14 @@ export class FetchRunner implements FetchPass {
)
}
const waitMs = policy.reason === 'configuration_unreachable' ? CONFIGURATION_RETRY_MS : ONE_MINUTE_MS
- return await this.republish(candidate, 'backoff', 'not_ready', waitMs, configurationUpdates)
+ return await this.republish(
+ republishBatch,
+ candidate,
+ 'backoff',
+ 'not_ready',
+ waitMs,
+ configurationUpdates
+ )
}
return this.terminal(
candidate,
@@ -250,6 +284,7 @@ export class FetchRunner implements FetchPass {
if (!this.budget.setCrawlDelay(candidate.origin, policy.crawlDelayMs, Date.now())) {
ImageFetchRequestMetrics.observePolicyAndBudgetDecision(true, 'origin_map_full')
return await this.republish(
+ republishBatch,
candidate,
'origin_map_full',
'origin_map_full',
@@ -319,7 +354,14 @@ export class FetchRunner implements FetchPass {
const stateFull = isRequestStateFull(reason)
const republishReason: RepublishReason = stateFull ? reason : 'not_ready'
const waitMs = reason === 'configuration_unreachable' ? CONFIGURATION_RETRY_MS : ONE_MINUTE_MS
- return await this.republish(attemptedCandidate, reason, republishReason, waitMs, configurationUpdates)
+ return await this.republish(
+ republishBatch,
+ attemptedCandidate,
+ reason,
+ republishReason,
+ waitMs,
+ configurationUpdates
+ )
}
return this.terminal(attemptedCandidate, reason, undefined, configurationUpdates, reason)
}
@@ -332,11 +374,22 @@ export class FetchRunner implements FetchPass {
: reason === 'deadline' && Date.now() >= deadlineMs
? 'pass_deadline'
: 'not_ready'
- const waitMs = Math.max(
- ONE_MINUTE_MS,
- result.schedulingWaitMs ?? this.budget.blockedForMs(attemptedCandidate.registrableDomain, Date.now())
+ const waitMs =
+ republishReason === 'pass_deadline'
+ ? 0
+ : Math.max(
+ ONE_MINUTE_MS,
+ result.schedulingWaitMs ??
+ this.budget.blockedForMs(attemptedCandidate.registrableDomain, Date.now())
+ )
+ return await this.republish(
+ republishBatch,
+ attemptedCandidate,
+ reason,
+ republishReason,
+ waitMs,
+ configurationUpdates
)
- return await this.republish(attemptedCandidate, reason, republishReason, waitMs, configurationUpdates)
}
ImageFetchRequestMetrics.observePolicyAndBudgetDecision(false)
@@ -348,15 +401,13 @@ export class FetchRunner implements FetchPass {
result.retryAfterMs
)
const attempt = await this.republish(
+ republishBatch,
attemptedCandidate,
result.outcome,
'retry',
delayMs,
configurationUpdates
)
- if (!attempt.finished && !attempt.lost) {
- ImageFetchRequestMetrics.incRetryCause(result.outcome)
- }
return attempt
}
@@ -370,6 +421,7 @@ export class FetchRunner implements FetchPass {
return this.terminal(attemptedCandidate, 'bad_redirect', result.cache, configurationUpdates)
}
return await this.republishToTarget(
+ republishBatch,
attemptedCandidate,
result.outcome,
{
@@ -409,6 +461,7 @@ export class FetchRunner implements FetchPass {
}
private async republish(
+ republishBatch: RepublishBatch,
candidate: FetchCandidate,
outcome: AttemptOutcome,
reason: RepublishReason,
@@ -416,6 +469,7 @@ export class FetchRunner implements FetchPass {
configurationUpdates: ConfigurationCacheItem[]
): Promise<FetchAttempt> {
return await this.republishToTarget(
+ republishBatch,
candidate,
outcome,
{
@@ -431,6 +485,7 @@ export class FetchRunner implements FetchPass {
}
private async republishToTarget(
+ republishBatch: RepublishBatch,
candidate: FetchCandidate,
outcome: AttemptOutcome,
target: Pick<FetchCandidate, 'currentUrl' | 'host' | 'origin' | 'registrableDomain'>,
@@ -441,7 +496,7 @@ export class FetchRunner implements FetchPass {
if ((reason === 'redirect' || reason === 'retry') && candidate.remainingHops <= 1) {
return this.terminal(candidate, HOPS_EXHAUSTED, undefined, configurationUpdates)
}
- const result: RepublishResult = await this.publisher.republish(candidate, target, reason, waitMs)
+ const result: RepublishResult = await republishBatch.republish(candidate, target, reason, waitMs)
if (result === 'refused_delay') {
return this.terminal(candidate, DELAY_TOO_LONG, undefined, configurationUpdates)
}
@@ -449,7 +504,7 @@ export class FetchRunner implements FetchPass {
candidate,
outcome,
finished: false,
- lost: result === 'failed',
+ lost: false,
configurationUpdates,
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
index 575ecdd55733..158fd56bb3a7 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
@@ -1,16 +1,23 @@
import { KafkaProducerWrapper } from '~/common/kafka/producer'
+import { parseJSON } from '~/common/utils/json-parse'
-import { FetchCandidate, MAX_HOPS, parseCollectedUrlsRecord } from './collected-urls-record'
-import { FrontierPublisher } from './frontier-publisher'
+import {
+ FetchCandidate,
+ MAX_HOPS,
+ MAX_JOBS_PER_RECORD,
+ MAX_RECORD_BYTES,
+ parseCollectedUrlsRecord,
+} from './collected-urls-record'
+import { FrontierPublisher, RepublishBatch } from './frontier-publisher'
import { ImageFetchResult } from './image-fetcher'
import { ImageFetchRequestMetrics } from './metrics'
const FRONTIER = 'session_replay_image_fetch'
const SCRUB = 'session_replay_image_scrub'
const TIERS = [
- { topic: 'retry_1m', delayMs: 60_000 },
- { topic: 'retry_10m', delayMs: 600_000 },
- { topic: 'retry_1h', delayMs: 3_600_000 },
+ { topic: 'retry_1m', delayMs: 60_000, metricTopic: 'retry_1m' as const },
+ { topic: 'retry_10m', delayMs: 600_000, metricTopic: 'retry_10m' as const },
+ { topic: 'retry_1h', delayMs: 3_600_000, metricTopic: 'retry_1h' as const },
]
function candidate(overrides: Partial<FetchCandidate> = {}): FetchCandidate {
@@ -37,7 +44,11 @@ interface SentMessage {
headers?: Record<string, string>
}
-function build(): { publisher: FrontierPublisher; sent: SentMessage[] } {
+function build(): {
+ publisher: FrontierPublisher
+ batch: RepublishBatch
+ sent: SentMessage[]
+} {
const sent: SentMessage[] = []
const producer = {
produce: (message: { topic: string; key: Buffer; value: Buffer; headers?: Record<string, string> }) => {
@@ -45,15 +56,14 @@ function build(): { publisher: FrontierPublisher; sent: SentMessage[] } {
return Promise.resolve()
},
} as unknown as KafkaProducerWrapper
- return {
- publisher: new FrontierPublisher(producer, {
- frontierTopic: FRONTIER,
- scrubTopic: SCRUB,
- delayTiers: TIERS,
- maxConcurrentImagePublishes: 2,
- }),
- sent,
- }
+ const publisher = new FrontierPublisher(producer, {
+ frontierTopic: FRONTIER,
+ scrubTopic: SCRUB,
+ delayTiers: TIERS,
+ maxConcurrentImagePublishes: 2,
+ maxConcurrentRepublishes: 2,
+ })
+ return { publisher, batch: publisher.createRepublishBatch(), sent }
}
describe('FrontierPublisher', () => {
@@ -63,22 +73,25 @@ describe('FrontierPublisher', () => {
jest.restoreAllMocks()
})
- it('keeps the global ref and durable state when it republishes a redirect', async () => {
- const { publisher, sent } = build()
+ it('groups frontier redirects by target registrable domain', async () => {
+ const { batch, sent } = build()
const republished = jest.spyOn(ImageFetchRequestMetrics, 'incRepublished').mockImplementation()
- const result = await publisher.republish(
- candidate(),
- {
- currentUrl: 'https://img.other.net/a.png',
- host: 'img.other.net',
- origin: 'https://img.other.net',
- registrableDomain: 'other.net',
- },
- 'redirect'
- )
+ const target = {
+ currentUrl: 'https://img.other.net/a.png',
+ host: 'img.other.net',
+ origin: 'https://img.other.net',
+ registrableDomain: 'other.net',
+ }
+
+ expect(await batch.republish(candidate(), target, 'redirect')).toBe('queued')
+ expect(
+ await batch.republish(candidate({ originalRef: `imageurl:${'b'.repeat(22)}` }), target, 'redirect')
+ ).toBe('queued')
+ expect(sent).toEqual([])
+ await expect(batch.flush()).resolves.toEqual({ failedUrls: 0 })
- expect(result).toBe('published')
- expect(republished).toHaveBeenCalledWith('redirect', 'frontier')
+ expect(republished).toHaveBeenCalledTimes(2)
+ expect(sent).toHaveLength(1)
expect(sent[0]).toMatchObject({ topic: FRONTIER, key: 'other.net' })
expect(parseCollectedUrlsRecord(sent[0].value, 'other.net')).toMatchObject({
ok: true,
@@ -90,6 +103,7 @@ describe('FrontierPublisher', () => {
republishCount: 1,
lastRepublishReason: 'redirect',
},
+ { originalRef: `imageurl:${'b'.repeat(22)}` },
],
})
})
@@ -100,10 +114,12 @@ describe('FrontierPublisher', () => {
['a medium retry', 120_000, 'retry_10m', 600_000],
['a long supported retry', 3_600_000, 'retry_1h', 3_600_000],
])('parks %s once in the smallest sufficient delay topic', async (_name, waitMs, topic, delayMs) => {
- const { publisher, sent } = build()
+ const { batch, sent } = build()
const republished = jest.spyOn(ImageFetchRequestMetrics, 'incRepublished').mockImplementation()
- expect(await publisher.republish(candidate(), candidate(), 'retry', waitMs)).toBe('published')
+ expect(await batch.republish(candidate(), candidate(), 'retry', waitMs)).toBe('queued')
+ await batch.flush()
+
expect(republished).toHaveBeenCalledWith('retry', 'delay')
expect(sent[0].topic).toBe(topic)
expect(parseCollectedUrlsRecord(sent[0].value, 'example.com')).toMatchObject({
@@ -112,32 +128,280 @@ describe('FrontierPublisher', () => {
})
})
+ it('groups delayed jobs by destination topic and registrable domain', async () => {
+ const { batch, sent } = build()
+ const second = candidate({ originalRef: `imageurl:${'b'.repeat(22)}` })
+ const other = candidate({
+ originalRef: `imageurl:${'c'.repeat(22)}`,
+ currentUrl: 'https://img.other.net/c.png',
+ host: 'img.other.net',
+ origin: 'https://img.other.net',
+ registrableDomain: 'other.net',
+ })
+
+ await batch.republish(candidate(), candidate(), 'retry', 30_000)
+ await batch.republish(second, second, 'not_ready', 30_000)
+ await batch.republish(other, other, 'retry', 30_000)
+ await batch.flush()
+
+ expect(sent).toHaveLength(2)
+ const example = sent.find((item) => item.key === 'example.com')!
+ expect(example.topic).toBe('retry_1m')
+ expect(parseCollectedUrlsRecord(example.value, 'example.com')).toMatchObject({
+ ok: true,
+ candidates: [{ originalRef: candidate().originalRef }, { originalRef: second.originalRef }],
+ })
+ })
+
+ it('keeps configured destination topics separate when they share a metric class', async () => {
+ const sent: SentMessage[] = []
+ const producer = {
+ produce: (message: { topic: string; key: Buffer; value: Buffer }) => {
+ sent.push({ ...message, key: message.key.toString() })
+ return Promise.resolve()
+ },
+ } as unknown as KafkaProducerWrapper
+ const publisher = new FrontierPublisher(producer, {
+ frontierTopic: FRONTIER,
+ scrubTopic: SCRUB,
+ delayTiers: [
+ { topic: 'short', delayMs: 60_000, metricTopic: 'retry_1m' },
+ { topic: 'long', delayMs: 120_000, metricTopic: 'retry_1m' },
+ ],
+ maxConcurrentImagePublishes: 2,
+ maxConcurrentRepublishes: 2,
+ })
+ const batch = publisher.createRepublishBatch()
+
+ await batch.republish(candidate(), candidate(), 'not_ready', 30_000)
+ await batch.republish(
+ candidate({ originalRef: `imageurl:${'b'.repeat(22)}` }),
+ candidate(),
+ 'not_ready',
+ 90_000
+ )
+ await batch.flush()
+
+ expect(sent.map((message) => message.topic).sort()).toEqual(['long', 'short'])
+ })
+
+ it('records messages, registrable domains, and delivery time for each destination topic', async () => {
+ const { batch } = build()
+ const observeRepublishBatch = jest.spyOn(ImageFetchRequestMetrics, 'observeRepublishBatch').mockImplementation()
+ const observeRepublishFlush = jest.spyOn(ImageFetchRequestMetrics, 'observeRepublishFlush').mockImplementation()
+ const other = candidate({
+ originalRef: `imageurl:${'b'.repeat(22)}`,
+ currentUrl: 'https://img.other.net/b.png',
+ host: 'img.other.net',
+ origin: 'https://img.other.net',
+ registrableDomain: 'other.net',
+ })
+
+ await batch.republish(candidate(), candidate(), 'pass_deadline')
+ await batch.republish(other, other, 'retry', 30_000)
+ await batch.flush()
+
+ expect(observeRepublishBatch).toHaveBeenCalledWith('frontier', 1, 1, expect.any(Number))
+ expect(observeRepublishBatch).toHaveBeenCalledWith('retry_1m', 1, 1, expect.any(Number))
+ expect(observeRepublishFlush).toHaveBeenCalledWith(expect.any(Number))
+ })
+
+ it('splits one registrable domain at the job-count limit', async () => {
+ const { batch, sent } = build()
+ const candidates = Array.from({ length: MAX_JOBS_PER_RECORD + 1 }, (_, index) =>
+ candidate({ originalRef: `imageurl:${index.toString().padStart(22, '0')}` })
+ )
+
+ await Promise.all(candidates.map((item) => batch.republish(item, item, 'pass_deadline')))
+ await batch.flush()
+
+ expect(sent).toHaveLength(2)
+ expect(sent.map((item) => (parseJSON(item.value.toString()) as { jobs: unknown[] }).jobs.length)).toEqual([
+ MAX_JOBS_PER_RECORD,
+ 1,
+ ])
+ })
+
+ it('splits one registrable domain at the serialized-byte limit', async () => {
+ const { batch, sent } = build()
+ const longPath = 'a'.repeat(Math.floor(MAX_RECORD_BYTES / 2))
+ const first = candidate({ currentUrl: `https://cdn.example.com/${longPath}/1.png` })
+ const second = candidate({
+ originalRef: `imageurl:${'b'.repeat(22)}`,
+ currentUrl: `https://cdn.example.com/${longPath}/2.png`,
+ })
+
+ await batch.republish(first, first, 'pass_deadline')
+ await batch.republish(second, second, 'pass_deadline')
+ await batch.flush()
+
+ expect(sent).toHaveLength(2)
+ expect(sent.every((item) => item.value.length <= MAX_RECORD_BYTES)).toBe(true)
+ })
+
it('refuses a delay longer than the largest deployed tier', async () => {
- const { publisher, sent } = build()
+ const { batch, sent } = build()
- expect(await publisher.republish(candidate(), candidate(), 'retry', 3_600_001)).toBe('refused_delay')
+ expect(await batch.republish(candidate(), candidate(), 'retry', 3_600_001)).toBe('refused_delay')
+ await batch.flush()
expect(sent).toEqual([])
})
it('refuses a redirect that has no hop left after republishing', async () => {
- const { publisher, sent } = build()
+ const { batch, sent } = build()
- expect(await publisher.republish(candidate({ remainingHops: 1 }), candidate(), 'redirect')).toBe(
- 'refused_delay'
- )
+ expect(await batch.republish(candidate({ remainingHops: 1 }), candidate(), 'redirect')).toBe('refused_delay')
+ await batch.flush()
expect(sent).toEqual([])
})
- it('reports a failed produce without throwing', async () => {
+ it('publishes every target-domain group from redirect fanout to the frontier', async () => {
+ const { batch, sent } = build()
+ const other = candidate({
+ originalRef: `imageurl:${'b'.repeat(22)}`,
+ currentUrl: 'https://img.other.net/b.png',
+ host: 'img.other.net',
+ origin: 'https://img.other.net',
+ registrableDomain: 'other.net',
+ })
+
+ await batch.republish(candidate(), candidate(), 'pass_deadline')
+ await batch.republish(other, other, 'redirect')
+
+ await expect(batch.flush()).resolves.toEqual({ failedUrls: 0 })
+ expect(sent).toHaveLength(2)
+ expect(sent.every((item) => item.topic === FRONTIER)).toBe(true)
+ const redirected = sent.find((item) => item.key === 'other.net')!
+ expect(parseCollectedUrlsRecord(redirected.value, 'other.net')).toMatchObject({
+ ok: true,
+ candidates: [{ lastRepublishReason: 'redirect', notBeforeMs: 0 }],
+ })
+ })
+
+ it('bounds concurrent Kafka republish deliveries', async () => {
+ let active = 0
+ let peak = 0
+ const releases: Array<() => void> = []
+ const producer = {
+ produce: () =>
+ new Promise<void>((resolve) => {
+ active++
+ peak = Math.max(peak, active)
+ releases.push(() => {
+ active--
+ resolve()
+ })
+ }),
+ } as unknown as KafkaProducerWrapper
+ const publisher = new FrontierPublisher(producer, {
+ frontierTopic: FRONTIER,
+ scrubTopic: SCRUB,
+ delayTiers: TIERS,
+ maxConcurrentImagePublishes: 2,
+ maxConcurrentRepublishes: 2,
+ })
+ const batch = publisher.createRepublishBatch()
+
+ for (const domain of ['one.example', 'two.example', 'three.example']) {
+ const item = candidate({
+ currentUrl: `https://${domain}/a.png`,
+ host: domain,
+ origin: `https://${domain}`,
+ registrableDomain: domain,
+ })
+ await batch.republish(item, item, 'pass_deadline')
+ }
+
+ const flushing = batch.flush()
+ expect(active).toBe(2)
+ expect(peak).toBe(2)
+
+ const firstTwo = releases.splice(0, 2)
+ firstTwo[0]()
+ for (let index = 0; index < 10; index++) {
+ await Promise.resolve()
+ }
+ expect(active).toBe(2)
+ expect(peak).toBe(2)
+
+ firstTwo[1]()
+ releases[0]()
+ await expect(flushing).resolves.toEqual({ failedUrls: 0 })
+ })
+
+ it('reports every URL in a failed grouped message', async () => {
const producer = { produce: () => Promise.reject(new Error('broker down')) } as unknown as KafkaProducerWrapper
const publisher = new FrontierPublisher(producer, {
frontierTopic: FRONTIER,
scrubTopic: SCRUB,
delayTiers: TIERS,
maxConcurrentImagePublishes: 2,
+ maxConcurrentRepublishes: 2,
+ })
+ const batch = publisher.createRepublishBatch()
+ const failed = jest.spyOn(ImageFetchRequestMetrics, 'incRepublishFailed').mockImplementation()
+
+ await batch.republish(candidate(), candidate(), 'pass_deadline')
+ await batch.republish(candidate({ originalRef: `imageurl:${'b'.repeat(22)}` }), candidate(), 'pass_deadline')
+
+ await expect(batch.flush()).resolves.toEqual({ failedUrls: 2 })
+ expect(failed).toHaveBeenCalledTimes(2)
+ })
+
+ it('stops starting republish deliveries after the first failure', async () => {
+ const produce = jest.fn(() => Promise.reject(new Error('broker down')))
+ const producer = { produce } as unknown as KafkaProducerWrapper
+ const publisher = new FrontierPublisher(producer, {
+ frontierTopic: FRONTIER,
+ scrubTopic: SCRUB,
+ delayTiers: TIERS,
+ maxConcurrentImagePublishes: 2,
+ maxConcurrentRepublishes: 1,
})
+ const batch = publisher.createRepublishBatch()
+
+ for (const domain of ['one.example', 'two.example', 'three.example']) {
+ const item = candidate({
+ currentUrl: `https://${domain}/a.png`,
+ host: domain,
+ origin: `https://${domain}`,
+ registrableDomain: domain,
+ })
+ await batch.republish(item, item, 'pass_deadline')
+ }
+
+ await expect(batch.flush()).resolves.toEqual({ failedUrls: 3 })
+ expect(produce).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not start republish deliveries after the finalization deadline', async () => {
+ const produce = jest.fn(() => Promise.resolve())
+ const producer = { produce } as unknown as KafkaProducerWrapper
+ const publisher = new FrontierPublisher(producer, {
+ frontierTopic: FRONTIER,
+ scrubTopic: SCRUB,
+ delayTiers: TIERS,
+ maxConcurrentImagePublishes: 2,
+ maxConcurrentRepublishes: 2,
+ })
+ const batch = publisher.createRepublishBatch(performance.now())
+ const deadlineExceeded = jest
+ .spyOn(ImageFetchRequestMetrics, 'incRepublishFlushDeadlineExceeded')
+ .mockImplementation()
+
+ for (const domain of ['one.example', 'two.example', 'three.example']) {
+ const item = candidate({
+ currentUrl: `https://${domain}/a.png`,
+ host: domain,
+ origin: `https://${domain}`,
+ registrableDomain: domain,
+ })
+ await batch.republish(item, item, 'pass_deadline')
+ }
- await expect(publisher.republish(candidate(), candidate(), 'retry')).resolves.toBe('failed')
+ await expect(batch.flush()).resolves.toEqual({ failedUrls: 3 })
+ expect(produce).not.toHaveBeenCalled()
+ expect(deadlineExceeded).toHaveBeenCalledTimes(1)
})
it('publishes fetched bytes under the original global ref', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
index 5749ee6ede25..9a20d6a85b31 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
@@ -2,13 +2,20 @@ import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { ConcurrencyController } from '~/common/utils/concurrencyController'
import { logger } from '~/common/utils/logger'
-import { FetchCandidate, RepublishReason, serializeFrontierRecord } from './collected-urls-record'
+import {
+ FetchCandidate,
+ MAX_JOBS_PER_RECORD,
+ MAX_RECORD_BYTES,
+ RepublishReason,
+ serializeFrontierRecord,
+} from './collected-urls-record'
import type { ImageFetchResult } from './image-fetcher'
-import { ImageFetchRequestMetrics } from './metrics'
+import { ImageFetchRequestMetrics, RepublishTopic } from './metrics'
export interface DelayTier {
topic: string
delayMs: number
+ metricTopic: Exclude<RepublishTopic, 'frontier'>
}
export interface FrontierPublisherOptions {
@@ -16,13 +23,58 @@ export interface FrontierPublisherOptions {
scrubTopic: string
delayTiers: DelayTier[]
maxConcurrentImagePublishes: number
+ maxConcurrentRepublishes: number
}
-export type RepublishResult = 'published' | 'refused_delay' | 'failed'
+export type RepublishResult = 'queued' | 'refused_delay'
+
+export interface RepublishFlushResult {
+ failedUrls: number
+}
+
+interface RepublishDestination {
+ topic: string
+ metricTopic: RepublishTopic
+ delayMs: number
+}
+
+interface PendingRepublish {
+ candidate: FetchCandidate
+ reason: RepublishReason
+ destination: RepublishDestination
+}
+
+interface PlannedRepublishMessage {
+ topic: string
+ metricTopic: RepublishTopic
+ registrableDomain: string
+ candidates: FetchCandidate[]
+ reasons: RepublishReason[]
+}
+
+interface RepublishDeliveryState {
+ failed: boolean
+ deadlineExceeded: boolean
+}
+
+type RepublishDeliveryResult = 'published' | 'failed' | 'skipped'
+
+const EMPTY_FRONTIER_RECORD_BYTES = serializeFrontierRecord([]).length
+
+export interface RepublishBatch {
+ republish(
+ candidate: FetchCandidate,
+ target: Pick<FetchCandidate, 'currentUrl' | 'host' | 'origin' | 'registrableDomain'>,
+ reason: RepublishReason,
+ waitMs?: number
+ ): Promise<RepublishResult>
+ flush(): Promise<RepublishFlushResult>
+}
export class FrontierPublisher {
private readonly delayTiers: DelayTier[]
private readonly imagePublishes: ConcurrencyController
+ private readonly republishes: ConcurrencyController
constructor(
private readonly producer: KafkaProducerWrapper,
@@ -35,56 +87,21 @@ export class FrontierPublisher {
if (!Number.isInteger(options.maxConcurrentImagePublishes) || options.maxConcurrentImagePublishes < 1) {
throw new Error('the image fetch lane needs a positive image publish limit')
}
+ if (!Number.isInteger(options.maxConcurrentRepublishes) || options.maxConcurrentRepublishes < 1) {
+ throw new Error('the image fetch lane needs a positive republish limit')
+ }
this.imagePublishes = new ConcurrencyController(options.maxConcurrentImagePublishes)
+ this.republishes = new ConcurrencyController(options.maxConcurrentRepublishes)
}
- public async republish(
- candidate: FetchCandidate,
- target: Pick<FetchCandidate, 'currentUrl' | 'host' | 'origin' | 'registrableDomain'>,
- reason: RepublishReason,
- waitMs = 0
- ): Promise<RepublishResult> {
- const spendsHop = reason === 'redirect' || reason === 'retry'
- const remainingHops = candidate.remainingHops - (spendsHop ? 1 : 0)
- if (remainingHops <= 0) {
- return 'refused_delay'
- }
-
- const effectiveWaitMs = reason === 'retry' ? Math.max(waitMs, this.delayTiers[0].delayMs) : waitMs
- const tier =
- effectiveWaitMs > 0
- ? this.delayTiers.find((candidateTier) => candidateTier.delayMs >= effectiveWaitMs)
- : undefined
- if (effectiveWaitMs > 0 && !tier) {
- return 'refused_delay'
- }
- const nowMs = Date.now()
- const republished: FetchCandidate = {
- ...candidate,
- ...target,
- remainingHops,
- notBeforeMs: tier ? nowMs + tier.delayMs : 0,
- republishCount: candidate.republishCount + 1,
- lastRepublishReason: reason,
- }
- const topic = tier?.topic ?? this.options.frontierTopic
- try {
- await this.producer.produce({
- topic,
- key: Buffer.from(target.registrableDomain),
- value: serializeFrontierRecord([republished]),
- })
- } catch (error) {
- logger.warn('🌐', 'ml_image_fetch_republish_failed', {
- reason,
- topic,
- error: error instanceof Error ? error.name : 'unknown',
- })
- ImageFetchRequestMetrics.incRepublishFailed(reason)
- return 'failed'
- }
- ImageFetchRequestMetrics.incRepublished(reason, tier ? 'delay' : 'frontier')
- return 'published'
+ public createRepublishBatch(deadlineAtMonotonicMs = Number.POSITIVE_INFINITY): RepublishBatch {
+ return new BufferedRepublishBatch(
+ this.producer,
+ this.options.frontierTopic,
+ this.delayTiers,
+ this.republishes,
+ deadlineAtMonotonicMs
+ )
}
public async publishImage(candidate: FetchCandidate, result: ImageFetchResult): Promise<void> {
@@ -108,3 +125,223 @@ export class FrontierPublisher {
})
}
}
+
+class BufferedRepublishBatch implements RepublishBatch {
+ private readonly pending: PendingRepublish[] = []
+ private flushed = false
+
+ constructor(
+ private readonly producer: KafkaProducerWrapper,
+ private readonly frontierTopic: string,
+ private readonly delayTiers: DelayTier[],
+ private readonly republishes: ConcurrencyController,
+ private readonly deadlineAtMonotonicMs: number
+ ) {}
+
+ public republish(
+ candidate: FetchCandidate,
+ target: Pick<FetchCandidate, 'currentUrl' | 'host' | 'origin' | 'registrableDomain'>,
+ reason: RepublishReason,
+ waitMs = 0
+ ): Promise<RepublishResult> {
+ if (this.flushed) {
+ return Promise.reject(new Error('an image fetch republish batch cannot accept work after its flush'))
+ }
+ const spendsHop = reason === 'redirect' || reason === 'retry'
+ const remainingHops = candidate.remainingHops - (spendsHop ? 1 : 0)
+ if (remainingHops <= 0) {
+ return Promise.resolve('refused_delay')
+ }
+
+ const effectiveWaitMs = reason === 'retry' ? Math.max(waitMs, this.delayTiers[0].delayMs) : waitMs
+ const destination = this.destination(effectiveWaitMs)
+ if (!destination) {
+ return Promise.resolve('refused_delay')
+ }
+ this.pending.push({
+ candidate: {
+ ...candidate,
+ ...target,
+ remainingHops,
+ notBeforeMs: destination.delayMs > 0 ? Date.now() + destination.delayMs : 0,
+ republishCount: candidate.republishCount + 1,
+ lastRepublishReason: reason,
+ },
+ reason,
+ destination,
+ })
+ return Promise.resolve('queued')
+ }
+
+ public async flush(): Promise<RepublishFlushResult> {
+ if (this.flushed) {
+ throw new Error('an image fetch republish batch cannot flush more than once')
+ }
+ this.flushed = true
+ if (this.pending.length === 0) {
+ return { failedUrls: 0 }
+ }
+ const startedAt = process.hrtime.bigint()
+ try {
+ const plans = this.planMessages()
+ const deliveryState: RepublishDeliveryState = { failed: false, deadlineExceeded: false }
+ const plansByTopic = new Map<RepublishTopic, PlannedRepublishMessage[]>()
+ for (const plan of plans) {
+ const topicPlans = plansByTopic.get(plan.metricTopic)
+ if (topicPlans) {
+ topicPlans.push(plan)
+ } else {
+ plansByTopic.set(plan.metricTopic, [plan])
+ }
+ }
+ const topicResults = await Promise.all(
+ [...plansByTopic.entries()].map(([metricTopic, topicPlans]) =>
+ this.publishTopic(metricTopic, topicPlans, deliveryState)
+ )
+ )
+ if (deliveryState.deadlineExceeded) {
+ ImageFetchRequestMetrics.incRepublishFlushDeadlineExceeded()
+ }
+ return { failedUrls: topicResults.reduce((sum, result) => sum + result.failedUrls, 0) }
+ } finally {
+ ImageFetchRequestMetrics.observeRepublishFlush(Number(process.hrtime.bigint() - startedAt) / 1e9)
+ }
+ }
+
+ private destination(waitMs: number): RepublishDestination | undefined {
+ if (waitMs <= 0) {
+ return { topic: this.frontierTopic, metricTopic: 'frontier', delayMs: 0 }
+ }
+ const tier = this.delayTiers.find((candidateTier) => candidateTier.delayMs >= waitMs)
+ return tier ? { topic: tier.topic, metricTopic: tier.metricTopic, delayMs: tier.delayMs } : undefined
+ }
+
+ private planMessages(): PlannedRepublishMessage[] {
+ const groups = new Map<string, PendingRepublish[]>()
+ for (const item of this.pending) {
+ const key = `${item.destination.topic}\0${item.candidate.registrableDomain}`
+ const group = groups.get(key)
+ if (group) {
+ group.push(item)
+ } else {
+ groups.set(key, [item])
+ }
+ }
+ return [...groups.values()].flatMap((items) => this.packGroup(items))
+ }
+
+ private packGroup(items: PendingRepublish[]): PlannedRepublishMessage[] {
+ const plans: PlannedRepublishMessage[] = []
+ let candidates: FetchCandidate[] = []
+ let reasons: RepublishReason[] = []
+ let recordBytes = EMPTY_FRONTIER_RECORD_BYTES
+ const finishPlan = (): void => {
+ if (candidates.length === 0) {
+ return
+ }
+ plans.push({
+ topic: items[0].destination.topic,
+ metricTopic: items[0].destination.metricTopic,
+ registrableDomain: items[0].candidate.registrableDomain,
+ candidates,
+ reasons,
+ })
+ candidates = []
+ reasons = []
+ recordBytes = EMPTY_FRONTIER_RECORD_BYTES
+ }
+ for (const item of items) {
+ const candidateBytes = serializeFrontierRecord([item.candidate]).length - EMPTY_FRONTIER_RECORD_BYTES
+ const nextRecordBytes = recordBytes + candidateBytes + (candidates.length > 0 ? 1 : 0)
+ if (
+ candidates.length > 0 &&
+ (candidates.length === MAX_JOBS_PER_RECORD || nextRecordBytes > MAX_RECORD_BYTES)
+ ) {
+ finishPlan()
+ }
+ recordBytes += candidateBytes + (candidates.length > 0 ? 1 : 0)
+ candidates.push(item.candidate)
+ reasons.push(item.reason)
+ if (recordBytes > MAX_RECORD_BYTES) {
+ throw new Error('one image fetch republish job exceeds the Kafka record limit')
+ }
+ }
+ finishPlan()
+ return plans
+ }
+
+ private async publishTopic(
+ metricTopic: RepublishTopic,
+ plans: PlannedRepublishMessage[],
+ deliveryState: RepublishDeliveryState
+ ): Promise<RepublishFlushResult> {
+ const startedAt = process.hrtime.bigint()
+ const results = await Promise.all(
+ plans.map((plan) =>
+ this.republishes.run({
+ debugTag: plan.metricTopic,
+ fn: async (): Promise<RepublishDeliveryResult> => {
+ if (deliveryState.failed) {
+ return 'skipped'
+ }
+ if (performance.now() >= this.deadlineAtMonotonicMs) {
+ deliveryState.failed = true
+ deliveryState.deadlineExceeded = true
+ return 'skipped'
+ }
+ try {
+ await this.producer.produce({
+ topic: plan.topic,
+ key: Buffer.from(plan.registrableDomain),
+ value: serializeFrontierRecord(plan.candidates),
+ })
+ return 'published'
+ } catch {
+ deliveryState.failed = true
+ return 'failed'
+ }
+ },
+ })
+ )
+ )
+ let failedUrls = 0
+ let attemptedMessages = 0
+ const attemptedRegistrableDomains = new Set<string>()
+ for (let index = 0; index < plans.length; index++) {
+ const plan = plans[index]
+ if (results[index] === 'skipped') {
+ failedUrls += plan.candidates.length
+ continue
+ }
+ attemptedMessages++
+ attemptedRegistrableDomains.add(plan.registrableDomain)
+ if (results[index] === 'failed') {
+ failedUrls += plan.candidates.length
+ this.recordFailedPlan(plan)
+ continue
+ }
+ for (const reason of plan.reasons) {
+ ImageFetchRequestMetrics.incRepublished(reason, metricTopic === 'frontier' ? 'frontier' : 'delay')
+ }
+ }
+ if (attemptedMessages > 0) {
+ ImageFetchRequestMetrics.observeRepublishBatch(
+ metricTopic,
+ attemptedMessages,
+ attemptedRegistrableDomains.size,
+ Number(process.hrtime.bigint() - startedAt) / 1e9
+ )
+ }
+ return { failedUrls }
+ }
+
+ private recordFailedPlan(plan: PlannedRepublishMessage): void {
+ logger.warn('🌐', 'ml_image_fetch_republish_failed', {
+ topic: plan.topic,
+ urls: plan.candidates.length,
+ })
+ for (const reason of plan.reasons) {
+ ImageFetchRequestMetrics.incRepublishFailed(reason)
+ }
+ }
+}
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 1d21195b7b58..664f2de7e542 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
@@ -21,6 +21,7 @@ export type DedupScope = 'batch' | 'store'
export type SchedulerWaitScope = 'origin_crawl_delay' | 'registrable_domain_rate' | 'request_capacity'
export 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 PolicyAndBudgetReason = FetchRefusalReason | RequestScheduleBlockReason | 'none'
export class ImageFetchConsumerMetrics {
@@ -52,6 +53,16 @@ export class ImageFetchConsumerMetrics {
help: 'Distinct origins in one poll batch',
buckets: [1, 2, 4, 8, 16, 32, 64],
})
+ private static readonly distinctOriginsPerBatch = new Histogram({
+ name: 'ml_image_fetch_consumer_distinct_origins_per_batch',
+ help: 'Distinct origins in one poll batch, including empty batches and the full configured batch range',
+ buckets: [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16_384],
+ })
+ private static readonly registrableDomainsPerBatch = new Histogram({
+ name: 'ml_image_fetch_consumer_registrable_domains_per_batch',
+ 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 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',
@@ -114,8 +125,10 @@ export class ImageFetchConsumerMetrics {
): void {
this.storeDuration.labels(operation, outcome).observe(durationSeconds)
}
- public static observeBatch(origins: number, durationSeconds: number): void {
+ public static observeBatch(origins: number, registrableDomains: number, durationSeconds: number): void {
this.originsPerBatch.observe(origins)
+ this.distinctOriginsPerBatch.observe(origins)
+ this.registrableDomainsPerBatch.observe(registrableDomains)
this.batchDuration.observe(durationSeconds)
}
public static startBatch(nowMs = performance.now()): void {
@@ -331,9 +344,36 @@ export class ImageFetchRequestMetrics {
})
private static readonly republishFailed = new Counter({
name: 'ml_image_fetch_republish_failed_total',
- help: 'URLs that could not be put back. Each one is dropped without a crawl history entry, so it returns only when a session refers to it again',
+ help: 'URLs in a Kafka message whose republish delivery failed. The input batch throws and leaves its offsets uncommitted',
labelNames: ['reason'],
})
+ private static readonly republishMessagesPerBatch = new Histogram({
+ name: 'ml_image_fetch_republish_messages_per_batch',
+ help: 'Kafka record delivery attempts by one fetch batch for each destination topic class',
+ labelNames: ['topic'],
+ buckets: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16_384],
+ })
+ private static readonly republishRegistrableDomainsPerBatch = new Histogram({
+ name: 'ml_image_fetch_republish_registrable_domains_per_batch',
+ help: 'Distinct registrable-domain keys in delivery attempts by one fetch batch for each destination topic class',
+ labelNames: ['topic'],
+ buckets: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16_384],
+ })
+ private static readonly republishDuration = new Histogram({
+ name: 'ml_image_fetch_republish_duration_seconds',
+ help: 'Wall time from scheduling one destination topic class until all its started Kafka delivery attempts settle',
+ labelNames: ['topic'],
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 240, 300],
+ })
+ private static readonly republishFlushDuration = new Histogram({
+ name: 'ml_image_fetch_republish_flush_duration_seconds',
+ help: 'Total wall time to group, serialize, and wait for every started republish delivery in one fetch batch',
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 240, 300],
+ })
+ private static readonly republishFlushDeadlineExceeded = new Counter({
+ name: 'ml_image_fetch_republish_flush_deadline_exceeded_total',
+ help: 'Fetch batches that stopped starting Kafka republish records to preserve final history-write and poll-interval margin',
+ })
/**
* Zero is the common case. The tail shows redirect chains and retries.
*/
@@ -349,6 +389,22 @@ export class ImageFetchRequestMetrics {
public static incRepublishFailed(reason: RepublishReason): void {
this.republishFailed.labels(reason).inc()
}
+ public static observeRepublishBatch(
+ topic: RepublishTopic,
+ messages: number,
+ registrableDomains: number,
+ durationSeconds: number
+ ): void {
+ this.republishMessagesPerBatch.labels(topic).observe(messages)
+ this.republishRegistrableDomainsPerBatch.labels(topic).observe(registrableDomains)
+ this.republishDuration.labels(topic).observe(durationSeconds)
+ }
+ public static observeRepublishFlush(durationSeconds: number): void {
+ this.republishFlushDuration.observe(durationSeconds)
+ }
+ public static incRepublishFlushDeadlineExceeded(): void {
+ this.republishFlushDeadlineExceeded.inc()
+ }
public static observeHops(hops: number): void {
this.hopsUsed.observe(hops)
}
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 7bf3e39d4cb6..7ebfcdeb80aa 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
@@ -3,8 +3,8 @@ import { Message } from 'node-rdkafka'
import { FetchCandidate, MAX_HOPS, serializeFrontierRecord } from './collected-urls-record'
import { CrawlHistoryItem, CrawlHistoryStore, configurationCacheKey } from './crawl-history'
import { AttemptOutcome, DELAY_TOO_LONG, FetchAttempt, FetchPass, HOPS_EXHAUSTED } from './fetch-runner'
-import { FrontierPublisher, RepublishResult } from './frontier-publisher'
-import { ImageFetchConsumerMetrics } from './metrics'
+import { FrontierPublisher, RepublishFlushResult, RepublishResult } from './frontier-publisher'
+import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'
import { UrlFetchConsumer } from './url-fetch-consumer'
const NOW_MS = 1_700_000_000_000
@@ -90,6 +90,7 @@ interface Harness {
history: FakeCrawlHistory
run: jest.Mock<Promise<FetchAttempt[]>, [FetchCandidate[], Map<string, CrawlHistoryItem>]>
republish: jest.Mock<Promise<RepublishResult>, any[]>
+ flush: jest.Mock<Promise<RepublishFlushResult>, []>
}
function build(dryRun = false): Harness {
@@ -97,14 +98,15 @@ function build(dryRun = false): Harness {
const run = jest.fn((candidates: FetchCandidate[], _stored: Map<string, CrawlHistoryItem>) =>
Promise.resolve(candidates.map((item) => terminal(item)))
)
- const republish = jest.fn(() => Promise.resolve('published' as const))
+ const republish = jest.fn(() => Promise.resolve('queued' as const))
+ const flush = jest.fn(() => Promise.resolve({ failedUrls: 0 }))
const consumer = new UrlFetchConsumer(
history,
- { republish } as unknown as FrontierPublisher,
+ { createRepublishBatch: () => ({ republish, flush }) } as unknown as FrontierPublisher,
{ seenTtlSeconds: 30 * 24 * 60 * 60, dryRun },
dryRun ? undefined : ({ run } as FetchPass)
)
- return { consumer, history, run, republish }
+ return { consumer, history, run, republish, flush }
}
describe('UrlFetchConsumer', () => {
@@ -153,6 +155,29 @@ describe('UrlFetchConsumer', () => {
expect(harness.history.writes[0]).toHaveLength(2)
})
+ it('records distinct origins and registrable domains for the poll batch', async () => {
+ const harness = build()
+ const observeBatch = jest.spyOn(ImageFetchConsumerMetrics, 'observeBatch')
+ const otherExampleOrigin = candidate('b', {
+ currentUrl: 'https://img.example.com/b.png',
+ host: 'img.example.com',
+ origin: 'https://img.example.com',
+ })
+ const otherRegistrableDomain = candidate('c', {
+ currentUrl: 'https://img.other.net/c.png',
+ host: 'img.other.net',
+ origin: 'https://img.other.net',
+ registrableDomain: 'other.net',
+ })
+
+ await harness.consumer.handleBatch(
+ [message([candidate('a'), otherExampleOrigin]), message([otherRegistrableDomain], 'other.net')],
+ NOW_MS
+ )
+
+ expect(observeBatch).toHaveBeenCalledWith(3, 2, expect.any(Number))
+ })
+
it('deduplicates one global ref within the batch', async () => {
const harness = build()
@@ -259,15 +284,57 @@ describe('UrlFetchConsumer', () => {
])
})
- it('throws when a not-ready republish fails', async () => {
+ it('throws when a not-ready republish delivery fails', async () => {
const harness = build()
- harness.republish.mockResolvedValue('failed')
+ harness.flush.mockResolvedValue({ failedUrls: 1 })
const early = candidate('a', { notBeforeMs: NOW_MS + 30_000 })
await expect(harness.consumer.handleBatch([message([early])], NOW_MS)).rejects.toThrow('account for 1 URLs')
expect(harness.history.writes).toEqual([])
})
+ it('records a retry cause after the republish batch is durable', async () => {
+ const harness = build()
+ const retryCause = jest.spyOn(ImageFetchRequestMetrics, 'incRetryCause').mockImplementation()
+ harness.run.mockImplementation((candidates) =>
+ Promise.resolve(
+ candidates.map((item) => ({
+ candidate: item,
+ outcome: 'server_error',
+ finished: false,
+ lost: false,
+ configurationUpdates: [],
+ }))
+ )
+ )
+
+ await harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)
+
+ expect(retryCause).toHaveBeenCalledWith('server_error')
+ })
+
+ it('does not record a retry cause when the republish batch fails', async () => {
+ const harness = build()
+ const retryCause = jest.spyOn(ImageFetchRequestMetrics, 'incRetryCause').mockImplementation()
+ harness.flush.mockResolvedValue({ failedUrls: 1 })
+ harness.run.mockImplementation((candidates) =>
+ Promise.resolve(
+ candidates.map((item) => ({
+ candidate: item,
+ outcome: 'server_error',
+ finished: false,
+ lost: false,
+ configurationUpdates: [],
+ }))
+ )
+ )
+
+ await expect(harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)).rejects.toThrow(
+ 'account for 1 URLs'
+ )
+ expect(retryCause).not.toHaveBeenCalled()
+ })
+
it('drops a malformed record without running the fetch pass', async () => {
const harness = build()
const invalid = message([candidate('a')])
@@ -301,7 +368,7 @@ describe('UrlFetchConsumer', () => {
const finishBatch = jest.spyOn(ImageFetchConsumerMetrics, 'finishBatch')
await expect(harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)).rejects.toThrow('read failed')
- expect(observeBatch).toHaveBeenCalledWith(1, expect.any(Number))
+ expect(observeBatch).toHaveBeenCalledWith(1, 1, expect.any(Number))
expect(observeStoreDuration).toHaveBeenCalledWith('read', 'error', expect.any(Number))
expect(startBatch).toHaveBeenCalledTimes(1)
expect(finishBatch).toHaveBeenCalledTimes(1)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
index c0343db44876..fb70bb28ddf8 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,11 +4,19 @@ 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 { AttemptOutcome, DELAY_TOO_LONG, FetchAttempt, FetchPass, HOPS_EXHAUSTED } from './fetch-runner'
-import { FrontierPublisher } from './frontier-publisher'
+import {
+ AttemptOutcome,
+ DELAY_TOO_LONG,
+ FetchAttempt,
+ FetchPass,
+ HOPS_EXHAUSTED,
+ isTransientOutcome,
+} from './fetch-runner'
+import { FrontierPublisher, RepublishBatch } from './frontier-publisher'
import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'
const ONE_HOUR_MS = 60 * 60 * 1000
+const REPUBLISH_DEADLINE_FROM_BATCH_START_MS = 200_000
export interface UrlFetchConsumerOptions {
seenTtlSeconds: number
@@ -33,10 +41,12 @@ export class UrlFetchConsumer {
public async handleBatch(messages: Message[], nowMs: number): Promise<void> {
const startedAt = process.hrtime.bigint()
+ const republishDeadlineAtMonotonicMs = performance.now() + REPUBLISH_DEADLINE_FROM_BATCH_START_MS
const drops = new Map<UrlDropReason, number>()
const candidatesByRef = new Map<string, FetchCandidate>()
let dedupedInBatch = 0
let originCount = 0
+ let registrableDomainCount = 0
ImageFetchConsumerMetrics.startBatch()
try {
@@ -62,8 +72,14 @@ export class UrlFetchConsumer {
}
}
const candidates = [...candidatesByRef.values()]
- const origins = new Set(candidates.map((candidate) => candidate.origin))
+ const origins = new Set<string>()
+ const registrableDomains = new Set<string>()
+ for (const candidate of candidates) {
+ origins.add(candidate.origin)
+ registrableDomains.add(candidate.registrableDomain)
+ }
originCount = origins.size
+ registrableDomainCount = registrableDomains.size
if (this.options.dryRun || candidates.length === 0) {
return
@@ -94,8 +110,14 @@ export class UrlFetchConsumer {
}
ImageFetchConsumerMetrics.incFetchable(fetchable.length)
- const attempts = await this.runner!.run(fetchable, stored)
- attempts.push(...(await Promise.all(notReady.map((candidate) => this.republishNotReady(candidate, nowMs)))))
+ const republishBatch = this.publisher.createRepublishBatch(republishDeadlineAtMonotonicMs)
+ const attempts = await this.runner!.run(fetchable, stored, republishBatch)
+ attempts.push(
+ ...(await Promise.all(
+ 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)
@@ -106,13 +128,18 @@ export class UrlFetchConsumer {
if (updates.length > 0) {
await this.runCrawlHistoryOperation('write', updates.length, () => this.crawlHistory.write(updates))
}
- const lost = attempts.filter((attempt) => attempt.lost).length
+ const lost = attempts.filter((attempt) => attempt.lost).length + republishResult.failedUrls
if (lost > 0) {
throw new Error(`the image fetch lane could not account for ${lost} URLs`)
}
+ for (const attempt of attempts) {
+ if (!attempt.finished && isTransientOutcome(attempt.outcome)) {
+ ImageFetchRequestMetrics.incRetryCause(attempt.outcome)
+ }
+ }
} finally {
ImageFetchConsumerMetrics.finishBatch()
- this.recordMetrics(drops, dedupedInBatch, originCount, startedAt)
+ this.recordMetrics(drops, dedupedInBatch, originCount, registrableDomainCount, startedAt)
}
}
@@ -149,12 +176,16 @@ export class UrlFetchConsumer {
}
}
- private async republishNotReady(candidate: FetchCandidate, nowMs: number): Promise<FetchAttempt> {
+ private async republishNotReady(
+ republishBatch: RepublishBatch,
+ candidate: FetchCandidate,
+ nowMs: number
+ ): Promise<FetchAttempt> {
if (candidate.remainingHops === 0) {
return this.terminalAttempt(candidate, HOPS_EXHAUSTED, nowMs)
}
const waitMs = candidate.notBeforeMs - nowMs
- const result = await this.publisher.republish(
+ const result = await republishBatch.republish(
candidate,
{
currentUrl: candidate.currentUrl,
@@ -172,7 +203,7 @@ export class UrlFetchConsumer {
candidate,
outcome: 'backoff',
finished: false,
- lost: result === 'failed',
+ lost: false,
configurationUpdates: [],
}
}
@@ -211,6 +242,7 @@ export class UrlFetchConsumer {
drops: Map<UrlDropReason, number>,
dedupedInBatch: number,
origins: number,
+ registrableDomains: number,
startedAt: bigint
): void {
if (dedupedInBatch > 0) {
@@ -219,7 +251,11 @@ export class UrlFetchConsumer {
for (const [reason, count] of drops) {
ImageFetchConsumerMetrics.incDropped(reason, count)
}
- ImageFetchConsumerMetrics.observeBatch(origins, Number(process.hrtime.bigint() - startedAt) / 1e9)
+ ImageFetchConsumerMetrics.observeBatch(
+ origins,
+ registrableDomains,
+ Number(process.hrtime.bigint() - startedAt) / 1e9
+ )
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 64f562aefd83..644257188706 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -225,7 +225,7 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
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_MAX_PENDING_PUBLISHES: 100,
- SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS: 20_000,
+ SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS: 40_000,
SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES: 20 * 1024 * 1024,
SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS: 10_000,
SESSION_RECORDING_ML_IMAGE_FETCH_MAX_REDIRECTS: 3,
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 c7508141d5b4..9edf15624a63 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
@@ -68,11 +68,12 @@ export function buildFrontierPublisher(
frontierTopic: KAFKA_SESSION_REPLAY_IMAGE_FETCH,
scrubTopic: KAFKA_SESSION_REPLAY_IMAGE_SCRUB,
delayTiers: [
- { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M, delayMs: 60_000 },
- { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M, delayMs: 600_000 },
- { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H, delayMs: 3_600_000 },
+ { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M, delayMs: 60_000, metricTopic: 'retry_1m' },
+ { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M, delayMs: 600_000, metricTopic: 'retry_10m' },
+ { topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H, delayMs: 3_600_000, metricTopic: 'retry_1h' },
],
maxConcurrentImagePublishes,
+ maxConcurrentRepublishes: maxConcurrentImagePublishes,
})
}