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): serve deferred image-fetch urls before later captures (#111331)

Robbieda78c1a0fb16
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 4e95af1b33b8..817b20576f16 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
@@ -42,7 +42,7 @@ The frontier consumer uses cooperative rebalancing. Its revoke path drains activ
Each image-fetch worker creates two Kafka group members by default. A local joiner combines their batches before it starts a fetch pass. When `SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES` is false, each member batch starts its own pass immediately, so a slow partition does not hold back the other members. Group assignments do not overlap, and each member can own multiple partitions. The joiner processes available batches when its join window ends. Each member waits for its group to start before it reads another batch, so a group has at most one contribution per member. The member then tracks completion through the shared Kafka consumer background-task mechanism. Each member can hold two unfinished batches. The consumer waits for the oldest batch at that limit and stores offsets in batch order. Shared request limits still bound total network concurrency. The background-task timeout is 240 seconds, leaving 60 seconds below the default Kafka poll allowance for joining and scheduling. Shutdown stops all consumer loops and waits for the actual joined processing promises before disconnecting consumers and destroying shared dependencies. This wait includes work that outlives the Kafka consumer drain or background-task timeout. The worker divides a 100 MiB Kafka prefetch budget across its group members, with a minimum of 25 MiB per member. This preserves the queue sizes for one to four members and allows a default maximum-sized record in each queue. Sixteen members have a combined prefetch budget of 400 MiB. During a mixed-version rollout, pods with more group members can receive more partitions until the rollout finishes. `SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH` accepts targets from one to sixteen for worker-count experiments.
-`SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL` replaces the joiner with one candidate pool for the worker (`fetch-candidate-pool.ts`). A batch no longer waits for the slowest job of another member's batch. The pool counts registrable-domain and origin slots across the worker, so two batches from one partition cannot each claim a domain's full limit. The fetch pass counts those slots per pass, and the request scheduler then refuses the excess as `connection_limit`. The fetch workers start with the first batch and take jobs among eligible origins in the order the jobs entered the pool. The pool holds an origin with a crawl delay until the delay passes, so a job does not hold a pod request slot while it waits. Each member returns from its batch handler only when its pool window has room (`pool-window-batch-handler.ts`), and it can hold four unfinished batches, which is the hard bound on its resident jobs. A fetch worker that finds no eligible job gives room to every member under the queued-job limit, because jobs that count as runnable can still wait on a crawl delay or on another member's hold on a domain. The room wait stops after 30 seconds, below the consumer's 60-second stalled-loop check, so the queued-job limit can be passed by about one batch. Crawl-history reads and writes and republish flushes stay per batch. Shutdown waits for every member batch that has started, including one still reading crawl history before it reaches the pool, before it stops the fetch workers. A batch can outlive the Kafka consumer drain, and the pool refuses candidates once it is closed.
+`SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL` replaces the joiner with one candidate pool for the worker (`fetch-candidate-pool.ts`). A batch no longer waits for the slowest job of another member's batch. The pool counts registrable-domain and origin slots across the worker, so two batches from one partition cannot each claim a domain's full limit. The fetch pass counts those slots per pass, and the request scheduler then refuses the excess as `connection_limit`. The fetch workers start with the first batch and take jobs among eligible origins in the order the jobs entered the pool. Inside one batch, jobs enter the pool in capture order, so a deferred job is not held behind later captures of its domain on every pass. The pool holds an origin with a crawl delay until the delay passes, so a job does not hold a pod request slot while it waits. Each member returns from its batch handler only when its pool window has room (`pool-window-batch-handler.ts`), and it can hold four unfinished batches, which is the hard bound on its resident jobs. A fetch worker that finds no eligible job gives room to every member under the queued-job limit, because jobs that count as runnable can still wait on a crawl delay or on another member's hold on a domain. The room wait stops after 30 seconds, below the consumer's 60-second stalled-loop check, so the queued-job limit can be passed by about one batch. Crawl-history reads and writes and republish flushes stay per batch. Shutdown waits for every member batch that has started, including one still reading crawl history before it reaches the pool, before it stops the fetch workers. A batch can outlive the Kafka consumer drain, and the pool refuses candidates once it is closed.
Retry jobs use 1-minute, 10-minute, and 1-hour Kafka topics. The topics use broker append timestamps.
@@ -115,34 +115,35 @@ The optional fetch dead-letter topic stores each rejected frontier record with i
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 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 counts, top 1, 5, and 10 URL shares, effective counts, immediately schedulable slots, scheduler waits, requests in flight, deadline deferrals, and `not_ready` republishes. | Fetch dashboard: batch diversity, request capacity, scheduler waits, origin policy, registrable-domain state, request outcomes, and republishes. | Increase batch size only when low diversity coincides with low request use, scoped scheduler wait, and sufficient Kafka poll margin. Scale pods for pod saturation. |
-| One frontier partition accumulates lag. | Per-partition input, fetchable, HTTP request, completion, republish, scheduler-wait, top-share, and effective-count metrics. | Fetch dashboard: partition flow, outcomes, scheduler waits, and concentration. | Separate high input volume from store filtering, HTTP work, politeness waits, and republish churn before changing capacity. |
-| A registrable domain repeatedly fails, or an origin refuses access. | Request outcomes, bounded retry causes, registrable-domain block state, origin-policy decisions, and terminal refusal reasons change. | Fetch dashboard: request outcomes, retry causes, policy and budget decisions, and refused URLs. | Check the origin policy and response status. Do not override an opt-out signal. |
-| Retry release cannot return work to the frontier. | `ml_image_fetch_retry_released_total{outcome="failed"}` and a durable consumer-loop error log. | Fetch dashboard: delivery failures. Loki alert: `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the frontier producer and Kafka connectivity. |
-| Retry input is invalid. | `ml_image_fetch_retry_released_total` increases with a `malformed` or `invalid_timestamp` outcome. Missing content is committed and dropped. An invalid timestamp leaves the offset uncommitted and writes a durable consumer-loop error log. | Fetch dashboard: delivery failures. Alerts: `IngestionSessionReplayImageFetchRetryInputRejected` for missing content and `IngestionSessionReplayImageFetchConsumerLoopFailed` for an invalid timestamp. | Check the retry producer and the delay topic's `LogAppendTime` configuration. |
-| The fetch consumer rejects frontier input. | `ml_image_fetch_consumer_dead_lettered_total` increases after Kafka acknowledges the original record. `ml_image_fetch_consumer_dropped_total` counts the rejected jobs. | Fetch dashboard: quarantine activity and **URLs refused**. Alert: `IngestionSessionReplayImageFetchInputRejected` for a sustained rate. | Check the mirror and fetch versions and the frontier record schema. Inspect the restricted dead-letter topic only when necessary. |
-| The fetch consumer skips unwanted frontier jobs. | `ml_image_fetch_consumer_skipped_total` increases by decline reason. After a beacon-list change it rises at the backlog's parse rate until the queued beacons drain. `ml_image_fetch_consumer_dropped_total` does not move. | Fetch dashboard: **Unwanted URLs skipped** and **Skipped share of parsed URLs**. | No action. A skipped job is counted after the batch finishes its durable work, so a failed batch is not counted twice. A crash before the offset store can count it once more, like every counter in this consumer. |
-| The fetch consumer cannot quarantine rejected input. | `ml_image_fetch_consumer_dead_letter_failed_total` increases and `ml_image_fetch_dead_letter_publish_failed` logs before the consumer fails the batch. The source offsets remain uncommitted. | Fetch dashboard: quarantine activity. Alerts: `IngestionSessionReplayImageFetchDeadLetterPublishFailed` and the durable-log `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the dead-letter topic, producer connectivity, and message-size configuration. |
-| 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`, `refused`, `reset`, or `transport`. | Scrub dashboard: scrub waits and sidecar pressure. Alert: `IngestionSessionReplayImageScrubSidecarUnreachable`. | Scale for `busy`. Check CPU for `timeout`. Check that the image-scrub container is running for `refused`. Expect `reset` on rollouts and scale-downs. Read the error text in the `image_scrub_image_stuck` log for `transport`. |
-| The sidecar answers but cannot scrub. | Scrub waits increase by `rejected`, stuck images rise, or `ml_mirror_image_scrub_consumer_dead_lettered_total` increases. | Scrub dashboard: scrub waits and quarantine events. | Check the image-scrub container logs for the failing stage. Fix the sidecar before Kafka retention removes the parked bytes. |
-| 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. |
-| Inline image scrub exceeds its delivery limit. | The p95 capture-to-S3 latency for inline images exceeds one hour for 30 minutes. | Scrub dashboard: end-to-end latency. Alert: `IngestionSessionReplayInlineImageScrubNotDraining`. | Check sidecar waits, CPU, memory, and consumer restarts. |
-| URL image scrub exceeds its delivery limit. | The p95 capture-to-S3 latency for URL images exceeds three days for 30 minutes. | Fetch and scrub dashboards: frontier health and end-to-end latency. Alert: `IngestionSessionReplayURLImageScrubNotDraining`. | Check the image-fetch frontier, retries, request outcomes, and sidecar waits. |
-
-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.
+| 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**. | Check the completion age first. A high share is expected when a registrable domain has more queued URLs than its concurrency limit can serve in one pass. One pod owns each registrable domain, so more pods do not drain that domain faster. 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. |
+| URLs reach a terminal outcome long after capture. | More than 5% of the URLs that completed during the last hour were captured more than six hours before, for one hour. `ml_image_fetch_completed_url_system_time_seconds` gives the distribution. | Fetch dashboard: **URL age and completion time**. Alert: `IngestionSessionReplayImageFetchCompletionDelayed`. | Check frontier lag, consumer members, pod CPU throttling, and request outcomes. |
+| 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 counts, top 1, 5, and 10 URL shares, effective counts, immediately schedulable slots, scheduler waits, requests in flight, deadline deferrals, and `not_ready` republishes. | Fetch dashboard: batch diversity, request capacity, scheduler waits, origin policy, registrable-domain state, request outcomes, and republishes. | Increase batch size only when low diversity coincides with low request use, scoped scheduler wait, and sufficient Kafka poll margin. Scale pods for pod saturation. |
+| One frontier partition accumulates lag. | Per-partition input, fetchable, HTTP request, completion, republish, scheduler-wait, top-share, and effective-count metrics. | Fetch dashboard: partition flow, outcomes, scheduler waits, and concentration. | Separate high input volume from store filtering, HTTP work, politeness waits, and republish churn before changing capacity. |
+| A registrable domain repeatedly fails, or an origin refuses access. | Request outcomes, bounded retry causes, registrable-domain block state, origin-policy decisions, and terminal refusal reasons change. | Fetch dashboard: request outcomes, retry causes, policy and budget decisions, and refused URLs. | Check the origin policy and response status. Do not override an opt-out signal. |
+| Retry release cannot return work to the frontier. | `ml_image_fetch_retry_released_total{outcome="failed"}` and a durable consumer-loop error log. | Fetch dashboard: delivery failures. Loki alert: `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the frontier producer and Kafka connectivity. |
+| Retry input is invalid. | `ml_image_fetch_retry_released_total` increases with a `malformed` or `invalid_timestamp` outcome. Missing content is committed and dropped. An invalid timestamp leaves the offset uncommitted and writes a durable consumer-loop error log. | Fetch dashboard: delivery failures. Alerts: `IngestionSessionReplayImageFetchRetryInputRejected` for missing content and `IngestionSessionReplayImageFetchConsumerLoopFailed` for an invalid timestamp. | Check the retry producer and the delay topic's `LogAppendTime` configuration. |
+| The fetch consumer rejects frontier input. | `ml_image_fetch_consumer_dead_lettered_total` increases after Kafka acknowledges the original record. `ml_image_fetch_consumer_dropped_total` counts the rejected jobs. | Fetch dashboard: quarantine activity and **URLs refused**. Alert: `IngestionSessionReplayImageFetchInputRejected` for a sustained rate. | Check the mirror and fetch versions and the frontier record schema. Inspect the restricted dead-letter topic only when necessary. |
+| The fetch consumer skips unwanted frontier jobs. | `ml_image_fetch_consumer_skipped_total` increases by decline reason. After a beacon-list change it rises at the backlog's parse rate until the queued beacons drain. `ml_image_fetch_consumer_dropped_total` does not move. | Fetch dashboard: **Unwanted URLs skipped** and **Skipped share of parsed URLs**. | No action. A skipped job is counted after the batch finishes its durable work, so a failed batch is not counted twice. A crash before the offset store can count it once more, like every counter in this consumer. |
+| The fetch consumer cannot quarantine rejected input. | `ml_image_fetch_consumer_dead_letter_failed_total` increases and `ml_image_fetch_dead_letter_publish_failed` logs before the consumer fails the batch. The source offsets remain uncommitted. | Fetch dashboard: quarantine activity. Alerts: `IngestionSessionReplayImageFetchDeadLetterPublishFailed` and the durable-log `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the dead-letter topic, producer connectivity, and message-size configuration. |
+| 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`, `refused`, `reset`, or `transport`. | Scrub dashboard: scrub waits and sidecar pressure. Alert: `IngestionSessionReplayImageScrubSidecarUnreachable`. | Scale for `busy`. Check CPU for `timeout`. Check that the image-scrub container is running for `refused`. Expect `reset` on rollouts and scale-downs. Read the error text in the `image_scrub_image_stuck` log for `transport`. |
+| The sidecar answers but cannot scrub. | Scrub waits increase by `rejected`, stuck images rise, or `ml_mirror_image_scrub_consumer_dead_lettered_total` increases. | Scrub dashboard: scrub waits and quarantine events. | Check the image-scrub container logs for the failing stage. Fix the sidecar before Kafka retention removes the parked bytes. |
+| 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. |
+| Inline image scrub exceeds its delivery limit. | The p95 capture-to-S3 latency for inline images exceeds one hour for 30 minutes. | Scrub dashboard: end-to-end latency. Alert: `IngestionSessionReplayImageScrubNotDraining`. | Check sidecar waits, CPU, memory, and consumer restarts. |
+| URL image scrub exceeds its delivery limit. | The p95 capture-to-S3 latency for URL images exceeds three days for 30 minutes. | Fetch and scrub dashboards: frontier health and end-to-end latency. Alert: `IngestionSessionReplayImageScrubNotDraining`. | Check the image-fetch frontier, retries, request outcomes, and sidecar waits. |
+
+The completion-age 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.
## Assumptions
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 abe85c396570..d3ede94ca8d3 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
@@ -301,7 +301,7 @@ Removing an eligible entry cannot permit an earlier request.
**5.20** Each worker creates one Kafka group member for each configured target partition. Group assignments do not overlap, so ready group members supply batches from different partitions. The worker joins their batches into one fetch pass. The target must be from one to four and defaults to two. The worker starts the fetch pass when all target batches arrive or the join window ends. If fewer batches arrive, the worker processes the available batches. A later group can run concurrently instead of waiting behind a full pass. Shared request limits still bound total network concurrency. The worker divides the existing Kafka prefetch memory budget across its group members.
-**5.21** When `SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL` is true, the worker does not join batches. Each group member batch adds its jobs to one candidate pool for the worker and finishes when its own jobs finish. The pool applies the registrable-domain and origin limits across the worker, not per batch. It selects the eligible registrable domain whose first waiting job entered the pool earliest. The order uses the time the worker received the job, not the age of the record, because the pass deadline and the batch timeout count from that time. An origin in its crawl delay is not eligible until the delay passes. At the pass deadline, the batch's waiting jobs leave the pool as pass-deadline deferrals. A group member reads its next batch only when fewer than `SESSION_RECORDING_ML_IMAGE_FETCH_POOL_REFILL_RUNNABLE_URLS` of its waiting jobs can run, and fewer than `SESSION_RECORDING_ML_IMAGE_FETCH_POOL_MAX_QUEUED_URLS_PER_MEMBER` of its jobs wait. A registrable domain counts as runnable only up to its concurrency limit. A member also reads its next batch when a fetch worker finds no eligible job and the member is under the queued-job limit. The member waits at most 30 seconds for room. After that it reads its next batch anyway, so its queued jobs can pass the limit by about one batch until pass deadlines remove them.
+**5.21** When `SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL` is true, the worker does not join batches. Each group member batch adds its jobs to one candidate pool for the worker and finishes when its own jobs finish. The pool applies the registrable-domain and origin limits across the worker, not per batch. It selects the eligible registrable domain whose first waiting job entered the pool earliest. The order uses the time the worker received the job, not the age of the record, because the pass deadline and the batch timeout count from that time. Inside one batch, jobs enter the pool in capture order, earliest first. A pass-deadline deferral returns to the end of its partition, behind URLs captured later, and this order keeps it from losing to those URLs on every pass. An origin in its crawl delay is not eligible until the delay passes. At the pass deadline, the batch's waiting jobs leave the pool as pass-deadline deferrals. A group member reads its next batch only when fewer than `SESSION_RECORDING_ML_IMAGE_FETCH_POOL_REFILL_RUNNABLE_URLS` of its waiting jobs can run, and fewer than `SESSION_RECORDING_ML_IMAGE_FETCH_POOL_MAX_QUEUED_URLS_PER_MEMBER` of its jobs wait. A registrable domain counts as runnable only up to its concurrency limit. A member also reads its next batch when a fetch worker finds no eligible job and the member is under the queued-job limit. The member waits at most 30 seconds for room. After that it reads its next batch anyway, so its queued jobs can pass the limit by about one batch until pass deadlines remove them.
### 6. Smokescreen
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.test.ts
index 06c51b76e57f..83ceb3210af6 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.test.ts
@@ -3,7 +3,7 @@ import { FetchCandidatePool, FetchCandidatePoolLease, OriginPacing } from './fet
const NOW_MS = 1_700_000_000_000
-function candidate(url: string, registrableDomain: string): FetchCandidate {
+function candidate(url: string, registrableDomain: string, firstSeenAtMs = NOW_MS): FetchCandidate {
const parsed = new URL(url)
return {
originalRef: `imageurl:${url}`,
@@ -13,7 +13,7 @@ function candidate(url: string, registrableDomain: string): FetchCandidate {
registrableDomain,
remainingHops: MAX_HOPS,
notBeforeMs: 0,
- firstSeenAtMs: NOW_MS,
+ firstSeenAtMs,
fetchCount: 0,
republishCount: 0,
lastRepublishReason: null,
@@ -57,13 +57,13 @@ describe('FetchCandidatePool', () => {
beforeEach(() => jest.useFakeTimers().setSystemTime(NOW_MS))
afterEach(() => jest.useRealTimers())
- it('takes the oldest candidate of a domain under its limit, across batches from different partitions', async () => {
+ it('takes the earliest captured candidates of a domain under its limit, across batches from different partitions', async () => {
const pool = buildPool()
pool.add(
[
candidate('https://cdn.hot.com/1.png', 'hot.com'),
candidate('https://cdn.hot.com/2.png', 'hot.com'),
- candidate('https://cdn.hot.com/3.png', 'hot.com'),
+ candidate('https://cdn.hot.com/deferred.png', 'hot.com', NOW_MS - 86_400_000),
],
'partition-1',
NOW_MS + 40_000
@@ -74,8 +74,8 @@ describe('FetchCandidatePool', () => {
const leases = [await takeReady(pool), await takeReady(pool), await takeReady(pool)]
expect(leases.map((lease) => lease?.candidate.currentUrl)).toEqual([
+ 'https://cdn.hot.com/deferred.png',
'https://cdn.hot.com/1.png',
- 'https://cdn.hot.com/2.png',
'https://cdn.quiet.com/1.png',
])
expect(leases[2]?.context).toBe('partition-2')
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.ts
index 1f3627b165ee..a1a65c2839a8 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.ts
@@ -85,8 +85,11 @@ const COMPACT_AFTER_ENTRIES = 64
* Every consumer's batch adds its candidates here, and the fetch workers take them in the order they
* entered the pool, among the origins that are under their limits and past their crawl delay. The
* order uses pool entry and not record age, because the pass deadline and the batch timeout count
- * from when the pod received the batch. The limits count across the pod, so two batches from one
- * partition cannot both claim a domain's slots.
+ * from when the pod received the batch. Inside one batch, the candidates enter in capture order. A
+ * pass-deadline deferral goes back to the end of its partition, behind URLs captured later. In input
+ * order, a domain that cannot serve its whole batch would serve those later URLs on every pass and
+ * never reach the deferred one. The limits count across the pod, so two batches from one partition
+ * cannot both claim a domain's slots.
*/
export class FetchCandidatePool<T> {
private readonly domains = new Map<string, DomainQueue<T>>()
@@ -137,7 +140,7 @@ export class FetchCandidatePool<T> {
const nowMs = Date.now()
const batch: PoolBatch<T> = { owner, entries: [], queued: 0, expiryTimer: undefined }
const touched = new Set<OriginQueue<T>>()
- for (const candidate of candidates) {
+ for (const candidate of [...candidates].sort((left, right) => left.firstSeenAtMs - right.firstSeenAtMs)) {
const origin = this.originQueueFor(candidate)
const entry: PoolEntry<T> = {
payload: { candidate, context, batch },