:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ai-research): label refused and dropped sidecar sockets apart (#96383)
Robbieffc35f14f676
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.mdindex 4a92a89675b3..3a46b97414be 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@@ -94,31 +94,32 @@ The optional fetch dead-letter topic stores each rejected frontier record with iThe 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`, 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. |-| 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. |+| 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.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.mdindex 114d53176eec..f86ee596c70f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md@@ -55,7 +55,7 @@ Requiring more than that makes the gate unreachable for an image late in a batchWhen no peer is available to vouch at all, the time spent on considered rejections and their backoffs opens the gate on its own.Request time counts because a wedged worker consumes most of the Kafka lease before each backoff starts.-Busy, timeout, and transport intervals do not consume this budget because they do not identify a bad image.+Busy, timeout, refused, and reset intervals do not consume this budget because they do not identify a bad image.That threshold has to fire comfortably inside `max.poll.interval.ms` (300s), which is the binding constraint rather than a preference: a batch cannot return while one of its images is in flight, so anything above the lease can never be reached — the group fences the pod first, the partition moves, and its new owner repeats the same work and is fenced in turn, circling the fleet forever.It is published through this lane's own producer slot on the replay cluster, which is where the source topic lives and which carries a `message.max.bytes` sized for these payloads; the generic slot points elsewhere with librdkafka's 1 MB default, where parking a normal image would fail on every attempt.@@ -67,11 +67,15 @@ A publish that keeps failing is retried rather than raised, because the Kafka loWith no dead-letter destination configured the client keeps waiting instead, because the only other option would be discarding.`ml_mirror_image_scrub_consumer_dead_lettered_total` should sit at zero; anything above a trickle is a sidecar bug reproducing across many images, and the fix belongs in the sidecar.-Waiting only applies to answers a later attempt could change: 5xx, 408, 429, and transport failures (a refused socket is the ordinary case while the sidecar is still starting in the same pod).+Waiting only applies to answers a later attempt could change: 5xx, 408, 429, and socket failures (a refused socket is the ordinary case while the image-scrub container is restarting in the same pod).Any other status, and a 200 carrying no bytes, is the sidecar answering a question we did not think we were asking, so it fails the batch loudly instead.Waiting on a 404 from a misdirected `SIDECAR_URL` would otherwise turn a deploy mistake into a pod that consumes nothing, passes every probe, and surfaces only as lag.-`ml_mirror_image_scrub_consumer_scrub_waits_total` (by `reason`: `busy`, `timeout`, `transport`) counts attempts that came back without bytes and will be retried, so it is a saturation signal and never a loss signal.+`ml_mirror_image_scrub_consumer_scrub_waits_total` (by `reason`: `busy`, `timeout`, `refused`, `reset`, `transport`, `rejected`) counts attempts that came back without bytes and will be retried, so it is a saturation signal and never a loss signal.+`refused` means nothing is listening on the sidecar port, which after boot means the image-scrub container has exited.+A `reset` is a connection the sidecar accepted and then dropped, which its shutdown does to idle keep-alive sockets, so resets are expected on every rollout and scale-down.+`transport` is any other socket failure, so a sustained rate outside a rollout is a fault to look at rather than noise.+The unreachable alert selects `refused` and `transport`, never `reset`.`ml_mirror_image_scrub_consumer_stuck_images_total` re-increments while any one image is still being retried past the point a healthy sidecar would have finished it, so it reads as a level rather than a one-off edge.**A stalled pod on this lane looks healthy to Kubernetes.** The lane runs the legacy heartbeat health check (`CONSUMER_LOOP_BASED_HEALTH_CHECK` is unset), and the consumer refreshes that heartbeat every 10s for the whole batch, so a pod blocked on one image stays Ready and Live indefinitely.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.tsindex acb3bf48d36f..b2fc445f6512 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts@@ -782,7 +782,7 @@ describe('ImageBatcher', () => {b.toString() === 'poison'? Promise.reject(new ScrubPoisoned('cannot process', {- reason: 'transport',+ reason: 'rejected',lastError: 'sidecar responded 500',attempts: 12,waitedMs: 60_000,@@ -924,7 +924,7 @@ describe('ImageBatcher', () => {scrub: () =>Promise.reject(new ScrubPoisoned('cannot process', {- reason: 'transport',+ reason: 'rejected',lastError: 'sidecar responded 500',attempts: 12,waitedMs: 60_000,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.tsindex 9b96d8552263..46755b6e4b45 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts@@ -68,7 +68,7 @@ export class ImageScrubConsumerMetrics {*/private static readonly scrubWaits = new Counter({name: 'ml_mirror_image_scrub_consumer_scrub_waits_total',- help: 'Scrub attempts that returned no bytes and will be retried, by reason: "busy" (503, shed), "timeout" (no reply inside the request timeout), "transport" (socket refused or reset, or an unexpected status). Retried rather than dropped, so this is backpressure and not loss',+ help: 'Scrub attempts that returned no bytes and will be retried, by reason: "busy" (503, shed), "timeout" (no reply inside the request timeout), "refused" (nothing listening on the sidecar port, so the sidecar is down or restarting), "reset" (a connection the sidecar accepted and then dropped before replying, which its shutdown does to idle sockets), "transport" (any other socket failure, so a sustained rate outside a rollout is a fault), "rejected" (a 5xx other than 503, a 408, a 429, or an empty 200). Retried rather than dropped, so this is backpressure and not loss. The unreachable alert selects "refused" and "transport"',labelNames: ['reason'],})/**diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.test.tsindex 7d1dc6756035..440c4198d90a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.test.ts@@ -1,9 +1,17 @@import { Server, createServer } from 'node:http'import { AddressInfo } from 'node:net'-import { POISON_MAX_REJECTED_MS, ScrubAborted, ScrubClient, ScrubContractError, ScrubPoisoned } from './scrub-client'+import { ImageScrubConsumerMetrics } from './metrics'+import {+ POISON_MAX_REJECTED_MS,+ ScrubAborted,+ ScrubClient,+ ScrubContractError,+ ScrubPoisoned,+ socketWaitReason,+} from './scrub-client'-type Reply = { status: number; body?: string; durationMs?: number }+type Reply = { status: number; body?: string; durationMs?: number; destroySocket?: boolean; neverReply?: boolean }describe('ScrubClient', () => {let server: Server@@ -11,6 +19,7 @@ describe('ScrubClient', () => {let requests: numberlet replyFor: ((body: string) => Reply | undefined) | undefinedlet nowMs: number+ let port: number// A real loopback server rather than a mocked `request`: the retry loop only matters in terms of// what it does with actual responses, and the 503 shed path in particular is a status the sidecar@@ -31,30 +40,43 @@ describe('ScrubClient', () => {const reply = replyFor?.(Buffer.concat(chunks).toString()) ??replies.shift() ?? { status: 200, body: 'scrubbed' }nowMs += reply.durationMs ?? 0+ if (reply.neverReply) {+ return+ }+ if (reply.destroySocket) {+ req.socket.destroy()+ return+ }res.writeHead(reply.status).end(reply.body ?? '')})})await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ port = (server.address() as AddressInfo).port})afterEach(async () => {await new Promise((resolve) => server.close(resolve))})- const client = (deadLetters = false): ScrubClient =>+ const client = (deadLetters = false, timeoutMs = 1000, onSleep?: () => Promise<void>): ScrubClient =>new ScrubClient(- `http://127.0.0.1:${(server.address() as AddressInfo).port}`,- 1000,+ `http://127.0.0.1:${port}`,+ timeoutMs,deadLetters,// Backoff is asserted separately; sleeping for real would only make this slow and flaky.- (ms) => {+ async (ms) => {nowMs += ms- return Promise.resolve()+ await onSleep?.()},() => 1,() => nowMs)+ const closeServer = (): Promise<void> =>+ new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))+ const listenAgain = (): Promise<void> =>+ server.listening ? Promise.resolve() : new Promise((resolve) => server.listen(port, '127.0.0.1', resolve))+it.each([['shed with 503', 503],['a 500 from a struggling sidecar', 500],@@ -98,25 +120,15 @@ describe('ScrubClient', () => {})it('retries until the sidecar listener accepts connections', async () => {- const address = server.address() as AddressInfo- const baseUrl = `http://127.0.0.1:${address.port}`- await new Promise<void>((resolve, reject) =>- server.close((error) => {- if (error) {- reject(error)- } else {- resolve()- }- })- )+ await closeServer()let retries = 0const failedProbesBeforeListen = 3- const scrubClient = new ScrubClient(baseUrl, 1000)+ const scrubClient = new ScrubClient(`http://127.0.0.1:${port}`, 1000)await scrubClient.waitUntilReachable(async () => {retries += 1if (retries === failedProbesBeforeListen) {- await new Promise<void>((resolve) => server.listen(address.port, '127.0.0.1', resolve))+ await listenAgain()}})@@ -124,6 +136,47 @@ describe('ScrubClient', () => {expect(requests).toBe(1)})+ it.each([+ ['nothing listening on the sidecar port', 'refused', { listening: false }],+ ['a connection the sidecar dropped before replying', 'reset', { reply: { status: 0, destroySocket: true } }],+ ['a request the sidecar never answered', 'timeout', { neverReplyToFirst: true, timeoutMs: 100 }],+ ] as const)('labels %s as "%s" and keeps waiting', async (_label, reason, setup) => {+ // A dropped socket is what every pod sees when the sidecar closes its idle connections on+ // shutdown, and a timeout is a sidecar that is slow rather than absent, so either of those+ // landing on "refused" would page for a rollout.+ const incScrubWait = jest.spyOn(ImageScrubConsumerMetrics, 'incScrubWait')+ if ('reply' in setup) {+ replies = [setup.reply]+ }+ // Keyed on the request count, not queued: a reply left unconsumed by a socket the client already destroyed would be served to the retry.+ if ('neverReplyToFirst' in setup) {+ replyFor = () => (requests === 1 ? { status: 0, neverReply: true } : undefined)+ }+ const scrubClient = client(false, 'timeoutMs' in setup ? setup.timeoutMs : 1000, listenAgain)+ if ('listening' in setup) {+ await closeServer()+ }++ await expect(scrubClient.scrub(Buffer.from('image'))).resolves.toEqual(Buffer.from('scrubbed'))++ expect(incScrubWait.mock.calls).toEqual([[reason]])+ incScrubWait.mockRestore()+ })++ it.each([+ ['ECONNREFUSED', 'refused'],+ ['ECONNRESET', 'reset'],+ ['EPIPE', 'reset'],+ ['ECONNABORTED', 'reset'],+ ['ENOTFOUND', 'transport'],+ ['ETIMEDOUT', 'transport'],+ ['EMFILE', 'transport'],+ [undefined, 'transport'],+ ])('maps socket error code %s to "%s"', (code, reason) => {+ // Only a peer closing an accepted connection may read as "reset"; anything else, or no code, must stay on a label the alert selects.+ expect(socketWaitReason(Object.assign(new Error('boom'), code ? { code } : {}))).toBe(reason)+ })+it('never dead-letters on saturation alone, however long the sidecar sheds', async () => {// The safety property of the whole dead-letter path. Under a backlog every image waits a// long time, so anything keyed on waiting or failure count alone would park the entirediff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.tsindex 63a2baf27ffb..51cdfc7d398a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client.ts@@ -11,10 +11,18 @@ const REACHABILITY_RETRY_MS = 1_000/*** Why a single attempt did not come back with bytes.*- * `rejected` is kept apart from `transport` because only it means the sidecar took the image,- * looked at it, and could not produce bytes. A refused or reset socket says nothing about content.+ * `rejected` is kept apart from the socket reasons because only it means the sidecar took the image,+ * looked at it, and could not produce bytes. A refused or dropped socket says nothing about content.+ *+ * The socket reasons are split by what they say about the sidecar. `refused` means nothing is+ * listening on the sidecar port. `reset` is a connection that was accepted and then dropped before+ * a reply, which the sidecar does to its idle keep-alive sockets on every shutdown, so it is expected+ * on a rollout or a scale-down and does not mean the sidecar is down. `transport` is every other+ * socket failure, including one that carries no error code, and is deliberately not folded into+ * `reset`: an unrecognised failure has to land on a label the unreachable alert selects, not on the+ * one the runbook tells the on-call to expect. The alert selects `refused` and `transport`.*/-export type ScrubWaitReason = 'busy' | 'timeout' | 'transport' | 'rejected'+export type ScrubWaitReason = 'busy' | 'timeout' | 'refused' | 'reset' | 'transport' | 'rejected'/** Raised only when the caller hangs up, which is the one condition that stops the wait. */export class ScrubAborted extends Error {}@@ -86,7 +94,7 @@ export const POISON_MIN_OTHER_SUCCESSES = 3* so a threshold above the lease can never be reached: the group fences the pod first, the partition* moves, and its new owner repeats the same work and is fenced in turn. The gate would be dead code* and the images would circle the fleet. Request time counts because a wedged worker consumes most- * of the lease before each backoff starts. Busy, timeout, and transport intervals stay outside this+ * of the lease before each backoff starts. Busy, timeout, and socket intervals stay outside this* budget because they do not blame the image.** The trade is deliberate. A sidecar broken for this long parks images rather than holding them,@@ -102,12 +110,14 @@ const BACKOFF_BASE_MS = 100* A 503 is the sidecar stating it is full, so backing off hard is the point: at the short cap eight* in-flight images per pod keep up a steady stream of re-posts against something already shedding,* which is load rather than backpressure and slows the recovery it is waiting for. A refused socket- * is different, because the ordinary cause is the sidecar still starting up in the same pod, and- * waiting half a minute to notice it came up is a needless stall.+ * is different, because the ordinary cause is the sidecar container restarting in the same pod and+ * reloading its models, and waiting half a minute to notice it came back is a needless stall.*/const BACKOFF_MAX_MS: Record<ScrubWaitReason, number> = {busy: 30_000,timeout: 5_000,+ refused: 5_000,+ reset: 5_000,transport: 5_000,// The sidecar answered, so it is neither full nor unreachable, and re-asking quickly costs it a// whole scrub attempt each time. Backed off like a shed request rather than like a lost socket.@@ -154,6 +164,17 @@ function isWaitable(status: number): boolean {return status >= 500 || status === 408 || status === 429}+/** The codes Node reports when the peer closes a connection it had accepted. Nothing else may read as a benign reset. */+const RESET_CODES = new Set(['ECONNRESET', 'EPIPE', 'ECONNABORTED'])++export function socketWaitReason(error: unknown): ScrubWaitReason {+ const code = (error as NodeJS.ErrnoException | undefined)?.code+ if (code === 'ECONNREFUSED') {+ return 'refused'+ }+ return code !== undefined && RESET_CODES.has(code) ? 'reset' : 'transport'+}+export class ScrubClient {private readonly url: URL/**@@ -245,10 +266,10 @@ export class ScrubClient {if (error instanceof ScrubAborted || error instanceof ScrubContractError) {throw error}- // Refused, reset, or destroyed by the request timeout. None of them say anything+ // Refused, dropped, or destroyed by the request timeout. None of them say anything// about this image, and none of them are fixed by dropping it.detail = (error as Error)?.message ?? String(error)- reason = detail === REQUEST_TIMED_OUT ? 'timeout' : 'transport'+ reason = detail === REQUEST_TIMED_OUT ? 'timeout' : socketWaitReason(error)}if (signal?.aborted) {throw new ScrubAborted('scrub batch aborted')