: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
feat(session-replay): complete remote image fetch pipeline (#87501)
Robbiebef59f32babd
diff --git a/nodejs/jest.config.js b/nodejs/jest.config.jsindex 1f5f0f59d19a..035aaaefa759 100644--- a/nodejs/jest.config.js+++ b/nodejs/jest.config.js@@ -25,9 +25,11 @@ module.exports = {// `dev/` folders hold dev-only benchmarks/scripts, never CI tests. Anchored to rootDir:// an unanchored '/dev/' also matches checkout paths like ~/dev/posthog and ignores every test.testPathIgnorePatterns: ['/node_modules/', '<rootDir>/(src|tests)(/.*)?/dev/'],+ transformIgnorePatterns: ['/node_modules/(?!\\.pnpm/@trybyte\\+robotstxt-parser|@trybyte/robotstxt-parser)'],// NOTE: This should be kept in sync with tsconfig.jsonmoduleNameMapper: {+ '^@trybyte/robotstxt-parser$': '<rootDir>/node_modules/@trybyte/robotstxt-parser/dist/index.js',// `~/...` -> src/, `~/tests/...` -> tests/. The `.js`-suffixed variants come first to strip the// nodenext extension: the production tsconfig is module: nodenext, which forces import()// specifiers to carry `.js` (TS2835/TS2307), so ts-jest emits e.g. `~/foo.js` while only adiff --git a/nodejs/package.json b/nodejs/package.jsonindex 6279514dfadb..551de7c2ac70 100644--- a/nodejs/package.json+++ b/nodejs/package.json@@ -100,6 +100,7 @@"@temporalio/proto": "1.15.0","@temporalio/worker": "1.15.0","@temporalio/workflow": "1.15.0",+ "@trybyte/robotstxt-parser": "^1.2.0","@types/node": "catalog:","@types/tail": "^2.2.1","avsc": "^5.7.9",@@ -137,6 +138,7 @@"puppeteer-capture": "^1.43.0","re2": "^1.22.1","snappy": "^7.2.2",+ "structured-headers": "^2.0.3","tail": "^2.2.6","tldts": "^6.1.57","typescript": "catalog:",diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.tsindex 8c11afd64d81..f7440166ff6c 100644--- a/nodejs/src/common/config/kafka-topics.ts+++ b/nodejs/src/common/config/kafka-topics.ts@@ -52,9 +52,9 @@ export const KAFKA_SESSION_REPLAY_IMAGE_FETCH = `${prefix}session_replay_image_f// Kafka has no delayed delivery, so a retry waits in a topic whose period is fixed. The period// belongs to the topic rather than to the record, so the records leave in the order they become// ready and an hour-long wait never sits in front of a one minute wait.-export const KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M = `${prefix}session_replay_image_fetch_retry_1m${suffix}`-export const KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M = `${prefix}session_replay_image_fetch_retry_10m${suffix}`-export const KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H = `${prefix}session_replay_image_fetch_retry_1h${suffix}`+export const KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M = `${prefix}ai_research_session_replay_image_fetch_retry_1m${suffix}`+export const KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M = `${prefix}ai_research_session_replay_image_fetch_retry_10m${suffix}`+export const KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H = `${prefix}ai_research_session_replay_image_fetch_retry_1h${suffix}`// images the scrub sidecar cannot process, parked so they stop holding the head of their partition.// The original bytes are kept: unscrubbed content must never reach the ML bucket, but it must not bediff --git a/nodejs/src/common/kafka/consumer/consumer-v2.ts b/nodejs/src/common/kafka/consumer/consumer-v2.tsindex caade8f990f3..6c5114136d37 100644--- a/nodejs/src/common/kafka/consumer/consumer-v2.ts+++ b/nodejs/src/common/kafka/consumer/consumer-v2.ts@@ -31,6 +31,7 @@ import {consumerBatchUtilization,consumerDrainDuration,consumerDrainTimeouts,+ consumerPolls,consumerStaleStoreOffsetsSkipped,kafkaConsumerAssignment,} from './metrics'@@ -51,6 +52,7 @@ export type KafkaConsumerV2Config = {autoOffsetStore?: booleanautoCommit?: booleanenablePartitionEof?: boolean+ fetchBatchSize?: number}export type RdKafkaConsumerOverrides = Omit<@@ -133,7 +135,7 @@ export class KafkaConsumerV2 {.toString(36).substring(2, 8)}`- this.fetchBatchSize = defaultConfig.CONSUMER_BATCH_SIZE+ this.fetchBatchSize = config.fetchBatchSize ?? defaultConfig.CONSUMER_BATCH_SIZEthis.batchTimeoutMs = this.config.batchTimeoutMs ?? DEFAULT_BATCH_TIMEOUT_MSthis.maxBackgroundTasks = defaultConfig.CONSUMER_MAX_BACKGROUND_TASKSthis.backgroundTaskTimeoutMs = defaultConfig.CONSUMER_BACKGROUND_TASK_TIMEOUT_MS@@ -307,6 +309,7 @@ export class KafkaConsumerV2 {promisifyCallback<Message[]>((cb) => this.rdKafkaConsumer.consume(this.fetchBatchSize, cb)))+ consumerPolls.labels(this.config.topic, this.config.groupId).inc()consumerBatchSize.observe(messages.length)consumerBatchSizeKb.observe(messages.reduce((acc, m) => (m.value?.length ?? 0) + acc, 0) / 1024)consumerBatchUtilization.labels({ groupId: this.config.groupId }).set(messages.length / this.fetchBatchSize)diff --git a/nodejs/src/common/kafka/consumer/metrics.ts b/nodejs/src/common/kafka/consumer/metrics.tsindex 403ec1dcc448..06714a3a625f 100644--- a/nodejs/src/common/kafka/consumer/metrics.ts+++ b/nodejs/src/common/kafka/consumer/metrics.ts@@ -51,6 +51,12 @@ export const consumerBatchSizeKb = new Histogram({buckets: [0, 128, 512, 1024, 5120, 10240, 20480, 51200, 102400, 204800, Infinity],})+export const consumerPolls = new Counter({+ name: 'kafka_consumer_polls_total',+ help: 'Number of completed Kafka polls, including empty polls',+ labelNames: ['topic', 'groupId'],+})+// v2-only metrics — kept here for symmetry. v1 doesn't reference these.export const consumerDrainDuration = new Histogram({diff --git a/nodejs/src/common/utils/request-streamed.test.ts b/nodejs/src/common/utils/request-streamed.test.tsindex 806aa88860ac..ddd9a551c4db 100644--- a/nodejs/src/common/utils/request-streamed.test.ts+++ b/nodejs/src/common/utils/request-streamed.test.ts@@ -11,7 +11,7 @@ jest.mock('undici', () => ({const requestMock = request as jest.MockedFunction<typeof request>-function respond(chunks: Buffer[], headers: Record<string, string> = {}): void {+function respond(chunks: Buffer[], headers: Record<string, string> | string[] = {}): void {requestMock.mockResolvedValue({statusCode: 200,headers,@@ -46,7 +46,16 @@ describe('fetchStreamed', () => {const { bytes, overLimit } = await response.read(10)expect(overLimit).toBe(true)- // Empty, because a truncated image is not an image and must not look like one to a caller.+ expect(bytes).toHaveLength(10)+ })++ it('can discard a capped prefix that its caller will not parse', async () => {+ respond([Buffer.alloc(8), Buffer.alloc(8)])++ const response = await fetchStreamed('https://example.com/a.png', { timeoutMs: 1000 })+ const { bytes, overLimit } = await response.read(10, false)++ expect(overLimit).toBe(true)expect(bytes).toHaveLength(0)})@@ -89,6 +98,23 @@ describe('fetchStreamed', () => {expect(Object.getPrototypeOf(response.headers)).toBeNull()})+ it('preserves repeated response field lines in their received order', async () => {+ respond([], ['X-Robots-Tag', 'index', 'Content-Type', 'image/png', 'X-Robots-Tag', 'noai'])++ const response = await fetchStreamed('https://example.com/a.png', { timeoutMs: 1000 })+ response.discard()++ expect(response.headerLines).toEqual([+ { name: 'x-robots-tag', value: 'index' },+ { name: 'content-type', value: 'image/png' },+ { name: 'x-robots-tag', value: 'noai' },+ ])+ expect(requestMock).toHaveBeenCalledWith(+ 'https://example.com/a.png',+ expect.objectContaining({ responseHeaders: 'raw' })+ )+ })+it.each([['ftp://example.com/a.png'], ['not a url']])('refuses %s before opening a socket', async (url) => {await expect(fetchStreamed(url, { timeoutMs: 1000 })).rejects.toThrow(InvalidRequestError)diff --git a/nodejs/src/common/utils/request.ts b/nodejs/src/common/utils/request.tsindex 45bc8b822f24..56e46418742a 100644--- a/nodejs/src/common/utils/request.ts+++ b/nodejs/src/common/utils/request.ts@@ -439,14 +439,41 @@ export type StreamedFetchOptions = {export type StreamedResponse = {status: numberheaders: Record<string, string>+ headerLines: Array<{ name: string; value: string }>/*** Reads at most `maxBytes`, then abandons the rest. `overLimit` says the response had more, and- * `bytes` is then empty, because a truncated payload is not usable.+ * `bytes` then contains the first `maxBytes`, so parsers with a bounded-prefix rule can use it.*/- read: (maxBytes: number) => Promise<{ bytes: Buffer; overLimit: boolean }>+ read: (maxBytes: number, retainPrefixOnOverflow?: boolean) => Promise<{ bytes: Buffer; overLimit: boolean }>discard: () => void}+function orderedHeaderLines(raw: unknown): Array<{ name: string; value: string }> {+ if (Array.isArray(raw)) {+ const lines: Array<{ name: string; value: string }> = []+ for (let index = 0; index + 1 < raw.length; index += 2) {+ lines.push({ name: String(raw[index]).toLowerCase(), value: String(raw[index + 1]) })+ }+ return lines+ }+ if (!raw || typeof raw !== 'object') {+ return []+ }+ return Object.entries(raw).flatMap(([name, value]) =>+ (Array.isArray(value) ? value : [value]).flatMap((line) =>+ line === undefined ? [] : [{ name: name.toLowerCase(), value: String(line) }]+ )+ )+}++function flattenHeaderLines(lines: Array<{ name: string; value: string }>): Record<string, string> {+ const headers: Record<string, string> = Object.create(null)+ for (const { name, value } of lines) {+ headers[name] ??= value+ }+ return headers+}+/*** Memory here follows the bytes that arrive, never the bytes a response claims.*@@ -457,7 +484,8 @@ export type StreamedResponse = {*/async function readCappedBody(body: Dispatcher.ResponseData['body'],- maxBytes: number+ maxBytes: number,+ retainPrefixOnOverflow: boolean): Promise<{ bytes: Buffer; overLimit: boolean }> {const chunks: Buffer[] = []let total = 0@@ -465,17 +493,26 @@ async function readCappedBody(try {for await (const chunk of body) {const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)- total += buffer.length- if (total > maxBytes) {+ const remaining = maxBytes - total+ if (buffer.length > remaining) {+ if (remaining > 0) {+ chunks.push(buffer.subarray(0, remaining))+ total += remaining+ }overLimit = true+ if (!retainPrefixOnOverflow) {+ chunks.length = 0+ total = 0+ }break}chunks.push(buffer)+ total += buffer.length}} finally {destroyBody(body)}- return { bytes: overLimit ? Buffer.alloc(0) : Buffer.concat(chunks), overLimit }+ return { bytes: Buffer.concat(chunks, total), overLimit }}/**@@ -502,6 +539,7 @@ export async function fetchStreamed(url: string, options: StreamedFetchOptions):headers: options.headers,dispatcher: sharedSecureAgent,signal: AbortSignal.timeout(options.timeoutMs),+ responseHeaders: 'raw',})} catch (error) {inflightExternalRequests.dec()@@ -520,16 +558,18 @@ export async function fetchStreamed(url: string, options: StreamedFetchOptions):return true}- const headers = flattenHeaders(result.headers)+ const headerLines = orderedHeaderLines(result.headers)+ const headers = flattenHeaderLines(headerLines)return {status: result.statusCode,headers,- read: async (maxBytes: number) => {+ headerLines,+ read: async (maxBytes: number, retainPrefixOnOverflow = true) => {if (settled) {return { bytes: Buffer.alloc(0), overLimit: false }}try {- return await readCappedBody(result.body, maxBytes)+ return await readCappedBody(result.body, maxBytes, retainPrefixOnOverflow)} finally {settle()}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 d9094efccff6..bce4c6f17650 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@@ -1,103 +1,149 @@# Image fetcher implementation notes-The [README](./README.md) is the normative specification. This file lists changes that the current implementation needs to satisfy that specification.+The [README](./README.md) is the normative specification. This file records the implementation, assumptions, and rollout constraints.-## Global URL refs+## Implementation map-The current URL ref has the form `imageurl:<pseudo-team>:<hash>`. The hash uses a key derived for one team. The crawl-history key also contains the team pseudonym.+### URL collection and identity-Change the URL collector, Kafka record parser, crawl-history key, image scrubber, S3 storage, and data-preparation lookup to use the global URL ref from requirement 13.5. Inline image refs can remain team-specific.+The shared Rust URL policy performs admission, canonicalization, and global ref creation. It refuses private targets, credentials, userinfo, and known signed URLs.-Derive one URL HMAC key from the existing ML pseudonymization secret without a team input. Pin the derivation from requirement 13.5 and the resulting test vectors in the shared Rust and Node fixtures before changing either producer.+The mirror emits versioned frontier jobs. Each job carries the original ref, current URL, remaining hops, timing, and amplification counters.-## Data-preparation ref attributes+Kafka uses the registrable domain as the frontier key. Rate, burst, active-request, transient back-off, and circuit-breaker state use that registrable domain. Policy caches and crawl delay use the full origin.-The anonymizer already stores a remote-image ref in `data-anon-image-ref-<attribute>`. The current ref resolver handles `image:` refs that replace an image value directly. It does not recognize `imageurl:` or use a sibling ref attribute to identify the placeholder that it must replace.+### Policy and network boundary-The current collector considers `src`, `rr_src`, and `poster`. Limit URL collection and sibling ref creation to `src` until the specification adds another source attribute.+The fetcher evaluates `robots.txt`, TDMRep, response opt-outs, and HTTP cache metadata. Configuration misses are coalesced per origin and file.-The packed DOM serializer treats an unrecognized `data-*` attribute as model input and tokenizes its value. Without a new removal step, it will tokenize the ref hash.+The fetcher follows configuration redirects only inside the source registrable domain. It treats a cross-registrable-domain redirect as unreachable.-Resolve the URL ref before rendering and tokenization. Use the sibling attribute's suffix as the destination attribute. Remove the sibling attribute after the lookup, including when the image is missing.+The shared streamed-request helper preserves repeated response field lines. Policy evaluation therefore sees every opt-out field in received order.-## Fetcher-to-scrubber record+Production requests use Smokescreen. The Rust admission policy also refuses every IP literal, including a public IP literal.-The mirror currently sends an image to the scrub topic with the ref as the Kafka key and the raw image bytes as the Kafka value. It sends no JSON envelope. The scrubber accepts `image:` refs and rejects `imageurl:` refs.+Web Bot Auth uses the shared PostHog key directory. The directory response has a 60-second public cache lifetime.-The fetcher does not publish images yet. The server enforces dry-run mode.+### Scheduling and retries-Publish the fetched response body in the Kafka value and add the headers from section 17. The current fetcher requests `identity` and refuses another content coding. Change it to accept the codings it advertises and pass the encoded response body to Kafka.+Each registrable domain has one token bucket, active-request limit, transient-failure count, and circuit breaker. Each origin has its own crawl delay and configuration-request state. Each runtime map contains at most 20,000 entries.-Change the scrubber to accept a global `imageurl:` ref. Decode its `content-encoding` with an uncompressed-size limit, then check its bytes against `content-type` before scrubbing it.+A registrable domain remains in memory while it is active, blocked, or has a pending request grant. An origin remains in memory while it has an active or scheduled request, a reserved image-request start, or an unelapsed crawl delay. A full map defers untracked work without network access.-The current scrubber writes every image into a binary shard and writes its location to a time-partitioned Parquet index. Store a URL-backed image at the deterministic object key from requirements 17.11 to 17.13 instead. Keep the shard and index path for inline images.+The frontier consumer uses cooperative rebalancing. Its revoke path drains active work before it releases assigned partitions.-The current dead-letter sink rebuilds the headers from diagnostic data, and its replay keeps only the replay counter. Change both paths to preserve `content-type` and `content-encoding`.+Retry jobs use 1-minute, 10-minute, and 1-hour Kafka topics. The topics use broker append timestamps.-The image-fetch producer currently uses the default Kafka message limit because its configuration has no `message.max.bytes` setting. Raise the configured response limit to 20 MiB and size the producer and both topics for that limit plus the maximum record overhead.+Each delay consumer waits once for the latest record in its batch. It then republishes the complete batch to the frontier.-## Durable completion+### Durable completion-The current fetcher records a successful fetch in DynamoDB without publishing its bytes. Change the handler to use the order in requirement 10.3.+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.-The current frontier record does not carry all state needed after a redirect or retry. Replace it with the versioned job schema in requirement 10.4 and keep its counters and not-before time through every frontier and delay-topic publish.+The client retries unprocessed keys and items with bounded concurrency and time. An incomplete chunk generation is a logged cache miss that the next configuration fetch repairs. A malformed base item fails the Kafka batch.-The current crawl-history client can return partial read or write failures. The consumer logs these failures and continues. Change these paths to throw from the Kafka batch. Do not store the input offsets after a DynamoDB failure.+For a successful fetch, the producer publishes the image before DynamoDB records completion. Kafka offsets commit only after both operations succeed.-## Configuration caches+Frontier records retain work until a terminal result. A pass deadline defers unfinished jobs instead of dropping them.-The current fetcher does not fetch or cache robots.txt or tdmrep.json.+### Fetch-to-scrub transport-The current request limits bound open sockets and the host-budget map. They do not coalesce concurrent cache misses for one origin. Add one in-flight configuration request per origin and file type. Other requests for that entry must wait for the same result.+The fetch producer sends the encoded response body as the Kafka value. Headers carry the content type and ordered content codings.-Use `@trybyte/robotstxt-parser` with the product token `PostHogImageFetcherBot`. Use its low-level parser for every extension field line in addition to its RFC 9309 group and path matcher.+The production fetch queue can hold one full 100-record batch at the response-size limit. The delay consumers publish sequentially to avoid queue-full replay loops.-## URL admission+The scrubber decodes supported codings in reverse order. It enforces the uncompressed limit during each decoding layer and verifies the image signature.-The current Rust collector removes userinfo before it emits the fetch URL. Change it to refuse the URL instead. The current collector also accepts several known pre-signed URL forms and removes their volatile parameters only from the dedup URL. Change it to refuse the pre-signed forms in requirement 1.2.+Inline images retain sharded storage and Parquet indexes. URL images use `scrubbed-images/url/<global-hash>` for deterministic direct lookup. Conditional creates keep the first scrubbed image written for each global ref.-Keep only the non-credential volatile query fields from requirement 13.3 in canonicalization. Pin the complete canonicalization behavior with shared Rust and Node test vectors.+URL-image S3 writes use the scrub worker concurrency bound. A full scrub batch cannot create an unbounded S3 request burst.-## Per-origin budgets+The ML data-preparation resolver reads URL images by global ref. It removes sibling ref attributes before rendering, including when an image is absent.-The current producer partitions the frontier by registrable domain. Keep that partition key so that every origin under the registrable domain has one steady-state pod owner.+### Operations-Change the rate limit, concurrency limit, back-off, circuit breaker, and configuration request lock to use the origin. Use the registrable and provider domains only for Kafka ownership and bounded metrics.+Metrics cover terminal outcomes, requests, origin policy, registrable-domain request state, retries, amplification, system time, and DynamoDB failures. Every metric label defined by this lane uses a fixed category.-The image-fetch server imports `KafkaConsumer` from `consumer-v1` directly. Move it to `KafkaConsumerV2`, whose cooperative revoke path drains the active batch before unassignment. Keep the bounded timeout exception from requirement 5.7. Do not add a distributed lease.+`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`.-## Error back-off+The Grafana dashboard uses these runtime metrics. Its frontier health panels exclude the delay topics so they do not double-count retry traffic.-The current host budget halves its rate after a failure, mixes refusals with transient failures, and does not have a half-open probe. Replace that behavior with the exact transient-failure count, jittered exponential delay, and half-open state in section 7. Configuration-file failures must not change this image-request state.+The Helm deployment defines fetch, scrub, and three retry consumers. Fetch and retry synchronization remains manual until their dependencies exist.-## Delay topics+## Failure-mode observability-The current delay consumer requires a batch size of 1 because it waits separately for each record. Change it to calculate the latest ready time for the batch, wait once, and then publish the batch.+The lane uses bounded labels for all signals. The dashboards group failures by a fixed operation, reason, outcome, stage, or destination.-The current delay topics do not require broker timestamps. Set `message.timestamp.type=LogAppendTime` on all three topics. The delay consumer must use the resulting Kafka record timestamp and must not use a producer timestamp.+| 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. |-The current publisher sends a delay longer than 1 hour through the 1-hour topic more than once. Change it to record a refusal when the required delay is longer than the longest delay topic.+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.-## Load handling+## Assumptions-The current consumer drops an input when its capture time is older than the configured maximum age. Remove this age-based drop.+- Only the `src` attribute creates a remote-image ref. The collector does not create refs for `rr_src` or `poster`.+- A response can contain at most four content-coding layers. This bound limits decompression work while retaining common stacked encodings.+- The standard pass is shorter than the minimum image retry delay. Active back-off therefore follows requirement 7.13 without an in-memory second pass.+- Smokescreen is the authoritative production DNS and connection boundary. Local URL admission is an additional fail-closed check.+- The fetch deployment uses Smokescreen without proxy credentials. The lane does not send `Proxy-Authorization`.+- The Web Bot Auth private key and Kubernetes secret remain operator-managed. No private key material belongs in these repositories.+- The DynamoDB table and its workload identity permissions exist before the fetch deployment becomes active.+- The shared ML bucket grants the data-preparation workload read access to the deterministic URL-image prefix.+- Retry topics use the `ai_research_session_replay_` naming convention.+- Replacement infrastructure provisions the required topics before consumers start. No deployed producer or consumer uses the deprecated names.+- Deprecated topics remain protected and unused. Their cleanup is not required for this rollout.+- Current public documentation already describes the collector-side image limits. No separate documentation repository change is required.+- A cross-registrable-domain configuration redirect fails closed. This rule prevents a source Kafka partition from creating request state for another partition's registrable domain.-The current fetch pass limits how many shed URLs it republishes. Remove this limit. Kafka stores load until the lane can process it. A pass deadline can stop new requests, but every unfinished URL must remain in Kafka.+## Delta from the original requirements-## Repeated response headers+The implementation has four product-behavior or interface deltas from the original requirements.-The current streamed-request helper keeps only the first value of a repeated response header. Change it to expose every field line in received order. Apply requirement 14.17 before parsing response-header opt-outs. Keeping only the first value can miss a later `X-Robots-Tag: noai` refusal.+| Original requirement | Final implementation | Reason and effect |+| ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Accept any number of supported content-coding layers. | Accept at most four layers. | This bound limits decompression work. A response with more than four layers is refused. Requirements 14.1 and 17.6 now state this bound. |+| Export top-N registrable and provider domains and exact HTTP response values. | Export no registrable-domain or provider-domain labels and group HTTP status by class. | The metrics system does not support high-cardinality labels. Fixed categories keep the number of time series bounded. Per-registrable-domain request share is not available in metrics. Requirements 11.2 and 11.6 now state this rule. |+| Apply one crawl delay across a registrable domain. | Apply each crawl delay only to the origin that published it. | robots.txt answers for one origin. Sibling origins still share rate, burst, active-request, transient back-off, and circuit-breaker controls. Requirements 5.11, 5.12, 7.10, and 7.11 state the split. |+| Follow a configuration redirect to any authority without Kafka republishing. | Follow it only inside the source registrable domain. | Cross-registrable-domain redirects could create a second pod-local budget outside the target Kafka owner. The lane treats the source configuration as unreachable and does not request the target. Requirements 3.5 and 5.4 state this bound. |-## Same-origin redirect continuation+The implementation also has these rollout and repository-state deltas. They do not change steady-state fetch behavior.-The current fetcher treats a fourth same-origin redirect as a terminal `too_many_redirects` result. Change it to republish the target with the original ref and remaining image-hop budget. Requirements 9.7 and 9.8 specify this 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.+- 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.+- The second activation charts change enables the version 2 mirror producer after active fetching is verified.+- Web Bot Auth private keys and the Kubernetes secret stay outside source control. An operator must create them before activation.+- The DynamoDB table and workload identity permissions were already present on the current infrastructure `main` branch. This work does not create a duplicate table or duplicate permissions.+- The required public documentation was already present on the current `posthog.com` `master` branch. This work does not create an empty documentation pull request.-## Bounded origin state+## Deployment order-The current budget map holds 20,000 entries. It can evict an origin while that origin is blocked. A later request creates a new entry with a full burst. That request can contact the origin before its `Retry-After` or breaker delay ends.+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.+4. Deploy the fetch and retry workloads with automatic synchronization disabled. Keep fetch dry-run enabled and the version 2 mirror producer disabled.+5. Start each retry tier, then start the fetch workload and verify policy, refusal, origin-state, and registrable-domain-state metrics.+6. Apply the first activation charts change to enable image publishing, then verify fetch processing and downstream delivery.+7. Apply the second activation charts change to enable the version 2 mirror producer.+8. Enable automatic synchronization after the first production verification succeeds.-Change the map to evict only entries that meet requirement 5.14. If no entry is eligible, send the job for the untracked origin to the 1-minute delay topic without making a network request.--## Key-directory caching--The current Django key-directory response sends `Cache-Control: no-store`. Change it to the 60-second public cache policy in requirement 4.11 while keeping the 5-minute response-signature lifetime.+Do not activate a delay consumer before its topic uses `LogAppendTime`. Producer timestamps do not provide the required delay guarantee.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.mdindex e191d292a1dc..6b44c8321dd5 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@@ -41,55 +41,55 @@ The [upstream Kafka consumer](/nodejs/src/ingestion/pipelines/sessionreplay/ml-mThe presence of a listed signature, credential, token, or signed-header list is enough to refuse the URL. The lane does not validate the value or require other fields from the same signing scheme. Supporting fields such as the algorithm, creation time, and expiry do not cause a refusal by themselves.-The lane checks every occurrence of a query parameter, including an occurrence with an empty value. It decodes percent-encoding in each parameter name before a case-insensitive comparison. It refuses the URL if it cannot enumerate and decode every parameter. The lane compares path patterns case-insensitively. A `*` wildcard in a domain pattern matches one non-empty DNS label.+The lane checks every occurrence of a query parameter, including an occurrence with an empty value. It decodes percent-encoding in each parameter name before a case-insensitive comparison. It refuses the URL if it cannot enumerate and decode every parameter. The lane compares path patterns case-insensitively. A `*` wildcard in a host pattern matches one non-empty DNS label.Query parameters:-| Parameter | Domain | Notes |-| ---------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `__cld_token__` | | [Cloudinary](https://cloudinary.com/documentation/control_access_to_media) access token |-| `__token__` | | [Akamai](https://techdocs.akamai.com/adaptive-media-delivery/docs/generate-a-token-and-apply-it-to-content) token |-| `access_token` | | |-| `api_key` | | |-| `apikey` | | |-| `auth_token` | | |-| `authorization` | | |-| `AWSAccessKeyId` | | AWS Signature Version 2 credential |-| `Credential` | | |-| `GoogleAccessId` | | [Google Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/signed-urls) Signature Version 2 credential |-| `hdnea` | | [Akamai](https://techdocs.akamai.com/adaptive-media-delivery/docs/generate-a-token-and-apply-it-to-content) token |-| `hdntl` | | [Akamai](https://techdocs.akamai.com/adaptive-media-delivery/docs/generate-a-token-and-apply-it-to-content) token |-| `hdnts` | | [Akamai](https://techdocs.akamai.com/adaptive-media-delivery/docs/generate-a-token-and-apply-it-to-content) token |-| `id_token` | | |-| `ik-s` | | [ImageKit](https://imagekit.io/docs/media-delivery-basic-security) signature |-| `jsessionid` | | [Jakarta Servlet](https://jakarta.ee/specifications/servlet/6.1/jakarta-servlet-spec-6.1.html) session token |-| `OSSAccessKeyId` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) credential |-| `phpsessid` | | |-| `q-ak` | | [Tencent COS](https://cloud.tencent.com/document/product/436/68284) credential |-| `q-signature` | | [Tencent COS](https://cloud.tencent.com/document/product/436/68284) signature |-| `s=<32-char token>` | | [Imgix](https://github.com/imgix/imgix-blueprint#securing-urls) |-| `security-token` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) temporary credential |-| `session_token` | | |-| `sessionid` | | |-| `sig` | | Includes [Azure SAS](https://learn.microsoft.com/en-us/rest/api/storageservices/create-account-sas) and [Cloudflare Images](https://developers.cloudflare.com/images/optimization/hosted-images/serve-private-images/) signatures |-| `Signature` | | Includes AWS, [CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html), and [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) signatures |-| `SignedHeaders` | | Signed URL header list |-| `token` | | Includes [Bunny](https://support.bunny.net/hc/en-us/articles/360016055099-How-to-sign-URLs-for-BunnyCDN-Token-Authentication) query tokens |-| `X-Amz-Credential` | | [AWS Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-query-string-auth.html) credential |-| `X-Amz-Security-Token` | | [AWS Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-query-string-auth.html) temporary credential |-| `X-Amz-Signature` | | [AWS Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-query-string-auth.html) signature |-| `X-Amz-SignedHeaders` | | [AWS Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-query-string-auth.html) signed header list |-| `X-Cos-Security-Token` | | [Tencent COS](https://cloud.tencent.com/document/product/436/68284) temporary credential |-| `X-Goog-Credential` | | [Google Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/signed-urls) Signature Version 4 credential |-| `X-Goog-Signature` | | [Google Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/signed-urls) Signature Version 4 signature |-| `X-Goog-SignedHeaders` | | [Google Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/signed-urls) Signature Version 4 signed header list |-| `x-oss-credential` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) Signature Version 4 credential |-| `x-oss-security-token` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) temporary credential |-| `x-oss-signature` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) Signature Version 4 signature |+| Parameter | Host pattern | Notes |+| ---------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `__cld_token__` | | [Cloudinary](https://cloudinary.com/documentation/control_access_to_media) access token |+| `__token__` | | [Akamai](https://techdocs.akamai.com/adaptive-media-delivery/docs/generate-a-token-and-apply-it-to-content) token |+| `access_token` | | |+| `api_key` | | |+| `apikey` | | |+| `auth_token` | | |+| `authorization` | | |+| `AWSAccessKeyId` | | AWS Signature Version 2 credential |+| `Credential` | | |+| `GoogleAccessId` | | [Google Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/signed-urls) Signature Version 2 credential |+| `hdnea` | | [Akamai](https://techdocs.akamai.com/adaptive-media-delivery/docs/generate-a-token-and-apply-it-to-content) token |+| `hdntl` | | [Akamai](https://techdocs.akamai.com/adaptive-media-delivery/docs/generate-a-token-and-apply-it-to-content) token |+| `hdnts` | | [Akamai](https://techdocs.akamai.com/adaptive-media-delivery/docs/generate-a-token-and-apply-it-to-content) token |+| `id_token` | | |+| `ik-s` | | [ImageKit](https://imagekit.io/docs/media-delivery-basic-security) signature |+| `jsessionid` | | [Jakarta Servlet](https://jakarta.ee/specifications/servlet/6.1/jakarta-servlet-spec-6.1.html) session token |+| `OSSAccessKeyId` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) credential |+| `phpsessid` | | |+| `q-ak` | | [Tencent COS](https://cloud.tencent.com/document/product/436/68284) credential |+| `q-signature` | | [Tencent COS](https://cloud.tencent.com/document/product/436/68284) signature |+| `s=<32-char token>` | | [Imgix](https://github.com/imgix/imgix-blueprint#securing-urls) |+| `security-token` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) temporary credential |+| `session_token` | | |+| `sessionid` | | |+| `sig` | | Includes [Azure SAS](https://learn.microsoft.com/en-us/rest/api/storageservices/create-account-sas) and [Cloudflare Images](https://developers.cloudflare.com/images/optimization/hosted-images/serve-private-images/) signatures |+| `Signature` | | Includes AWS, [CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html), and [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) signatures |+| `SignedHeaders` | | Signed URL header list |+| `token` | | Includes [Bunny](https://support.bunny.net/hc/en-us/articles/360016055099-How-to-sign-URLs-for-BunnyCDN-Token-Authentication) query tokens |+| `X-Amz-Credential` | | [AWS Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-query-string-auth.html) credential |+| `X-Amz-Security-Token` | | [AWS Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-query-string-auth.html) temporary credential |+| `X-Amz-Signature` | | [AWS Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-query-string-auth.html) signature |+| `X-Amz-SignedHeaders` | | [AWS Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sigv4-query-string-auth.html) signed header list |+| `X-Cos-Security-Token` | | [Tencent COS](https://cloud.tencent.com/document/product/436/68284) temporary credential |+| `X-Goog-Credential` | | [Google Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/signed-urls) Signature Version 4 credential |+| `X-Goog-Signature` | | [Google Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/signed-urls) Signature Version 4 signature |+| `X-Goog-SignedHeaders` | | [Google Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/signed-urls) Signature Version 4 signed header list |+| `x-oss-credential` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) Signature Version 4 credential |+| `x-oss-security-token` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) temporary credential |+| `x-oss-signature` | | [Alibaba OSS](https://www.alibabacloud.com/help/en/oss/developer-reference/add-signatures-to-urls) Signature Version 4 signature |Path patterns:-| Pattern | Domain | Notes |+| Pattern | Host pattern | Notes || --------------------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `/bcdn_token=<token>[&<field>=<value>...]/` | | [Bunny](https://support.bunny.net/hc/en-us/articles/360016055099-How-to-sign-URLs-for-BunnyCDN-Token-Authentication) token in the first path segment || `/p/<token>/n/` | `objectstorage.*.oraclecloud.com` | [Oracle pre-authenticated request](https://docs.oracle.com/en-us/iaas/Content/Object/Tasks/usingpreauthenticatedrequests_topic-To_create_a_preauthenticated_request_for_all_objects_in_a_bucket.htm) |@@ -155,7 +155,7 @@ XMP is an opt-out for that image when it has one of these values:**3.4** To avoid interruptions, the lane starts to refresh robots.txt and tdmrep.json when the cached version is 23 hours old. The lane can use the current cached version while one refresh is in progress.-**3.5** The lane follows up to 5 redirects when requesting robots.txt and tdmrep.json, including to a different authority. It follows these redirects without publishing to Kafka. The result still applies to the original origin. Configuration-file requests use the failure, cache, and retry rules in this section rather than the redirected authority's per-origin image back-off or circuit-breaker state.+**3.5** The lane follows up to 5 redirects when requesting robots.txt and tdmrep.json, including to a different authority in the same registrable domain. It follows these redirects without publishing to Kafka. The result still applies to the original origin. A redirect to another registrable domain makes the configuration file unreachable. This rule prevents a source partition from creating a second request budget for the redirect target. Configuration-file requests use the failure, cache, and retry rules in this section. They do not read or change image back-off or circuit-breaker state.**3.6** A redirect chain longer than 5 counts as unreachable.@@ -223,17 +223,17 @@ key at `https://us.posthog.com/.well-known/http-message-signatures-directory`, a**5.1** Requests in flight never exceed the pod limit.-**5.2** Requests in flight to one origin never exceed the origin limit during steady-state ownership. A bounded exception applies during the Kafka rebalance window described below.+**5.2** Requests in flight to one registrable domain never exceed the registrable-domain limit during steady-state ownership. A bounded exception applies during the Kafka rebalance window described below.-**5.3** Requests to one origin never exceed the rate its token bucket allows during steady-state ownership. The same bounded rebalance exception applies.+**5.3** Requests to one registrable domain never exceed the rate its token bucket allows during steady-state ownership. The same bounded rebalance exception applies.-**5.4** A redirect is not a way around any limit. For example, if a request to `https://a.com/image` redirects to `https://b.com/image`, the first request counts against the first origin and the second request counts against the second origin.+**5.4** A redirect is not a way around any limit. Each image request counts against the registrable-domain budget of its target and the crawl delay of its target origin. The lane follows a configuration redirect only when its target has the same registrable domain. Each followed configuration request counts against that shared registrable-domain budget.-**5.5** A wait is not a way around any limit. For example, a URL that waits for the pod limit must check the per-origin limit and all other limits before it resumes.+**5.5** A wait is not a way around any limit. A URL that waits for the pod limit must check the registrable-domain limit, the origin crawl delay, and all other limits before it resumes.-**5.6** There is no global handling of concurrent request limits. The Kafka topic is partitioned by registrable domain, using both the ICANN and private sections of the Public Suffix List. All origins under one registrable domain therefore go to one partition, and one pod normally holds the separate request-control state for each of those origins.+**5.6** There is no global handling of concurrent request limits. The Kafka topic is partitioned by registrable domain, using both the ICANN and private sections of the Public Suffix List. All origins under one registrable domain therefore go to one partition. One pod normally holds the shared registrable-domain request budget and the separate policy and crawl-delay state for each origin.-**5.7** On partition revocation, the consumer stops starting work for the revoked partitions and drains their active batch before it unassigns them. If the drain exceeds Kafka's rebalance timeout, Kafka can assign the partition to a new pod while the old pod finishes its active requests. During this exceptional window, one old owner and one new owner can each apply the origin limit and token bucket. The pod limit still applies independently to each pod. The lane does not use a distributed lease to close this window.+**5.7** On partition revocation, the consumer stops starting work for the revoked partitions and drains their active batch before it unassigns them. If the drain exceeds Kafka's rebalance timeout, Kafka can assign the partition to a new pod while the old pod finishes its active requests. During this exceptional window, one old owner and one new owner can each apply the registrable-domain limit and token bucket. The pod limit still applies independently to each pod. The lane does not use a distributed lease to close this window.**5.8** In-flight concurrency limits apply to all external URL fetches (e.g. `robots.txt` files), not just images. It does not apply to internal services like DynamoDB or Kafka.@@ -241,44 +241,51 @@ key at `https://us.posthog.com/.well-known/http-message-signatures-directory`, a**5.10** These are the limits in the system:-| Constant | Scope | Value |-| --------------------------------------- | ------------------------------------------------- | ---------- |-| Requests in flight | pod | 300 |-| Requests in flight per origin | origin | 6 |-| Requests per second per origin | origin | 1, burst 5 |-| Hop budget | one original URL, across every message it becomes | 10 |-| Redirects followed without republishing | one fetch | 3 |-| Response bytes, compressed | one response | 20 MiB |-| Request timeout | one URL, redirects included | 10 seconds |-| Pass deadline | one pass | 20 seconds |-| Pass wall time, worst case | one pass | 30 seconds |-| Origins tracked | pod | 20000 |-| Crawl history entry | one URL | 30 days |+| Constant | Scope | Value |+| ------------------------------------------ | ------------------------------------------------- | ---------- |+| Requests in flight | pod | 300 |+| Requests in flight per registrable domain | registrable domain | 6 |+| Requests per second per registrable domain | registrable domain | 1, burst 5 |+| Hop budget | one original URL, across every message it becomes | 10 |+| Redirects followed without republishing | one fetch | 3 |+| Response bytes, compressed | one response | 20 MiB |+| Request timeout | one URL, redirects included | 10 seconds |+| Pass deadline | one pass | 20 seconds |+| Pass wall time, worst case | one pass | 30 seconds |+| Registrable domains tracked | pod | 20,000 |+| Origins tracked | pod | 20,000 |+| Crawl history entry | one URL | 30 days |**5.11** State is stored as follows:-| State | Key | Location |-| ----------------------------------------------------------------------------------------------------- | --------------------------- | -------------------------------------------------------- |-| Active requests, token bucket, crawl delay, back-off, circuit breaker, and configuration request lock | Origin | Memory on the pod that owns the origin's Kafka partition |-| robots.txt and tdmrep.json results | Origin and file type | DynamoDB, with an optional hot cache in pod memory |-| URL crawl history and HTTP cache metadata | Global canonical URL | DynamoDB |-| Original ref, current URL, remaining image hops, and earliest retry time | One URL job | Kafka record |-| Top-N metric labels | Registrable/provider domain | Bounded pod memory |+| State | Key | Location |+| ------------------------------------------------------------------------ | -------------------- | ------------------------------------------------------------ |+| Active requests, token bucket, back-off, and circuit breaker | Registrable domain | Memory on the pod that owns the Kafka partition |+| Crawl delay and scheduled request count | Origin | Memory on the pod that owns the registrable-domain partition |+| Configuration request coalescing lock | Origin and file type | Memory on the pod that owns the registrable-domain partition |+| robots.txt and tdmrep.json results | Origin and file type | DynamoDB, with an optional hot cache in pod memory |+| URL crawl history and HTTP cache metadata | Global canonical URL | DynamoDB |+| Original ref, current URL, remaining image hops, and earliest retry time | One URL job | Kafka record |-**5.12** No request-control state uses the registrable domain or provider domain as its key.+**5.12** Request rate, burst, active-request count, transient back-off, `Retry-After`, and circuit-breaker state use the registrable domain as their key. Configuration policy and `Crawl-delay` use the origin as their key. No request-control state uses the provider domain as its key.-**5.13** The pod limits its origin runtime map to 20,000 entries because the number of origins is unbounded.+**5.13** The pod limits both its registrable-domain runtime map and its origin runtime map to 20,000 entries because both key sets are unbounded.-**5.14** The pod can evict an origin entry only when all these conditions apply:+**5.14** The pod can evict a registrable-domain entry only when all these conditions apply:-- The origin has no active request.-- The origin has no configuration request in progress.-- The origin has no active delay or breaker.-- The origin's token bucket is full.+- The registrable domain has no active request or pending request grant.+- The registrable domain has no active back-off or breaker.+- The registrable domain's token bucket is full.++The pod can evict an origin entry only when all these conditions apply:++- The origin has no active or scheduled request.+- The origin has no reserved image-request start time.+- The origin's crawl delay has elapsed.Removing an eligible entry cannot permit an earlier request.-**5.15** If the map is full and has no eligible entry, the pod does not contact an untracked origin. It sends the job to the 1-minute delay topic.+**5.15** If either map is full and has no eligible entry, the pod does not make the request. It sends the job to the 1-minute delay topic. The record names `origin_map_full` or `registrable_domain_map_full` as the reason.### 6. Smokescreen@@ -294,27 +301,27 @@ Removing an eligible entry cannot permit an earlier request.### 7. Back-off and retry delay-**7.1** This section applies to image requests. Configuration-file requests use the failure and retry rules in section 3 and do not change an origin's image back-off or circuit-breaker state.+**7.1** This section applies to image requests. Configuration-file requests use the failure and retry rules in section 3 and do not change a registrable domain's image back-off or circuit-breaker state.-**7.2** A network error, timeout, HTTP 408, HTTP 425, HTTP 429, or HTTP 5xx response is a transient failure. It increments the origin's consecutive transient-failure count. A successful response, valid redirect, or terminal HTTP response resets that count.+**7.2** A network error, timeout, HTTP 408, HTTP 425, HTTP 429, or HTTP 5xx response is a transient failure. It increments the registrable domain's consecutive transient-failure count. A successful response, valid redirect, or terminal HTTP response resets that count.-**7.3** One transient failure for an origin applies to every image URL queued for that origin in the same pass.+**7.3** One transient failure for a registrable domain applies to every image URL queued for that registrable domain in the same pass.**7.4** The retry back-off after the first consecutive transient failure is 1 minute. Each further consecutive failure doubles the maximum delay, up to 1 hour. The actual delay is selected uniformly between one half and all of that maximum, inclusive.**7.5** A valid `Retry-After` on HTTP 429 or HTTP 503 sets a minimum retry delay. The lane accepts either a non-negative integer number of seconds or an HTTP date. It uses the longer of `Retry-After` and the delay from requirement 7.4. It ignores an invalid or past value.-**7.6** After 5 consecutive transient failures, the origin's circuit breaker opens for the calculated delay. When that period ends, one image request becomes the half-open probe. Other image requests for the origin remain delayed until the probe completes.+**7.6** After 5 consecutive transient failures, the registrable domain's circuit breaker opens for the calculated delay. When that period ends, one image request becomes the half-open probe. Other image requests for the registrable domain remain delayed until the probe completes.**7.7** A successful, redirected, or terminal response to the half-open probe closes the circuit breaker and resets its failure count. A transient failure reopens it with the next exponential delay.-**7.8** Per-origin delays, failure counts, and circuit-breaker state use the bounded pod memory described in requirement 5.11.+**7.8** Registrable-domain back-off, failure counts, and circuit-breaker state use the bounded pod memory described in requirement 5.11.**7.9** The lane respects every `Crawl-delay` field line in the selected robots.txt group for `PostHogImageFetcherBot`. It accepts a non-negative decimal number of seconds, ignores invalid values, and uses the greatest valid value.-**7.10** `Crawl-delay` is the minimum interval between the start times of two image requests to the same origin. The lane uses the longer of its 1-request-per-second interval and `Crawl-delay`.+**7.10** `Crawl-delay` is the minimum interval between the start times of two image requests to the same origin. The 1-request-per-second interval applies across the registrable domain. A request must satisfy both limits.-**7.11** One active delay, whether it comes from back-off, `Retry-After`, `Crawl-delay`, or an open circuit breaker, applies to every image URL queued for that origin. The lane uses the latest resulting not-before time.+**7.11** Back-off, `Retry-After`, and an open circuit breaker apply to every image URL queued for the registrable domain. `Crawl-delay` applies only to image URLs queued for the origin that published it. The lane uses the latest applicable not-before time.**7.12** A delayed retry must not block processing. It goes to the back of the queue for its current batch. If the delay has not elapsed when it returns to the front, the lane republishes it to a delay Kafka topic.@@ -395,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`, or `origin_map_full`.+`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`.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.@@ -416,12 +423,10 @@ that scenario.**11.2** These metrics are tracked for each completed fetch request (images and other files)-- Registrable domain (top N, bounded with Space-Saving algorithm)-- Provider domain (top N, bounded with Space-Saving algorithm)- Time taken-- HTTP response / network failure if any+- HTTP response class or network failure-**11.3** These metrics are tracked for each origin after establishing whether it is blocked or not+**11.3** These metrics are tracked for each origin-policy or registrable-domain request-control decision- Block status- Block reason if any@@ -430,7 +435,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** Each top-N metric uses 200 Space-Saving counters per pod for one 10-minute window. It exports the 20 largest labels and one `other` label as gauges. At the window boundary, it clears the estimator and removes the labels from the previous window before it starts the next window.+**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.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.++**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.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.### 12. Conditional requests@@ -460,7 +471,7 @@ that scenario.**13.3** The key uses the shared Rust URL-policy implementation to canonicalize the URL. The canonical form uses the parser's serialized HTTPS URL, lowercases and IDNA-encodes the host, removes a trailing DNS root dot, removes the fragment, omits the explicit default port `443`, and uses `/` for an empty path. It does not sort path segments or query fields. The shared parser's serialization is authoritative for percent-encoding and dot-segment normalization.-After parsing and before final serialization, the implementation removes every occurrence of a volatile query field after percent-decoding its name and comparing it case-insensitively. The global volatile field names are `cb`, `nocache`, and `rnd`. If the URL contains `_nc_ohc`, the scoped volatile field names are `_nc_ohc`, `_nc_ht`, `ccb`, `oe`, `oh`, and `stp`. These lists are part of the shared URL policy. A new volatile field requires a specification change and shared test vectors. A credential field is refused under requirement 1.2 before canonicalization and is never removed to make a URL acceptable.+The fetch URL keeps the original query verbatim. The global ref uses a canonical query that removes every occurrence of a volatile query field after percent-decoding its name and comparing it case-insensitively. The implementation filters raw query fields and never rebuilds a query. Every retained field stays byte-for-byte unchanged. The global volatile field names are `cb`, `nocache`, and `rnd`. If the URL contains `_nc_ohc`, the scoped volatile field names are `_nc_ohc`, `_nc_ht`, `ccb`, `oe`, `oh`, and `stp`. These lists are part of the shared URL policy. A new volatile field requires a specification change and shared test vectors. A credential field is refused under requirement 1.2 before canonicalization and is never removed to make a URL acceptable. If several fetch URLs in one collection batch map to one global ref, the first collected fetch URL becomes the fetch candidate.**13.4** A URL ref does not contain a team identifier, a team pseudonym, or a key derived from one team. The same canonical URL produces the same ref for every team.@@ -474,7 +485,7 @@ After parsing and before final serialization, the implementation removes every o### 14. HTTP request/response-**14.1** The lane accepts the `identity`, `gzip`, `deflate`, `br`, and `zstd` content codings and refuses every other coding. It sends `gzip, deflate, br, zstd` in `Accept-Encoding`; `identity` remains acceptable as HTTP defines.+**14.1** The lane accepts up to 4 `identity`, `gzip`, `deflate`, `br`, and `zstd` content codings and refuses every other coding. It sends `gzip, deflate, br, zstd` in `Accept-Encoding`; `identity` remains acceptable as HTTP defines.**14.2** The lane never sends cookies, and ignores cookies that are set by the response@@ -501,7 +512,6 @@ the userinfo of a URL, cookies, and known credential query parameters| `image/jpeg` | JPEG || `image/gif` | GIF || `image/webp` | WebP |-| `image/bmp` | BMP || `image/avif` | AVIF |**14.11** This lane does not check that the downloaded bytes match the expected media type. It is expected that the image scrubber will do this.@@ -538,7 +548,7 @@ the userinfo of a URL, cookies, and known credential query parameters**15.8** The robots.txt and tdmrep.json caches use separate per-origin items. They do not share a TTL or an item with URL crawl history.-**15.9** The registrable-domain Kafka key puts all origins under that domain on one pod, while each DynamoDB item belongs to one URL or one origin. Outside the bounded rebalance exception in requirement 5.7, one pod therefore builds updates for a given item. Before each `BatchWriteItem` call, the lane folds repeated updates for one item into the last in-memory state so that a request never contains duplicate keys. A rebalance replay can write the same final state again, which requirement 15.4 permits. The lane does not use conditional writes or a distributed DynamoDB concurrency lock.+**15.9** The registrable-domain Kafka key puts all origins under that registrable domain on one pod, while each DynamoDB item belongs to one URL or one origin. Outside the bounded rebalance exception in requirement 5.7, one pod therefore builds updates for a given item. Before each `BatchWriteItem` call, the lane folds repeated updates for one item into the last in-memory state so that a request never contains duplicate keys. A rebalance replay can write the same final state again, which requirement 15.4 permits. The lane does not use conditional writes or a distributed DynamoDB concurrency lock.## 16. Delay topics@@ -583,7 +593,7 @@ ai_research_session_replay_image_fetch_retry_1h**17.5** The fetcher omits `content-encoding` when the response has no content coding or specifies `identity`. The scrubber treats a missing header as `identity`.-**17.6** The scrubber decodes the content codings in reverse order. It refuses an unsupported or malformed coding. It must enforce its uncompressed input limit while it decodes the value.+**17.6** The scrubber decodes up to 4 content codings in reverse order. It refuses an unsupported, malformed, or longer coding list. It must enforce its uncompressed input limit while it decodes the value.**17.7** After content decoding, the scrubber checks that the bytes match `content-type` before it sends them to the image scrubber.@@ -595,7 +605,7 @@ ai_research_session_replay_image_fetch_retry_1h**17.11** After scrubbing a URL-backed image, the image scrubber writes it to the deterministic S3 object key `<configured image prefix>/url/<hash>`, where `<hash>` comes from the `imageurl:<hash>` ref. URL-backed images do not use the time-partitioned shard index used by inline images.-**17.12** A later successful scrub for the same ref overwrites that object. The last completed S3 write is the version that data preparation reads. This policy avoids a version index or a search across historical shards.+**17.12** The image scrubber creates a URL object with `If-None-Match: *`. If an object already exists for the ref, the scrubber keeps it and treats the write as complete. The first completed S3 write is the version that data preparation reads. This policy makes the first fetch URL that reaches storage win when several fetch URLs map to one global ref.**17.13** Data preparation converts each distinct ref to the deterministic object key and performs one direct S3 read. A missing object leaves the image placeholder in place and does not require a recrawl.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.tsindex d819535b1fde..e812ca02aa84 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.test.ts@@ -1,114 +1,140 @@-import { parseCollectedUrlsRecord } from './collected-urls-record'--const TEAM = '0123456789abcdef0123456789abcdef'-const HASH = 'a'.padEnd(22, '0')+import {+ FetchCandidate,+ MAX_HOPS,+ MAX_JOBS_PER_RECORD,+ MAX_RECORD_BYTES,+ parseCollectedUrlsRecord,+ serializeFrontierRecord,+} from './collected-urls-record'++const REF = `imageurl:${'a'.repeat(22)}`++function candidate(overrides: Partial<FetchCandidate> = {}): FetchCandidate {+ return {+ originalRef: REF,+ currentUrl: 'https://cdn.example.com/a.png',+ host: 'cdn.example.com',+ origin: 'https://cdn.example.com',+ registrableDomain: 'example.com',+ remainingHops: MAX_HOPS,+ notBeforeMs: 0,+ firstSeenAtMs: 1_700_000_000_000,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,+ ...overrides,+ }+}-function body(fields: string): Buffer {+function record(overrides: Record<string, unknown> = {}): Buffer {return Buffer.from(- `{"v":1,"pseudoTeam":"${TEAM}",${fields},` +- `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://cdn.example.com/a.png","host":"cdn.example.com"}]}`+ JSON.stringify({+ v: 2,+ jobs: [+ {+ originalRef: REF,+ currentUrl: 'https://cdn.example.com/a.png',+ remainingHops: MAX_HOPS,+ notBeforeMs: 0,+ firstSeenAtMs: 1_700_000_000_000,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,+ ...overrides,+ },+ ],+ }))}-describe('parseCollectedUrlsRecord', () => {- it.each([- ['a magnitude no double can hold', '"capturedAtMs":-1e400'],- ['a positive one', '"capturedAtMs":1e400'],- ])('refuses %s rather than passing a non-finite timestamp on', (_name, fields) => {- // JSON.stringify cannot produce these, so this writes the record by hand. They parse to- // Infinity, which reaches a histogram as an infinite observation, and prom-client throws- // there. A throw inside a batch stops the consumer and replays the same record forever.- const parsed = parseCollectedUrlsRecord(body(fields), 'example.com')+describe('frontier record', () => {+ it('round trips the durable job state', () => {+ const parsed = parseCollectedUrlsRecord(serializeFrontierRecord([candidate()]), 'example.com')- expect(parsed).toEqual({ ok: false, reason: 'malformed' })+ expect(parsed).toEqual({ ok: true, candidates: [candidate()], urlCount: 1, rejected: [] })})it.each([- ['a fully qualified host against a bare key', 'cdn.example.com.', 'example.com'],- ['a bare host against a fully qualified key', 'cdn.example.com', 'example.com.'],- ['both fully qualified', 'cdn.example.com.', 'example.com.'],- ])('keeps %s', (_name, host, key) => {- // politenessKey strips the trailing dot, so a record written before the canonicalizer did- // the same carries a dotted host against a bare key. A plain string comparison drops every- // such URL as foreign, and those records are already in the topic.- const value = Buffer.from(- `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` +- `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://${host}/a.png","host":"${host}"}]}`- )-- const parsed = parseCollectedUrlsRecord(value, key)-- expect(parsed.ok && parsed.candidates).toHaveLength(1)+ ['missing value', null, 'example.com', 'malformed'],+ ['missing key', record(), null, 'malformed'],+ ['invalid JSON', Buffer.from('{'), 'example.com', 'malformed'],+ ['unknown version', Buffer.from('{"v":3,"jobs":[]}'), 'example.com', 'unsupported_version'],+ ['oversized bytes', Buffer.alloc(MAX_RECORD_BYTES + 1), 'example.com', 'oversized_record'],+ [+ 'too many jobs',+ Buffer.from(JSON.stringify({ v: 2, jobs: Array(MAX_JOBS_PER_RECORD + 1).fill({}) })),+ 'example.com',+ 'oversized_record',+ ],+ ])('refuses %s', (_name, value, key, reason) => {+ expect(parseCollectedUrlsRecord(value, key)).toEqual({ ok: false, reason })})it.each([- ['a key that is a subdomain rather than the operator', 'cdn.example.com', 'cdn.example.com'],- ['a key belonging to another operator', 'cdn.example.com', 'other.net'],- ])('drops %s (requirement 3)', (_name, host, key) => {- // The key scopes the rate budget. One key for each subdomain would give one operator a- // multiple of the rate we promise it, and the record would be on the wrong partition too.- const value = Buffer.from(- `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` +- `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://${host}/a.png","host":"${host}"}]}`- )-- const parsed = parseCollectedUrlsRecord(value, key)-- expect(parsed.ok && parsed.candidates).toHaveLength(0)- expect(parsed.ok && parsed.rejected).toEqual([{ reason: 'foreign_domain' }])+ ['legacy team-scoped ref', `imageurl:${'b'.repeat(32)}:${'a'.repeat(22)}`, 'bad_ref'],+ ['byte ref', `image:${'b'.repeat(32)}:${'a'.repeat(22)}`, 'bad_ref'],+ ['credentials', 'https://user:[email protected]/a.png', 'bad_url'],+ ['HTTP', 'http://cdn.example.com/a.png', 'bad_url'],+ ['non-default port', 'https://cdn.example.com:444/a.png', 'bad_url'],+ ['private address', 'https://127.0.0.1/a.png', 'bad_url'],+ ['non-canonical URL', 'https://CDN.EXAMPLE.COM/a.png', 'bad_url'],+ ])('drops a job with %s', (_name, value, reason) => {+ const overrides = value.startsWith('image') ? { originalRef: value } : { currentUrl: value }+ const parsed = parseCollectedUrlsRecord(record(overrides), 'example.com')++ expect(parsed).toEqual({ ok: false, reason })})- it.each([- ['plain HTTP', 'http://cdn.example.com/a.png'],- ['a scheme this lane never fetches', 'ftp://cdn.example.com/a.png'],- ])('drops %s (requirements 34 and 35)', (_name, url) => {- // The collector produces HTTPS only. Anything else means a wrong or stale producer, and a- // fetch would put an image on the wire in clear text.- const value = Buffer.from(- `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` +- `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"${url}","host":"cdn.example.com"}]}`- )-- const parsed = parseCollectedUrlsRecord(value, 'example.com')-- expect(parsed.ok && parsed.rejected).toEqual([{ reason: 'bad_url' }])- })-- it.each([- ['a name that only resolves inside a network', 'wiki.corp'],- ['a link-local address', '169.254.169.254'],- ['a loopback address', '127.0.0.1'],- ])('drops %s (requirement 35)', (_name, host) => {- // The connect-time address check cannot refuse a name like wiki.corp whose DNS answer is- // public, so this is the only place that does.- const value = Buffer.from(- `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` +- `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://${host}/a.png","host":"${host}"}]}`- )-- const parsed = parseCollectedUrlsRecord(value, host)+ it('drops a job placed on another registrable-domain partition', () => {+ const parsed = parseCollectedUrlsRecord(record(), 'other.net')- expect(parsed.ok && parsed.rejected).toEqual([{ reason: 'private_host' }])+ expect(parsed).toEqual({ ok: false, reason: 'foreign_domain' })})- it('keys one domain by one spelling, whatever the record key used', () => {- // The budget, the metrics, and the republish key all read this. Two spellings of one- // domain would take two budgets on the same pod, so each would get the full rate.+ it('converts a retained v1 record into durable candidates', () => {+ const pseudoTeam = 'b'.repeat(32)+ const legacyRef = `imageurl:${pseudoTeam}:${'c'.repeat(22)}`const value = Buffer.from(- `{"v":1,"pseudoTeam":"${TEAM}","capturedAtMs":1700000000000,` +- `"urls":[{"ref":"imageurl:${TEAM}:${HASH}","url":"https://cdn.example.com/a.png","host":"cdn.example.com"}]}`+ JSON.stringify({+ v: 1,+ pseudoTeam,+ capturedAtMs: 1_700_000_000_000,+ hopsRemaining: 7,+ notBeforeMs: 1_700_000_060_000,+ urls: [+ {+ ref: legacyRef,+ url: 'https://CDN.EXAMPLE.COM./a.png',+ host: 'cdn.example.com.',+ },+ ],+ }))- const dotted = parseCollectedUrlsRecord(value, 'example.com.')- const bare = parseCollectedUrlsRecord(value, 'example.com')-- expect(dotted.ok && dotted.candidates[0].domain).toBe('example.com')- expect(bare.ok && bare.candidates[0].domain).toBe('example.com')+ expect(parseCollectedUrlsRecord(value, 'example.com.')).toEqual({+ ok: true,+ candidates: [+ candidate({+ originalRef: legacyRef,+ remainingHops: 7,+ notBeforeMs: 1_700_000_060_000,+ }),+ ],+ urlCount: 1,+ rejected: [],+ })})- it('accepts an ordinary timestamp', () => {- const parsed = parseCollectedUrlsRecord(body('"capturedAtMs":1700000000000'), 'example.com')-- expect(parsed.ok).toBe(true)+ it.each([+ ['remainingHops', MAX_HOPS + 1],+ ['notBeforeMs', -1],+ ['firstSeenAtMs', Number.POSITIVE_INFINITY],+ ['fetchCount', 1.5],+ ['republishCount', Number.MAX_SAFE_INTEGER + 1],+ ['lastRepublishReason', 'unknown'],+ ])('drops an invalid %s', (field, value) => {+ const parsed = parseCollectedUrlsRecord(record({ [field]: value }), 'example.com')++ expect(parsed).toEqual({ ok: false, reason: 'bad_url' })})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.tsindex 82932d05111d..14fc80bd7f99 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts@@ -1,101 +1,151 @@import { parseJSON } from '~/common/utils/json-parse'import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'-import { UrlDropReason } from './metrics'-import { isPublicHost, politenessKey } from './politeness-key'+import { canonicalizeUrl } from './politeness-key'-/** Beyond this the URL is not something the mirror produced, so it is a format disagreement. */-const MAX_URL_LENGTH = 2048+export const MAX_HOPS = 10+export const MAX_JOBS_PER_RECORD = 1_000+export const MAX_RECORD_BYTES = 512 * 1024-/**- * A record holds one domain from one message, and the collector caps a message at 512, so a- * well-formed record stays under this. The headroom is small on purpose, because crawl-history- * request fan-out and the in-memory candidate set both scale with this value.- */-const MAX_URLS_PER_RECORD = 640+export type UrlDropReason =+ | 'malformed'+ | 'unsupported_version'+ | 'bad_ref'+ | 'bad_url'+ | 'foreign_domain'+ | 'oversized_record'+export type RepublishReason =+ | 'redirect'+ | 'retry'+ | 'not_ready'+ | 'pass_deadline'+ | 'origin_map_full'+ | 'registrable_domain_map_full'export interface FetchCandidate {- ref: string- urlHash: string- url: string+ originalRef: string+ currentUrl: stringhost: string- domain: string- pseudoTeam: string- capturedAtMs: number- /** Moves this URL may still make. A republish and a retry each spend one. Requirement 11. */- hopsRemaining: number- /** The lane must not fetch this URL before this epoch ms. Zero means now. Requirement 15. */+ origin: string+ registrableDomain: string+ remainingHops: numbernotBeforeMs: number+ firstSeenAtMs: number+ fetchCount: number+ republishCount: number+ lastRepublishReason: RepublishReason | null}-/**- * One budget rather than one counter for redirects and another for retries, because a chain that- * alternates between the two would otherwise never end. Requirement 11.- */-export const MAX_HOPS = 10+export interface FrontierRecord {+ v: 2+ jobs: Array<+ Pick<+ FetchCandidate,+ | 'originalRef'+ | 'currentUrl'+ | 'remainingHops'+ | 'notBeforeMs'+ | 'firstSeenAtMs'+ | 'fetchCount'+ | 'republishCount'+ | 'lastRepublishReason'+ >+ >+}export type RecordParse =| { ok: true; candidates: FetchCandidate[]; urlCount: number; rejected: { reason: UrlDropReason }[] }- | { ok: false; reason: Extract<UrlDropReason, 'malformed' | 'unsupported_version' | 'oversized_record'> }+ | {+ ok: false+ reason: Extract<+ UrlDropReason,+ 'malformed' | 'unsupported_version' | 'oversized_record' | 'bad_ref' | 'bad_url' | 'foreign_domain'+ >+ }-function isStringRecord(value: unknown): value is Record<string, unknown> {+function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value)}-/**- * The producer and this consumer ship from separate deployments, so a record can arrive from a- * mirror older or newer than this code. This checks every field rather than trusts it, and it counts- * and drops a record that does not parse instead of throwing, because one bad record must not stall- * the partition it shares with every other site.- *- * `domain` comes from the Kafka key, because the key routed the record to this partition, so the key- * is what the politeness budget must be scoped to.- */+function isNonNegativeSafeInteger(value: unknown): value is number {+ return Number.isSafeInteger(value) && (value as number) >= 0+}++function isRepublishReason(value: unknown): value is RepublishReason | null {+ return (+ value === null ||+ value === 'redirect' ||+ value === 'retry' ||+ value === 'not_ready' ||+ value === 'pass_deadline' ||+ value === 'origin_map_full' ||+ value === 'registrable_domain_map_full'+ )+}+export function parseCollectedUrlsRecord(value: Buffer | null, key: string | null): RecordParse {if (!value || !key) {return { ok: false, reason: 'malformed' }}- // Normalized once here, because the budget, the metrics, and the republish key all read it. A- // record written before the producer stripped the trailing dot carries the dotted spelling, and- // two spellings of one domain would take two budgets on the same pod.- const domain = withoutTrailingDot(key)+ if (value.length > MAX_RECORD_BYTES) {+ return { ok: false, reason: 'oversized_record' }+ }+let parsed: unknowntry {parsed = parseJSON(value.toString())} catch {return { ok: false, reason: 'malformed' }}- if (!isStringRecord(parsed)) {+ if (!isRecord(parsed)) {return { ok: false, reason: 'malformed' }}- if (parsed.v !== 1) {- return { ok: false, reason: 'unsupported_version' }+ if (parsed.v === 1 && Array.isArray(parsed.urls)) {+ return parseLegacyRecord(parsed, key)}- const { pseudoTeam, capturedAtMs, urls, hopsRemaining, notBeforeMs } = parsed- if (typeof pseudoTeam !== 'string' || !pseudoTeam || typeof capturedAtMs !== 'number' || !Array.isArray(urls)) {- return { ok: false, reason: 'malformed' }+ if (parsed.v !== 2 && !(parsed.v === 1 && Array.isArray(parsed.jobs))) {+ return { ok: false, reason: 'unsupported_version' }}- // Finite, not merely a number: JSON carries `-1e400`, which parses to -Infinity and would reach- // a histogram as an infinite age. prom-client throws on that, and a throw here stops the- // consumer and replays the same record forever.- if (!Number.isFinite(capturedAtMs)) {+ if (!Array.isArray(parsed.jobs) || parsed.jobs.length === 0) {return { ok: false, reason: 'malformed' }}- if (urls.length > MAX_URLS_PER_RECORD) {+ if (parsed.jobs.length > MAX_JOBS_PER_RECORD) {return { ok: false, reason: 'oversized_record' }}- // Absent means a record straight from the mirror, which has made no moves and may go now. Both- // fields are optional additions rather than a new version, so a consumer that predates them- // reads such a record as it always did: full budget, fetch immediately.- const hops = clampHops(hopsRemaining)- const notBefore = typeof notBeforeMs === 'number' && Number.isFinite(notBeforeMs) ? notBeforeMs : 0+ const candidates: FetchCandidate[] = []+ const rejected: { reason: UrlDropReason }[] = []+ for (const job of parsed.jobs) {+ const parsedJob = parseJob(job, key)+ if (!parsedJob.ok) {+ return { ok: false, reason: parsedJob.reason }+ }+ candidates.push(parsedJob.candidate)+ }+ return { ok: true, candidates, urlCount: parsed.jobs.length, rejected }+}+function parseLegacyRecord(parsed: Record<string, unknown>, kafkaKey: string): RecordParse {+ const { pseudoTeam, capturedAtMs, urls, hopsRemaining, notBeforeMs } = parsed+ if (+ typeof pseudoTeam !== 'string' ||+ pseudoTeam.length === 0 ||+ !isNonNegativeSafeInteger(capturedAtMs) ||+ !Array.isArray(urls) ||+ urls.length === 0+ ) {+ return { ok: false, reason: 'malformed' }+ }+ if (urls.length > MAX_JOBS_PER_RECORD) {+ return { ok: false, reason: 'oversized_record' }+ }+ const remainingHops = isNonNegativeSafeInteger(hopsRemaining) ? Math.min(hopsRemaining, MAX_HOPS) : MAX_HOPS+ const readyAtMs = isNonNegativeSafeInteger(notBeforeMs) ? notBeforeMs : 0const candidates: FetchCandidate[] = []const rejected: { reason: UrlDropReason }[] = []for (const entry of urls) {- if (!isStringRecord(entry) || typeof entry.ref !== 'string' || typeof entry.url !== 'string') {- rejected.push({ reason: 'bad_ref' })+ if (!isRecord(entry) || typeof entry.ref !== 'string' || typeof entry.url !== 'string') {+ rejected.push({ reason: 'bad_url' })continue}const ref = parseImageRef(entry.ref)@@ -103,86 +153,106 @@ export function parseCollectedUrlsRecord(value: Buffer | null, key: string | nulrejected.push({ reason: 'bad_ref' })continue}- const host = typeof entry.host === 'string' ? entry.host : ''- if (!isFetchableUrl(entry.url, host)) {+ const canonical = canonicalizeUrl(entry.url)+ if (!canonical) {rejected.push({ reason: 'bad_url' })continue}- // The connection layer refuses a private address, so this is not the only guard against- // one. It is the only guard against a name that looks internal and resolves to a public- // address, because no address check can refuse that. Requirement 35.- if (!isPublicHost(withoutTrailingDot(host))) {- rejected.push({ reason: 'private_host' })- continue- }- if (!hostIsKeyedByItsOperator(host, key)) {+ if (canonical.domain !== kafkaKey.replace(/\.$/, '')) {rejected.push({ reason: 'foreign_domain' })continue}candidates.push({- ref: entry.ref,- urlHash: ref.hash,- url: entry.url,- host,- domain,- pseudoTeam,- capturedAtMs,- hopsRemaining: hops,- notBeforeMs: notBefore,+ originalRef: entry.ref,+ currentUrl: canonical.fetch,+ host: canonical.host,+ origin: new URL(canonical.fetch).origin,+ registrableDomain: canonical.domain,+ remainingHops,+ notBeforeMs: readyAtMs,+ firstSeenAtMs: capturedAtMs,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,})}return { ok: true, candidates, urlCount: urls.length, rejected }}-/** A record naming more hops than the budget allows is treated as a full budget, so a bad producer cannot buy itself extra trips. */-function clampHops(value: unknown): number {- if (typeof value !== 'number' || !Number.isFinite(value)) {- return MAX_HOPS+function parseJob(+ job: unknown,+ kafkaKey: string+):+ | { ok: true; candidate: FetchCandidate }+ | { ok: false; reason: Extract<UrlDropReason, 'bad_ref' | 'bad_url' | 'foreign_domain'> } {+ if (!isRecord(job)) {+ return { ok: false, reason: 'bad_url' }+ }+ const {+ originalRef,+ currentUrl,+ remainingHops,+ notBeforeMs,+ firstSeenAtMs,+ fetchCount,+ republishCount,+ lastRepublishReason,+ } = job+ if (+ typeof originalRef !== 'string' ||+ typeof currentUrl !== 'string' ||+ !isNonNegativeSafeInteger(remainingHops) ||+ remainingHops > MAX_HOPS ||+ !isNonNegativeSafeInteger(notBeforeMs) ||+ !isNonNegativeSafeInteger(firstSeenAtMs) ||+ !isNonNegativeSafeInteger(fetchCount) ||+ !isNonNegativeSafeInteger(republishCount) ||+ !isRepublishReason(lastRepublishReason)+ ) {+ return { ok: false, reason: 'bad_url' }+ }+ const ref = parseImageRef(originalRef)+ if (!ref || ref.source !== 'url' || ref.pseudoTeam !== undefined) {+ return { ok: false, reason: 'bad_ref' }+ }+ const canonical = canonicalizeUrl(currentUrl)+ if (!canonical || canonical.fetch !== currentUrl) {+ return { ok: false, reason: 'bad_url' }+ }+ if (canonical.domain !== kafkaKey) {+ return { ok: false, reason: 'foreign_domain' }+ }+ return {+ ok: true,+ candidate: {+ originalRef,+ currentUrl,+ host: canonical.host,+ origin: new URL(currentUrl).origin,+ registrableDomain: canonical.domain,+ remainingHops,+ notBeforeMs,+ firstSeenAtMs,+ fetchCount,+ republishCount,+ lastRepublishReason,+ },}- return Math.max(0, Math.min(MAX_HOPS, Math.floor(value)))-}--/**- * The key must be the registrable domain of the host, not merely a domain the host sits under. A key- * of `cdn.example.com` would give that subdomain a rate budget of its own, and a producer that- * writes one key for each subdomain would hand one operator a multiple of the rate we promise it.- * The key also decides the partition, so a record that fails this test is on the wrong partition as- * well. Requirement 3.- *- * This drops the trailing dot first. `example.com.` and `example.com` name the same host, and a- * record written before the producer stripped the dot carries the dotted form.- */-function hostIsKeyedByItsOperator(host: string, key: string): boolean {- return politenessKey(withoutTrailingDot(host)) === withoutTrailingDot(key)-}--function withoutTrailingDot(value: string): string {- return value.endsWith('.') ? value.slice(0, -1) : value}-/**- * The mirror already applied the full URL policy before producing, so this repeats only the checks- * that a wrong or stale producer could get past. It is not the SSRF gate: that belongs immediately- * before a request goes out, against the host of every redirect, and no request goes out here.- */-function isFetchableUrl(url: string, host: string): boolean {- if (url.length > MAX_URL_LENGTH || !host) {- return false- }- try {- const parsed = new URL(url)- // HTTPS only, which is what the collector produces. A plain HTTP URL would put an image on- // the wire in clear text, and requirement 9 keeps a redirect off HTTP only if the first URL- // is HTTPS.- if (parsed.protocol !== 'https:' || parsed.hostname !== host) {- return false- }- // The lane refuses both on a redirect target, so it holds the first hop to the same rule. A- // port other than the scheme's own would make this lane a port prober, and userinfo is a- // credential this lane never sends. The canonicalizer strips both, so this checks against a- // wrong or stale producer rather than an expected case.- return parsed.port === '' && !parsed.username && !parsed.password- } catch {- return false+export function serializeFrontierRecord(candidates: FetchCandidate[]): Buffer {+ const record: FrontierRecord = {+ v: 2,+ jobs: candidates.map((candidate) => ({+ originalRef: candidate.originalRef,+ currentUrl: candidate.currentUrl,+ remainingHops: candidate.remainingHops,+ notBeforeMs: candidate.notBeforeMs,+ firstSeenAtMs: candidate.firstSeenAtMs,+ fetchCount: candidate.fetchCount,+ republishCount: candidate.republishCount,+ lastRepublishReason: candidate.lastRepublishReason,+ })),}+ return Buffer.from(JSON.stringify(record))}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.tsnew file mode 100644index 000000000000..5676391c2080--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.test.ts@@ -0,0 +1,483 @@+import { StreamedResponse, fetchStreamed } from '~/common/utils/request'++import {+ ConfigurationFetchResult,+ ConfigurationPolicyService,+ HttpConfigurationFetcher,+ explicitFreshnessLifetimeMs,+ parseRobotsPolicy,+ responseOptOutReason,+} from './configuration-policy'+import { ConfigurationCacheItem, ConfigurationFile, configurationCacheKey } from './crawl-history'++jest.mock('~/common/utils/request', () => ({+ ...jest.requireActual('~/common/utils/request'),+ fetchStreamed: jest.fn(),+}))++const fetchStreamedMock = fetchStreamed as jest.MockedFunction<typeof fetchStreamed>++const NOW_MS = Date.parse('2026-08-22T12:00:00Z')+const ORIGIN = 'https://example.com'++function cached(+ file: ConfigurationFile,+ status: ConfigurationCacheItem['status'],+ body?: string+): ConfigurationCacheItem {+ return {+ kind: file,+ key: configurationCacheKey(ORIGIN, file),+ origin: ORIGIN,+ status,+ body,+ fetchedAtMs: NOW_MS,+ refreshAtMs: NOW_MS + 23 * 60 * 60 * 1000,+ freshUntilMs: NOW_MS + 24 * 60 * 60 * 1000,+ retryAtMs: NOW_MS,+ storageExpiresAtMs: NOW_MS + 30 * 24 * 60 * 60 * 1000,+ }+}++function service(results: Partial<Record<ConfigurationFile, ConfigurationFetchResult>> = {}): {+ policy: ConfigurationPolicyService+ fetch: jest.Mock+} {+ const fetch = jest.fn((_: string, file: ConfigurationFile) =>+ Promise.resolve(results[file] ?? ({ outcome: 'absent' } as const))+ )+ return {+ policy: new ConfigurationPolicyService({ fetch } as unknown as HttpConfigurationFetcher),+ fetch,+ }+}++function response(+ status: number,+ headerLines: Array<{ name: string; value: string }> = [],+ body: { bytes: Buffer; overLimit: boolean } = { bytes: Buffer.alloc(0), overLimit: false }+): StreamedResponse {+ return {+ status,+ headers: Object.fromEntries(headerLines.map(({ name, value }) => [name, value])),+ headerLines,+ read: jest.fn().mockResolvedValue(body),+ discard: jest.fn(),+ }+}++function httpFetcher(headersForGet = jest.fn().mockReturnValue({})): HttpConfigurationFetcher {+ return new HttpConfigurationFetcher(+ { headersForGet },+ {+ run: async (_url, _deadlineMs, request) => ({ ran: true as const, value: await request() }),+ },+ 5_000+ )+}++describe('robots policy', () => {+ it('uses the RFC 9309 group and path matcher', async () => {+ const body = [+ 'User-agent: *',+ 'Disallow: /wildcard',+ 'User-agent: PostHogImageFetcherBot',+ 'Disallow: /private',+ 'Allow: /private/public.png',+ ].join('\n')++ await expect(parseRobotsPolicy(body, `${ORIGIN}/private/image.png`)).resolves.toMatchObject({+ allowed: false,+ reason: 'robots_disallow',+ })+ await expect(parseRobotsPolicy(body, `${ORIGIN}/private/public.png`)).resolves.toMatchObject({ allowed: true })+ await expect(parseRobotsPolicy(body, `${ORIGIN}/wildcard/image.png`)).resolves.toMatchObject({ allowed: true })+ })++ it('uses the greatest valid crawl delay in every selected field line', async () => {+ const body = [+ 'User-agent: PostHogImageFetcherBot',+ 'Crawl-delay: 0.25',+ 'Crawl-delay: invalid',+ 'Crawl-delay: 0x10',+ 'Crawl-delay: 1e3',+ 'Crawl-delay: 2.5',+ 'Allow: /',+ ].join('\n')++ const result = await parseRobotsPolicy(body, `${ORIGIN}/image.png`)+ expect(result).toMatchObject({+ allowed: true,+ crawlDelayMs: 2_500,+ })+ })++ it.each([+ ['a token refusal', 'train-ai=n', false],+ ['a later allowance', 'train-ai=n, train-ai=y', true],+ ['a quoted value', 'train-ai="n"', true],+ ['a boolean value', 'train-ai=?0', true],+ ['an invalid dictionary', 'train-ai=n, INVALID=y', true],+ ])('applies Content-Usage with %s', async (_name, value, allowed) => {+ const body = `User-agent: *\nContent-Usage: ${value}\nAllow: /`++ await expect(parseRobotsPolicy(body, `${ORIGIN}/image.png`)).resolves.toMatchObject({ allowed })+ })++ it('applies a path-scoped Content-Signal only to a matching URL', async () => {+ const body = 'User-agent: *\nContent-Signal: /private/ ai-train=no, search=yes\nAllow: /'++ await expect(parseRobotsPolicy(body, `${ORIGIN}/private/image.png`)).resolves.toMatchObject({+ allowed: false,+ reason: 'content_signal',+ })+ await expect(parseRobotsPolicy(body, `${ORIGIN}/public/image.png`)).resolves.toMatchObject({ allowed: true })+ })+})++describe('response opt-out policy', () => {+ it('uses the last duplicate Content-Usage dictionary member', () => {+ expect(+ responseOptOutReason(+ [+ { name: 'content-usage', value: 'train-ai=n' },+ { name: 'content-usage', value: 'train-ai=y' },+ ],+ false+ )+ ).toBeUndefined()+ expect(+ responseOptOutReason(+ [+ { name: 'content-usage', value: 'train-ai=y' },+ { name: 'content-usage', value: 'train-ai=n' },+ ],+ false+ )+ ).toBe('content_usage')+ })++ it('lets the response TDM value override the tdmrep file', () => {+ expect(responseOptOutReason([{ name: 'tdm-reservation', value: '0' }], true)).toBeUndefined()+ expect(responseOptOutReason([{ name: 'tdm-reservation', value: '1' }], false)).toBe('tdm_reservation')+ })++ it('applies a bot-specific X-Robots-Tag refusal', () => {+ expect(+ responseOptOutReason([{ name: 'x-robots-tag', value: 'PostHogImageFetcherBot: noindex, noimageai' }], false)+ ).toBe('x_robots_tag')+ expect(responseOptOutReason([{ name: 'x-robots-tag', value: 'OtherBot: noai' }], false)).toBeUndefined()+ })+})++describe('ConfigurationPolicyService', () => {+ it('checks both files before it allows an image request', async () => {+ const { policy, fetch } = service()++ await expect(policy.check(`${ORIGIN}/image.png`, new Map(), NOW_MS)).resolves.toMatchObject({ allowed: true })+ expect(fetch.mock.calls).toEqual([+ [ORIGIN, 'robots'],+ [ORIGIN, 'tdmrep'],+ ])+ })++ it('uses a cached configuration without a new request', async () => {+ const { policy, fetch } = service()+ const cache = new Map([+ [configurationCacheKey(ORIGIN, 'robots'), cached('robots', 'absent')],+ [configurationCacheKey(ORIGIN, 'tdmrep'), cached('tdmrep', 'absent')],+ ])++ await expect(policy.check(`${ORIGIN}/image.png`, cache, NOW_MS)).resolves.toMatchObject({ allowed: true })+ expect(fetch).not.toHaveBeenCalled()+ })++ it('parses each cached policy revision once in a fetch pass', async () => {+ const { ParsedRobots } = await import('@trybyte/robotstxt-parser')+ const parseRobots = jest.spyOn(ParsedRobots, 'parse')+ const parseJson = jest.spyOn(JSON, 'parse')+ const { policy } = service()+ const robotsBody = 'User-agent: *\nAllow: /'+ const tdmrepBody = JSON.stringify([{ location: '/', 'tdm-reservation': 0 }])+ const cache = new Map([+ [configurationCacheKey(ORIGIN, 'robots'), cached('robots', 'available', robotsBody)],+ [configurationCacheKey(ORIGIN, 'tdmrep'), cached('tdmrep', 'available', tdmrepBody)],+ ])++ try {+ const pass = policy.createPass()+ await pass.check(`${ORIGIN}/first.png`, cache, NOW_MS)+ await pass.check(`${ORIGIN}/second.png`, cache, NOW_MS)++ expect(parseRobots.mock.calls.filter(([body]) => body === robotsBody)).toHaveLength(1)+ expect(parseJson.mock.calls.filter(([body]) => body === tdmrepBody)).toHaveLength(1)++ const revisedCache = new Map(+ [...cache].map(([key, item]) => [key, { ...item, fetchedAtMs: item.fetchedAtMs + 1 }] as const)+ )+ await pass.check(`${ORIGIN}/third.png`, revisedCache, NOW_MS)++ expect(parseRobots.mock.calls.filter(([body]) => body === robotsBody)).toHaveLength(2)+ expect(parseJson.mock.calls.filter(([body]) => body === tdmrepBody)).toHaveLength(2)++ await policy.createPass().check(`${ORIGIN}/fourth.png`, cache, NOW_MS)++ expect(parseRobots.mock.calls.filter(([body]) => body === robotsBody)).toHaveLength(3)+ expect(parseJson.mock.calls.filter(([body]) => body === tdmrepBody)).toHaveLength(3)+ } finally {+ parseRobots.mockRestore()+ parseJson.mockRestore()+ }+ })++ it('uses the first matching TDMRep rule and honors the end anchor', async () => {+ const { policy } = service()+ const cache = new Map([+ [configurationCacheKey(ORIGIN, 'robots'), cached('robots', 'absent')],+ [+ configurationCacheKey(ORIGIN, 'tdmrep'),+ cached(+ 'tdmrep',+ 'available',+ JSON.stringify([+ { location: '/private/exact$', 'tdm-reservation': 0 },+ { location: '/private/*', 'tdm-reservation': 1 },+ ])+ ),+ ],+ ])++ await expect(policy.check(`${ORIGIN}/private/exact`, cache, NOW_MS)).resolves.toMatchObject({ allowed: true })+ await expect(policy.check(`${ORIGIN}/private/exact-more`, cache, NOW_MS)).resolves.toMatchObject({+ allowed: true,+ tdmrepReservation: true,+ })+ })++ it('keeps a previous usable file when its refresh is unreachable', async () => {+ const { policy } = service({ robots: { outcome: 'unreachable' } })+ const previous = { ...cached('robots', 'absent'), refreshAtMs: NOW_MS - 1 }+ const cache = new Map([+ [configurationCacheKey(ORIGIN, 'robots'), previous],+ [configurationCacheKey(ORIGIN, 'tdmrep'), cached('tdmrep', 'absent')],+ ])++ await expect(policy.check(`${ORIGIN}/image.png`, cache, NOW_MS)).resolves.toMatchObject({+ allowed: true,+ updates: [expect.objectContaining({ kind: 'robots', status: 'absent', retryAtMs: NOW_MS + 3_600_000 })],+ })+ })++ it('returns a transient refusal when no configuration file is reachable', async () => {+ const { policy } = service({ robots: { outcome: 'unreachable' } })++ await expect(policy.check(`${ORIGIN}/image.png`, new Map(), NOW_MS)).resolves.toMatchObject({+ allowed: false,+ transient: true,+ reason: 'configuration_unreachable',+ })+ })++ it('preserves a registrable-domain state deferral', async () => {+ const { policy } = service({+ robots: { outcome: 'deferred', reason: 'registrable_domain_map_full' },+ })++ await expect(policy.check(`${ORIGIN}/image.png`, new Map(), NOW_MS)).resolves.toMatchObject({+ allowed: false,+ transient: true,+ reason: 'registrable_domain_map_full',+ })+ })++ it('keeps a terminal refusal when the other configuration file is unreachable', async () => {+ const { policy } = service({+ robots: {+ outcome: 'available',+ body: 'User-agent: *\nDisallow: /private',+ cache: { requestTimeMs: NOW_MS, responseTimeMs: NOW_MS },+ },+ tdmrep: { outcome: 'unreachable' },+ })++ await expect(policy.check(`${ORIGIN}/private/image.png`, new Map(), NOW_MS)).resolves.toMatchObject({+ allowed: false,+ transient: false,+ reason: 'robots_disallow',+ })+ })+})++describe('HttpConfigurationFetcher', () => {+ beforeEach(() => {+ fetchStreamedMock.mockReset()+ })++ it.each([+ [404, 'absent'],+ [410, 'absent'],+ [401, 'refused'],+ [403, 'refused'],+ [429, 'unreachable'],+ [500, 'unreachable'],+ [204, 'unreachable'],+ ])('maps HTTP %s to %s', async (status, outcome) => {+ fetchStreamedMock.mockResolvedValue(response(status))++ await expect(httpFetcher().fetch(ORIGIN, 'robots')).resolves.toMatchObject({ outcome })+ })++ it('uses the retained prefix when robots.txt exceeds its byte limit', async () => {+ fetchStreamedMock.mockResolvedValue(+ response(200, [], { bytes: Buffer.from('User-agent: *\nDisallow: /private'), overLimit: true })+ )++ await expect(httpFetcher().fetch(ORIGIN, 'robots')).resolves.toMatchObject({+ outcome: 'available',+ body: 'User-agent: *\nDisallow: /private',+ })+ })++ it('treats an oversized or invalid TDMRep document as unreachable', async () => {+ fetchStreamedMock+ .mockResolvedValueOnce(response(200, [], { bytes: Buffer.from('[]'), overLimit: true }))+ .mockResolvedValueOnce(response(200, [], { bytes: Buffer.from('{invalid'), overLimit: false }))++ await expect(httpFetcher().fetch(ORIGIN, 'tdmrep')).resolves.toMatchObject({ outcome: 'unreachable' })+ await expect(httpFetcher().fetch(ORIGIN, 'tdmrep')).resolves.toMatchObject({ outcome: 'unreachable' })+ })++ it('treats repeated Location field lines as unreachable', async () => {+ fetchStreamedMock.mockResolvedValue(+ response(302, [+ { name: 'location', value: '/first' },+ { name: 'location', value: '/second' },+ ])+ )++ await expect(httpFetcher().fetch(ORIGIN, 'robots')).resolves.toMatchObject({ outcome: 'unreachable' })+ expect(fetchStreamedMock).toHaveBeenCalledTimes(1)+ })++ it('follows and signs each configuration redirect target', async () => {+ fetchStreamedMock+ .mockResolvedValueOnce(response(302, [{ name: 'location', value: 'https://cdn.example.com/robots' }]))+ .mockResolvedValueOnce(+ response(200, [], { bytes: Buffer.from('User-agent: *\nAllow: /'), overLimit: false })+ )+ const headersForGet = jest+ .fn()+ .mockReturnValueOnce({ signature: 'first' })+ .mockReturnValueOnce({ signature: 'second' })++ await expect(httpFetcher(headersForGet).fetch(ORIGIN, 'robots')).resolves.toMatchObject({+ outcome: 'available',+ })+ expect(headersForGet.mock.calls).toEqual([+ ['https://example.com/robots.txt'],+ ['https://cdn.example.com/robots'],+ ])+ })++ it('does not follow a configuration redirect to another registrable domain', async () => {+ fetchStreamedMock.mockResolvedValueOnce(+ response(302, [{ name: 'location', value: 'https://cdn.example.net/robots' }])+ )+ const headersForGet = jest.fn().mockReturnValue({ signature: 'value' })++ await expect(httpFetcher(headersForGet).fetch(ORIGIN, 'robots')).resolves.toMatchObject({+ outcome: 'unreachable',+ })+ expect(fetchStreamedMock).toHaveBeenCalledTimes(1)+ expect(headersForGet).toHaveBeenCalledTimes(1)+ })+})++describe('explicitFreshnessLifetimeMs', () => {+ it('uses s-maxage and subtracts the corrected current age', () => {+ expect(+ explicitFreshnessLifetimeMs(+ {+ requestTimeMs: NOW_MS - 2_000,+ responseTimeMs: NOW_MS,+ date: new Date(NOW_MS - 1_000).toUTCString(),+ age: '10',+ cacheControl: 'max-age=100, s-maxage=200',+ },+ NOW_MS+ )+ ).toBe(188_000)+ })++ it.each(['no-cache', 'no-store', 'private', 'must-revalidate'])('does not extend freshness for %s', (directive) => {+ expect(+ explicitFreshnessLifetimeMs(+ {+ requestTimeMs: NOW_MS,+ responseTimeMs: NOW_MS,+ cacheControl: `${directive}, max-age=999999`,+ },+ NOW_MS+ )+ ).toBe(0)+ })++ it.each([+ ['duplicate max-age', 'max-age=60, max-age=120'],+ ['decimal max-age', 'max-age=1.5'],+ ['exponent max-age', 'max-age=1e3'],+ ['unsafe max-age', 'max-age=9007199254740992'],+ ['invalid s-maxage before a valid max-age', 's-maxage=invalid, max-age=3600'],+ ])('does not extend freshness for %s', (_name, cacheControl) => {+ expect(+ explicitFreshnessLifetimeMs(+ {+ requestTimeMs: NOW_MS,+ responseTimeMs: NOW_MS,+ cacheControl,+ },+ NOW_MS+ )+ ).toBe(0)+ })++ it('uses every combined Cache-Control field line', () => {+ expect(+ explicitFreshnessLifetimeMs(+ {+ requestTimeMs: NOW_MS,+ responseTimeMs: NOW_MS,+ cacheControl: 'public, max-age=86400, no-store',+ },+ NOW_MS+ )+ ).toBe(0)+ })++ it('ignores a decimal Age value', () => {+ expect(+ explicitFreshnessLifetimeMs(+ {+ requestTimeMs: NOW_MS,+ responseTimeMs: NOW_MS,+ age: '1.5',+ cacheControl: 'max-age=10',+ },+ NOW_MS+ )+ ).toBe(10_000)+ })++ it('subtracts time spent resident after the response arrived', () => {+ expect(+ explicitFreshnessLifetimeMs(+ {+ requestTimeMs: NOW_MS,+ responseTimeMs: NOW_MS,+ cacheControl: 'max-age=10',+ },+ NOW_MS + 4_000+ )+ ).toBe(6_000)+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.tsnew file mode 100644index 000000000000..4caa5263e0a5--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy.ts@@ -0,0 +1,761 @@+import type { ParsedRobots, RobotsParseHandler } from '@trybyte/robotstxt-parser'+import { Token, parseDictionary } from 'structured-headers'++import { parseJSON } from '~/common/utils/json-parse'+import { fetchStreamed } from '~/common/utils/request'++import { ConfigurationCacheItem, ConfigurationFile, HttpCacheMetadata, configurationCacheKey } from './crawl-history'+import { ImageFetchRequestMetrics } from './metrics'+import { canonicalizeUrl, politenessKey } from './politeness-key'+import { WebBotAuthRequestSigner } from './web-bot-auth'++const BOT_NAME = 'PostHogImageFetcherBot'+const USER_AGENT = `${BOT_NAME}/1.0 (+https://posthog.com/docs/ai-research/image-fetcher-bot)`+const CONFIG_BODY_LIMIT = 500 * 1024+const CONFIG_REDIRECT_LIMIT = 5+const CONFIG_FRESH_MS = 24 * 60 * 60 * 1000+const CONFIG_REFRESH_MS = 23 * 60 * 60 * 1000+const CONFIG_RETRY_MS = 60 * 60 * 1000+const CONFIG_STORAGE_MS = 30 * 24 * 60 * 60 * 1000+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])++export type ConfigurationFetchResult =+ | { outcome: 'available'; body: string; cache: HttpCacheMetadata }+ | { outcome: 'absent' | 'refused' | 'unreachable'; cache?: HttpCacheMetadata }+ | { outcome: 'deferred'; reason: ConfigurationRequestBlockReason }++export type ConfigurationRequestBlockReason =+ | 'breaker_open'+ | 'backoff'+ | 'deadline'+ | 'origin_map_full'+ | 'registrable_domain_map_full'+ | 'connection_limit'++export type RobotsPolicyRefusalReason = 'robots_disallow' | 'content_usage' | 'content_signal'+export type OriginPolicyReason =+ | RobotsPolicyRefusalReason+ | 'robots_refused'+ | 'tdmrep_refused'+ | 'origin_map_full'+ | 'registrable_domain_map_full'+ | 'configuration_deferred'+ | 'configuration_unreachable'+export type ResponseOptOutReason = 'x_robots_tag' | 'content_usage' | 'tdm_reservation'++export interface ConfigurationRequestScheduler {+ run<T>(+ url: URL,+ deadlineMs: number,+ request: () => Promise<T>+ ): Promise<{ ran: true; value: T } | { ran: false; reason: ConfigurationRequestBlockReason }>+}++type ConfigurationHop =+ | { kind: 'redirect'; location: string; cache: HttpCacheMetadata }+ | { kind: 'done'; result: ConfigurationFetchResult }++export class HttpConfigurationFetcher {+ constructor(+ private readonly signer: WebBotAuthRequestSigner,+ private readonly scheduler: ConfigurationRequestScheduler,+ private readonly timeoutMs: number+ ) {}++ public async fetch(origin: string, file: ConfigurationFile): Promise<ConfigurationFetchResult> {+ const deadlineMs = Date.now() + this.timeoutMs+ let target = new URL(file === 'robots' ? '/robots.txt' : '/.well-known/tdmrep.json', origin)+ const registrableDomain = politenessKey(target.hostname)+ for (let redirects = 0; ; redirects++) {+ const canonical = canonicalizeUrl(target.toString())+ if (!canonical) {+ return { outcome: 'refused' }+ }+ target = new URL(canonical.fetch)+ let scheduled:+ | { ran: true; value: ConfigurationHop }+ | { ran: false; reason: ConfigurationRequestBlockReason }+ try {+ scheduled = await this.scheduler.run(target, deadlineMs, () => this.hop(target, file, deadlineMs))+ } catch {+ return { outcome: 'unreachable' }+ }+ if (!scheduled.ran) {+ return { outcome: 'deferred', reason: scheduled.reason }+ }+ const hop = scheduled.value+ if (hop.kind === 'done') {+ return hop.result+ }+ if (redirects >= CONFIG_REDIRECT_LIMIT) {+ return { outcome: 'unreachable', cache: hop.cache }+ }+ try {+ const redirectTarget = new URL(hop.location, target)+ if (politenessKey(redirectTarget.hostname) !== registrableDomain) {+ return { outcome: 'unreachable', cache: hop.cache }+ }+ target = redirectTarget+ } catch {+ return { outcome: 'unreachable', cache: hop.cache }+ }+ }+ }++ private async hop(target: URL, file: ConfigurationFile, deadlineMs: number): Promise<ConfigurationHop> {+ const requestTimeMs = Date.now()+ const canonical = canonicalizeUrl(target.toString())+ let response: Awaited<ReturnType<typeof fetchStreamed>>+ try {+ response = await fetchStreamed(target.toString(), {+ timeoutMs: Math.max(1, deadlineMs - Date.now()),+ headers: {+ 'user-agent': USER_AGENT,+ accept: file === 'robots' ? 'text/plain,*/*;q=0.1' : 'application/json,*/*;q=0.1',+ 'accept-encoding': 'identity',+ ...this.signer.headersForGet(target.toString()),+ },+ })+ } catch (error) {+ if (canonical) {+ ImageFetchRequestMetrics.observeRequest('network_error', (Date.now() - requestTimeMs) / 1000)+ }+ throw error+ }+ const complete = (result: ConfigurationHop): ConfigurationHop => {+ if (canonical) {+ ImageFetchRequestMetrics.observeRequest(+ ImageFetchRequestMetrics.outcomeForHttpStatus(response.status),+ (Date.now() - requestTimeMs) / 1000+ )+ }+ return result+ }+ const cache = cacheMetadata(requestTimeMs, Date.now(), response.headerLines)+ if (REDIRECT_STATUSES.has(response.status)) {+ response.discard()+ const locations = headerValues(response.headerLines, 'location')+ const location = locations.length === 1 ? locations[0] : undefined+ return complete(+ location+ ? { kind: 'redirect', location, cache }+ : { kind: 'done', result: { outcome: 'unreachable', cache } }+ )+ }+ if (response.status === 404 || response.status === 410) {+ response.discard()+ return complete({ kind: 'done', result: { outcome: 'absent', cache } })+ }+ if (response.status === 429 || response.status >= 500) {+ response.discard()+ return complete({ kind: 'done', result: { outcome: 'unreachable', cache } })+ }+ if (response.status >= 400 && response.status < 500) {+ response.discard()+ return complete({ kind: 'done', result: { outcome: 'refused', cache } })+ }+ if (response.status !== 200) {+ response.discard()+ return complete({ kind: 'done', result: { outcome: 'unreachable', cache } })+ }+ const body = await response.read(CONFIG_BODY_LIMIT)+ if (body.overLimit && file === 'tdmrep') {+ return complete({ kind: 'done', result: { outcome: 'unreachable', cache } })+ }+ const text = body.bytes.toString('utf8')+ if (file === 'tdmrep' && !isValidTdmrepDocument(text)) {+ return complete({ kind: 'done', result: { outcome: 'unreachable', cache } })+ }+ return complete({ kind: 'done', result: { outcome: 'available', body: text, cache } })+ }+}++export interface OriginPolicyDecision {+ allowed: boolean+ transient: boolean+ reason?: OriginPolicyReason+ crawlDelayMs: number+ tdmrepReservation: boolean+ updates: ConfigurationCacheItem[]+}++export interface ConfigurationPolicyPass {+ check(url: string, cached: Map<string, ConfigurationCacheItem>, nowMs: number): Promise<OriginPolicyDecision>+}++interface ParsedRobotsConfiguration {+ matcher: ParsedRobots+ fields: Array<{ name: string; value: string }>+}++interface ParsedConfigurationCache {+ robots: Map<string, Promise<ParsedRobotsConfiguration>>+ tdmrep: Map<string, unknown>+}++export class ConfigurationPolicyService {+ private readonly inFlight = new Map<string, Promise<ConfigurationFetchResult>>()++ constructor(private readonly fetcher: HttpConfigurationFetcher) {}++ public createPass(): ConfigurationPolicyPass {+ const parsed: ParsedConfigurationCache = {+ robots: new Map(),+ tdmrep: new Map(),+ }+ return {+ check: (url, cached, nowMs) => this.checkWithParsedCache(url, cached, nowMs, parsed),+ }+ }++ public async check(+ url: string,+ cached: Map<string, ConfigurationCacheItem>,+ nowMs: number+ ): Promise<OriginPolicyDecision> {+ return await this.createPass().check(url, cached, nowMs)+ }++ private async checkWithParsedCache(+ url: string,+ cached: Map<string, ConfigurationCacheItem>,+ nowMs: number,+ parsed: ParsedConfigurationCache+ ): Promise<OriginPolicyDecision> {+ const origin = new URL(url).origin+ const [robots, tdmrep] = await Promise.all([+ this.load(origin, 'robots', cached.get(configurationCacheKey(origin, 'robots')), nowMs),+ this.load(origin, 'tdmrep', cached.get(configurationCacheKey(origin, 'tdmrep')), nowMs),+ ])+ const updates = [...robots.updates, ...tdmrep.updates]+ if (robots.item.status === 'refused') {+ return {+ allowed: false,+ transient: false,+ reason: 'robots_refused',+ crawlDelayMs: 1_000,+ tdmrepReservation: false,+ updates,+ }+ }+ if (tdmrep.item.status === 'refused') {+ return {+ allowed: false,+ transient: false,+ reason: 'tdmrep_refused',+ crawlDelayMs: 1_000,+ tdmrepReservation: false,+ updates,+ }+ }++ const robotsPolicy = robots.item.body+ ? evaluateRobotsPolicy(await parsedRobotsConfiguration(robots.item, parsed), url)+ : defaultRobotsPolicy()+ if (!robotsPolicy.allowed) {+ return {+ allowed: false,+ transient: false,+ reason: robotsPolicy.reason,+ crawlDelayMs: robotsPolicy.crawlDelayMs,+ tdmrepReservation: false,+ updates,+ }+ }+ const tdmrepReservation = Boolean(+ tdmrep.item.body && tdmrepRefuses(parsedTdmrepDocument(tdmrep.item, parsed), new URL(url))+ )+ const deferredReason = requestControlDeferralReason(robots.deferredReason, tdmrep.deferredReason)+ if (deferredReason) {+ return {+ allowed: false,+ transient: true,+ reason: deferredReason,+ crawlDelayMs: 1_000,+ tdmrepReservation: false,+ updates,+ }+ }+ if (robots.item.status === 'unreachable' || tdmrep.item.status === 'unreachable') {+ return {+ allowed: false,+ transient: true,+ reason: 'configuration_unreachable',+ crawlDelayMs: 1_000,+ tdmrepReservation: false,+ updates,+ }+ }+ return {+ allowed: true,+ transient: false,+ crawlDelayMs: robotsPolicy.crawlDelayMs,+ tdmrepReservation,+ updates,+ }+ }++ private async load(+ origin: string,+ file: ConfigurationFile,+ previous: ConfigurationCacheItem | undefined,+ nowMs: number+ ): Promise<{+ item: ConfigurationCacheItem+ updates: ConfigurationCacheItem[]+ deferredReason?: ConfigurationRequestBlockReason+ }> {+ if (previous && previous.storageExpiresAtMs <= nowMs) {+ previous = undefined+ }+ if (previous && previous.refreshAtMs > nowMs) {+ return { item: previous, updates: [] }+ }+ if (previous?.status === 'unreachable' && previous.retryAtMs > nowMs) {+ return { item: previous, updates: [] }+ }+ const key = configurationCacheKey(origin, file)+ let request = this.inFlight.get(key)+ if (!request) {+ request = this.fetcher.fetch(origin, file).finally(() => this.inFlight.delete(key))+ this.inFlight.set(key, request)+ }+ const fetched = await request+ if (fetched.outcome === 'deferred') {+ return {+ item: previous ?? unreachableItem(origin, file, nowMs),+ updates: [],+ deferredReason: fetched.reason,+ }+ }+ if (fetched.outcome === 'unreachable' && previous && previous.status !== 'unreachable') {+ const retained = {+ ...previous,+ refreshAtMs: nowMs + CONFIG_RETRY_MS,+ retryAtMs: nowMs + CONFIG_RETRY_MS,+ storageExpiresAtMs: Math.max(previous.storageExpiresAtMs, nowMs + CONFIG_STORAGE_MS),+ }+ return { item: retained, updates: [retained] }+ }+ const explicitFreshMs = fetched.cache ? explicitFreshnessLifetimeMs(fetched.cache) : 0+ const freshForMs =+ fetched.outcome === 'unreachable' ? CONFIG_RETRY_MS : Math.max(CONFIG_FRESH_MS, explicitFreshMs)+ const item: ConfigurationCacheItem = {+ kind: file,+ key,+ origin,+ status: fetched.outcome,+ body: fetched.outcome === 'available' ? fetched.body : undefined,+ fetchedAtMs: nowMs,+ refreshAtMs: nowMs + (fetched.outcome === 'unreachable' ? CONFIG_RETRY_MS : CONFIG_REFRESH_MS),+ freshUntilMs: nowMs + freshForMs,+ retryAtMs: nowMs + (fetched.outcome === 'unreachable' ? CONFIG_RETRY_MS : 0),+ storageExpiresAtMs: nowMs + Math.max(CONFIG_STORAGE_MS, freshForMs),+ }+ return { item, updates: [item] }+ }+}++function requestControlDeferralReason(+ ...reasons: Array<ConfigurationRequestBlockReason | undefined>+):+ | Extract<OriginPolicyReason, 'origin_map_full' | 'registrable_domain_map_full' | 'configuration_deferred'>+ | undefined {+ if (reasons.includes('registrable_domain_map_full')) {+ return 'registrable_domain_map_full'+ }+ if (reasons.includes('origin_map_full')) {+ return 'origin_map_full'+ }+ return reasons.some(Boolean) ? 'configuration_deferred' : undefined+}++function unreachableItem(origin: string, file: ConfigurationFile, nowMs: number): ConfigurationCacheItem {+ return {+ kind: file,+ key: configurationCacheKey(origin, file),+ origin,+ status: 'unreachable',+ fetchedAtMs: nowMs,+ refreshAtMs: nowMs + CONFIG_RETRY_MS,+ freshUntilMs: nowMs + CONFIG_RETRY_MS,+ retryAtMs: nowMs + CONFIG_RETRY_MS,+ storageExpiresAtMs: nowMs + CONFIG_STORAGE_MS,+ }+}++interface ExtensionGroup {+ userAgents: string[]+ fields: Array<{ name: string; value: string }>+}++class ExtensionCollector implements RobotsParseHandler {+ public readonly groups: ExtensionGroup[] = []+ private current: ExtensionGroup | undefined+ private hasRules = false++ handleRobotsStart(): void {}+ handleRobotsEnd(): void {}+ reportLineMetadata(): void {}++ handleUserAgent(_lineNum: number, value: string): void {+ if (!this.current || this.hasRules) {+ this.current = { userAgents: [], fields: [] }+ this.groups.push(this.current)+ this.hasRules = false+ }+ this.current.userAgents.push(value.trim().toLowerCase())+ }++ handleAllow(): void {+ this.hasRules = true+ }++ handleDisallow(): void {+ this.hasRules = true+ }++ handleSitemap(): void {+ this.hasRules = true+ }++ handleUnknownAction(_lineNum: number, action: string, value: string): void {+ if (!this.current) {+ return+ }+ this.hasRules = true+ this.current.fields.push({ name: action.trim().toLowerCase(), value: value.trim() })+ }+}++function selectedExtensionFields(+ body: string,+ parseRobotsTxt: typeof import('@trybyte/robotstxt-parser').parseRobotsTxt+): Array<{ name: string; value: string }> {+ const collector = new ExtensionCollector()+ parseRobotsTxt(body, collector)+ const bot = BOT_NAME.toLowerCase()+ const matches = collector.groups.map((group) => ({+ group,+ specificity: Math.max(+ ...group.userAgents.map((agent) => (agent !== '*' && bot.startsWith(agent) ? agent.length : 0)),+ 0+ ),+ wildcard: group.userAgents.includes('*'),+ }))+ const specificity = Math.max(...matches.map((match) => match.specificity), 0)+ const selected =+ specificity > 0+ ? matches.filter((match) => match.specificity === specificity)+ : matches.filter((match) => match.wildcard)+ return selected.flatMap((match) => match.group.fields)+}++function defaultRobotsPolicy(): { allowed: true; crawlDelayMs: number } {+ return { allowed: true, crawlDelayMs: 1_000 }+}++export async function parseRobotsPolicy(+ body: string,+ url: string+): Promise<{ allowed: boolean; crawlDelayMs: number; reason?: RobotsPolicyRefusalReason }> {+ return evaluateRobotsPolicy(await parseRobotsConfiguration(body), url)+}++async function parseRobotsConfiguration(body: string): Promise<ParsedRobotsConfiguration> {+ const robotsParser = await import('@trybyte/robotstxt-parser')+ const { ParsedRobots, parseRobotsTxt } = robotsParser+ return {+ matcher: ParsedRobots.parse(body),+ fields: selectedExtensionFields(body, parseRobotsTxt),+ }+}++function evaluateRobotsPolicy(+ parsed: ParsedRobotsConfiguration,+ url: string+): { allowed: boolean; crawlDelayMs: number; reason?: RobotsPolicyRefusalReason } {+ if (!parsed.matcher.checkUrl(BOT_NAME, url).allowed) {+ return { allowed: false, crawlDelayMs: 1_000, reason: 'robots_disallow' }+ }+ const crawlDelayMs = Math.max(+ 1_000,+ ...parsed.fields+ .filter((field) => field.name === 'crawl-delay')+ .flatMap((field) => {+ const value = field.value.trim()+ if (!/^\d+(?:\.\d+)?$/.test(value)) {+ return []+ }+ const milliseconds = Number(value) * 1000+ return Number.isSafeInteger(milliseconds) ? [milliseconds] : []+ })+ )+ if (+ contentUsageRefuses(parsed.fields.filter((field) => field.name === 'content-usage').map((field) => field.value))+ ) {+ return { allowed: false, crawlDelayMs, reason: 'content_usage' }+ }+ if (parsed.fields.some((field) => field.name === 'content-signal' && contentSignalRefuses(field.value, url))) {+ return { allowed: false, crawlDelayMs, reason: 'content_signal' }+ }+ return { allowed: true, crawlDelayMs }+}++function parseTdmrepDocument(body: string): unknown {+ try {+ return parseJSON(body)+ } catch {+ return undefined+ }+}++function tdmrepRefuses(parsed: unknown, url: URL): boolean {+ if (!Array.isArray(parsed)) {+ return false+ }+ for (const rule of parsed) {+ if (!isObject(rule) || typeof rule.location !== 'string') {+ continue+ }+ if (tdmLocationMatches(rule.location, url.pathname)) {+ return rule['tdm-reservation'] === 1+ }+ }+ return false+}++function isValidTdmrepDocument(body: string): boolean {+ const parsed = parseTdmrepDocument(body)+ return (+ Array.isArray(parsed) &&+ parsed.every(+ (rule) =>+ isObject(rule) &&+ typeof rule.location === 'string' &&+ (rule['tdm-reservation'] === 0 || rule['tdm-reservation'] === 1)+ )+ )+}++async function parsedRobotsConfiguration(+ item: ConfigurationCacheItem,+ parsed: ParsedConfigurationCache+): Promise<ParsedRobotsConfiguration> {+ const revision = configurationRevision(item)+ let configuration = parsed.robots.get(revision)+ if (!configuration) {+ configuration = parseRobotsConfiguration(item.body ?? '')+ parsed.robots.set(revision, configuration)+ }+ return await configuration+}++function parsedTdmrepDocument(item: ConfigurationCacheItem, parsed: ParsedConfigurationCache): unknown {+ const revision = configurationRevision(item)+ if (!parsed.tdmrep.has(revision)) {+ parsed.tdmrep.set(revision, parseTdmrepDocument(item.body ?? ''))+ }+ return parsed.tdmrep.get(revision)+}++function configurationRevision(item: ConfigurationCacheItem): string {+ return `${item.key}\0${item.fetchedAtMs}`+}++function tdmLocationMatches(pattern: string, pathname: string): boolean {+ const decodedPattern = decodeUnreserved(pattern)+ const endAnchored = decodedPattern.endsWith('$')+ const matchPattern = endAnchored ? decodedPattern.slice(0, -1) : decodedPattern+ const escaped = matchPattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')+ const source = endAnchored ? `${escaped}$` : `${escaped}.*`+ try {+ return new RegExp(`^${source}`).test(decodeUnreserved(pathname))+ } catch {+ return false+ }+}++function decodeUnreserved(value: string): string {+ return value.replace(/%[0-9A-Fa-f]{2}/g, (encoded) => {+ const character = String.fromCharCode(Number.parseInt(encoded.slice(1), 16))+ return /^[A-Za-z0-9._~-]$/.test(character) ? character : encoded.toUpperCase()+ })+}++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function contentUsageRefuses(values: string[]): boolean {+ if (values.length === 0) {+ return false+ }+ try {+ const trainAi = parseDictionary(values.join(', ')).get('train-ai')+ return Boolean(+ trainAi && !Array.isArray(trainAi[0]) && trainAi[0] instanceof Token && trainAi[0].toString() === 'n'+ )+ } catch {+ return false+ }+}++function contentSignalRefuses(value: string, url: string): boolean {+ const trimmed = value.trim()+ const pathEnd = trimmed.startsWith('/') ? trimmed.search(/\s/) : -1+ if (pathEnd > 0 && !tdmLocationMatches(trimmed.slice(0, pathEnd), new URL(url).pathname)) {+ return false+ }+ const preferences = (pathEnd > 0 ? trimmed.slice(pathEnd) : trimmed)+ .split(',')+ .map((part) => part.trim().split('=', 2))+ const aiTrain = preferences.filter(([name]) => name === 'ai-train').at(-1)+ return aiTrain?.[1] === 'no'+}++export function responseOptOutReason(+ headerLines: Array<{ name: string; value: string }>,+ tdmrepReservation: boolean+): ResponseOptOutReason | undefined {+ if (headerLines.some((line) => line.name === 'x-robots-tag' && xRobotsTagRefuses(line.value))) {+ return 'x_robots_tag'+ }+ if (contentUsageRefuses(headerLines.filter((line) => line.name === 'content-usage').map((line) => line.value))) {+ return 'content_usage'+ }+ const headerReservation = tdmReservationHeader(headerLines)+ if (headerReservation ?? tdmrepReservation) {+ return 'tdm_reservation'+ }+ return undefined+}++function xRobotsTagRefuses(value: string): boolean {+ const lower = value.toLowerCase()+ const colon = lower.indexOf(':')+ const directives = colon >= 0 ? lower.slice(colon + 1) : lower+ if (colon >= 0 && lower.slice(0, colon).trim() !== BOT_NAME.toLowerCase()) {+ return false+ }+ return directives.split(',').some((directive) => ['noai', 'noimageai'].includes(directive.trim()))+}++function tdmReservationHeader(headerLines: Array<{ name: string; value: string }>): boolean | undefined {+ const values = headerLines+ .filter((line) => line.name === 'tdm-reservation')+ .flatMap((line) => line.value.split(','))+ .map((value) => value.trim())+ if (values.includes('1')) {+ return true+ }+ if (values.includes('0')) {+ return false+ }+ return undefined+}++function headerValues(headerLines: Array<{ name: string; value: string }>, name: string): string[] {+ return headerLines.filter((line) => line.name === name).map((line) => line.value)+}++function cacheMetadata(+ requestTimeMs: number,+ responseTimeMs: number,+ headerLines: Array<{ name: string; value: string }>+): HttpCacheMetadata {+ return {+ requestTimeMs,+ responseTimeMs,+ etag: singletonHeader(headerLines, 'etag'),+ lastModified: singletonHeader(headerLines, 'last-modified'),+ date: singletonHeader(headerLines, 'date'),+ age: singletonHeader(headerLines, 'age'),+ cacheControl: combinedHeader(headerLines, 'cache-control'),+ expires: singletonHeader(headerLines, 'expires'),+ }+}++function singletonHeader(headerLines: Array<{ name: string; value: string }>, name: string): string | undefined {+ const values = headerValues(headerLines, name)+ return values.length === 1 ? values[0] : undefined+}++function combinedHeader(headerLines: Array<{ name: string; value: string }>, name: string): string | undefined {+ const values = headerValues(headerLines, name)+ return values.length > 0 ? values.join(', ') : undefined+}++export function explicitFreshnessLifetimeMs(cache: HttpCacheMetadata, nowMs = Date.now()): number {+ const directives = cacheControlDirectives(cache.cacheControl)+ if (['no-cache', 'no-store', 'private', 'must-revalidate'].some((directive) => directives.has(directive))) {+ return 0+ }+ let lifetimeMs = 0+ if (directives.has('s-maxage')) {+ lifetimeMs = singletonDeltaSeconds(directives.get('s-maxage')) * 1000+ } else if (directives.has('max-age')) {+ lifetimeMs = singletonDeltaSeconds(directives.get('max-age')) * 1000+ } else if (cache.expires) {+ const expiresMs = Date.parse(cache.expires)+ const dateMs = cache.date ? Date.parse(cache.date) : cache.responseTimeMs+ if (Number.isFinite(expiresMs) && Number.isFinite(dateMs)) {+ lifetimeMs = Math.max(0, expiresMs - dateMs)+ }+ }+ const dateMs = cache.date ? Date.parse(cache.date) : cache.responseTimeMs+ const apparentAgeMs = Number.isFinite(dateMs) ? Math.max(0, cache.responseTimeMs - dateMs) : 0+ const ageValueMs = nonNegativeInteger(cache.age) * 1000+ const correctedAgeMs = ageValueMs + Math.max(0, cache.responseTimeMs - cache.requestTimeMs)+ const currentAgeMs = Math.max(apparentAgeMs, correctedAgeMs) + Math.max(0, nowMs - cache.responseTimeMs)+ return Math.max(0, lifetimeMs - currentAgeMs)+}++function cacheControlDirectives(cacheControl: string | undefined): Map<string, Array<string | undefined>> {+ const directives = new Map<string, Array<string | undefined>>()+ for (const directive of splitCommaSeparatedValues(cacheControl ?? '')) {+ const [rawName, ...rawValueParts] = directive.trim().split('=')+ const name = rawName.toLowerCase()+ if (!name) {+ continue+ }+ const rawValue = rawValueParts.length > 0 ? rawValueParts.join('=').trim() : undefined+ const value = rawValue?.startsWith('"') && rawValue.endsWith('"') ? rawValue.slice(1, -1) : rawValue+ directives.set(name, [...(directives.get(name) ?? []), value])+ }+ return directives+}++function splitCommaSeparatedValues(value: string): string[] {+ const values: string[] = []+ let start = 0+ let quoted = false+ let escaped = false+ for (let index = 0; index < value.length; index++) {+ const character = value[index]+ if (escaped) {+ escaped = false+ } else if (character === '\\' && quoted) {+ escaped = true+ } else if (character === '"') {+ quoted = !quoted+ } else if (character === ',' && !quoted) {+ values.push(value.slice(start, index))+ start = index + 1+ }+ }+ values.push(value.slice(start))+ return values+}++function singletonDeltaSeconds(values: Array<string | undefined> | undefined): number {+ return values?.length === 1 ? nonNegativeInteger(values[0]) : 0+}++function nonNegativeInteger(value: string | undefined): number {+ if (!value || !/^\d+$/.test(value.trim())) {+ return 0+ }+ const parsed = Number(value)+ return Number.isSafeInteger(parsed) ? parsed : 0+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.tsindex 5420762f950a..5140a1bb7e36 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history.ts@@ -1,15 +1,46 @@-const CRAWL_HISTORY_PREFIX = 'imgfetch:seen'+export interface HttpCacheMetadata {+ requestTimeMs: number+ responseTimeMs: number+ etag?: string+ lastModified?: string+ date?: string+ age?: string+ cacheControl?: string+ expires?: string+}-export function crawlHistoryKey(pseudoTeam: string, urlHash: string): string {- return `${CRAWL_HISTORY_PREFIX}:${pseudoTeam}:${urlHash}`+export interface UrlCrawlHistoryItem {+ kind: 'url'+ key: string+ nextFetchAtMs: number+ storageExpiresAtMs: number+ outcome: string+ cache?: HttpCacheMetadata}-export interface CrawlHistoryReadResult {- known: Set<number>- failed: Set<number>+export type ConfigurationFile = 'robots' | 'tdmrep'+export type ConfigurationStatus = 'available' | 'absent' | 'refused' | 'unreachable'++export interface ConfigurationCacheItem {+ kind: ConfigurationFile+ key: string+ origin: string+ status: ConfigurationStatus+ body?: string+ fetchedAtMs: number+ refreshAtMs: number+ freshUntilMs: number+ retryAtMs: number+ storageExpiresAtMs: number+}++export type CrawlHistoryItem = UrlCrawlHistoryItem | ConfigurationCacheItem++export function configurationCacheKey(origin: string, file: ConfigurationFile): string {+ return `imgfetch:config:${file}:${origin}`}export interface CrawlHistoryStore {- read(keys: string[], nowMs: number): Promise<CrawlHistoryReadResult>- record(keys: string[], nowMs: number, ttlSeconds: number): Promise<{ failed: Set<number> }>+ read(keys: string[]): Promise<Map<string, CrawlHistoryItem>>+ write(items: CrawlHistoryItem[]): Promise<void>}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.integration.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.integration.test.tsindex 01114f268cc0..38b19b5a0a17 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.integration.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.integration.test.ts@@ -6,6 +6,7 @@ import {waitUntilTableExists,} from '@aws-sdk/client-dynamodb'+import { UrlCrawlHistoryItem } from './crawl-history'import { DynamoDBCrawlHistory } from './dynamodb-crawl-history'const DYNAMODB_ENDPOINT = 'http://127.0.0.1:18010'@@ -44,15 +45,22 @@ describe('DynamoDBCrawlHistory integration', () => {const crawlHistory = new DynamoDBCrawlHistory(client, TABLE_NAME, 5_000, 30_000)await crawlHistory.validateAccess(NOW_MS)- const writeResult = await crawlHistory.record(KEYS, NOW_MS, TTL_SECONDS)- const readResult = await crawlHistory.read([...KEYS, 'missing'], NOW_MS)+ const storageExpiresAtMs = NOW_MS + TTL_SECONDS * 1000+ const items: UrlCrawlHistoryItem[] = KEYS.map((key) => ({+ kind: 'url',+ key,+ nextFetchAtMs: storageExpiresAtMs,+ storageExpiresAtMs,+ outcome: 'ok',+ }))+ await crawlHistory.write(items)+ const readResult = await crawlHistory.read([...KEYS, 'missing'])const storedItem = await client.send(new GetItemCommand({ TableName: TABLE_NAME, Key: { key: { S: KEYS[0] } }, ConsistentRead: true }))- expect(writeResult.failed).toEqual(new Set())- expect(readResult.failed).toEqual(new Set())- expect(readResult.known).toEqual(new Set(KEYS.map((_key, index) => index)))+ expect(readResult.size).toBe(KEYS.length)+ expect([...readResult.keys()].sort()).toEqual([...KEYS].sort())expect(storedItem.Item?.expires_at?.N).toBe(String(NOW_SECONDS + TTL_SECONDS))})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.test.tsindex 3ac453d2a366..fb6ffae7b4a7 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.test.ts@@ -1,211 +1,291 @@import { BatchGetItemCommand, BatchWriteItemCommand } from '@aws-sdk/client-dynamodb'+import { parseJSON } from '~/common/utils/json-parse'++import { ConfigurationCacheItem, CrawlHistoryItem, UrlCrawlHistoryItem } from './crawl-history'import { DynamoDBCrawlHistory, DynamoDBCrawlHistoryClient } from './dynamodb-crawl-history'-const TABLE = 'ai-research-image-fetch-crawl-history'-const NOW_MS = 1_700_000_000_000-const NOW_SECONDS = Math.floor(NOW_MS / 1000)-const KEYS = Array.from({ length: 205 }, (_value, index) => `k${index}`)+const TABLE = 'crawl-history'+const NOW_MS = 1_700_000_000_123++function urlItem(key: string, overrides: Partial<UrlCrawlHistoryItem> = {}): UrlCrawlHistoryItem {+ return {+ kind: 'url',+ key,+ nextFetchAtMs: NOW_MS + 30 * 24 * 60 * 60 * 1000,+ storageExpiresAtMs: NOW_MS + 30 * 24 * 60 * 60 * 1000,+ outcome: 'ok',+ ...overrides,+ }+}-function dynamoClient(send: jest.Mock): DynamoDBCrawlHistoryClient {- return { send }+function stored(item: CrawlHistoryItem): Record<string, { S?: string; N?: string }> {+ return {+ key: { S: item.key },+ expires_at: { N: String(Math.ceil(item.storageExpiresAtMs / 1000)) },+ value: { S: JSON.stringify(item) },+ }+}++function build(send: jest.Mock, batchBudgetMs = 10_000): DynamoDBCrawlHistory {+ return new DynamoDBCrawlHistory({ send } as unknown as DynamoDBCrawlHistoryClient, TABLE, 1_000, batchBudgetMs)}function requestedReadKeys(command: BatchGetItemCommand): string[] {- return (command.input.RequestItems?.[TABLE].Keys ?? []).flatMap((key) => (key.key?.S ? [key.key.S] : []))+ return command.input.RequestItems?.[TABLE]?.Keys?.flatMap((key) => (key.key?.S ? [key.key.S] : [])) ?? []}-function requestedWriteKeys(command: BatchWriteItemCommand): string[] {- return (command.input.RequestItems?.[TABLE] ?? []).flatMap((request) =>- request.PutRequest?.Item?.key?.S ? [request.PutRequest.Item.key.S] : []- )+function requestedWrites(+ command: BatchWriteItemCommand+): NonNullable<BatchWriteItemCommand['input']['RequestItems']>[string] {+ return command.input.RequestItems?.[TABLE] ?? []}describe('DynamoDBCrawlHistory', () => {- const build = (send: jest.Mock): DynamoDBCrawlHistory =>- new DynamoDBCrawlHistory(dynamoClient(send), TABLE, 1_000, 60_000)-- it('validates batch write and consistent read access', async () => {- const send = jest.fn((command: BatchGetItemCommand | BatchWriteItemCommand) =>- command instanceof BatchWriteItemCommand- ? Promise.resolve({})- : Promise.resolve({ Responses: { [TABLE]: [{ key: { S: 'imgfetch:access-probe' } }] } })- )+ it('reads each distinct key in batches of at most 100', async () => {+ const send = jest.fn((command: BatchGetItemCommand) => {+ const items = requestedReadKeys(command).map((key) => stored(urlItem(key)))+ return Promise.resolve({ Responses: { [TABLE]: items } })+ })+ const keys = [...Array.from({ length: 205 }, (_, index) => `k${index}`), 'k0']- await build(send).validateAccess(NOW_MS)+ const result = await build(send).read(keys)- expect(send).toHaveBeenCalledTimes(2)- expect(send.mock.calls[0][0]).toBeInstanceOf(BatchWriteItemCommand)- const readCommand = send.mock.calls[1][0] as BatchGetItemCommand- expect(readCommand).toBeInstanceOf(BatchGetItemCommand)- expect(readCommand.input.RequestItems?.[TABLE].ConsistentRead).toBe(true)+ expect(result).toHaveProperty('size', 205)+ expect(send).toHaveBeenCalledTimes(3)+ expect(send.mock.calls.map(([command]) => requestedReadKeys(command))).toEqual(+ expect.arrayContaining([expect.any(Array), expect.any(Array), expect.any(Array)])+ )+ expect(send.mock.calls.every(([command]) => requestedReadKeys(command).length <= 100)).toBe(true)})- it.each([- {- name: 'an unprocessed write',- responses: [- {- UnprocessedItems: {- [TABLE]: [{ PutRequest: { Item: { key: { S: 'imgfetch:access-probe' } } } }],- },+ it('reads a legacy expiry-only URL item', async () => {+ const send = jest.fn(() =>+ Promise.resolve({+ Responses: {+ [TABLE]: [{ key: { S: 'legacy' }, expires_at: { N: String(Math.ceil(NOW_MS / 1000)) } }],},- ],- },- {- name: 'an unprocessed read',- responses: [{}, { UnprocessedKeys: { [TABLE]: { Keys: [{ key: { S: 'imgfetch:access-probe' } }] } } }],- },- {- name: 'a missing probe record',- responses: [{}, { Responses: { [TABLE]: [] } }],- },- ])('rejects $name during access validation', async ({ responses }) => {- const send = jest.fn()- responses.forEach((response) => send.mockResolvedValueOnce(response))-- await expect(build(send).validateAccess(NOW_MS)).rejects.toThrow('access probe')- })-- it('reads the whole candidate set with DynamoDB batch operations', async () => {- const active = new Set(['k0', 'k99', 'k100', 'k204'])- const send = jest.fn((command: BatchGetItemCommand) => {- const items = requestedReadKeys(command)- .filter((key) => active.has(key) || key === 'k1')- .map((key) => ({- key: { S: key },- expires_at: { N: String(key === 'k1' ? NOW_SECONDS : NOW_SECONDS + 1) },- }))- return Promise.resolve({ Responses: { [TABLE]: items } })- })-- const result = await build(send).read(KEYS, NOW_MS)+ })+ )- expect([...result.known].sort((left, right) => left - right)).toEqual([0, 99, 100, 204])- expect(result.failed.size).toBe(0)- const commands = send.mock.calls.map(([command]) => command as BatchGetItemCommand)- expect(commands).toHaveLength(3)- expect(commands.every((command) => requestedReadKeys(command).length <= 100)).toBe(true)+ await expect(build(send).read(['legacy'])).resolves.toEqual(+ new Map([+ [+ 'legacy',+ {+ kind: 'url',+ key: 'legacy',+ nextFetchAtMs: Math.ceil(NOW_MS / 1000) * 1000,+ storageExpiresAtMs: Math.ceil(NOW_MS / 1000) * 1000,+ outcome: 'legacy',+ },+ ],+ ])+ )})- it('runs read batches with bounded concurrency', async () => {- const manyKeys = Array.from({ length: 1_601 }, (_value, index) => `key-${index}`)- let holdInitialRequests = true- const releaseInitialRequests: Array<() => void> = []- const send = jest.fn(() => {- if (!holdInitialRequests) {- return Promise.resolve({ Responses: { [TABLE]: [] } })- }- return new Promise((resolve) => releaseInitialRequests.push(() => resolve({ Responses: { [TABLE]: [] } })))- })+ it('retries only unprocessed read keys', async () => {+ const send = jest+ .fn()+ .mockResolvedValueOnce({+ Responses: { [TABLE]: [stored(urlItem('done'))] },+ UnprocessedKeys: { [TABLE]: { Keys: [{ key: { S: 'retry' } }] } },+ })+ .mockResolvedValueOnce({ Responses: { [TABLE]: [stored(urlItem('retry'))] } })- const readPromise = build(send).read(manyKeys, NOW_MS)- await Promise.resolve()+ const result = await build(send).read(['done', 'retry'])- expect(send.mock.calls.length).toBeGreaterThan(1)- expect(send.mock.calls.length).toBeLessThan(Math.ceil(manyKeys.length / 100))+ expect([...result.keys()].sort()).toEqual(['done', 'retry'])+ expect(requestedReadKeys(send.mock.calls[1][0])).toEqual(['retry'])+ })- holdInitialRequests = false- releaseInitialRequests.forEach((release) => release())- await readPromise+ it('throws when a read request fails', async () => {+ const send = jest.fn(() => Promise.reject(new Error('DynamoDB unavailable')))- expect(send).toHaveBeenCalledTimes(Math.ceil(manyKeys.length / 100))+ await expect(build(send).read(['a'])).rejects.toThrow('DynamoDB unavailable')})- it('treats expired rows as absent before DynamoDB deletes them', async () => {+ it('throws when DynamoDB returns a malformed item', async () => {const send = jest.fn(() =>- Promise.resolve({- Responses: {- [TABLE]: [{ key: { S: 'expired' }, expires_at: { N: String(NOW_SECONDS - 1) } }],- },- })+ Promise.resolve({ Responses: { [TABLE]: [{ key: { S: 'a' }, expires_at: { N: 'invalid' } }] } }))- const result = await build(send).read(['expired'], NOW_MS)-- expect(result.known.size).toBe(0)- expect(result.failed.size).toBe(0)+ await expect(build(send).read(['a'])).rejects.toThrow('malformed crawl-history item')})- it('reports only the keys whose batched read failed', async () => {- const send = jest.fn((command: BatchGetItemCommand) => {- const requested = requestedReadKeys(command)- return requested.includes('k100')- ? Promise.reject(new Error('dynamodb unavailable'))- : Promise.resolve({ Responses: { [TABLE]: [] } })- })+ it('throws when a stored value has an invalid nested shape', async () => {+ const item = stored(urlItem('a'))+ item.value = { S: JSON.stringify({ ...urlItem('a'), cache: { requestTimeMs: 'invalid' } }) }+ const send = jest.fn(() => Promise.resolve({ Responses: { [TABLE]: [item] } }))- const result = await build(send).read(KEYS, NOW_MS)+ await expect(build(send).read(['a'])).rejects.toThrow('invalid crawl-history value')+ })- expect(result.failed.size).toBe(100)- expect(result.failed.has(100)).toBe(true)- expect(result.failed.has(99)).toBe(false)+ it('folds repeated updates and writes batches of at most 25', async () => {+ const send: jest.Mock<Promise<unknown>, [BatchWriteItemCommand]> = jest.fn((_command) => Promise.resolve({}))+ const first = urlItem('same', { outcome: 'first' })+ const last = urlItem('same', { outcome: 'last', storageExpiresAtMs: NOW_MS + 1 })+ const items = [first, ...Array.from({ length: 55 }, (_, index) => urlItem(`k${index}`)), last]++ await build(send).write(items)++ expect(send).toHaveBeenCalledTimes(3)+ const requests = send.mock.calls.flatMap(([command]) => requestedWrites(command))+ expect(send.mock.calls.every(([command]) => requestedWrites(command).length <= 25)).toBe(true)+ expect(requests).toHaveLength(56)+ const same = requests.find((request) => request.PutRequest?.Item?.key?.S === 'same')+ expect(parseJSON(same?.PutRequest?.Item?.value?.S ?? '{}')).toMatchObject({ outcome: 'last' })+ expect(same?.PutRequest?.Item?.expires_at?.N).toBe(String(Math.ceil((NOW_MS + 1) / 1000)))})- it('retries unprocessed read keys as a batch', async () => {+ it('retries only unprocessed writes', async () => {const send = jest.fn()- .mockResolvedValueOnce({- UnprocessedKeys: { [TABLE]: { Keys: [{ key: { S: 'retry' } }] } },- })- .mockResolvedValueOnce({+ .mockImplementationOnce((command: BatchWriteItemCommand) =>+ Promise.resolve({ UnprocessedItems: { [TABLE]: [requestedWrites(command)[1]] } })+ )+ .mockResolvedValueOnce({})++ await build(send).write([urlItem('done'), urlItem('retry')])++ expect(requestedWrites(send.mock.calls[1][0])).toHaveLength(1)+ expect(requestedWrites(send.mock.calls[1][0])[0].PutRequest?.Item?.key?.S).toBe('retry')+ })++ it('splits and reassembles a 500 KiB configuration body', async () => {+ const dynamoItems = new Map<string, Record<string, { S?: string; N?: string }>>()+ const send = jest.fn((command: BatchWriteItemCommand | BatchGetItemCommand) => {+ if (command instanceof BatchWriteItemCommand) {+ for (const request of requestedWrites(command)) {+ const item = request.PutRequest?.Item as Record<string, { S?: string; N?: string }>+ dynamoItems.set(item.key.S ?? '', item)+ }+ return Promise.resolve({})+ }+ return Promise.resolve({Responses: {- [TABLE]: [{ key: { S: 'retry' }, expires_at: { N: String(NOW_SECONDS + 1) } }],+ [TABLE]: requestedReadKeys(command).flatMap((key) => {+ const item = dynamoItems.get(key)+ return item ? [item] : []+ }),},})+ })+ const body = 'abc😀'.repeat(73_000)+ const item: ConfigurationCacheItem = {+ kind: 'robots',+ key: 'imgfetch:config:robots:https://example.com',+ origin: 'https://example.com',+ status: 'available',+ body,+ fetchedAtMs: NOW_MS,+ refreshAtMs: NOW_MS + 1,+ freshUntilMs: NOW_MS + 2,+ retryAtMs: NOW_MS,+ storageExpiresAtMs: NOW_MS + 3,+ }+ const store = build(send)++ await store.write([item])+ const result = await store.read([item.key])++ expect(result.get(item.key)).toEqual(item)+ expect(dynamoItems.size).toBe(4)+ const writeCalls = send.mock.calls.filter(([command]) => command instanceof BatchWriteItemCommand)+ expect(requestedWrites(writeCalls[0][0] as BatchWriteItemCommand)).toHaveLength(3)+ expect(+ requestedWrites(writeCalls[0][0] as BatchWriteItemCommand).every((request) =>+ request.PutRequest?.Item?.key?.S?.startsWith(`${item.key}:body:`)+ )+ ).toBe(true)+ expect(requestedWrites(writeCalls[1][0] as BatchWriteItemCommand)[0].PutRequest?.Item?.key?.S).toBe(item.key)+ expect(+ [...dynamoItems.values()].every((storedItem) => Buffer.byteLength(JSON.stringify(storedItem)) < 400 * 1024)+ ).toBe(true)+ })++ it('treats an incomplete configuration body generation as a cache miss', async () => {+ const sha256 = 'a'.repeat(64)+ const item: ConfigurationCacheItem = {+ kind: 'robots',+ key: 'imgfetch:config:robots:https://example.com',+ origin: 'https://example.com',+ status: 'available',+ fetchedAtMs: NOW_MS,+ refreshAtMs: NOW_MS + 1,+ freshUntilMs: NOW_MS + 2,+ retryAtMs: NOW_MS,+ storageExpiresAtMs: NOW_MS + 3,+ }+ const manifest = stored(item)+ manifest.value = { S: JSON.stringify({ ...item, _bodyChunks: { count: 2, sha256 } }) }+ const send = jest+ .fn()+ .mockResolvedValueOnce({ Responses: { [TABLE]: [manifest] } })+ .mockResolvedValueOnce({ Responses: { [TABLE]: [] } })++ await expect(build(send).read([item.key])).resolves.toEqual(new Map())+ })++ it('does not publish a manifest when its body chunks cannot be written', async () => {+ jest.useFakeTimers()+ jest.spyOn(Math, 'random').mockReturnValue(0)+ const sentKeys: string[] = []+ const send = jest.fn((command: BatchWriteItemCommand) => {+ const writes = requestedWrites(command)+ sentKeys.push(...writes.flatMap((request) => request.PutRequest?.Item?.key?.S ?? []))+ return Promise.resolve({ UnprocessedItems: { [TABLE]: writes } })+ })+ const key = 'imgfetch:config:robots:https://example.com'+ const item: ConfigurationCacheItem = {+ kind: 'robots',+ key,+ origin: 'https://example.com',+ status: 'available',+ body: 'abc😀'.repeat(73_000),+ fetchedAtMs: NOW_MS,+ refreshAtMs: NOW_MS + 1,+ freshUntilMs: NOW_MS + 2,+ retryAtMs: NOW_MS,+ storageExpiresAtMs: NOW_MS + 3,+ }- const result = await build(send).read(['retry'], NOW_MS)+ const write = build(send).write([item])+ const refused = expect(write).rejects.toThrow('crawl-history writes unprocessed')+ await jest.runAllTimersAsync()- expect(result.known).toEqual(new Set([0]))- expect(result.failed.size).toBe(0)- expect(send).toHaveBeenCalledTimes(2)+ await refused+ expect(sentKeys.length).toBeGreaterThan(0)+ expect(sentKeys.every((sentKey) => sentKey.startsWith(`${key}:body:`))).toBe(true)+ jest.useRealTimers()})- it.each([- {- name: 'read',- response: { UnprocessedKeys: { [TABLE]: { Keys: [{ key: { S: 'retry' } }] } } },- run: (crawlHistory: DynamoDBCrawlHistory) => crawlHistory.read(['retry'], NOW_MS),- },- {- name: 'write',- response: {- UnprocessedItems: {- [TABLE]: [{ PutRequest: { Item: { key: { S: 'retry' } } } }],- },- },- run: (crawlHistory: DynamoDBCrawlHistory) => crawlHistory.record(['retry'], NOW_MS, 60),- },- ])('reports a failed key when unprocessed $name retries are exhausted', async ({ response, run }) => {+ it('throws after unprocessed write retries are exhausted', async () => {jest.useFakeTimers()- try {- const send = jest.fn().mockResolvedValue(response)- const resultPromise = run(build(send))+ jest.spyOn(Math, 'random').mockReturnValue(0)+ const send = jest.fn((command: BatchWriteItemCommand) =>+ Promise.resolve({ UnprocessedItems: { [TABLE]: requestedWrites(command) } })+ )- await jest.runAllTimersAsync()- const result = await resultPromise+ const write = build(send).write([urlItem('retry')])+ const refused = expect(write).rejects.toThrow('crawl-history writes unprocessed: retry')+ await jest.runAllTimersAsync()- expect(result.failed).toEqual(new Set([0]))- expect(send).toHaveBeenCalledTimes(5)- } finally {- jest.useRealTimers()- }+ await refused+ expect(send).toHaveBeenCalledTimes(5)+ jest.useRealTimers()})- it('flushes every new row with bounded batch writes and one expiry', async () => {- const send = jest.fn((_command: BatchWriteItemCommand) => Promise.resolve({}))+ it('validates write and consistent read access', async () => {+ const send = jest+ .fn()+ .mockResolvedValueOnce({})+ .mockResolvedValueOnce({ Responses: { [TABLE]: [{ key: { S: 'imgfetch:access-probe' } }] } })- const result = await build(send).record(KEYS, NOW_MS, 30 * 24 * 60 * 60)+ await build(send).validateAccess(NOW_MS)- expect(result.failed.size).toBe(0)- const commands = send.mock.calls.map(([command]) => command as BatchWriteItemCommand)- expect(commands).toHaveLength(9)- expect(commands.every((command) => requestedWriteKeys(command).length <= 25)).toBe(true)- expect(commands.flatMap(requestedWriteKeys).sort()).toEqual([...KEYS].sort())- for (const command of commands) {- for (const request of command.input.RequestItems?.[TABLE] ?? []) {- expect(request.PutRequest?.Item?.expires_at?.N).toBe(String(NOW_SECONDS + 30 * 24 * 60 * 60))- }- }+ expect(send.mock.calls[0][0]).toBeInstanceOf(BatchWriteItemCommand)+ expect(send.mock.calls[1][0]).toBeInstanceOf(BatchGetItemCommand)+ expect(send.mock.calls[1][0].input.RequestItems?.[TABLE]?.ConsistentRead).toBe(true)})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.tsindex 3d716a540577..adf728c809b1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history.ts@@ -1,4 +1,5 @@import {+ AttributeValue,BatchGetItemCommand,BatchGetItemCommandOutput,BatchWriteItemCommand,@@ -6,11 +7,16 @@ import {DynamoDBClient,WriteRequest,} from '@aws-sdk/client-dynamodb'+import { createHash } from 'node:crypto'-import { CrawlHistoryReadResult, CrawlHistoryStore } from './crawl-history'+import { parseJSON } from '~/common/utils/json-parse'+import { logger } from '~/common/utils/logger'++import { ConfigurationCacheItem, CrawlHistoryItem, CrawlHistoryStore } from './crawl-history'const KEY_ATTRIBUTE = 'key'const EXPIRES_AT_ATTRIBUTE = 'expires_at'+const VALUE_ATTRIBUTE = 'value'const BATCH_GET_SIZE = 100const BATCH_WRITE_SIZE = 25const MAX_CONCURRENT_BATCH_REQUESTS = 8@@ -18,6 +24,23 @@ const UNPROCESSED_MAX_ATTEMPTS = 5const UNPROCESSED_INITIAL_BACKOFF_MS = 50const ACCESS_PROBE_KEY = 'imgfetch:access-probe'const ACCESS_PROBE_TTL_SECONDS = 5 * 60+const SAFE_ITEM_SIZE_BYTES = 350 * 1024+const BODY_CHUNK_SIZE_BYTES = 240 * 1024+const MAX_BODY_CHUNKS = 3++interface StoredBodyChunks {+ count: number+ sha256: string+}++type ParsedStoredItem =+ | { item: CrawlHistoryItem; bodyChunks?: undefined }+ | { item: ConfigurationCacheItem; bodyChunks: StoredBodyChunks }++interface ItemWritePlan {+ bodyChunkRequests: WriteRequest[]+ manifestRequest: WriteRequest+}export type DynamoDBCrawlHistoryClient = Pick<DynamoDBClient, 'send'>@@ -29,29 +52,161 @@ function chunk<T>(items: T[], size: number): T[][] {return chunks}-function indexKeys(keys: string[]): Map<string, number[]> {- const indexesByKey = new Map<string, number[]>()- keys.forEach((key, index) => {- const indexes = indexesByKey.get(key) ?? []- indexes.push(index)- indexesByKey.set(key, indexes)- })- return indexesByKey+function keyFromWriteRequest(request: WriteRequest): string | undefined {+ return request.PutRequest?.Item?.[KEY_ATTRIBUTE]?.S+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function isFiniteNumber(value: unknown): value is number {+ return typeof value === 'number' && Number.isFinite(value)+}++function isOptionalString(value: unknown): value is string | undefined {+ return value === undefined || typeof value === 'string'+}++function isHttpCacheMetadata(value: unknown): boolean {+ if (!isRecord(value) || !isFiniteNumber(value.requestTimeMs) || !isFiniteNumber(value.responseTimeMs)) {+ return false+ }+ return ['etag', 'lastModified', 'date', 'age', 'cacheControl', 'expires'].every((field) =>+ isOptionalString(value[field])+ )+}++function isCrawlHistoryItem(value: unknown, expectedKey: string): value is CrawlHistoryItem {+ if (!isRecord(value) || value.key !== expectedKey || !isFiniteNumber(value.storageExpiresAtMs)) {+ return false+ }+ if (value.kind === 'url') {+ return (+ isFiniteNumber(value.nextFetchAtMs) &&+ typeof value.outcome === 'string' &&+ (value.cache === undefined || isHttpCacheMetadata(value.cache))+ )+ }+ return (+ (value.kind === 'robots' || value.kind === 'tdmrep') &&+ typeof value.origin === 'string' &&+ ['available', 'absent', 'refused', 'unreachable'].includes(String(value.status)) &&+ isOptionalString(value.body) &&+ isFiniteNumber(value.fetchedAtMs) &&+ isFiniteNumber(value.refreshAtMs) &&+ isFiniteNumber(value.freshUntilMs) &&+ isFiniteNumber(value.retryAtMs)+ )}-function addIndexes(target: Set<number>, keys: string[], indexesByKey: Map<string, number[]>): void {- for (const key of keys) {- for (const index of indexesByKey.get(key) ?? []) {- target.add(index)+function parseStoredItem(item: Record<string, AttributeValue>): ParsedStoredItem {+ const key = item[KEY_ATTRIBUTE]?.S+ const expiresAtSeconds = Number(item[EXPIRES_AT_ATTRIBUTE]?.N)+ if (!key || !Number.isFinite(expiresAtSeconds)) {+ throw new Error('DynamoDB returned a malformed crawl-history item')+ }+ const serialized = item[VALUE_ATTRIBUTE]?.S+ if (!serialized) {+ return {+ item: {+ kind: 'url',+ key,+ nextFetchAtMs: expiresAtSeconds * 1000,+ storageExpiresAtMs: expiresAtSeconds * 1000,+ outcome: 'legacy',+ },}}+ const parsed = parseJSON(serialized)+ if (!isRecord(parsed)) {+ throw new Error('DynamoDB returned an invalid crawl-history value')+ }+ const storedBodyChunks = parsed._bodyChunks+ if (storedBodyChunks === undefined) {+ if (!isCrawlHistoryItem(parsed, key)) {+ throw new Error('DynamoDB returned an invalid crawl-history value')+ }+ return { item: parsed }+ }+ const { _bodyChunks: _storedBodyChunks, ...applicationItem } = parsed+ if (+ !isCrawlHistoryItem(applicationItem, key) ||+ applicationItem.kind === 'url' ||+ applicationItem.body !== undefined ||+ !isRecord(storedBodyChunks) ||+ !Number.isInteger(storedBodyChunks.count) ||+ (storedBodyChunks.count as number) < 1 ||+ (storedBodyChunks.count as number) > MAX_BODY_CHUNKS ||+ typeof storedBodyChunks.sha256 !== 'string' ||+ !/^[0-9a-f]{64}$/.test(storedBodyChunks.sha256)+ ) {+ throw new Error('DynamoDB returned invalid crawl-history body chunks')+ }+ return {+ item: applicationItem,+ bodyChunks: { count: storedBodyChunks.count as number, sha256: storedBodyChunks.sha256 },+ }+}++function bodyChunkKey(key: string, sha256: string, index: number): string {+ return `${key}:body:${sha256}:${index}`+}++function putRequest(key: string, storageExpiresAtMs: number, serialized: string): WriteRequest {+ const expiresAt = String(Math.ceil(storageExpiresAtMs / 1000))+ const sizeBytes =+ Buffer.byteLength(KEY_ATTRIBUTE) ++ Buffer.byteLength(key) ++ Buffer.byteLength(EXPIRES_AT_ATTRIBUTE) ++ Buffer.byteLength(expiresAt) ++ Buffer.byteLength(VALUE_ATTRIBUTE) ++ Buffer.byteLength(serialized)+ if (sizeBytes > SAFE_ITEM_SIZE_BYTES) {+ throw new Error(`crawl-history item ${key} exceeds the safe DynamoDB item size`)+ }+ return {+ PutRequest: {+ Item: {+ [KEY_ATTRIBUTE]: { S: key },+ [EXPIRES_AT_ATTRIBUTE]: { N: expiresAt },+ [VALUE_ATTRIBUTE]: { S: serialized },+ },+ },+ }}-function keysFromWriteRequests(requests: WriteRequest[]): string[] {- return requests.flatMap((request) => {- const key = request.PutRequest?.Item?.[KEY_ATTRIBUTE]?.S- return key ? [key] : []- })+function writePlanForItem(item: CrawlHistoryItem): ItemWritePlan {+ const serialized = JSON.stringify(item)+ if (Buffer.byteLength(serialized) <= SAFE_ITEM_SIZE_BYTES / 2 || item.kind === 'url' || !item.body) {+ return {+ bodyChunkRequests: [],+ manifestRequest: putRequest(item.key, item.storageExpiresAtMs, serialized),+ }+ }+ const body = Buffer.from(item.body, 'utf8')+ const bodyChunks: Buffer[] = []+ for (let offset = 0; offset < body.length; offset += BODY_CHUNK_SIZE_BYTES) {+ bodyChunks.push(body.subarray(offset, offset + BODY_CHUNK_SIZE_BYTES))+ }+ if (bodyChunks.length > MAX_BODY_CHUNKS) {+ throw new Error(`crawl-history body ${item.key} needs too many DynamoDB items`)+ }+ const sha256 = createHash('sha256').update(body).digest('hex')+ const storedItem = {+ ...item,+ body: undefined,+ _bodyChunks: {+ count: bodyChunks.length,+ sha256,+ },+ }+ return {+ bodyChunkRequests: bodyChunks.map((bodyChunk, index) =>+ putRequest(bodyChunkKey(item.key, sha256, index), item.storageExpiresAtMs, bodyChunk.toString('base64'))+ ),+ manifestRequest: putRequest(item.key, item.storageExpiresAtMs, JSON.stringify(storedItem)),+ }}export class DynamoDBCrawlHistory implements CrawlHistoryStore {@@ -83,7 +238,6 @@ export class DynamoDBCrawlHistory implements CrawlHistoryStore {if ((writeResponse.UnprocessedItems?.[this.tableName] ?? []).length > 0) {throw new Error('DynamoDB crawl-history access probe write was not processed')}-const readResponse = await this.sendBatchGet(new BatchGetItemCommand({RequestItems: {@@ -96,147 +250,161 @@ export class DynamoDBCrawlHistory implements CrawlHistoryStore {},}))- const readWasUnprocessed = (readResponse.UnprocessedKeys?.[this.tableName]?.Keys ?? []).length > 0- const probeWasRead = (readResponse.Responses?.[this.tableName] ?? []).some(- (item) => item[KEY_ATTRIBUTE]?.S === ACCESS_PROBE_KEY- )- if (readWasUnprocessed || !probeWasRead) {+ if (+ (readResponse.UnprocessedKeys?.[this.tableName]?.Keys ?? []).length > 0 ||+ !(readResponse.Responses?.[this.tableName] ?? []).some(+ (item) => item[KEY_ATTRIBUTE]?.S === ACCESS_PROBE_KEY+ )+ ) {throw new Error('DynamoDB crawl-history access probe read was not processed')}}- public async read(keys: string[], nowMs: number): Promise<CrawlHistoryReadResult> {- const known = new Set<number>()- const failed = new Set<number>()- const indexesByKey = indexKeys(keys)- const uniqueKeys = [...indexesByKey.keys()]+ public async read(keys: string[]): Promise<Map<string, CrawlHistoryItem>> {+ const result = new Map<string, CrawlHistoryItem>()const startedAt = process.hrtime.bigint()- const nowSeconds = Math.floor(nowMs / 1000)+ const bodyChunks = new Map<string, { item: ConfigurationCacheItem; metadata: StoredBodyChunks }>()+ for (const item of await this.readRawItems([...new Set(keys)], startedAt)) {+ const parsed = parseStoredItem(item)+ if (parsed.bodyChunks) {+ bodyChunks.set(parsed.item.key, { item: parsed.item, metadata: parsed.bodyChunks })+ } else {+ result.set(parsed.item.key, parsed.item)+ }+ }+ if (bodyChunks.size === 0) {+ return result+ }- await this.runChunks(chunk(uniqueKeys, BATCH_GET_SIZE), async (batch) => {- let pending = batch- for (let attempt = 1; attempt <= UNPROCESSED_MAX_ATTEMPTS; attempt++) {- if (this.batchBudgetSpent(startedAt)) {- addIndexes(failed, pending, indexesByKey)- return+ const chunkKeys = [...bodyChunks].flatMap(([key, value]) =>+ Array.from({ length: value.metadata.count }, (_unused, index) =>+ bodyChunkKey(key, value.metadata.sha256, index)+ )+ )+ const encodedChunks = new Map<string, string>()+ for (const item of await this.readRawItems(chunkKeys, startedAt)) {+ const key = item[KEY_ATTRIBUTE]?.S+ const encoded = item[VALUE_ATTRIBUTE]?.S+ if (!key || !encoded) {+ logger.warn('🌐', 'ml_image_fetch_crawl_history_chunk_invalid', { key: key ?? 'missing' })+ continue+ }+ encodedChunks.set(key, encoded)+ }+ for (const [key, value] of bodyChunks) {+ try {+ const chunks = Array.from({ length: value.metadata.count }, (_unused, index) => {+ const encoded = encodedChunks.get(bodyChunkKey(key, value.metadata.sha256, index))+ if (!encoded) {+ throw new Error('missing')+ }+ const decoded = Buffer.from(encoded, 'base64')+ if (decoded.toString('base64') !== encoded) {+ throw new Error('invalid base64')+ }+ return decoded+ })+ const body = Buffer.concat(chunks)+ if (createHash('sha256').update(body).digest('hex') !== value.metadata.sha256) {+ throw new Error('checksum mismatch')}+ result.set(key, { ...value.item, body: new TextDecoder('utf-8', { fatal: true }).decode(body) })+ } catch (error) {+ logger.warn('🌐', 'ml_image_fetch_crawl_history_chunk_incomplete', {+ key,+ error: String(error),+ })+ }+ }+ return result+ }- let response: BatchGetItemCommandOutput- try {- response = await this.sendBatchGet(- new BatchGetItemCommand({- RequestItems: {- [this.tableName]: {- Keys: pending.map((key) => ({ [KEY_ATTRIBUTE]: { S: key } })),- ProjectionExpression: '#key, #expiresAt',- ExpressionAttributeNames: {- '#key': KEY_ATTRIBUTE,- '#expiresAt': EXPIRES_AT_ATTRIBUTE,- },+ private async readRawItems(keys: string[], startedAt: bigint): Promise<Record<string, AttributeValue>[]> {+ const result: Record<string, AttributeValue>[] = []+ await this.runChunks(chunk(keys, BATCH_GET_SIZE), async (batch) => {+ let pending = batch+ for (let attempt = 1; pending.length > 0; attempt++) {+ this.requireBudget(startedAt)+ const response = await this.sendBatchGet(+ new BatchGetItemCommand({+ RequestItems: {+ [this.tableName]: {+ Keys: pending.map((key) => ({ [KEY_ATTRIBUTE]: { S: key } })),+ ProjectionExpression: '#key, #expiresAt, #value',+ ExpressionAttributeNames: {+ '#key': KEY_ATTRIBUTE,+ '#expiresAt': EXPIRES_AT_ATTRIBUTE,+ '#value': VALUE_ATTRIBUTE,},},- })- )- } catch {- addIndexes(failed, pending, indexesByKey)- return- }-+ },+ })+ )for (const item of response.Responses?.[this.tableName] ?? []) {- const key = item[KEY_ATTRIBUTE]?.S- const expiresAt = Number(item[EXPIRES_AT_ATTRIBUTE]?.N)- if (!key || !Number.isFinite(expiresAt)) {- if (key) {- addIndexes(failed, [key], indexesByKey)- }- continue- }- if (expiresAt > nowSeconds) {- addIndexes(known, [key], indexesByKey)- }+ result.push(item)}-- pending = (response.UnprocessedKeys?.[this.tableName]?.Keys ?? []).flatMap((key) => {- const value = key[KEY_ATTRIBUTE]?.S- return value ? [value] : []- })- if (pending.length === 0) {- return- }- if (attempt === UNPROCESSED_MAX_ATTEMPTS) {- addIndexes(failed, pending, indexesByKey)- return+ pending = (response.UnprocessedKeys?.[this.tableName]?.Keys ?? []).flatMap((key) =>+ key[KEY_ATTRIBUTE]?.S ? [key[KEY_ATTRIBUTE].S] : []+ )+ if (pending.length > 0) {+ if (attempt >= UNPROCESSED_MAX_ATTEMPTS) {+ throw new Error(`DynamoDB left ${pending.length} crawl-history reads unprocessed`)+ }+ await this.backoffBeforeRetry(attempt)}- await this.backoffBeforeRetry(attempt)}})-- return { known, failed }+ return result}- public async record(keys: string[], nowMs: number, ttlSeconds: number): Promise<{ failed: Set<number> }> {- const failed = new Set<number>()- const indexesByKey = indexKeys(keys)- const expiresAt = Math.floor(nowMs / 1000) + ttlSeconds- const requests = [...indexesByKey.keys()].map(- (key): WriteRequest => ({- PutRequest: {- Item: {- [KEY_ATTRIBUTE]: { S: key },- [EXPIRES_AT_ATTRIBUTE]: { N: String(expiresAt) },- },- },- })- )+ public async write(items: CrawlHistoryItem[]): Promise<void> {+ const byKey = new Map(items.map((item) => [item.key, item]))+ const plans = [...byKey.values()].map(writePlanForItem)const startedAt = process.hrtime.bigint()+ await this.writeRequests(+ plans.flatMap((plan) => plan.bodyChunkRequests),+ startedAt+ )+ await this.writeRequests(+ plans.map((plan) => plan.manifestRequest),+ startedAt+ )+ }+ private async writeRequests(requests: WriteRequest[], startedAt: bigint): Promise<void> {await this.runChunks(chunk(requests, BATCH_WRITE_SIZE), async (batch) => {let pending = batch- for (let attempt = 1; attempt <= UNPROCESSED_MAX_ATTEMPTS; attempt++) {- if (this.batchBudgetSpent(startedAt)) {- addIndexes(failed, keysFromWriteRequests(pending), indexesByKey)- return- }-- let response: BatchWriteItemCommandOutput- try {- response = await this.sendBatchWrite(- new BatchWriteItemCommand({ RequestItems: { [this.tableName]: pending } })- )- } catch {- addIndexes(failed, keysFromWriteRequests(pending), indexesByKey)- return- }-+ for (let attempt = 1; pending.length > 0; attempt++) {+ this.requireBudget(startedAt)+ const response = await this.sendBatchWrite(+ new BatchWriteItemCommand({ RequestItems: { [this.tableName]: pending } })+ )pending = response.UnprocessedItems?.[this.tableName] ?? []- if (pending.length === 0) {- return- }- if (attempt === UNPROCESSED_MAX_ATTEMPTS) {- addIndexes(failed, keysFromWriteRequests(pending), indexesByKey)- return+ if (pending.length > 0) {+ if (attempt >= UNPROCESSED_MAX_ATTEMPTS) {+ const keys = pending.flatMap((request) => keyFromWriteRequest(request) ?? [])+ throw new Error(`DynamoDB left crawl-history writes unprocessed: ${keys.join(',')}`)+ }+ await this.backoffBeforeRetry(attempt)}- await this.backoffBeforeRetry(attempt)}})-- return { failed }}private async runChunks<T>(chunks: T[][], run: (batch: T[]) => Promise<void>): Promise<void> {let nextChunk = 0const worker = async (): Promise<void> => {while (nextChunk < chunks.length) {- const batch = chunks[nextChunk++]- await run(batch)+ await run(chunks[nextChunk++])}}- const workerCount = Math.min(chunks.length, MAX_CONCURRENT_BATCH_REQUESTS)- await Promise.all(Array.from({ length: workerCount }, worker))+ await Promise.all(Array.from({ length: Math.min(chunks.length, MAX_CONCURRENT_BATCH_REQUESTS) }, worker))}- private batchBudgetSpent(startedAt: bigint): boolean {- return Number(process.hrtime.bigint() - startedAt) / 1e6 > this.batchBudgetMs+ private requireBudget(startedAt: bigint): void {+ if (Number(process.hrtime.bigint() - startedAt) / 1e6 > this.batchBudgetMs) {+ throw new Error('DynamoDB crawl-history batch budget was exhausted')+ }}private async backoffBeforeRetry(attempt: number): Promise<void> {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.tsindex 68a0c32580c3..a742f8e545c1 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@@ -1,490 +1,501 @@-import { delay } from '~/common/utils/utils'-import { FetchCandidate, MAX_HOPS } from './collected-urls-record'-import { FetchRunner, FetchRunnerOptions, isTerminal } from './fetch-runner'-import { FrontierPublisher } from './frontier-publisher'+import { ConfigurationPolicyService, OriginPolicyDecision } from './configuration-policy'+import { ConfigurationCacheItem, CrawlHistoryItem, HttpCacheMetadata } from './crawl-history'+import { DELAY_TOO_LONG, FetchRunner, FetchRunnerOptions, HOPS_EXHAUSTED } from './fetch-runner'+import { FrontierPublisher, RepublishResult } from './frontier-publisher'import { HostBudget } from './host-budget'-import { FetchOutcome, ImageFetchResult, ImageFetcher, RedirectDecision } from './image-fetcher'+import { ImageFetchOptions, ImageFetchResult, ImageFetcher } from './image-fetcher'+import { ImageFetchRequestMetrics } from './metrics'+import { OriginRequestScheduler } from './origin-request-scheduler'+const NOW_MS = 1_700_000_000_000const OPTIONS: FetchRunnerOptions = {- maxConcurrentPerDomain: 2,+ maxConcurrentPerRegistrableDomain: 2,maxInFlightRequests: 50,- batchBudgetMs: 5000,- maxBytes: 1000,- requestTimeoutMs: 1000,+ batchBudgetMs: 20_000,+ maxBytes: 20 * 1024 * 1024,+ requestTimeoutMs: 10_000,maxRedirects: 3,- defaultRetryAfterMs: 60_000,+ seenTtlSeconds: 30 * 24 * 60 * 60,}-function candidate(domain: string, index: number): FetchCandidate {+function candidate(overrides: Partial<FetchCandidate> = {}): FetchCandidate {return {- ref: `imageurl:team:${domain}-${index}`,- urlHash: `${domain}-${index}`,- url: `https://cdn.${domain}/${index}.png`,- host: `cdn.${domain}`,- domain,- pseudoTeam: 'team',- capturedAtMs: 1000,- hopsRemaining: MAX_HOPS,+ originalRef: `imageurl:${'a'.repeat(22)}`,+ currentUrl: 'https://cdn.example.com/a.png',+ host: 'cdn.example.com',+ origin: 'https://cdn.example.com',+ registrableDomain: 'example.com',+ remainingHops: MAX_HOPS,notBeforeMs: 0,+ firstSeenAtMs: NOW_MS - 1_000,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,+ ...overrides,}}-class FakeFetcher implements ImageFetcher {- public calls: string[] = []- public peakConcurrent = 0- private inFlight = 0-- constructor(private readonly answer: (url: string) => Partial<ImageFetchResult>) {}-- public async fetch(url: string): Promise<ImageFetchResult> {- this.calls.push(url)- this.inFlight++- this.peakConcurrent = Math.max(this.peakConcurrent, this.inFlight)- await Promise.resolve()- this.inFlight--- return { outcome: 'ok', redirects: 0, ...this.answer(url) }- }+interface Harness {+ runner: FetchRunner+ fetch: jest.Mock<Promise<ImageFetchResult>, [string, ImageFetchOptions]>+ check: jest.Mock<Promise<OriginPolicyDecision>, [string, Map<string, ConfigurationCacheItem>, number]>+ createPass: jest.Mock+ republish: jest.Mock<Promise<RepublishResult>, any[]>+ publishImage: jest.Mock<Promise<void>, any[]>}-const FAR_FUTURE = 10 ** 12--const defaultBudget = (): HostBudget =>- new HostBudget({- requestsPerSecond: 1000,- burst: 1000,- maxConcurrent: 4,- breakerFailures: 3,+function build(+ result: Partial<ImageFetchResult> = {},+ policy: Partial<OriginPolicyDecision> = {},+ republishResult: RepublishResult = 'published',+ options: FetchRunnerOptions = OPTIONS+): Harness {+ const fetch = jest.fn((url: string, _options: ImageFetchOptions) =>+ Promise.resolve({ outcome: 'ok', redirects: 0, currentUrl: url, ...result } as ImageFetchResult)+ )+ const check = jest.fn((_url: string, _cached: Map<string, ConfigurationCacheItem>, _nowMs: number) =>+ Promise.resolve({+ allowed: true,+ transient: false,+ crawlDelayMs: 1_000,+ tdmrepReservation: false,+ updates: [],+ ...policy,+ } as OriginPolicyDecision)+ )+ const createPass = jest.fn(() => ({ check }))+ const republish = jest.fn(() => Promise.resolve(republishResult))+ const publishImage = jest.fn(() => Promise.resolve())+ const scheduler = {+ runImage: async (_url: URL, _deadlineMs: number, request: () => Promise<ImageFetchResult>) => ({+ ran: true as const,+ value: await request(),+ }),+ authorizeImageRedirect: () => Promise.resolve(true),+ } as unknown as OriginRequestScheduler+ const budget = new HostBudget({+ requestsPerSecond: 1,+ burst: 5,+ maxConcurrent: 6,+ breakerFailures: 5,breakerCooldownMs: 60_000,- breakerMaxCooldownMs: 600_000,- maxTrackedDomains: 100,+ breakerMaxCooldownMs: 3_600_000,+ maxTrackedRegistrableDomains: 20_000,+ maxTrackedOrigins: 20_000,+ random: () => 0,})--function runner(- fetcher: ImageFetcher,- options: Partial<FetchRunnerOptions> = {},- budget = new HostBudget({- requestsPerSecond: 1000,- burst: 1000,- maxConcurrent: 4,- breakerFailures: 3,- breakerCooldownMs: 60_000,- breakerMaxCooldownMs: 600_000,- maxTrackedDomains: 100,- }),- publisher: FrontierPublisher = noopPublisher()-): FetchRunner {- return new FetchRunner(fetcher, budget, { ...OPTIONS, ...options }, publisher)-}--function noopPublisher(): FrontierPublisher {- return { republish: () => Promise.resolve(true) } as unknown as FrontierPublisher+ const runner = new FetchRunner(+ { fetch } as ImageFetcher,+ budget,+ scheduler,+ { createPass } as unknown as ConfigurationPolicyService,+ options,+ { republish, publishImage } as unknown as FrontierPublisher+ )+ return { runner, fetch, check, createPass, republish, publishImage }}describe('FetchRunner', () => {- it('sheds every remaining URL of a domain that answered 429, and leaves the other domain alone', async () => {- const fetcher = new FakeFetcher((url) =>- url.includes('busy.com') ? { outcome: 'rate_limited', status: 429 } : { outcome: 'ok' }- )- const candidates = [- ...[0, 1, 2].map((index) => candidate('busy.com', index)),- ...[0, 1].map((index) => candidate('calm.com', index)),- ]+ beforeEach(() => jest.useFakeTimers().setSystemTime(NOW_MS))+ afterEach(() => {+ jest.useRealTimers()+ jest.restoreAllMocks()+ })- const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1 }).run(candidates)+ it('passes cached validators and TDM state to the image request', async () => {+ const harness = build({}, { tdmrepReservation: true })+ const cache: HttpCacheMetadata = {+ requestTimeMs: NOW_MS - 10,+ responseTimeMs: NOW_MS,+ etag: '"image-v1"',+ }+ const stored = new Map<string, CrawlHistoryItem>([+ [+ candidate().originalRef,+ {+ kind: 'url',+ key: candidate().originalRef,+ nextFetchAtMs: NOW_MS,+ storageExpiresAtMs: NOW_MS,+ outcome: 'ok',+ cache,+ },+ ],+ ])- expect(fetcher.calls.filter((url) => url.includes('busy.com'))).toHaveLength(1)- expect(attempts.filter((a) => a.outcome === 'rate_limited')).toHaveLength(3)- expect(attempts.filter((a) => a.candidate.domain === 'calm.com' && a.outcome === 'ok')).toHaveLength(2)+ await harness.runner.run([candidate()], stored)++ expect(harness.fetch.mock.calls[0][1]).toMatchObject({+ maxBytes: OPTIONS.maxBytes,+ maxRedirects: OPTIONS.maxRedirects,+ cache,+ tdmrepReservation: true,+ })})- it('stops sending to a domain once its breaker opens', async () => {- const fetcher = new FakeFetcher(() => ({ outcome: 'timeout' }))- const candidates = [0, 1, 2, 3, 4, 5].map((index) => candidate('broken.com', index))+ it('publishes an accepted image and records a terminal URL result', async () => {+ const bytes = Buffer.from('image')+ const harness = build({ bytes, contentType: 'image/png' })- const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1 }).run(candidates)+ const [attempt] = await harness.runner.run([candidate()], new Map())- expect(fetcher.calls).toHaveLength(3)- expect(attempts.filter((a) => a.outcome === 'breaker_open')).toHaveLength(3)+ expect(harness.publishImage).toHaveBeenCalledWith(+ expect.objectContaining({ originalRef: candidate().originalRef }),+ expect.objectContaining({ bytes })+ )+ expect(attempt).toMatchObject({+ outcome: 'ok',+ finished: true,+ lost: false,+ history: { kind: 'url', key: candidate().originalRef, nextFetchAtMs: NOW_MS + 30 * 24 * 60 * 60 * 1000 },+ })})- it('holds one domain to the configured number of connections', async () => {- const fetcher = new FakeFetcher(() => ({ outcome: 'ok' }))-- await runner(fetcher, { maxConcurrentPerDomain: 2 }).run(- [0, 1, 2, 3, 4, 5].map((index) => candidate('example.com', index))+ it('uses one worker limit across sibling origins', async () => {+ const harness = build({}, {}, 'published', { ...OPTIONS, maxConcurrentPerRegistrableDomain: 1 })+ let releaseFirst: (() => void) | undefined+ harness.fetch.mockImplementationOnce(+ (url: string) =>+ new Promise<ImageFetchResult>((resolve) => {+ releaseFirst = () => resolve({ outcome: 'ok', redirects: 0, currentUrl: url })+ }))+ const sibling = candidate({+ originalRef: `imageurl:${'b'.repeat(22)}`,+ currentUrl: 'https://images.example.com/b.png',+ host: 'images.example.com',+ origin: 'https://images.example.com',+ })++ const run = harness.runner.run([candidate(), sibling], new Map())+ await Promise.resolve()+ await Promise.resolve()- expect(fetcher.peakConcurrent).toBe(2)+ expect(harness.fetch).toHaveBeenCalledTimes(1)+ expect(releaseFirst).toBeDefined()+ releaseFirst?.()+ await run+ expect(harness.fetch).toHaveBeenCalledTimes(2)})- it('sheds what the rate would not carry before the batch budget runs out', async () => {- const budget = new HostBudget({- requestsPerSecond: 1,- burst: 1,- maxConcurrent: 4,- breakerFailures: 100,- breakerCooldownMs: 60_000,- breakerMaxCooldownMs: 600_000,- maxTrackedDomains: 100,+ it('does not let one origin occupy every registrable-domain worker', async () => {+ const harness = build({}, {}, 'published', { ...OPTIONS, maxConcurrentPerRegistrableDomain: 2 })+ let releaseFirst: (() => void) | undefined+ let releaseSecond: (() => void) | undefined+ harness.fetch+ .mockImplementationOnce(+ (url: string) =>+ new Promise<ImageFetchResult>((resolve) => {+ releaseFirst = () => resolve({ outcome: 'ok', redirects: 0, currentUrl: url })+ })+ )+ .mockImplementationOnce(+ (url: string) =>+ new Promise<ImageFetchResult>((resolve) => {+ releaseSecond = () => resolve({ outcome: 'ok', redirects: 0, currentUrl: url })+ })+ )+ const sameOrigin = candidate({ originalRef: `imageurl:${'b'.repeat(22)}` })+ const siblingOrigin = candidate({+ originalRef: `imageurl:${'c'.repeat(22)}`,+ currentUrl: 'https://images.example.com/c.png',+ host: 'images.example.com',+ origin: 'https://images.example.com',})- const fetcher = new FakeFetcher(() => ({ outcome: 'ok' }))- // Long enough to grant the first URL whatever the machine is doing, and far shorter than- // the wait of the second. A budget of zero makes the first grant depend on less than a- // millisecond passing between two clock reads, which is a race a loaded runner loses.- const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1, batchBudgetMs: 50 }, budget).run(- [0, 1, 2].map((index) => candidate('slow.com', index))- )+ const run = harness.runner.run([candidate(), sameOrigin, siblingOrigin], new Map())+ await Promise.resolve()+ await Promise.resolve()- // The burst token carries the first URL. Each of the rest needs a second of waiting, which- // the batch does not have.- expect(fetcher.calls).toHaveLength(1)- expect(attempts.filter((a) => a.outcome === 'deadline')).toHaveLength(2)+ expect(harness.fetch.mock.calls.map(([url]) => url)).toEqual([candidate().currentUrl, siblingOrigin.currentUrl])+ releaseFirst?.()+ releaseSecond?.()+ await run+ expect(harness.fetch).toHaveBeenCalledTimes(3)})- it('does not write off a URL whose redirect target had no budget left', async () => {- const fetcher = new FakeFetcher(() => ({ outcome: 'redirect_deferred', status: 302 }))+ it('marks an image publish failure as lost after all candidate work settles', async () => {+ const harness = build({ bytes: Buffer.from('image'), contentType: 'image/png' })+ harness.publishImage.mockRejectedValue(new Error('queue full'))- const attempts = await runner(fetcher).run([candidate('example.com', 0)])+ const [attempt] = await harness.runner.run([candidate()], new Map())- expect(isTerminal(attempts[0].outcome)).toBe(false)+ expect(attempt).toMatchObject({ outcome: 'publish_failed', finished: false, lost: true })})- it('handles a domain with more queued URLs than a spread can carry', async () => {- // One batch offers up to BATCH_SIZE x MAX_URLS_PER_RECORD URLs, and the topic keys by- // domain, so a popular CDN can fill one queue past the argument limit of Function.apply. A- // RangeError escapes the pass, and the consumer then records nothing for the batch.- const budget = new HostBudget({- requestsPerSecond: 1,- burst: 1,- maxConcurrent: 4,- breakerFailures: 100,- breakerCooldownMs: 60_000,- breakerMaxCooldownMs: 600_000,- maxTrackedDomains: 100,- })- const fetcher = new FakeFetcher(() => ({ outcome: 'ok' }))- const many = Array.from({ length: 130_000 }, (_value, index) => candidate('big.com', index))+ it('writes a terminal policy refusal without opening an image socket', async () => {+ const harness = build({}, { allowed: false, transient: false, reason: 'robots_disallow' })- // A zero budget is safe here because the count below is the same whether or not the first- // URL wins its grant. Do not copy it into a test that asserts how many requests went out,- // because that turns on less than a millisecond passing between two clock reads.- const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1, batchBudgetMs: 0 }, budget).run(many)+ const [attempt] = await harness.runner.run([candidate()], new Map())- expect(attempts).toHaveLength(many.length)+ expect(harness.fetch).not.toHaveBeenCalled()+ expect(attempt).toMatchObject({ outcome: 'robots_disallow', finished: true })})- it('hands a redirect off rather than following it to another domain (requirement 7)', async () => {- const published: { domain: string; url: string; reason: string }[] = []- const publisher = {- republish: (candidate: FetchCandidate, target: { url: string; domain: string }, reason: string) => {- published.push({ domain: target.domain, url: target.url, reason })- return Promise.resolve(true)- },- } as unknown as FrontierPublisher- let offsite: boolean | undefined- const fetcher: ImageFetcher = {- fetch: (_url, options) => {- offsite = options.isOffsite(new URL('https://img.other-site.net/a.png'))- return Promise.resolve({- outcome: 'redirect_offsite',- redirects: 1,- redirectTarget: { url: 'https://img.other-site.net/a.png', host: 'img.other-site.net' },- })- },- }+ it('delays a transient configuration failure without writing URL history', async () => {+ const harness = build({}, { allowed: false, transient: true, reason: 'configuration_unreachable' })- const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([candidate('example.com', 0)])+ const [attempt] = await harness.runner.run([candidate()], new Map())- expect(offsite).toBe(true)- expect(published).toEqual([- { domain: 'other-site.net', url: 'https://img.other-site.net/a.png', reason: 'redirect' },- ])- // The URL comes back on another partition, so a crawl history entry would stop that.- expect(attempts[0].finished).toBe(false)+ expect(harness.republish).toHaveBeenCalledWith(+ candidate(),+ {+ currentUrl: candidate().currentUrl,+ host: candidate().host,+ origin: candidate().origin,+ registrableDomain: candidate().registrableDomain,+ },+ 'not_ready',+ 3_600_000+ )+ expect(attempt).toMatchObject({ outcome: 'backoff', finished: false, lost: false })+ expect(attempt.history).toBeUndefined()})- it('stops a redirect whose domain was blocked while it waited (requirement 5)', async () => {- const budget = new HostBudget({- requestsPerSecond: 1,- burst: 1,- maxConcurrent: 6,- breakerFailures: 100,- breakerCooldownMs: 60_000,- breakerMaxCooldownMs: 600_000,- maxTrackedDomains: 100,+ it('keeps the effective URL and charges every request before retrying', async () => {+ const harness = build({+ outcome: 'server_error',+ status: 503,+ redirects: 2,+ currentUrl: 'https://cdn.example.com/final.png',+ retryAfterMs: 120_000,})- // Spend the burst token, so the redirect below has to wait a second for the next one.- budget.take('example.com', Date.now(), Date.now() + 60_000)- let decision: RedirectDecision | undefined- const fetcher: ImageFetcher = {- fetch: async (_url, options) => {- setTimeout(() => budget.recordRetryAfter('example.com', Date.now(), 60_000), 5)- decision = await options.authorizeRedirect(new URL('https://img2.example.com/a.png'), 30_000)- return { outcome: 'ok', redirects: 1 }- },- }-- await runner(fetcher, {}, budget).run([candidate('example.com', 0)])-- expect(decision).toBe('defer')+ const retryCause = jest.spyOn(ImageFetchRequestMetrics, 'incRetryCause').mockImplementation()++ const [attempt] = await harness.runner.run([candidate()], new Map())++ expect(harness.republish).toHaveBeenCalledWith(+ expect.objectContaining({+ currentUrl: 'https://cdn.example.com/final.png',+ remainingHops: MAX_HOPS - 2,+ fetchCount: 3,+ }),+ expect.objectContaining({ currentUrl: 'https://cdn.example.com/final.png' }),+ 'retry',+ 120_000+ )+ expect(retryCause).toHaveBeenCalledWith('server_error')+ expect(attempt).toMatchObject({ outcome: 'server_error', finished: false })})- it('follows a redirect that stays on the same domain (requirement 6)', async () => {- let decision: RedirectDecision | undefined- const fetcher: ImageFetcher = {- fetch: async (_url, options) => {- decision = await options.authorizeRedirect(new URL('https://img2.example.com/a.png'), 5000)- return { outcome: 'ok', redirects: 1 }- },- }+ it('republishes an unfollowed redirect target with the original ref', async () => {+ const harness = build({+ outcome: 'redirect_offsite',+ status: 302,+ currentUrl: candidate().currentUrl,+ redirectTarget: { url: 'https://img.other.net/a.png', host: 'img.other.net' },+ })- await runner(fetcher).run([candidate('example.com', 0)])+ const [attempt] = await harness.runner.run([candidate()], new Map())- expect(decision).toBe('allow')+ expect(harness.republish).toHaveBeenCalledWith(+ expect.objectContaining({ originalRef: candidate().originalRef, fetchCount: 1 }),+ {+ currentUrl: 'https://img.other.net/a.png',+ host: 'img.other.net',+ origin: 'https://img.other.net',+ registrableDomain: 'other.net',+ },+ 'redirect',+ 0+ )+ expect(attempt).toMatchObject({ outcome: 'redirect_offsite', finished: false })})- it('publishes a transient failure to a delay topic rather than dropping it (requirement 14)', async () => {- const published: { reason: string; waitMs: number }[] = []- const publisher = {- republish: (_c: FetchCandidate, _t: unknown, reason: string, waitMs: number) => {- published.push({ reason, waitMs })- return Promise.resolve(true)- },- } as unknown as FrontierPublisher- const fetcher = new FakeFetcher(() => ({ outcome: 'rate_limited', status: 429, retryAfterMs: 30_000 }))+ it('records a terminal refusal from a same-origin redirect policy check', async () => {+ const harness = build({+ outcome: 'redirect_policy_refused',+ redirects: 1,+ currentUrl: 'https://cdn.example.com/private/a.png',+ refusalReason: 'robots_disallow',+ policyTransient: false,+ })- const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([candidate('busy.com', 0)])+ const [attempt] = await harness.runner.run([candidate()], new Map())- expect(published).toEqual([{ reason: 'retry', waitMs: 30_000 }])- expect(attempts[0].finished).toBe(false)+ expect(harness.republish).not.toHaveBeenCalled()+ expect(attempt).toMatchObject({+ outcome: 'robots_disallow',+ finished: true,+ candidate: { remainingHops: MAX_HOPS - 1, fetchCount: 1 },+ })})- it.each([- ['a retry', { outcome: 'timeout' as const }],- [- 'a redirect',- {- outcome: 'redirect_offsite' as const,- redirectTarget: { url: 'https://cdn.other.com/i.png', host: 'cdn.other.com' },- },- ],- ])(- 'reports %s the publisher could not send, so the batch does not commit past it (requirement 21)',- async (_name, result) => {- const publisher = { republish: () => Promise.resolve(false) } as unknown as FrontierPublisher- const fetcher = new FakeFetcher(() => result)-- const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([candidate('example.com', 0)])+ it('delays a transient same-origin redirect policy failure without spending another hop', async () => {+ const harness = build({+ outcome: 'redirect_policy_refused',+ redirects: 1,+ currentUrl: 'https://cdn.example.com/next/a.png',+ refusalReason: 'configuration_unreachable',+ policyTransient: true,+ })- expect(attempts[0]).toMatchObject({ finished: false, lost: true })- }- )+ await harness.runner.run([candidate()], new Map())++ expect(harness.republish).toHaveBeenCalledWith(+ expect.objectContaining({+ currentUrl: 'https://cdn.example.com/next/a.png',+ remainingHops: MAX_HOPS - 1,+ fetchCount: 1,+ }),+ expect.any(Object),+ 'not_ready',+ 3_600_000+ )+ })- it('reports nothing lost when the publisher sent the URL', async () => {- const publisher = { republish: () => Promise.resolve(true) } as unknown as FrontierPublisher- const fetcher = new FakeFetcher(() => ({ outcome: 'timeout' as const }))+ it('persists a crawl wait that extends beyond the current pass', async () => {+ const harness = build({+ outcome: 'request_deferred',+ schedulingReason: 'deadline',+ schedulingWaitMs: 600_000,+ })- const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([candidate('example.com', 0)])+ await harness.runner.run([candidate()], new Map())- expect(attempts[0]).toMatchObject({ finished: false, lost: false })+ expect(harness.republish).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), 'not_ready', 600_000)})- it('checks again when a request reaches the front of the pod queue (requirement 5)', async () => {- // A sibling request can meet a `Retry-After` while this one waits for a pod slot, and a- // request sent after that reaches a site which just asked to be left alone.- const budget = defaultBudget()- const published: string[] = []- const publisher = {- republish: (_c: FetchCandidate, _t: unknown, reason: string) => {- published.push(reason)- return Promise.resolve(true)- },- } as unknown as FrontierPublisher- const fetcher: ImageFetcher = {- fetch: async (url: string) => {- if (url.endsWith('/0.png')) {- // This yields first, so the second request passes the token bucket and reaches- // the pod queue before the hold exists. Without the yield the token bucket- // refuses it, and this test passes whatever the queue does.- await delay(1)- budget.recordRetryAfter('example.com', Date.now(), 60_000)- }- return { outcome: 'ok' as const, redirects: 0 }- },- }+ it('finishes a retry when its last hop was the failed request', async () => {+ const harness = build({ outcome: 'timeout' })- const attempts = await runner(fetcher, { maxInFlightRequests: 1 }, budget, publisher).run([- candidate('example.com', 0),- candidate('example.com', 1),- ])+ const [attempt] = await harness.runner.run([candidate({ remainingHops: 1 })], new Map())- expect(attempts.map((attempt) => attempt.outcome).sort()).toEqual(['ok', 'rate_limited'])- expect(published).toEqual(['retry'])+ expect(harness.republish).not.toHaveBeenCalled()+ expect(attempt).toMatchObject({ outcome: HOPS_EXHAUSTED, finished: true })})- it('puts back a bounded number of shed URLs, and does it in one go', async () => {- // A shed runs after the pass deadline has passed. One awaited produce for each URL of a- // large back queue would run past max.poll.interval.ms and lose the partition mid-batch,- // and putting every one of them back answers overload with more Kafka traffic.- let open = 0- let peak = 0- let published = 0- const publisher = {- republish: async () => {- open++- peak = Math.max(peak, open)- await Promise.resolve()- published++- open--- return true- },- } as unknown as FrontierPublisher- const fetcher = new FakeFetcher(() => ({ outcome: 'rate_limited', status: 429, retryAfterMs: 30_000 }))- const queue = Array.from({ length: 2500 }, () => candidate('busy.com', 0))-- const attempts = await runner(fetcher, {}, defaultBudget(), publisher).run(queue)-- expect(attempts).toHaveLength(2500)- // The cap, plus the few that held a burst token and were fetched before the 429 blocked the- // domain. Well under 2500, which is what one awaited produce for each would have cost.- expect(published).toBeGreaterThanOrEqual(1000)- expect(published).toBeLessThanOrEqual(1000 + OPTIONS.maxConcurrentPerDomain)- // More than one produce was open at a time, so the shed did not await them one by one.- expect(peak).toBeGreaterThan(1)+ it('does not start policy or image requests when the hop budget is empty', async () => {+ const harness = build()++ const [attempt] = await harness.runner.run([candidate({ remainingHops: 0 })], new Map())++ expect(harness.check).not.toHaveBeenCalled()+ expect(harness.fetch).not.toHaveBeenCalled()+ expect(attempt).toMatchObject({ outcome: HOPS_EXHAUSTED, finished: true })})- it('bounds the shed republish across the whole pass, not once for each domain', async () => {- // Domains run at the same time, so an allowance for each of them multiplies by however many- // a batch touches. One busy domain per record of a full batch would open that many times- // the cap as Kafka produces at once, past what the producer queue holds.- let open = 0- let peak = 0- let published = 0- const publisher = {- republish: async () => {- open++- peak = Math.max(peak, open)- await Promise.resolve()- published++- open--- return true- },- } as unknown as FrontierPublisher- const fetcher = new FakeFetcher(() => ({ outcome: 'rate_limited', status: 429, retryAfterMs: 30_000 }))- // 40 domains, 100 URLs each. A per-domain cap of 1000 would put back all 4000.- const queue = Array.from({ length: 40 }).flatMap((_unused, domain) =>- Array.from({ length: 100 }, () => candidate(`site${domain}.com`, 0))- )+ 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 attempts = await runner(fetcher, {}, defaultBudget(), publisher).run(queue)+ const [attempt] = await harness.runner.run([candidate()], new Map())- expect(attempts).toHaveLength(4000)- // The pass allowance, plus the few per domain that held a burst token and were fetched.- expect(published).toBeLessThanOrEqual(1000 + 40 * OPTIONS.maxConcurrentPerDomain)- expect(peak).toBeLessThanOrEqual(1000 + 40 * OPTIONS.maxConcurrentPerDomain)+ expect(retryCause).not.toHaveBeenCalled()+ expect(attempt).toMatchObject({ outcome: 'timeout', finished: false, lost: true })})- it('gives up and records a URL with no hops left (requirement 12)', async () => {- const publisher = { republish: () => Promise.resolve(true) } as unknown as FrontierPublisher- const fetcher = new FakeFetcher(() => ({ outcome: 'timeout' }))- const spent = { ...candidate('example.com', 0), hopsRemaining: 1 }+ 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 attempts = await runner(fetcher, {}, defaultBudget(), publisher).run([spent])+ const [attempt] = await harness.runner.run([candidate()], new Map())- expect(attempts[0]).toMatchObject({ outcome: 'hops_exhausted', finished: true })+ expect(retryCause).not.toHaveBeenCalled()+ expect(attempt).toMatchObject({ outcome: DELAY_TOO_LONG, finished: true })})- it('runs every domain at once but holds the requests under them to the in-flight limit', async () => {- let inFlight = 0- let peak = 0- const fetcher: ImageFetcher = {- fetch: async () => {- peak = Math.max(peak, ++inFlight)- await new Promise((resolve) => setTimeout(resolve, 5))- inFlight--- return { outcome: 'ok', redirects: 0 }- },+ it('merges a 304 response into the previous cache metadata', async () => {+ const previousCache: HttpCacheMetadata = {+ requestTimeMs: NOW_MS - 2_000,+ responseTimeMs: NOW_MS - 1_000,+ etag: '"v1"',+ lastModified: 'yesterday',}- const domains = Array.from({ length: 60 }, (_value, index) => candidate(`site${index}.com`, 0))+ const harness = build({+ outcome: 'not_modified',+ status: 304,+ cache: { requestTimeMs: NOW_MS - 10, responseTimeMs: NOW_MS, etag: '"v2"' },+ })+ const stored = new Map<string, CrawlHistoryItem>([+ [+ candidate().originalRef,+ {+ kind: 'url',+ key: candidate().originalRef,+ nextFetchAtMs: NOW_MS,+ storageExpiresAtMs: NOW_MS,+ outcome: 'ok',+ cache: previousCache,+ },+ ],+ ])- const attempts = await runner(fetcher, { maxInFlightRequests: 5 }).run(domains)+ const [attempt] = await harness.runner.run([candidate()], stored)- expect(peak).toBe(5)- expect(attempts.filter((a) => a.outcome === 'ok')).toHaveLength(60)+ expect(attempt.history?.cache).toMatchObject({ etag: '"v2"', lastModified: 'yesterday' })})- it.each([- ['a 429', 'rate_limited' as const, undefined, true],- ['a 503 that named a period', 'server_error' as const, 30_000, true],- ['a one-off 500', 'server_error' as const, undefined, false],- ])('holds the whole domain after %s: %s', async (_name, outcome, retryAfterMs, expectHeld) => {- // A hold silences every URL of the domain. A site that failed one request did not ask for- // that, so it gets the rate cut and the breaker count instead.- const fetcher = new FakeFetcher(() => ({ outcome, status: 500, retryAfterMs }))-- const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1 }).run(- [0, 1].map((index) => candidate('site.com', index))- )+ it('retains validators that a 304 response omits', async () => {+ const previousCache: HttpCacheMetadata = {+ requestTimeMs: NOW_MS - 2_000,+ responseTimeMs: NOW_MS - 1_000,+ etag: '"v1"',+ lastModified: 'yesterday',+ }+ const harness = build({+ outcome: 'not_modified',+ status: 304,+ cache: { requestTimeMs: NOW_MS - 10, responseTimeMs: NOW_MS },+ })+ const stored = new Map<string, CrawlHistoryItem>([+ [+ candidate().originalRef,+ {+ kind: 'url',+ key: candidate().originalRef,+ nextFetchAtMs: NOW_MS,+ storageExpiresAtMs: NOW_MS,+ outcome: 'ok',+ cache: previousCache,+ },+ ],+ ])- expect(attempts.some((a) => a.outcome === 'rate_limited')).toBe(expectHeld)+ const [attempt] = await harness.runner.run([candidate()], stored)++ expect(attempt.history?.cache).toMatchObject({+ requestTimeMs: NOW_MS - 10,+ responseTimeMs: NOW_MS,+ etag: '"v1"',+ lastModified: 'yesterday',+ })})- it('does not send a request whose domain was blocked while it waited (requirement 5)', async () => {- const budget = new HostBudget({- requestsPerSecond: 1,- burst: 1,- maxConcurrent: 6,- breakerFailures: 100,- breakerCooldownMs: 60_000,- breakerMaxCooldownMs: 600_000,- maxTrackedDomains: 100,+ it('does not store a redirect target validator under the original URL ref', async () => {+ const harness = build({+ redirects: 1,+ currentUrl: 'https://cdn.example.com/moved.png',+ cache: {+ requestTimeMs: NOW_MS - 10,+ responseTimeMs: NOW_MS,+ etag: '"redirect-target"',+ lastModified: 'today',+ cacheControl: 'max-age=60',+ },})- const fetcher = new FakeFetcher(() => ({ outcome: 'ok' }))- // The burst token carries the first URL. The second waits a second for its token, and the- // site says stop during that wait.- setTimeout(() => budget.recordRetryAfter('slow.com', Date.now(), 60_000), 5)- const attempts = await runner(fetcher, { maxConcurrentPerDomain: 1 }, budget).run(- [0, 1].map((index) => candidate('slow.com', index))- )+ const [attempt] = await harness.runner.run([candidate()], new Map())- expect(fetcher.calls).toHaveLength(1)- expect(attempts.filter((a) => a.outcome === 'rate_limited')).toHaveLength(1)+ expect(attempt.history?.cache).toMatchObject({ cacheControl: 'max-age=60' })+ expect(attempt.history?.cache?.etag).toBeUndefined()+ expect(attempt.history?.cache?.lastModified).toBeUndefined()})- it('returns the token of a request it did not send (requirement 5)', () => {- const budget = new HostBudget({- requestsPerSecond: 1,- burst: 2,- maxConcurrent: 6,- breakerFailures: 100,- breakerCooldownMs: 60_000,- breakerMaxCooldownMs: 600_000,- maxTrackedDomains: 100,+ it('extends URL history to the end of explicit freshness', async () => {+ const fortyDaysMs = 40 * 24 * 60 * 60 * 1000+ const harness = build({+ cache: {+ requestTimeMs: NOW_MS,+ responseTimeMs: NOW_MS,+ cacheControl: `s-maxage=${fortyDaysMs / 1000}`,+ },})- budget.take('example.com', 1000, FAR_FUTURE)- budget.take('example.com', 1000, FAR_FUTURE)- budget.returnGrant('example.com', 1000)-- expect(budget.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 0 })- })+ const [attempt] = await harness.runner.run([candidate()], new Map())- it.each([- ['ok', true],- ['not_found', true],- ['too_large', true],- ['blocked', true],- ['timeout', false],- ['rate_limited', false],- ['server_error', false],- ['breaker_open', false],- ['deadline', false],- ])('treats %s as terminal: %s', (outcome, terminal) => {- // A terminal outcome writes a crawl history entry, which is the one thing that stops this- // lane from looking at the URL again. A transient outcome must not write one.- expect(isTerminal(outcome as FetchOutcome)).toBe(terminal)+ expect(attempt.history?.nextFetchAtMs).toBe(NOW_MS + fortyDaysMs)+ expect(attempt.history?.storageExpiresAtMs).toBe(NOW_MS + fortyDaysMs)})})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.tsindex d39e310ce969..ab16743af35d 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@@ -1,516 +1,522 @@import { ConcurrencyController } from '~/common/utils/concurrencyController'import { logger } from '~/common/utils/logger'-import { delay } from '~/common/utils/utils'-import { FetchCandidate, MAX_HOPS } from './collected-urls-record'-import { FrontierPublisher } from './frontier-publisher'+import { FetchCandidate, MAX_HOPS, RepublishReason } from './collected-urls-record'+import {+ ConfigurationPolicyPass,+ ConfigurationPolicyService,+ explicitFreshnessLifetimeMs,+} from './configuration-policy'+import { ConfigurationCacheItem, CrawlHistoryItem, HttpCacheMetadata, UrlCrawlHistoryItem } from './crawl-history'+import { FrontierPublisher, RepublishResult } from './frontier-publisher'import { HostBudget } from './host-budget'-import { FetchOutcome, ImageFetchResult, ImageFetcher, RedirectDecision } from './image-fetcher'+import {+ FetchOutcome,+ FetchRefusalReason,+ ImageFetcher,+ RequestScheduleBlockReason,+ TransientFetchOutcome,+} from './image-fetcher'import { ImageFetchRequestMetrics } from './metrics'-import { politenessKey } from './politeness-key'+import { OriginRequestScheduler } from './origin-request-scheduler'+import { canonicalizeUrl } from './politeness-key'-/** Why a URL never reached a request. It shares `rate_limited` with the response of the same name, because both mean the site asked us to wait. */-export type ShedReason = 'breaker_open' | 'rate_limited' | 'deadline' | 'connection_limit'--/** A URL that ran out of hops. The lane records it so it stops coming back. Requirement 12. */+export type ShedReason =+ | 'breaker_open'+ | 'backoff'+ | 'deadline'+ | 'connection_limit'+ | 'origin_map_full'+ | 'registrable_domain_map_full'export const HOPS_EXHAUSTED = 'hops_exhausted'--export type AttemptOutcome = FetchOutcome | ShedReason | typeof HOPS_EXHAUSTED+export const DELAY_TOO_LONG = 'delay_too_long'+export type AttemptOutcome =+ | FetchOutcome+ | FetchRefusalReason+ | ShedReason+ | 'publish_failed'+ | typeof HOPS_EXHAUSTED+ | typeof DELAY_TOO_LONGexport interface FetchAttempt {candidate: FetchCandidateoutcome: AttemptOutcome- /**- * True when the lane is done with this URL and must write it to the crawl history.- *- * False means the URL comes back, from a republish to the frontier or to a delay topic, or from- * a failed republish. A crawl history entry for one of those stops it ever being fetched.- * Requirements 12 and 24.- */finished: boolean- /**- * True when the URL was meant to go back to Kafka and did not.- *- * Nothing else holds it, so its offset must not commit. The URL is otherwise gone until a- * session refers to the same image again. Requirement 21.- */lost: boolean+ history?: UrlCrawlHistoryItem+ configurationUpdates: ConfigurationCacheItem[]}export interface FetchRunnerOptions {- /** Workers per domain. The limit itself lives in the budget, because a redirect reaches a domain without passing through this pool. */- maxConcurrentPerDomain: number- /**- * Requests open across every domain at once. This bounds the pod rather than politeness.- *- * The lane reads a body into a buffer, so the peak memory is about this number times the byte- * limit. The sockets and the DNS lookups come with it.- */+ maxConcurrentPerRegistrableDomain: numbermaxInFlightRequests: number- /** Wall time the whole pass may take. The lane sheds a URL it does not reach, and fetches it again when a session next refers to it. */batchBudgetMs: numbermaxBytes: numberrequestTimeoutMs: numbermaxRedirects: number- /** Used for a 429 or a 503 that named no period, so a site that only says "slow down" still gets a pause. */- defaultRetryAfterMs: number-}--/**- * Outcomes that will not change if the lane tries the same URL again.- *- * Only these write a crawl history entry. The lane leaves a URL shed by the budget, or lost to a- * timeout, unrecorded, because it goes back to a delay topic and comes round again. An entry for one- * of those would suppress the URL for the whole crawl history TTL because a site was busy for a- * moment.- */-const TERMINAL_OUTCOMES: ReadonlySet<AttemptOutcome> = new Set<AttemptOutcome>([- 'ok',- 'not_found',- 'forbidden',- 'too_large',- 'not_image',- 'blocked',- 'bad_redirect',- 'too_many_redirects',- 'unexpected_status',- // A property of the origin rather than of the moment, so a retry meets the same response and- // spends a hop for nothing.- 'unsupported_encoding',-])--/**- * URLs one pass puts back after a shed, across every domain in it.- *- * A shed happens under overload, and one back queue can hold every URL of a batch. Republishing all- * of them answers overload with more Kafka traffic, and the same URLs arrive again a minute later- * having each spent a hop. Past this the rest are left unrecorded, so the mirror offers them again.- *- * One allowance for the pass rather than one for each domain, because domains run at the same time.- * A per-domain cap multiplies by however many domains a batch touches, and a batch that offers- * URLs across hundreds of them would open that many times this number of produces at once.- */-const MAX_SHED_REPUBLISHED_PER_PASS = 1000--/** What is left of the pass allowance. Read and written between awaits, so a domain never sees a torn value. */-interface ShedAllowance {- remaining: number+ seenTtlSeconds: number}-/** Hosts named in one batch-level log line, bounded so one bad batch cannot log a host list of its own size. */-const MAX_LOGGED_HOSTS = 5+const TRANSIENT_OUTCOMES = new Set<TransientFetchOutcome>(['timeout', 'error', 'rate_limited', 'server_error'])+const ONE_MINUTE_MS = 60_000+const CONFIGURATION_RETRY_MS = 60 * 60 * 1000-/** These values come from the environment, where a typo parses to NaN and switches a politeness control off. */-function requirePositive(name: string, value: number): number {+function requirePositive(name: string, value: number): void {if (!Number.isFinite(value) || value <= 0) {throw new Error(`${name} must be a positive number, got ${value}`)}- return value}-export function isTerminal(outcome: AttemptOutcome): boolean {- return TERMINAL_OUTCOMES.has(outcome)+function isTransientOutcome(outcome: FetchOutcome): outcome is TransientFetchOutcome {+ return TRANSIENT_OUTCOMES.has(outcome as TransientFetchOutcome)+}++function isRequestStateFull(+ reason: string | undefined+): reason is Extract<RequestScheduleBlockReason, 'origin_map_full' | 'registrable_domain_map_full'> {+ return reason === 'origin_map_full' || reason === 'registrable_domain_map_full'}-/** What the consumer needs of the fetch pass, so its tests use the real contract rather than a cast. */export interface FetchPass {- run(candidates: FetchCandidate[]): Promise<FetchAttempt[]>+ run(candidates: FetchCandidate[], stored: Map<string, CrawlHistoryItem>): Promise<FetchAttempt[]>}-/**- * Runs the fetches of one poll batch inside the per-domain budget.- *- * Domains run in parallel, so one slow site delays only its own URLs. Inside a domain the worker- * count is the connection limit and the token bucket is the rate, so a domain receives from this- * pod exactly what an operator configured for it.- *- * Wall time bounds the pass rather than work. A batch can hold more URLs for one domain than a- * polite rate carries in the time a Kafka batch may take, and the lane then fetches fewer of them.- */export class FetchRunner implements FetchPass {- private readonly inFlight: ConcurrencyController+ private readonly candidateWork: ConcurrencyControllerconstructor(private readonly fetcher: ImageFetcher,private readonly budget: HostBudget,+ private readonly scheduler: OriginRequestScheduler,+ private readonly configurationPolicy: ConfigurationPolicyService,private readonly options: FetchRunnerOptions,- /** Required, because without it every transient outcome becomes a loss rather than a retry. */private readonly publisher: FrontierPublisher) {- requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN', options.maxConcurrentPerDomain)+ requirePositive(+ 'SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN',+ options.maxConcurrentPerRegistrableDomain+ )requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS', options.maxInFlightRequests)- this.inFlight = new ConcurrencyController(options.maxInFlightRequests)- ImageFetchRequestMetrics.trackBudget(budget, this.inFlight)requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES', options.maxBytes)requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS', options.requestTimeoutMs)- requirePositive('SESSION_RECORDING_ML_IMAGE_FETCH_DEFAULT_RETRY_AFTER_MS', options.defaultRetryAfterMs)- // Zero is meaningful for both, and means no fetch at all and no redirect at all.+ requirePositive('AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS', options.seenTtlSeconds)if (!Number.isFinite(options.batchBudgetMs) || !Number.isFinite(options.maxRedirects)) {- throw new Error('SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS and MAX_REDIRECTS must be numbers')+ throw new Error('image fetch pass limits must be finite numbers')}+ this.candidateWork = new ConcurrencyController(options.maxInFlightRequests)+ ImageFetchRequestMetrics.trackBudget(budget, scheduler)}- public async run(candidates: FetchCandidate[]): Promise<FetchAttempt[]> {- if (candidates.length === 0) {- return []- }+ public async run(candidates: FetchCandidate[], stored: Map<string, CrawlHistoryItem>): Promise<FetchAttempt[]> {const deadlineMs = Date.now() + this.options.batchBudgetMs- const byDomain = new Map<string, FetchCandidate[]>()+ const configurationPolicy = this.configurationPolicy.createPass()+ const configurationItems = new Map<string, ConfigurationCacheItem>()+ for (const [key, item] of stored) {+ if (item.kind === 'robots' || item.kind === 'tdmrep') {+ configurationItems.set(key, item)+ }+ }+ const byRegistrableDomain = new Map<string, FetchCandidate[]>()for (const candidate of candidates) {- const backQueue = byDomain.get(candidate.domain)- if (backQueue) {- backQueue.push(candidate)+ const queue = byRegistrableDomain.get(candidate.registrableDomain)+ if (queue) {+ queue.push(candidate)} else {- byDomain.set(candidate.domain, [candidate])+ byRegistrableDomain.set(candidate.registrableDomain, [candidate])}}-- const attempts = await this.runDomains([...byDomain], deadlineMs, { remaining: MAX_SHED_REPUBLISHED_PER_PASS })+ const attempts: FetchAttempt[] = []+ const registrableDomainRuns = [...byRegistrableDomain].map(([registrableDomain, queue]) =>+ this.runRegistrableDomainQueue(+ registrableDomain,+ queue,+ stored,+ configurationItems,+ configurationPolicy,+ deadlineMs,+ attempts+ )+ )+ const settledRegistrableDomains = await Promise.allSettled(registrableDomainRuns)+ const failedRegistrableDomain = settledRegistrableDomains.find(+ (settled): settled is PromiseRejectedResult => settled.status === 'rejected'+ )+ if (failedRegistrableDomain) {+ throw failedRegistrableDomain.reason+ }this.logFailures(attempts)return attempts}- /**- * One line for each outcome of the whole pass, because a site that is down turns every URL of a- * batch into a log line. The counts answer the same question, and the hosts say where to look.- *- * A URL is page content, so it appears in no log.- */- private logFailures(attempts: FetchAttempt[]): void {- const byOutcome = new Map<AttemptOutcome, { count: number; hosts: Set<string> }>()- for (const attempt of attempts) {- if (attempt.outcome === 'ok') {- continue- }- const seen = byOutcome.get(attempt.outcome) ?? { count: 0, hosts: new Set<string>() }- seen.count++- if (seen.hosts.size < MAX_LOGGED_HOSTS) {- seen.hosts.add(attempt.candidate.host)+ private async runRegistrableDomainQueue(+ registrableDomain: string,+ queue: FetchCandidate[],+ stored: Map<string, CrawlHistoryItem>,+ configurationItems: Map<string, ConfigurationCacheItem>,+ configurationPolicy: ConfigurationPolicyPass,+ deadlineMs: number,+ attempts: FetchAttempt[]+ ): Promise<void> {+ const byOrigin = new Map<string, FetchCandidate[]>()+ for (const candidate of queue) {+ const originQueue = byOrigin.get(candidate.origin)+ if (originQueue) {+ originQueue.push(candidate)+ } else {+ byOrigin.set(candidate.origin, [candidate])}- byOutcome.set(attempt.outcome, seen)}- for (const [outcome, seen] of byOutcome) {- logger.warn('🌐', 'ml_image_fetch_batch_failures', {- outcome,- count: seen.count,- hosts: [...seen.hosts],- })+ const registrableDomainWork = new ConcurrencyController(this.options.maxConcurrentPerRegistrableDomain)+ const runOriginQueue = async (originQueue: FetchCandidate[]): Promise<void> => {+ for (const candidate of originQueue) {+ if (candidate.remainingHops === 0) {+ attempts.push(this.terminal(candidate, HOPS_EXHAUSTED, undefined, []))+ continue+ }+ if (Date.now() > deadlineMs) {+ attempts.push(await this.republish(candidate, 'deadline', 'pass_deadline', ONE_MINUTE_MS, []))+ continue+ }+ attempts.push(+ await registrableDomainWork.run({+ debugTag: candidate.origin,+ fn: () =>+ this.candidateWork.run({+ debugTag: registrableDomain,+ fn: () => {+ if (Date.now() > deadlineMs) {+ return this.republish(candidate, 'deadline', 'pass_deadline', ONE_MINUTE_MS, [])+ }+ return this.fetchOne(+ candidate,+ stored,+ configurationItems,+ configurationPolicy,+ deadlineMs+ )+ },+ }),+ })+ )+ }}- }-- /**- * Every domain runs at once. A domain spends nearly all of its time waiting on its own rate- * limit, so thousands of them cost a queue and a closure each, and a cap on domains would make- * unrelated sites wait for each other for no reason of politeness.- *- * `maxInFlightRequests` bounds the requests underneath them.- */- private async runDomains(- entries: [string, FetchCandidate[]][],- deadlineMs: number,- allowance: ShedAllowance- ): Promise<FetchAttempt[]> {- // Every domain writes into this array rather than concatenating afterwards. One batch can- // offer hundreds of thousands of URLs to a single domain, and both `push(...array)` and- // `concat` of that size exceed the argument limit of `Function.apply`.- const attempts: FetchAttempt[] = []- await Promise.all(- entries.map(([domain, backQueue]) => this.runBackQueue(domain, backQueue, deadlineMs, attempts, allowance))+ const settledWorkers = await Promise.allSettled([...byOrigin.values()].map(runOriginQueue))+ const failedWorker = settledWorkers.find(+ (settled): settled is PromiseRejectedResult => settled.status === 'rejected')- return attempts+ if (failedWorker) {+ throw failedWorker.reason+ }}- /** A back queue is the crawler term for the queue of one registrable domain, which a politeness limit applies to. */- private async runBackQueue(- domain: string,- backQueue: FetchCandidate[],- deadlineMs: number,- attempts: FetchAttempt[],- allowance: ShedAllowance- ): Promise<void> {- let next = 0- // A refusal is a property of the domain, so it applies to every URL still queued for it.- const shedRemaining = async (reason: ShedReason, first?: FetchCandidate): Promise<void> => {- const shed = first ? [first, ...backQueue.slice(next)] : backQueue.slice(next)- next = backQueue.length- if (shed.length === 0) {- return+ private async fetchOne(+ candidate: FetchCandidate,+ stored: Map<string, CrawlHistoryItem>,+ configurationItems: Map<string, ConfigurationCacheItem>,+ configurationPolicy: ConfigurationPolicyPass,+ deadlineMs: number+ ): Promise<FetchAttempt> {+ if (candidate.remainingHops === 0) {+ return this.terminal(candidate, HOPS_EXHAUSTED, undefined, [])+ }+ const policy = await configurationPolicy.check(candidate.currentUrl, configurationItems, Date.now())+ const configurationUpdates = [...policy.updates]+ for (const update of policy.updates) {+ configurationItems.set(update.key, update)+ }+ if (!policy.allowed) {+ ImageFetchRequestMetrics.observePolicyAndBudgetDecision(true, policy.reason ?? 'configuration_refused')+ if (policy.transient) {+ if (isRequestStateFull(policy.reason)) {+ return await this.republish(+ candidate,+ policy.reason,+ policy.reason,+ ONE_MINUTE_MS,+ configurationUpdates+ )+ }+ const waitMs = policy.reason === 'configuration_unreachable' ? CONFIGURATION_RETRY_MS : ONE_MINUTE_MS+ return await this.republish(candidate, 'backoff', 'not_ready', waitMs, configurationUpdates)}- ImageFetchRequestMetrics.incOutcome(reason, shed.length)- const waitMs = this.budget.blockedForMs(domain, Date.now())- // Taken before the first await, so two domains shedding at once cannot both read the- // same remainder and spend it twice.- const takes = Math.min(shed.length, allowance.remaining)- allowance.remaining -= takes- // Together rather than one after another. A shed runs once the pass deadline has passed,- // and one awaited produce for each of tens of thousands of URLs would run past- // `max.poll.interval.ms` and lose the partition in the middle of the batch.- const republished = await Promise.all(- shed.slice(0, takes).map((candidate) => this.reschedule(candidate, reason, waitMs))+ return this.terminal(+ candidate,+ policy.reason ?? 'configuration_refused',+ undefined,+ configurationUpdates,+ policy.reason ?? 'configuration_refused'+ )+ }+ if (!this.budget.setCrawlDelay(candidate.origin, policy.crawlDelayMs, Date.now())) {+ ImageFetchRequestMetrics.observePolicyAndBudgetDecision(true, 'origin_map_full')+ return await this.republish(+ candidate,+ 'origin_map_full',+ 'origin_map_full',+ ONE_MINUTE_MS,+ configurationUpdates)- for (const attempt of republished) {- attempts.push(attempt)- }- for (const candidate of shed.slice(takes)) {- attempts.push({ candidate, outcome: reason, finished: false, lost: false })- }- if (shed.length > takes) {- ImageFetchRequestMetrics.incShedDropped(shed.length - takes)- }}- const worker = async (): Promise<void> => {- while (next < backQueue.length) {- const grant = this.budget.take(domain, Date.now(), deadlineMs)- if (!grant.granted) {- await shedRemaining(grant.reason)- return+ const previous = stored.get(candidate.originalRef)+ const previousUrl = previous?.kind === 'url' ? previous : undefined+ const result = await this.fetcher.fetch(candidate.currentUrl, {+ maxBytes: this.options.maxBytes,+ timeoutMs: this.options.requestTimeoutMs,+ maxRedirects: Math.min(this.options.maxRedirects, candidate.remainingHops),+ cache: previousUrl?.cache,+ tdmrepReservation: policy.tdmrepReservation,+ onRedirectResponse: () => this.budget.recordCompletedResponse(candidate.registrableDomain, Date.now()),+ isDifferentOrigin: (url) => url.origin !== candidate.origin,+ scheduleRequest: (url, requestDeadlineMs, request) =>+ this.scheduler.runImage(url, Math.min(deadlineMs, requestDeadlineMs), request),+ checkRedirectPolicy: async (url) => {+ const redirectPolicy = await configurationPolicy.check(url, configurationItems, Date.now())+ for (const update of redirectPolicy.updates) {+ configurationItems.set(update.key, update)+ configurationUpdates.push(update)}- const candidate = backQueue[next++]- ImageFetchRequestMetrics.observeBudgetWait(grant.waitMs / 1000)- if (grant.waitMs > 0) {- await delay(grant.waitMs)- // The budget granted this before the wait. A `Retry-After` or an open breaker- // can arrive during the wait, and the deadline can pass. Requirement 5.- const stale = this.staleAfterWait(domain, deadlineMs)- if (stale) {- this.budget.returnGrant(domain, Date.now())- // The whole back queue, not this URL alone. Whatever went stale during the- // wait is a property of the domain, so it holds for every URL still queued- // for it. Requirement 16.- await shedRemaining(stale, candidate)- return+ if (!redirectPolicy.allowed) {+ return {+ allowed: false,+ transient: redirectPolicy.transient,+ reason: redirectPolicy.reason ?? 'configuration_refused',}}- attempts.push(await this.fetchOne(candidate, deadlineMs))- }+ const origin = new URL(url).origin+ if (!this.budget.setCrawlDelay(origin, redirectPolicy.crawlDelayMs, Date.now())) {+ return { allowed: false, transient: true, reason: 'origin_map_full' }+ }+ return { allowed: true, tdmrepReservation: redirectPolicy.tdmrepReservation }+ },+ })+ ImageFetchRequestMetrics.observeRedirectCount(result.redirects)+ if (result.bytes) {+ ImageFetchRequestMetrics.observeBytes(result.bytes.length)}- const workers = Math.min(this.options.maxConcurrentPerDomain, backQueue.length)- await Promise.all(Array.from({ length: workers }, () => worker()))- }-- /** Why a granted request must not go out after its wait, or null when it may still go out. Requirement 5. */- private staleAfterWait(domain: string, deadlineMs: number): ShedReason | null {- const nowMs = Date.now()- const blocked = this.budget.blockedReason(domain, nowMs)- if (blocked) {- return blocked+ const effectiveUrl = canonicalizeUrl(result.currentUrl)+ if (!effectiveUrl) {+ return this.terminal(candidate, 'bad_redirect', result.cache, configurationUpdates)}- return nowMs > deadlineMs ? 'deadline' : null- }-- /**- * The request keeps its whole configured timeout even when the pass deadline is closer.- *- * A request that the batch clock cut short would time out through no fault of the site, and the- * budget would read that as the site failing. So the deadline decides whether a request starts,- * and never how long it may take. One pass can therefore run to `batchBudgetMs` plus one- * request timeout, which is still far inside Kafka's max.poll.interval.ms.- */- private async fetchOne(candidate: FetchCandidate, deadlineMs: number): Promise<FetchAttempt> {- // One slot, held until the chain ends. A chain reaches only its own domain, because- // `isOffsite` refuses every other target, and the set makes a second take of the same- // domain free so a redirect back to it cannot deadlock against itself.- const held = new Set<string>()- const acquire = (domain: string): boolean => {- if (held.has(domain)) {- return true- }- if (!this.budget.acquireConnection(domain, Date.now())) {- return false- }- held.add(domain)- return true+ const attemptedCandidate: FetchCandidate = {+ ...candidate,+ currentUrl: effectiveUrl.fetch,+ host: effectiveUrl.host,+ origin: new URL(effectiveUrl.fetch).origin,+ registrableDomain: effectiveUrl.domain,+ remainingHops: candidate.remainingHops - result.redirects,+ fetchCount:+ candidate.fetchCount ++ result.redirects ++ (result.outcome === 'request_deferred' || result.outcome === 'redirect_policy_refused' ? 0 : 1),}- const releaseAll = (): void => {- for (const domain of held) {- this.budget.releaseConnection(domain)++ if (result.outcome === 'redirect_policy_refused') {+ const reason = result.refusalReason ?? 'configuration_refused'+ ImageFetchRequestMetrics.observePolicyAndBudgetDecision(true, reason)+ if (result.policyTransient) {+ 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 this.terminal(attemptedCandidate, reason, undefined, configurationUpdates, reason)}- if (!acquire(candidate.domain)) {- // One setting feeds both the worker count and this limit, so the pool already holds a- // domain to the same number and nothing gets here today. The budget is where the limit- // belongs, so the check stays. A refusal means the domain is busy now, which is not a- // fact about the URL, so the lane writes no crawl history entry for it.- this.budget.returnGrant(candidate.domain, Date.now())- ImageFetchRequestMetrics.incOutcome('connection_limit')- return await this.reschedule(candidate, 'connection_limit', 0)+ if (result.outcome === 'request_deferred') {+ const reason = result.schedulingReason ?? 'deadline'+ ImageFetchRequestMetrics.observePolicyAndBudgetDecision(true, reason)+ const republishReason: RepublishReason = isRequestStateFull(reason)+ ? reason+ : 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())+ )+ return await this.republish(attemptedCandidate, reason, republishReason, waitMs, configurationUpdates)}- const startedAt = process.hrtime.bigint()- let outcome: ImageFetchResult | { shed: ShedReason }- try {- outcome = await this.inFlight.run<ImageFetchResult | { shed: ShedReason }>({- debugTag: candidate.domain,- fn: () => {- // The pod queue is the third place a request waits, after the token bucket and- // the connection limit, and it can hold a request longest because its slots- // serve every domain this pod owns. A sibling request can meet a `Retry-After`- // while this one queues. Requirement 5.- const stale = this.staleAfterWait(candidate.domain, deadlineMs)- if (stale) {- return Promise.resolve({ shed: stale })- }- return this.fetcher.fetch(candidate.url, {- maxBytes: this.options.maxBytes,- timeoutMs: this.options.requestTimeoutMs,- maxRedirects: this.options.maxRedirects,- isOffsite: (url) => politenessKey(url.hostname) !== candidate.domain,- // The earlier of the two clocks, because a wait that outlives the request- // reports the site as timing out.- authorizeRedirect: (url, remainingMs) =>- this.authorizeRedirect(- Math.min(deadlineMs, Date.now() + remainingMs),- acquire,- candidate.domain- ),- })- },- })- } catch (error) {- // The fetcher answers with an outcome rather than a throw, so a throw here means a- // defect. The catch stays because a throw would leave the other domains of this batch- // running while the partition replays them.- logger.error('🌐', 'ml_image_fetch_unhandled_error', {- host: candidate.host,- // The name only. An error message from the request layer can carry the URL, and a- // URL is page content.- error: error instanceof Error ? error.name : 'unknown',- })- ImageFetchRequestMetrics.incOutcome('error')- return await this.reschedule(candidate, 'error', 0)- } finally {- releaseAll()- }- if ('shed' in outcome) {- this.budget.returnGrant(candidate.domain, Date.now())- ImageFetchRequestMetrics.incOutcome(outcome.shed)- return await this.reschedule(- candidate,- outcome.shed,- this.budget.blockedForMs(candidate.domain, Date.now())+ ImageFetchRequestMetrics.observePolicyAndBudgetDecision(false)++ if (isTransientOutcome(result.outcome)) {+ const delayMs = this.budget.recordTransientFailure(+ candidate.registrableDomain,+ Date.now(),+ result.retryAfterMs+ )+ const attempt = await this.republish(+ attemptedCandidate,+ result.outcome,+ 'retry',+ delayMs,+ configurationUpdates)+ if (!attempt.finished && !attempt.lost) {+ ImageFetchRequestMetrics.incRetryCause(result.outcome)+ }+ return attempt}- const result = outcome- const durationSeconds = Number(process.hrtime.bigint() - startedAt) / 1e9- this.applyToBudget(candidate.domain, result.outcome, result.retryAfterMs)- ImageFetchRequestMetrics.observeRequest(result.outcome, durationSeconds, result.redirects)- if (result.bytes) {- ImageFetchRequestMetrics.observeBytes(result.bytes.length)- }- if (result.outcome === 'redirect_offsite' && result.redirectTarget) {- return await this.handOff(candidate, result.redirectTarget)+ this.budget.recordCompletedResponse(candidate.registrableDomain, Date.now())+ if (+ (result.outcome === 'redirect_offsite' || result.outcome === 'redirect_continuation') &&+ result.redirectTarget+ ) {+ const canonical = canonicalizeUrl(result.redirectTarget.url)+ if (!canonical) {+ return this.terminal(attemptedCandidate, 'bad_redirect', result.cache, configurationUpdates)+ }+ return await this.republishToTarget(+ attemptedCandidate,+ result.outcome,+ {+ currentUrl: canonical.fetch,+ host: canonical.host,+ origin: new URL(canonical.fetch).origin,+ registrableDomain: canonical.domain,+ },+ 'redirect',+ 0,+ configurationUpdates+ )}- if (isTerminal(result.outcome)) {- ImageFetchRequestMetrics.observeHops(MAX_HOPS - candidate.hopsRemaining)- return { candidate, outcome: result.outcome, finished: true, lost: false }+ if (result.outcome === 'ok') {+ try {+ await this.publisher.publishImage(attemptedCandidate, result)+ } catch {+ return {+ candidate: attemptedCandidate,+ outcome: 'publish_failed',+ finished: false,+ lost: true,+ configurationUpdates,+ }+ }}- return await this.reschedule(- candidate,+ const responseCache = result.redirects > 0 ? withoutValidators(result.cache) : result.cache+ const mergedCache =+ result.outcome === 'not_modified' ? mergeCache(previousUrl?.cache, responseCache) : responseCache+ return this.terminal(+ attemptedCandidate,result.outcome,- result.retryAfterMs ?? this.budget.blockedForMs(candidate.domain, Date.now())+ mergedCache,+ configurationUpdates,+ result.refusalReason)}- private applyToBudget(domain: string, outcome: FetchOutcome, retryAfterMs: number | undefined): void {- const nowMs = Date.now()- if (outcome === 'ok') {- this.budget.recordSuccess(domain, nowMs)- return- }- if (outcome === 'rate_limited' || outcome === 'server_error') {- // The lane holds the whole domain when the site asked to be left alone, which means a- // 429 or any response that named a period. A one-off 500 gets the rate cut and the- // breaker count instead, because it says this request failed and nothing more.- if (outcome === 'rate_limited' || retryAfterMs !== undefined) {- this.budget.recordRetryAfter(domain, nowMs, retryAfterMs ?? this.options.defaultRetryAfterMs)- }- this.budget.recordBackoff(domain, nowMs)- return- }- if (outcome === 'timeout' || outcome === 'error') {- this.budget.recordBackoff(domain, nowMs)- return+ private async republish(+ candidate: FetchCandidate,+ outcome: AttemptOutcome,+ reason: RepublishReason,+ waitMs: number,+ configurationUpdates: ConfigurationCacheItem[]+ ): Promise<FetchAttempt> {+ return await this.republishToTarget(+ candidate,+ outcome,+ {+ currentUrl: candidate.currentUrl,+ host: candidate.host,+ origin: candidate.origin,+ registrableDomain: candidate.registrableDomain,+ },+ reason,+ waitMs,+ configurationUpdates+ )+ }++ private async republishToTarget(+ candidate: FetchCandidate,+ outcome: AttemptOutcome,+ target: Pick<FetchCandidate, 'currentUrl' | 'host' | 'origin' | 'registrableDomain'>,+ reason: RepublishReason,+ waitMs: number,+ configurationUpdates: ConfigurationCacheItem[]+ ): Promise<FetchAttempt> {+ if ((reason === 'redirect' || reason === 'retry') && candidate.remainingHops <= 1) {+ return this.terminal(candidate, HOPS_EXHAUSTED, undefined, configurationUpdates)}- if (outcome === 'redirect_deferred' || outcome === 'unsupported_encoding') {- // Neither says anything about the load this domain is under.- return+ const result: RepublishResult = await this.publisher.republish(candidate, target, reason, waitMs)+ if (result === 'refused_delay') {+ return this.terminal(candidate, DELAY_TOO_LONG, undefined, configurationUpdates)}- if (outcome === 'forbidden') {- // One 403 is a missing image, which is no reason to slow down. A run of them is an- // anti-bot rule, which the breaker must catch.- this.budget.recordRefusal(domain, nowMs)+ return {+ candidate,+ outcome,+ finished: false,+ lost: result === 'failed',+ configurationUpdates,}}- /**- * Put a URL back for another try, or give up on it.- *- * The lane records a URL with no hops left, so it stops coming back and stops costing requests.- * Requirement 12. Everything else goes to the delay topic whose period covers the wait, and the- * lane records nothing, because the URL has no answer yet. Requirements 13 to 15.- */- private async reschedule(+ private terminal(candidate: FetchCandidate,outcome: AttemptOutcome,- waitMs: number- ): Promise<FetchAttempt> {- if (candidate.hopsRemaining <= 1) {- ImageFetchRequestMetrics.incOutcome(HOPS_EXHAUSTED)- ImageFetchRequestMetrics.observeHops(MAX_HOPS)- return { candidate, outcome: HOPS_EXHAUSTED, finished: true, lost: false }+ cache: HttpCacheMetadata | undefined,+ configurationUpdates: ConfigurationCacheItem[],+ refusalReason: FetchRefusalReason | 'none' = 'none'+ ): FetchAttempt {+ const nowMs = Date.now()+ const minimumNextFetchAtMs = nowMs + this.options.seenTtlSeconds * 1000+ const explicitNextFetchAtMs = cache ? nowMs + explicitFreshnessLifetimeMs(cache, nowMs) : 0+ const nextFetchAtMs = Math.max(minimumNextFetchAtMs, explicitNextFetchAtMs)+ ImageFetchRequestMetrics.observeCompletedUrl(+ outcome,+ refusalReason,+ Math.max(0, nowMs - candidate.firstSeenAtMs) / 1000,+ candidate.fetchCount,+ candidate.republishCount+ )+ ImageFetchRequestMetrics.observeHops(MAX_HOPS - candidate.remainingHops)+ return {+ candidate,+ outcome,+ finished: true,+ lost: false,+ history: {+ kind: 'url',+ key: candidate.originalRef,+ nextFetchAtMs,+ storageExpiresAtMs: nextFetchAtMs,+ outcome: String(outcome),+ cache,+ },+ configurationUpdates,}- const target = { url: candidate.url, host: candidate.host, domain: candidate.domain }- const republished = await this.publisher.republish(candidate, target, 'retry', waitMs)- return { candidate, outcome, finished: false, lost: !republished }}- /**- * Send a redirect target to the consumer that owns its domain.- *- * This pod does not follow the hop. That domain's rate, breaker, and connection count live in- * the pod holding its partition, and a hop followed from this pod spends none of them.- * Requirement 7.- */- private async handOff(candidate: FetchCandidate, target: { url: string; host: string }): Promise<FetchAttempt> {- if (candidate.hopsRemaining <= 1) {- ImageFetchRequestMetrics.incOutcome(HOPS_EXHAUSTED)- ImageFetchRequestMetrics.observeHops(MAX_HOPS)- return { candidate, outcome: HOPS_EXHAUSTED, finished: true, lost: false }+ private logFailures(attempts: FetchAttempt[]): void {+ const failures = attempts.filter((attempt) => attempt.outcome !== 'ok' && attempt.outcome !== 'not_modified')+ if (failures.length === 0) {+ return}- const domain = politenessKey(target.host)- const republished = await this.publisher.republish(candidate, { ...target, domain }, 'redirect')- return { candidate, outcome: 'redirect_offsite', finished: false, lost: !republished }+ logger.warn('🌐', 'ml_image_fetch_batch_failures', {+ count: failures.length,+ outcomes: [...new Set(failures.map((attempt) => String(attempt.outcome)))].slice(0, 10),+ hosts: [...new Set(failures.map((attempt) => attempt.candidate.host))].slice(0, 5),+ })}+}- /** The target belongs to `domain`, because `isOffsite` already refused every other one. A hop spends a token like a first request. */- private async authorizeRedirect(- deadlineMs: number,- acquire: (domain: string) => boolean,- domain: string- ): Promise<RedirectDecision> {- if (!acquire(domain)) {- return 'defer'- }- const grant = this.budget.take(domain, Date.now(), deadlineMs)- if (!grant.granted) {- // Deferred rather than refused, so the lane writes no crawl history entry. Every- // refusal reason here is about this moment rather than about the URL.- return 'defer'- }- ImageFetchRequestMetrics.observeBudgetWait(grant.waitMs / 1000)- if (grant.waitMs > 0) {- await delay(grant.waitMs)- // A `Retry-After` or an open breaker can arrive while a redirect waits, exactly as it- // can while a first request waits. Requirement 5.- if (this.staleAfterWait(domain, deadlineMs)) {- this.budget.returnGrant(domain, Date.now())- return 'defer'- }- }- return 'allow'+function mergeCache(+ previous: HttpCacheMetadata | undefined,+ update: HttpCacheMetadata | undefined+): HttpCacheMetadata | undefined {+ if (!previous) {+ return update}+ if (!update) {+ return previous+ }+ const definedUpdate = Object.fromEntries(Object.entries(update).filter(([, value]) => value !== undefined))+ return { ...previous, ...definedUpdate }+}++function withoutValidators(cache: HttpCacheMetadata | undefined): HttpCacheMetadata | undefined {+ return cache ? { ...cache, etag: undefined, lastModified: undefined } : undefined}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.tsindex 54efafca0b92..575ecdd55733 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,10 +1,12 @@import { KafkaProducerWrapper } from '~/common/kafka/producer'-import { parseJSON } from '~/common/utils/json-parse'-import { FetchCandidate, MAX_HOPS } from './collected-urls-record'+import { FetchCandidate, MAX_HOPS, parseCollectedUrlsRecord } from './collected-urls-record'import { FrontierPublisher } 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 },@@ -13,131 +15,149 @@ const TIERS = [function candidate(overrides: Partial<FetchCandidate> = {}): FetchCandidate {return {- ref: 'imageurl:team:originalhash0000000000',- urlHash: 'originalhash0000000000',- url: 'https://cdn.example.com/a.png',+ originalRef: `imageurl:${'a'.repeat(22)}`,+ currentUrl: 'https://cdn.example.com/a.png',host: 'cdn.example.com',- domain: 'example.com',- pseudoTeam: 'team',- capturedAtMs: 1_700_000_000_000,- hopsRemaining: MAX_HOPS,+ origin: 'https://cdn.example.com',+ registrableDomain: 'example.com',+ remainingHops: MAX_HOPS,notBeforeMs: 0,+ firstSeenAtMs: 1_700_000_000_000,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,...overrides,}}-function build(): { publisher: FrontierPublisher; sent: { topic: string; key: string; body: any }[] } {- const sent: { topic: string; key: string; body: any }[] = []+interface SentMessage {+ topic: string+ key: string+ value: Buffer+ headers?: Record<string, string>+}++function build(): { publisher: FrontierPublisher; sent: SentMessage[] } {+ const sent: SentMessage[] = []const producer = {- produce: ({ topic, key, value }: { topic: string; key: Buffer; value: Buffer }) => {- sent.push({ topic, key: key.toString(), body: parseJSON(value.toString()) })+ produce: (message: { topic: string; key: Buffer; value: Buffer; headers?: Record<string, string> }) => {+ sent.push({ ...message, key: message.key.toString() })return Promise.resolve()},} as unknown as KafkaProducerWrapper- return { publisher: new FrontierPublisher(producer, { frontierTopic: FRONTIER, delayTiers: TIERS }), sent }+ return {+ publisher: new FrontierPublisher(producer, {+ frontierTopic: FRONTIER,+ scrubTopic: SCRUB,+ delayTiers: TIERS,+ maxConcurrentImagePublishes: 2,+ }),+ sent,+ }}describe('FrontierPublisher', () => {- it('keeps the original ref when handing a redirect target on (requirement 10)', async () => {- // The recording points at the original ref. A hash of the redirect target names an image- // nothing refers to, so the fetch would succeed and the image would still be unreachable.- const { publisher, sent } = build()+ beforeEach(() => jest.useFakeTimers().setSystemTime(1_700_000_000_000))+ afterEach(() => {+ jest.useRealTimers()+ jest.restoreAllMocks()+ })- await publisher.republish(+ it('keeps the global ref and durable state when it republishes a redirect', async () => {+ const { publisher, sent } = build()+ const republished = jest.spyOn(ImageFetchRequestMetrics, 'incRepublished').mockImplementation()+ const result = await publisher.republish(candidate(),- { url: 'https://img.other.net/a.png', host: 'img.other.net', domain: 'other.net' },+ {+ currentUrl: 'https://img.other.net/a.png',+ host: 'img.other.net',+ origin: 'https://img.other.net',+ registrableDomain: 'other.net',+ },'redirect')- expect(sent).toHaveLength(1)- expect(sent[0].key).toBe('other.net')- expect(sent[0].body.urls[0]).toEqual({- ref: 'imageurl:team:originalhash0000000000',- url: 'https://img.other.net/a.png',- host: 'img.other.net',+ expect(result).toBe('published')+ expect(republished).toHaveBeenCalledWith('redirect', 'frontier')+ expect(sent[0]).toMatchObject({ topic: FRONTIER, key: 'other.net' })+ expect(parseCollectedUrlsRecord(sent[0].value, 'other.net')).toMatchObject({+ ok: true,+ candidates: [+ {+ originalRef: `imageurl:${'a'.repeat(22)}`,+ currentUrl: 'https://img.other.net/a.png',+ remainingHops: MAX_HOPS - 1,+ republishCount: 1,+ lastRepublishReason: 'redirect',+ },+ ],})})- it('spends a hop on every republish (requirement 11)', async () => {- const { publisher, sent } = build()-- await publisher.republish(candidate({ hopsRemaining: 4 }), targetOf(), 'retry', 0)-- expect(sent[0].body.hopsRemaining).toBe(3)- })-- it('refuses to republish a URL with one hop left, so nothing circulates forever', async () => {- const { publisher, sent } = build()-- const published = await publisher.republish(candidate({ hopsRemaining: 1 }), targetOf(), 'retry', 0)-- expect(published).toBe(false)- expect(sent).toEqual([])- })-it.each([- ['a retry with no period named', 0, 'retry_1m'],- ['a wait inside the first tier', 30_000, 'retry_1m'],- ['a wait between tiers', 120_000, 'retry_10m'],- ['a wait past every tier', 24 * 3_600_000, 'retry_1h'],- ])('parks %s in the right topic', async (_name, waitMs, topic) => {+ ['an unspecified retry', 0, 'retry_1m', 60_000],+ ['a short retry', 30_000, 'retry_1m', 60_000],+ ['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 republished = jest.spyOn(ImageFetchRequestMetrics, 'incRepublished').mockImplementation()- await publisher.republish(candidate(), targetOf(), 'retry', waitMs)-+ expect(await publisher.republish(candidate(), candidate(), 'retry', waitMs)).toBe('published')+ expect(republished).toHaveBeenCalledWith('retry', 'delay')expect(sent[0].topic).toBe(topic)+ expect(parseCollectedUrlsRecord(sent[0].value, 'example.com')).toMatchObject({+ ok: true,+ candidates: [{ notBeforeMs: 1_700_000_000_000 + delayMs }],+ })})- it('never sends a retry straight back to the frontier (requirement 14)', async () => {- // A retry sent to the frontier is a loop: the consumer reads the record, meets the same- // condition, and publishes it again, spending a hop each lap until the URL is written off- // without ever being fetched.+ it('refuses a delay longer than the largest deployed tier', async () => {const { publisher, sent } = build()- await publisher.republish(candidate(), targetOf(), 'retry', 0)-- expect(sent[0].topic).not.toBe(FRONTIER)- expect(sent[0].body.notBeforeMs).toBeGreaterThan(Date.now())+ expect(await publisher.republish(candidate(), candidate(), 'retry', 3_600_001)).toBe('refused_delay')+ expect(sent).toEqual([])})- it('sends a redirect to the frontier at once, because its target is ready', async () => {+ it('refuses a redirect that has no hop left after republishing', async () => {const { publisher, sent } = build()- await publisher.republish(candidate(), targetOf(), 'redirect')-- expect(sent[0].topic).toBe(FRONTIER)- expect(sent[0].body.notBeforeMs).toBe(0)+ expect(await publisher.republish(candidate({ remainingHops: 1 }), candidate(), 'redirect')).toBe(+ 'refused_delay'+ )+ expect(sent).toEqual([])})- it('keeps the requested wait when it is longer than every tier (requirement 15)', async () => {- // A site that names a day comes back after an hour. The record says it is not due, so the- // consumer leaves it alone rather than fetching it 23 hours early.- const { publisher, sent } = build()- const before = Date.now()-- await publisher.republish(candidate(), targetOf(), 'retry', 24 * 3_600_000)+ it('reports a failed produce without throwing', 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,+ })- expect(sent[0].body.notBeforeMs).toBeGreaterThanOrEqual(before + 24 * 3_600_000)+ await expect(publisher.republish(candidate(), candidate(), 'retry')).resolves.toBe('failed')})- it('holds a short wait for the whole period of the tier it parks in', async () => {+ it('publishes fetched bytes under the original global ref', async () => {const { publisher, sent } = build()- const before = Date.now()-- await publisher.republish(candidate(), targetOf(), 'retry', 30_000)-- expect(sent[0].body.notBeforeMs).toBeGreaterThanOrEqual(before + 60_000)- })-- it('reports a failed publish rather than throwing', async () => {- const producer = { produce: () => Promise.reject(new Error('broker down')) } as unknown as KafkaProducerWrapper- const publisher = new FrontierPublisher(producer, { frontierTopic: FRONTIER, delayTiers: TIERS })-- // One failed produce must not abandon the rest of the batch.- await expect(publisher.republish(candidate(), targetOf(), 'retry', 0)).resolves.toBe(false)+ const fetchResult = {+ outcome: 'ok',+ redirects: 0,+ currentUrl: candidate().currentUrl,+ bytes: Buffer.from('image'),+ contentType: 'image/png',+ contentEncoding: 'gzip',+ } as ImageFetchResult++ await publisher.publishImage(candidate(), fetchResult)++ expect(sent[0]).toEqual({+ topic: SCRUB,+ key: `imageurl:${'a'.repeat(22)}`,+ value: Buffer.from('image'),+ headers: { 'content-type': 'image/png', 'content-encoding': 'gzip' },+ })})})--function targetOf(): { url: string; host: string; domain: string } {- return { url: 'https://cdn.example.com/a.png', host: 'cdn.example.com', domain: 'example.com' }-}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.tsindex 25dca2d3803f..5749ee6ede25 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@@ -1,10 +1,11 @@import { KafkaProducerWrapper } from '~/common/kafka/producer'+import { ConcurrencyController } from '~/common/utils/concurrencyController'import { logger } from '~/common/utils/logger'-import { FetchCandidate } from './collected-urls-record'+import { FetchCandidate, RepublishReason, serializeFrontierRecord } from './collected-urls-record'+import type { ImageFetchResult } from './image-fetcher'import { ImageFetchRequestMetrics } from './metrics'-/** One delay topic. Every record in it waits the same period, so the records leave in the order they become ready. */export interface DelayTier {topic: stringdelayMs: number@@ -12,91 +13,98 @@ export interface DelayTier {export interface FrontierPublisherOptions {frontierTopic: string- /** Ordered by delay, shortest first, because the publisher takes the first tier that covers the wait. */+ scrubTopic: stringdelayTiers: DelayTier[]+ maxConcurrentImagePublishes: number}-export type RepublishReason = 'redirect' | 'retry' | 'not_ready'+export type RepublishResult = 'published' | 'refused_delay' | 'failed'-/**- * Sends a URL back to the frontier, at once or after a wait.- *- * Two things use this. A redirect that leaves the registrable domain cannot be followed here,- * because the budget for the new domain belongs to whichever consumer owns its partition, so the- * target goes back as a new candidate. A transient failure cannot be retried here either, because- * waiting in place holds the partition against every other site on it.- *- * Both spend a hop, so neither can go around forever. See the README, requirements 7 and 11 to 15.- */export class FrontierPublisher {+ private readonly delayTiers: DelayTier[]+ private readonly imagePublishes: ConcurrencyController+constructor(private readonly producer: KafkaProducerWrapper,private readonly options: FrontierPublisherOptions) {- if (options.delayTiers.length === 0) {- throw new Error('the image fetch lane needs at least one delay tier to retry with')+ this.delayTiers = [...options.delayTiers].sort((left, right) => left.delayMs - right.delayMs)+ if (this.delayTiers.length === 0) {+ throw new Error('the image fetch lane needs at least one delay tier')+ }+ if (!Number.isInteger(options.maxConcurrentImagePublishes) || options.maxConcurrentImagePublishes < 1) {+ throw new Error('the image fetch lane needs a positive image publish limit')}+ this.imagePublishes = new ConcurrencyController(options.maxConcurrentImagePublishes)}- /**- * The ref stays the original one. The recording points at that ref, and a hash of a redirect- * target matches nothing, so a new ref would leave the image unreachable. Requirement 10.- */public async republish(candidate: FetchCandidate,- target: { url: string; host: string; domain: string },+ target: Pick<FetchCandidate, 'currentUrl' | 'host' | 'origin' | 'registrableDomain'>,reason: RepublishReason,waitMs = 0- ): Promise<boolean> {- const hopsRemaining = candidate.hopsRemaining - 1- if (hopsRemaining <= 0) {- return false+ ): Promise<RepublishResult> {+ const spendsHop = reason === 'redirect' || reason === 'retry'+ const remainingHops = candidate.remainingHops - (spendsHop ? 1 : 0)+ if (remainingHops <= 0) {+ return 'refused_delay'}- // A retry always waits, even when nothing named a period. A timeout, a connection error,- // and a batch that ran out of time name none, and publishing those straight back to the- // frontier is a loop: the consumer reads the record, meets the same condition, and- // publishes it again, spending a hop each lap until the URL is written off unfetched. A URL- // that arrived early waits for the same reason, for a period it already knows. A redirect- // goes back at once, because its target is a different domain with its own budget.- const tier = reason === 'redirect' ? undefined : this.tierFor(Math.max(waitMs, 1))- const topic = tier?.topic ?? this.options.frontierTopic- const value = Buffer.from(- JSON.stringify({- v: 1,- pseudoTeam: candidate.pseudoTeam,- capturedAtMs: candidate.capturedAtMs,- hopsRemaining,- // The longer of the wait asked for and the period of the tier holding it. A wait- // past the longest tier arrives before it is due, and the consumer sends it back- // for the rest. Requirement 15.- notBeforeMs: tier ? Date.now() + Math.max(waitMs, tier.delayMs) : 0,- urls: [{ ref: candidate.ref, url: target.url, host: target.host }],- })- )+ 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.frontierTopictry {- await this.producer.produce({ topic, key: Buffer.from(target.domain), value })+ await this.producer.produce({+ topic,+ key: Buffer.from(target.registrableDomain),+ value: serializeFrontierRecord([republished]),+ })} catch (error) {- // Nothing throws here, because one failed produce must not abandon the rest of the- // batch. The caller counts the false return and holds the batch instead. Requirement 21.logger.warn('🌐', 'ml_image_fetch_republish_failed', {reason,topic,error: error instanceof Error ? error.name : 'unknown',})ImageFetchRequestMetrics.incRepublishFailed(reason)- return false+ return 'failed'}- ImageFetchRequestMetrics.incRepublished(reason, topic)- return true+ ImageFetchRequestMetrics.incRepublished(reason, tier ? 'delay' : 'frontier')+ return 'published'}- /**- * A wait longer than every tier comes back early, spends another hop, and waits again. That is- * cheaper than a tier long enough for the worst `Retry-After` a site can name, and the host- * budget refuses an early arrival without sending anything.- */- private tierFor(waitMs: number): DelayTier {- return this.options.delayTiers.find((tier) => tier.delayMs >= waitMs) ?? this.options.delayTiers.at(-1)!+ public async publishImage(candidate: FetchCandidate, result: ImageFetchResult): Promise<void> {+ if (!result.bytes || !result.contentType) {+ throw new Error('an image publish needs response bytes and a content type')+ }+ const bytes = result.bytes+ const headers: Record<string, string> = { 'content-type': result.contentType }+ if (result.contentEncoding) {+ headers['content-encoding'] = result.contentEncoding+ }+ await this.imagePublishes.run({+ debugTag: candidate.registrableDomain,+ fn: () =>+ this.producer.produce({+ topic: this.options.scrubTopic,+ key: Buffer.from(candidate.originalRef),+ value: bytes,+ headers,+ }),+ })}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.tsindex c3fe2178bbcb..9d229055a4ae 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.test.ts@@ -3,220 +3,244 @@ import { HostBudget, HostBudgetOptions } from './host-budget'const OPTIONS: HostBudgetOptions = {requestsPerSecond: 1,burst: 2,- maxConcurrent: 4,+ maxConcurrent: 2,breakerFailures: 3,breakerCooldownMs: 60_000,breakerMaxCooldownMs: 600_000,- maxTrackedDomains: 3,+ maxTrackedRegistrableDomains: 3,+ maxTrackedOrigins: 3,+ random: () => 1,}+const DEADLINE_MS = 1_000_000+const REGISTRABLE_DOMAIN = 'example.com'+const ORIGIN = 'https://cdn.example.com'function budget(overrides: Partial<HostBudgetOptions> = {}): HostBudget {return new HostBudget({ ...OPTIONS, ...overrides })}-const FAR_FUTURE = 10 ** 12-describe('HostBudget', () => {- it('spends the burst at once and then paces at the configured rate', () => {- const host = budget()+ it('does not reserve a token before a crawl-delay wait finishes', () => {+ const host = budget({ burst: 5 })- const grants = [0, 0, 0, 0].map(() => host.take('example.com', 1000, FAR_FUTURE))-- expect(grants).toEqual([- { granted: true, waitMs: 0 },- { granted: true, waitMs: 0 },- { granted: true, waitMs: 1000 },- { granted: true, waitMs: 2000 },- ])+ const first = host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)+ expect(first).toEqual({+ granted: true,+ waitMs: 0,+ waitScope: null,+ halfOpenProbe: false,+ reservedStartAtMs: 1_000,+ })+ host.markRequestStarted(+ REGISTRABLE_DOMAIN,+ ORIGIN,+ 1_000,+ first.granted ? first.reservedStartAtMs : null,+ 'image'+ )+ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)).toEqual({+ granted: true,+ waitMs: 1_000,+ waitScope: 'origin_crawl_delay',+ halfOpenProbe: false,+ reservedStartAtMs: null,+ })+ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)).toEqual({+ granted: true,+ waitMs: 1_000,+ waitScope: 'origin_crawl_delay',+ halfOpenProbe: false,+ reservedStartAtMs: null,+ })})- it('refuses rather than granting a slot that lands after the deadline', () => {- const host = budget()- host.take('example.com', 1000, FAR_FUTURE)- host.take('example.com', 1000, FAR_FUTURE)+ it('uses the larger robots crawl delay', () => {+ const host = budget({ burst: 5 })+ host.setCrawlDelay(ORIGIN, 4_000, 1_000)- // A grant here spends a token for a request the caller cannot send, and the next batch then- // waits that token out for nothing.- expect(host.take('example.com', 1000, 1500)).toEqual({ granted: false, reason: 'deadline' })- expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 1000 })+ const first = host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)+ host.markRequestStarted(+ REGISTRABLE_DOMAIN,+ ORIGIN,+ 1_000,+ first.granted ? first.reservedStartAtMs : null,+ 'image'+ )++ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)).toMatchObject({ waitMs: 4_000 })})- it('opens the breaker on consecutive failures and closes it when the cooldown passes', () => {- const host = budget()+ it('keeps crawl delay separate for sibling origins', () => {+ const host = budget({ burst: 5 })+ host.setCrawlDelay('https://a.example.com', 4_000, 1_000)- for (let i = 0; i < OPTIONS.breakerFailures; i++) {- host.recordBackoff('example.com', 1000)- }+ host.take(REGISTRABLE_DOMAIN, 'https://a.example.com', 1_000, DEADLINE_MS)- expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: false, reason: 'breaker_open' })- expect(host.blockedDomains(1000)).toBe(1)- expect(host.take('example.com', 1000 + OPTIONS.breakerCooldownMs + 1, FAR_FUTURE)).toMatchObject({+ expect(host.take(REGISTRABLE_DOMAIN, 'https://b.example.com', 1_000, DEADLINE_MS)).toMatchObject({granted: true,+ waitMs: 0,})})- it('doubles the cooldown for a domain that fails again after the breaker closed', () => {- const host = budget()- const openBreaker = (atMs: number): void => {- for (let i = 0; i < OPTIONS.breakerFailures; i++) {- host.recordBackoff('example.com', atMs)- }- }-- openBreaker(1000)- const reopenedAt = 1000 + OPTIONS.breakerCooldownMs + 1- openBreaker(reopenedAt)+ it('shares token capacity across sibling origins', () => {+ const host = budget({ burst: 1 })- // Still blocked one cooldown later, because the second cooldown is twice the first.- expect(host.take('example.com', reopenedAt + OPTIONS.breakerCooldownMs + 1, FAR_FUTURE)).toEqual({- granted: false,- reason: 'breaker_open',+ expect(host.take(REGISTRABLE_DOMAIN, 'https://a.example.com', 1_000, DEADLINE_MS)).toMatchObject({+ granted: true,+ waitMs: 0,+ })+ expect(host.take(REGISTRABLE_DOMAIN, 'https://b.example.com', 1_000, DEADLINE_MS)).toMatchObject({+ granted: true,+ waitMs: 1_000,})})- it.each([- ['a period the site named', 30_000, 30_000],- ['a period longer than the cap', 24 * 60 * 60 * 1000, OPTIONS.breakerMaxCooldownMs],- ])('holds the domain for %s', (_name, retryAfterMs, expectedHoldMs) => {- const host = budget()-- host.recordRetryAfter('example.com', 1000, retryAfterMs)+ it('returns a token when a reserved request cannot run', () => {+ const host = budget({ burst: 1 })+ const grant = host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)+ expect(grant.granted).toBe(true)+ host.returnGrant(REGISTRABLE_DOMAIN, ORIGIN, 1_000, grant.granted ? grant.reservedStartAtMs : null)- expect(host.take('example.com', 1000 + expectedHoldMs - 1, FAR_FUTURE)).toEqual({- granted: false,- reason: 'rate_limited',- })- expect(host.take('example.com', 1000 + expectedHoldMs + 1, FAR_FUTURE)).toMatchObject({ granted: true })+ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)).toMatchObject({ granted: true })})- it('halves the rate on a backoff and never raises it above the configured one', () => {- const host = budget({ requestsPerSecond: 4, burst: 1 })-- host.recordBackoff('example.com', 1000)- // The burst went with the halving, so even the first request waits. At 2 per second rather- // than 4, that wait is 500ms. Requirement 16.- expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 500 })- expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 1000 })+ it('applies half-to-full jitter exponential backoff and Retry-After', () => {+ const host = budget()- for (let i = 0; i < 20; i++) {- host.recordSuccess('example.com', 1000)- }- host.take('example.com', 20_000, FAR_FUTURE)- expect(host.take('example.com', 20_000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 250 })+ expect(host.recordTransientFailure(REGISTRABLE_DOMAIN, 1_000)).toBe(60_000)+ expect(host.recordTransientFailure(REGISTRABLE_DOMAIN, 1_000, 180_000)).toBe(180_000)+ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 180_999, DEADLINE_MS)).toEqual({+ granted: false,+ reason: 'backoff',+ waitMs: 1,+ })})- it('makes one failure reach the URLs already queued for the domain (requirement 16)', () => {- // Without this a site that just failed still receives the whole burst, and the cut reaches- // only the URLs behind them.- const host = budget({ requestsPerSecond: 1, burst: 5 })-- expect(host.take('example.com', 1000, FAR_FUTURE)).toEqual({ granted: true, waitMs: 0 })- host.recordBackoff('example.com', 1000)+ it('does not shorten a future block when a concurrent request succeeds', () => {+ const host = budget()+ host.recordTransientFailure(REGISTRABLE_DOMAIN, 1_000, 180_000)+ host.recordCompletedResponse(REGISTRABLE_DOMAIN, 2_000)- expect(host.take('example.com', 1000, FAR_FUTURE)).toMatchObject({ granted: true, waitMs: 2000 })+ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 2_000, DEADLINE_MS)).toEqual({+ granted: false,+ reason: 'backoff',+ waitMs: 179_000,+ })})- it('does not shorten a Retry-After hold when the breaker opens inside it', () => {+ it('opens the breaker after three consecutive transient failures', () => {const host = budget()- const anHourMs = 60 * 60 * 1000- host.recordRetryAfter('example.com', 1000, anHourMs)-- for (let i = 0; i < OPTIONS.breakerFailures; i++) {- host.recordBackoff('example.com', 1000)+ for (let failure = 0; failure < OPTIONS.breakerFailures; failure++) {+ host.recordTransientFailure(REGISTRABLE_DOMAIN, 1_000)}- // The breaker cooldown is one minute. A cooldown that replaces the hold sends us back to a- // site that asked for an hour, 59 minutes early.- expect(host.take('example.com', 1000 + OPTIONS.breakerCooldownMs + 1, FAR_FUTURE)).toEqual({+ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)).toEqual({granted: false,- reason: 'rate_limited',+ reason: 'breaker_open',+ waitMs: 240_000,})+ expect(host.blockedRegistrableDomains(1_000)).toBe(1)})- it('holds one domain to its connection limit however many callers ask', () => {- const host = budget({ maxConcurrent: 2 })-- expect(host.acquireConnection('example.com', 1000)).toBe(true)- expect(host.acquireConnection('example.com', 1000)).toBe(true)- expect(host.acquireConnection('example.com', 1000)).toBe(false)-- host.releaseConnection('example.com')+ it('applies a transient failure to sibling origins', () => {+ const host = budget()+ host.recordTransientFailure(REGISTRABLE_DOMAIN, 1_000)- expect(host.acquireConnection('example.com', 1000)).toBe(true)+ expect(host.take(REGISTRABLE_DOMAIN, 'https://other.example.com', 1_000, DEADLINE_MS)).toMatchObject({+ granted: false,+ reason: 'backoff',+ })})- it('keeps a domain holding a connection out of the eviction scan', () => {- // An eviction drops the in-flight count, and the next caller then opens one more connection- // than the limit allows.- const host = budget({ maxTrackedDomains: 2, maxConcurrent: 1 })- host.acquireConnection('busy.com', 1000)- host.take('idle.com', 1000, FAR_FUTURE)-- host.take('new.com', 1000, FAR_FUTURE)+ it('grants one half-open probe after the breaker cooldown', () => {+ const host = budget()+ for (let failure = 0; failure < OPTIONS.breakerFailures; failure++) {+ host.recordTransientFailure(REGISTRABLE_DOMAIN, 1_000)+ }+ const afterCooldownMs = 1_000 + 240_000- expect(host.acquireConnection('busy.com', 1000)).toBe(false)+ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, afterCooldownMs, DEADLINE_MS)).toEqual({+ granted: true,+ waitMs: 0,+ waitScope: null,+ halfOpenProbe: true,+ reservedStartAtMs: afterCooldownMs,+ })+ expect(host.take(REGISTRABLE_DOMAIN, 'https://other.example.com', afterCooldownMs, DEADLINE_MS)).toEqual({+ granted: false,+ reason: 'breaker_open',+ waitMs: OPTIONS.breakerCooldownMs,+ })})- it('opens the breaker on a domain that fails more often than it succeeds', () => {- // Two failures for every success never make a run of failures, so a counter that cleared on- // success leaves a mostly broken domain in retry forever.+ it('closes the breaker after the half-open probe gets a response', () => {const host = budget()-- for (let round = 0; round < 5; round++) {- host.recordBackoff('flapping.com', 1000)- host.recordBackoff('flapping.com', 1000)- host.recordSuccess('flapping.com', 1000)+ for (let failure = 0; failure < OPTIONS.breakerFailures; failure++) {+ host.recordTransientFailure(REGISTRABLE_DOMAIN, 1_000)}+ const afterCooldownMs = 1_000 + 240_000+ host.take(REGISTRABLE_DOMAIN, ORIGIN, afterCooldownMs, DEADLINE_MS)+ host.recordCompletedResponse(REGISTRABLE_DOMAIN, afterCooldownMs)- expect(host.take('flapping.com', 1000, FAR_FUTURE)).toEqual({ granted: false, reason: 'breaker_open' })+ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, afterCooldownMs, DEADLINE_MS)).toMatchObject({ granted: true })})- it('keeps reporting an open breaker when a shorter rate-limit hold arrives inside it', () => {+ it('limits concurrent connections across sibling origins', () => {const host = budget()- for (let i = 0; i < OPTIONS.breakerFailures; i++) {- host.recordBackoff('example.com', 1000)+ const origins = ['https://a.example.com', 'https://b.example.com', 'https://c.example.com']+ for (const origin of origins) {+ host.take(REGISTRABLE_DOMAIN, origin, 1_000, DEADLINE_MS)}- host.recordRetryAfter('example.com', 1000, 1_000)-- // The shed outcome and the metric carry this reason. A rename by the shorter hold hides the- // breaker from the one number that exists to show it.- expect(host.take('example.com', 2000, FAR_FUTURE)).toEqual({ granted: false, reason: 'breaker_open' })+ expect(host.acquireConnection(REGISTRABLE_DOMAIN, origins[0])).toBe(true)+ expect(host.acquireConnection(REGISTRABLE_DOMAIN, origins[1])).toBe(true)+ expect(host.acquireConnection(REGISTRABLE_DOMAIN, origins[2])).toBe(false)+ host.releaseConnection(REGISTRABLE_DOMAIN, origins[0])+ expect(host.acquireConnection(REGISTRABLE_DOMAIN, origins[2])).toBe(true)})- it('does not report a busy but unblocked domain as one whose hold it forgot', () => {- // The eviction scan skips a domain that is blocked or that has connections open. Only the- // first kind loses a hold, and the metric carries the name of that kind.- const host = budget({ maxTrackedDomains: 1, maxConcurrent: 1 })- host.acquireConnection('busy.com', 1000)-- host.take('new.com', 1000, FAR_FUTURE)+ it('does not evict an origin with a connection or scheduled request', () => {+ const host = budget({ maxTrackedRegistrableDomains: 2, maxTrackedOrigins: 2, maxConcurrent: 1 })+ host.take('busy.example', 'https://busy.example', 1_000, DEADLINE_MS)+ host.acquireConnection('busy.example', 'https://busy.example')+ host.requestScheduled('https://config.example', 1_000)+ host.take('config.example', 'https://config.example', 1_000, DEADLINE_MS, true)- expect(host.evictedWhileBlocked).toBe(0)+ expect(host.take('new.example', 'https://new.example', 1_000, DEADLINE_MS)).toEqual({+ granted: false,+ reason: 'registrable_domain_map_full',+ waitMs: 0,+ })+ expect(host.acquireConnection('busy.example', 'https://busy.example')).toBe(false)})- it('never evicts a domain holding connections, so its slots are not leaked', () => {- // A slot is released by domain name. A lost entry leaks every slot it held, and the domain- // can then hold more than its limit for the rest of the pod's life.- const host = budget({ maxTrackedDomains: 2, maxConcurrent: 1 })- expect(host.acquireConnection('busy.com', 1000)).toBe(true)+ it('evicts an idle full-budget origin', () => {+ const host = budget({ maxTrackedRegistrableDomains: 1, maxTrackedOrigins: 1 })+ const grant = host.take('idle.example', 'https://idle.example', 1_000, DEADLINE_MS)+ expect(grant.granted).toBe(true)+ host.returnGrant('idle.example', 'https://idle.example', 1_000, grant.granted ? grant.reservedStartAtMs : null)- host.take('a.com', 1000, FAR_FUTURE)- host.take('b.com', 1000, FAR_FUTURE)-- // Its entry survived the eviction, so it is still at its limit. A dropped entry would come- // back with no connections counted and let this domain hold a second one.- expect(host.acquireConnection('busy.com', 1000)).toBe(false)+ expect(host.take('new.example', 'https://new.example', 1_000, DEADLINE_MS)).toMatchObject({ granted: true })+ expect(host.trackedRegistrableDomains).toBe(1)+ expect(host.trackedOrigins).toBe(1)})- it('evicts an idle domain in preference to one it is still holding back', () => {- const host = budget({ maxTrackedDomains: 2 })- host.recordRetryAfter('blocked.com', 1000, 60_000)- host.take('idle.com', 1000, FAR_FUTURE)-- host.take('new.com', 1000, FAR_FUTURE)-- expect(host.trackedDomains).toBe(2)- expect(host.take('blocked.com', 1000, FAR_FUTURE)).toEqual({ granted: false, reason: 'rate_limited' })+ it('returns a crawl wait that extends beyond the pass deadline', () => {+ const host = budget({ burst: 5 })+ host.setCrawlDelay(ORIGIN, 600_000, 1_000)+ const first = host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, DEADLINE_MS)+ host.markRequestStarted(+ REGISTRABLE_DOMAIN,+ ORIGIN,+ 1_000,+ first.granted ? first.reservedStartAtMs : null,+ 'image'+ )++ expect(host.take(REGISTRABLE_DOMAIN, ORIGIN, 1_000, 20_000)).toEqual({+ granted: false,+ reason: 'deadline',+ waitMs: 600_000,+ })})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.tsindex beebbe247d89..d6c613c537c2 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget.ts@@ -1,305 +1,399 @@export interface HostBudgetOptions {- /** The ceiling for one registrable domain. Only a backoff moves a domain off it, and always downward. */requestsPerSecond: number- /** Tokens a domain holds while idle, so a domain seen once an hour can send a few requests together. */burst: number- /** Connections open to one domain at once. This counts them rather than the caller's worker pool, because a redirect reaches a domain without going through that pool. */maxConcurrent: numberbreakerFailures: numberbreakerCooldownMs: number- /** The longest a domain stays blocked. It bounds the doubling cooldown and a `Retry-After` header alike. */breakerMaxCooldownMs: number- maxTrackedDomains: number+ maxTrackedRegistrableDomains: number+ maxTrackedOrigins: number+ random?: () => number}+export type BudgetBlockReason =+ | 'breaker_open'+ | 'backoff'+ | 'deadline'+ | 'origin_map_full'+ | 'registrable_domain_map_full'+export type BudgetWaitScope = 'origin_crawl_delay' | 'registrable_domain_rate'export type BudgetGrant =- | { granted: true; waitMs: number }- | { granted: false; reason: 'breaker_open' | 'rate_limited' | 'deadline' }+ | {+ granted: true+ waitMs: number+ waitScope: BudgetWaitScope | null+ halfOpenProbe: boolean+ reservedStartAtMs: number | null+ }+ | { granted: false; reason: BudgetBlockReason; waitMs: number }-interface DomainState {+const EVICTION_SCAN_LIMIT = 64++interface RegistrableDomainState {inFlight: number+ pendingGrants: numbertokens: numberlastRefillMs: number- requestsPerSecond: number- failureScore: number- cooldownMs: number+ consecutiveTransientFailures: numberblockedUntilMs: number- blockedReason: 'breaker_open' | 'rate_limited'+ breakerOpen: boolean+ halfOpenProbeInFlight: boolean}-/** A domain's rate never falls below the configured rate divided by this. */-const MIN_RATE_DIVISOR = 16--/** Domains checked for an idle one before an eviction falls back to the oldest entry. */-const EVICTION_SCAN = 16+interface OriginState {+ inFlight: number+ pendingRequests: number+ lastRequestStartedAtMs: number | null+ reservedStartTimesMs: number[]+ crawlDelayMs: number+}-/**- * How fast this pod may send to one registrable domain.- *- * The domain rather than the host, because one operator can serve images from many hostnames, and a- * rate limit protects the operator. The topic uses the same key, so a domain lands on one partition- * and one pod, and this budget is then the whole rate that domain receives from this lane. A- * rebalance can put two pods on one domain for a few seconds, which doubles the rate for that long.- * No counter across pods closes that window.- *- * A restart loses this state, including an open breaker, so a restart sends one more round of- * requests to a failing site before the breaker opens again.- */export class HostBudget {- private readonly domains = new Map<string, DomainState>()+ private readonly registrableDomains = new Map<string, RegistrableDomainState>()+ private readonly origins = new Map<string, OriginState>()+ private readonly random: () => numberconstructor(private readonly options: HostBudgetOptions) {- // These values arrive from the environment, where a typo parses to NaN. A NaN rate makes- // every wait NaN and every comparison against it false, so the rate limit stops existing.for (const [name, value] of Object.entries(options)) {- if (!Number.isFinite(value) || value <= 0) {- throw new Error(`the image fetch host budget needs a positive ${name}, got ${value}`)+ if (name !== 'random' && (!Number.isFinite(value) || (value as number) <= 0)) {+ throw new Error(`the image fetch request budget needs a positive ${name}, got ${value}`)}}+ this.random = options.random ?? Math.random}- /**- * Take the right to send one request to `domain`, or learn why this pod must not send to it.- *- * A grant carries the time the caller must wait before it sends. The grant already spent the- * token, so a caller that waits keeps the rate exact, and a caller that drops the grant only- * slows the domain down. A grant that lands after `deadlineMs` is refused instead, because- * nobody sends it and the next batch still waits the token out.- */- public take(domain: string, nowMs: number, deadlineMs: number): BudgetGrant {- const state = this.stateFor(domain, nowMs)- if (state.blockedUntilMs > nowMs) {- return { granted: false, reason: state.blockedReason }- }- this.refill(state, nowMs)- const waitMs = state.tokens >= 1 ? 0 : Math.ceil(((1 - state.tokens) / state.requestsPerSecond) * 1000)+ public take(+ registrableDomain: string,+ origin: string,+ nowMs: number,+ deadlineMs: number,+ ignoreImageDelay = false+ ): BudgetGrant {+ const registrableDomainState = this.registrableDomainStateFor(registrableDomain, nowMs)+ if (!registrableDomainState) {+ return { granted: false, reason: 'registrable_domain_map_full', waitMs: 0 }+ }+ const originState = this.originStateFor(origin, nowMs)+ if (!originState) {+ return { granted: false, reason: 'origin_map_full', waitMs: 0 }+ }+ let halfOpenProbe = false+ if (!ignoreImageDelay) {+ if (registrableDomainState.blockedUntilMs > nowMs) {+ return {+ granted: false,+ reason: registrableDomainState.breakerOpen ? 'breaker_open' : 'backoff',+ waitMs: registrableDomainState.blockedUntilMs - nowMs,+ }+ }+ if (registrableDomainState.breakerOpen) {+ if (registrableDomainState.halfOpenProbeInFlight) {+ return { granted: false, reason: 'breaker_open', waitMs: this.options.breakerCooldownMs }+ }+ halfOpenProbe = true+ }+ }+ this.refill(registrableDomainState, nowMs)+ const tokenWaitMs =+ registrableDomainState.tokens >= 1+ ? 0+ : Math.ceil(((1 - registrableDomainState.tokens) / this.options.requestsPerSecond) * 1000)+ const previousStartMs = originState.lastRequestStartedAtMs ?? Number.NEGATIVE_INFINITY+ const crawlWaitMs = ignoreImageDelay ? 0 : Math.max(0, previousStartMs + originState.crawlDelayMs - nowMs)+ const waitMs = Math.max(tokenWaitMs, crawlWaitMs)+ const waitScope: BudgetWaitScope | null =+ waitMs === 0 ? null : crawlWaitMs > tokenWaitMs ? 'origin_crawl_delay' : 'registrable_domain_rate'if (nowMs + waitMs > deadlineMs) {- return { granted: false, reason: 'deadline' }+ return { granted: false, reason: 'deadline', waitMs }+ }+ if (waitMs > 0) {+ return {+ granted: true,+ waitMs,+ waitScope,+ halfOpenProbe: false,+ reservedStartAtMs: null,+ }}- state.tokens -= 1- return { granted: true, waitMs }+ if (halfOpenProbe) {+ registrableDomainState.halfOpenProbeInFlight = true+ }+ registrableDomainState.tokens -= 1+ registrableDomainState.pendingGrants += 1+ const reservedStartAtMs = ignoreImageDelay ? null : nowMs+ if (reservedStartAtMs !== null) {+ originState.reservedStartTimesMs.push(reservedStartAtMs)+ }+ return { granted: true, waitMs, waitScope, halfOpenProbe, reservedStartAtMs }}- /**- * Why this pod must not send to the domain, or null when it may.- *- * A caller that waited for a token asks again before it sends. A `Retry-After` or an open- * breaker can arrive during a wait, and a request sent after that reaches a site which just- * asked to be left alone. Requirement 5.- */- public blockedReason(domain: string, nowMs: number): 'breaker_open' | 'rate_limited' | null {- const state = this.domains.get(domain)- return state && state.blockedUntilMs > nowMs ? state.blockedReason : null+ public markRequestStarted(+ registrableDomain: string,+ origin: string,+ nowMs: number,+ reservedStartAtMs: number | null,+ requestKind: 'configuration' | 'image'+ ): void {+ const registrableDomainState = this.registrableDomains.get(registrableDomain)+ if (registrableDomainState) {+ registrableDomainState.pendingGrants = Math.max(0, registrableDomainState.pendingGrants - 1)+ }+ const originState = this.origins.get(origin)+ if (originState && requestKind === 'image') {+ this.removeReservation(originState, reservedStartAtMs)+ originState.lastRequestStartedAtMs = nowMs+ }}- /**- * How long the domain stays blocked, so a retry can wait that long rather than guess.- *- * An unknown domain reads as not blocked, and this creates no entry for it. An entry would let- * a question about one domain evict the hold on another.- */- public blockedForMs(domain: string, nowMs: number): number {- const state = this.domains.get(domain)- return state ? Math.max(0, state.blockedUntilMs - nowMs) : 0+ public blockedForMs(registrableDomain: string, nowMs: number): number {+ const state = this.registrableDomains.get(registrableDomain)+ if (!state) {+ return 0+ }+ if (state.breakerOpen && state.halfOpenProbeInFlight && state.blockedUntilMs <= nowMs) {+ return this.options.breakerCooldownMs+ }+ return Math.max(0, state.blockedUntilMs - nowMs)}- /**- * Give back a token for a request that never went out.- *- * The rate limits what leaves this pod, so a grant that went stale during its wait must not- * count against the domain. The burst caps the return, so a return cannot create capacity.- */- public returnGrant(domain: string, nowMs: number): void {- const state = this.stateFor(domain, nowMs)- state.tokens = Math.min(this.options.burst, state.tokens + 1)+ public returnGrant(+ registrableDomain: string,+ origin: string,+ nowMs: number,+ reservedStartAtMs: number | null,+ halfOpenProbe = false+ ): void {+ const originState = this.origins.get(origin)+ if (originState) {+ this.removeReservation(originState, reservedStartAtMs)+ }+ const registrableDomainState = this.registrableDomains.get(registrableDomain)+ if (!registrableDomainState) {+ return+ }+ registrableDomainState.pendingGrants = Math.max(0, registrableDomainState.pendingGrants - 1)+ this.refill(registrableDomainState, nowMs)+ registrableDomainState.tokens = Math.min(this.options.burst, registrableDomainState.tokens + 1)+ if (halfOpenProbe && registrableDomainState.breakerOpen) {+ registrableDomainState.halfOpenProbeInFlight = false+ }}- /**- * Take one of the domain's connection slots, or report that they are all taken.- *- * The rate limit and the connection limit answer different questions: how often we may start,- * and how many we may hold open. A slow site makes the second one bind, and a redirect target- * reaches this without passing through the per-domain worker pool that would otherwise bound it.- */- public acquireConnection(domain: string, nowMs: number): boolean {- const state = this.stateFor(domain, nowMs)- if (state.inFlight >= this.options.maxConcurrent) {+ public acquireConnection(registrableDomain: string, origin: string): boolean {+ const registrableDomainState = this.registrableDomains.get(registrableDomain)+ const originState = this.origins.get(origin)+ if (!registrableDomainState || !originState || registrableDomainState.inFlight >= this.options.maxConcurrent) {return false}- state.inFlight += 1+ registrableDomainState.inFlight += 1+ originState.inFlight += 1return true}- public releaseConnection(domain: string): void {- const state = this.domains.get(domain)- if (state) {- state.inFlight = Math.max(0, state.inFlight - 1)+ public releaseConnection(registrableDomain: string, origin: string): void {+ const registrableDomainState = this.registrableDomains.get(registrableDomain)+ if (registrableDomainState) {+ registrableDomainState.inFlight = Math.max(0, registrableDomainState.inFlight - 1)+ }+ const originState = this.origins.get(origin)+ if (originState) {+ originState.inFlight = Math.max(0, originState.inFlight - 1)}}- public recordSuccess(domain: string, nowMs: number): void {- const state = this.stateFor(domain, nowMs)- // Decremented rather than cleared. A domain that fails two requests for every one it answers- // never reaches a run of failures, and a counter that resets never opens its breaker.- state.failureScore = Math.max(0, state.failureScore - 1)- const step = this.options.requestsPerSecond / 8- state.requestsPerSecond = Math.min(this.options.requestsPerSecond, state.requestsPerSecond + step)- // The doubling ladder clears only once the rate is fully back, so a site that fails,- // recovers for one request, and fails again keeps escalating. It does not restart at the- // base cooldown every time.- if (state.requestsPerSecond >= this.options.requestsPerSecond) {- state.cooldownMs = 0+ public requestScheduled(origin: string, nowMs: number): boolean {+ const state = this.originStateFor(origin, nowMs)+ if (!state) {+ return false}+ state.pendingRequests += 1+ return true}- /**- * A site said it is unhappy. Halve the rate, and count toward the breaker.- *- * The rate halves on the first signal rather than after a threshold. A cut that comes too early- * costs one slower domain. A cut that comes too late adds load to a site that asked us to stop.- *- * The tokens go with it. A domain holds a burst while it is idle, so without this the URLs- * already queued behind the failed one would leave at the old rate and the cut would reach only- * the URLs after them. Requirement 16.- */- public recordBackoff(domain: string, nowMs: number): void {- const state = this.stateFor(domain, nowMs)- const floor = this.options.requestsPerSecond / MIN_RATE_DIVISOR- state.requestsPerSecond = Math.max(floor, state.requestsPerSecond / 2)- state.tokens = 0- this.countTowardBreaker(state, nowMs)+ public requestFinished(origin: string): void {+ const state = this.origins.get(origin)+ if (state) {+ state.pendingRequests = Math.max(0, state.pendingRequests - 1)+ }}- /**- * A refusal that says nothing about load, such as a 403 from an anti-bot rule.- *- * It counts toward the breaker, because a run of refusals means the site refuses this bot and- * more requests only add to that. It leaves the rate alone, because one refused image is an- * ordinary answer that must not slow down the images beside it.- */- public recordRefusal(domain: string, nowMs: number): void {- this.countTowardBreaker(this.stateFor(domain, nowMs), nowMs)+ public setCrawlDelay(origin: string, crawlDelayMs: number, nowMs: number): boolean {+ const state = this.originStateFor(origin, nowMs)+ if (!state) {+ return false+ }+ state.crawlDelayMs = Math.max(1_000, crawlDelayMs)+ return true}- private countTowardBreaker(state: DomainState, nowMs: number): void {- state.failureScore += 1- if (state.failureScore < this.options.breakerFailures) {- return+ public recordTransientFailure(registrableDomain: string, nowMs: number, retryAfterMs?: number): number {+ const state = this.registrableDomainStateFor(registrableDomain, nowMs)+ if (!state) {+ return this.options.breakerCooldownMs}- // Doubled from the last cooldown rather than reset, so a site that keeps failing after the- // breaker closes gets a longer pause each time rather than a probe on a fixed beat.- state.cooldownMs = Math.min(- state.cooldownMs > 0 ? state.cooldownMs * 2 : this.options.breakerCooldownMs,+ state.consecutiveTransientFailures += 1+ const maximumDelayMs = Math.min(+ this.options.breakerCooldownMs * 2 ** (state.consecutiveTransientFailures - 1),this.options.breakerMaxCooldownMs)- // Extended rather than replaced. A breaker that opens inside an hour-long hold must not- // shorten that hold to its own cooldown.- const openUntilMs = nowMs + state.cooldownMs- if (openUntilMs > state.blockedUntilMs) {- state.blockedUntilMs = openUntilMs- state.blockedReason = 'breaker_open'- }- state.failureScore = 0+ const minimumDelayMs = Math.ceil(maximumDelayMs / 2)+ const jitteredDelayMs = Math.min(+ maximumDelayMs,+ minimumDelayMs + Math.floor(this.random() * (maximumDelayMs - minimumDelayMs + 1))+ )+ const delayMs = Math.max(jitteredDelayMs, retryAfterMs ?? 0)+ state.blockedUntilMs = Math.max(state.blockedUntilMs, nowMs + delayMs)+ if (state.consecutiveTransientFailures >= this.options.breakerFailures) {+ state.breakerOpen = true+ state.halfOpenProbeInFlight = false+ }+ return delayMs}- /**- * Hold the domain for the period a `Retry-After` header asked for.- *- * The clamp is necessary because a site can name any period, and an unclamped one holds a- * domain in this pod's memory for as long as the pod lives.- */- public recordRetryAfter(domain: string, nowMs: number, retryAfterMs: number): void {- const state = this.stateFor(domain, nowMs)- const held = Math.min(Math.max(retryAfterMs, 0), this.options.breakerMaxCooldownMs)- // The reason moves only when this hold wins. A domain already held by an open breaker would- // otherwise report every later shed as a rate limit, which hides the breaker from the- // metric that exists to show it.- if (nowMs + held > state.blockedUntilMs) {- state.blockedUntilMs = nowMs + held- state.blockedReason = 'rate_limited'+ public recordCompletedResponse(registrableDomain: string, nowMs: number): void {+ const state = this.registrableDomains.get(registrableDomain)+ if (!state) {+ return}+ state.consecutiveTransientFailures = 0+ state.blockedUntilMs = Math.max(state.blockedUntilMs, nowMs)+ state.breakerOpen = false+ state.halfOpenProbeInFlight = false+ }++ public get trackedRegistrableDomains(): number {+ return this.registrableDomains.size}- public get trackedDomains(): number {- return this.domains.size+ public get trackedOrigins(): number {+ return this.origins.size}- /** Domains this dropped while they were still blocked, which resumes traffic to a site that asked us to wait. */public evictedWhileBlocked = 0- public blockedDomains(nowMs: number): number {+ public blockedRegistrableDomains(nowMs: number): number {let blocked = 0- for (const state of this.domains.values()) {- if (state.blockedUntilMs > nowMs) {- blocked+++ for (const state of this.registrableDomains.values()) {+ if (state.blockedUntilMs > nowMs || state.breakerOpen) {+ blocked += 1}}return blocked}- private refill(state: DomainState, nowMs: number): void {+ private refill(state: RegistrableDomainState, nowMs: number): void {const elapsedMs = Math.max(0, nowMs - state.lastRefillMs)state.lastRefillMs = nowMs- state.tokens = Math.min(this.options.burst, state.tokens + (elapsedMs / 1000) * state.requestsPerSecond)+ state.tokens = Math.min(this.options.burst, state.tokens + (elapsedMs / 1000) * this.options.requestsPerSecond)}- private stateFor(domain: string, nowMs: number): DomainState {- const existing = this.domains.get(domain)+ private registrableDomainStateFor(registrableDomain: string, nowMs: number): RegistrableDomainState | undefined {+ const existing = this.registrableDomains.get(registrableDomain)if (existing) {- // Re-inserted so that the map orders by last use, which the eviction below reads.- this.domains.delete(domain)- this.domains.set(domain, existing)+ this.registrableDomains.delete(registrableDomain)+ this.registrableDomains.set(registrableDomain, existing)return existing}- this.evictIfFull(nowMs)- const state: DomainState = {+ if (!this.evictRegistrableDomainIfFull(nowMs)) {+ return undefined+ }+ const state: RegistrableDomainState = {inFlight: 0,+ pendingGrants: 0,tokens: this.options.burst,lastRefillMs: nowMs,- requestsPerSecond: this.options.requestsPerSecond,- failureScore: 0,- cooldownMs: 0,+ consecutiveTransientFailures: 0,blockedUntilMs: 0,- blockedReason: 'breaker_open',+ breakerOpen: false,+ halfOpenProbeInFlight: false,}- this.domains.set(domain, state)+ this.registrableDomains.set(registrableDomain, state)return state}- /**- * An evicted domain loses its block, so the scan prefers an idle domain. When the map holds- * only blocked domains the oldest one goes anyway, because a refusal to evict grows the map- * without a bound and the memory limit is the harder failure.- */- private evictIfFull(nowMs: number): void {- if (this.domains.size < this.options.maxTrackedDomains) {- return+ private originStateFor(origin: string, nowMs: number): OriginState | undefined {+ const existing = this.origins.get(origin)+ if (existing) {+ this.origins.delete(origin)+ this.origins.set(origin, existing)+ return existing}- let oldest: string | undefined- let scanned = 0- for (const [domain, state] of this.domains) {- if (state.inFlight > 0) {- // Never evicted. A slot is released by domain name, so a lost entry leaks every- // slot it held and the domain can then hold more than its limit. The map cannot- // grow without a bound this way, because the pod caps its requests in flight.- continue- }- oldest = oldest ?? domain- if (state.blockedUntilMs <= nowMs) {- this.domains.delete(domain)- return+ if (!this.evictOriginIfFull(nowMs)) {+ return undefined+ }+ const state: OriginState = {+ inFlight: 0,+ pendingRequests: 0,+ lastRequestStartedAtMs: null,+ reservedStartTimesMs: [],+ crawlDelayMs: 1_000,+ }+ this.origins.set(origin, state)+ return state+ }++ private evictRegistrableDomainIfFull(nowMs: number): boolean {+ if (this.registrableDomains.size < this.options.maxTrackedRegistrableDomains) {+ return true+ }+ for (let scanned = 0; scanned < EVICTION_SCAN_LIMIT; scanned++) {+ const oldest = this.registrableDomains.entries().next().value as+ | [string, RegistrableDomainState]+ | undefined+ if (!oldest) {+ return true}- if (++scanned >= EVICTION_SCAN) {- break+ const [registrableDomain, state] = oldest+ this.refill(state, nowMs)+ const eligible =+ state.inFlight === 0 &&+ state.pendingGrants === 0 &&+ state.blockedUntilMs <= nowMs &&+ !state.breakerOpen &&+ !state.halfOpenProbeInFlight &&+ state.tokens >= this.options.burst+ if (eligible) {+ this.registrableDomains.delete(registrableDomain)+ return true}+ this.registrableDomains.delete(registrableDomain)+ this.registrableDomains.set(registrableDomain, state)+ }+ return false+ }++ private evictOriginIfFull(nowMs: number): boolean {+ if (this.origins.size < this.options.maxTrackedOrigins) {+ return true}- if (oldest) {- // Counted only when the entry really was blocked.- const evicted = this.domains.get(oldest)- this.domains.delete(oldest)- if (evicted && evicted.blockedUntilMs > nowMs) {- this.evictedWhileBlocked+++ for (let scanned = 0; scanned < EVICTION_SCAN_LIMIT; scanned++) {+ const oldest = this.origins.entries().next().value as [string, OriginState] | undefined+ if (!oldest) {+ return true+ }+ const [origin, state] = oldest+ const eligible =+ state.inFlight === 0 &&+ state.pendingRequests === 0 &&+ state.reservedStartTimesMs.length === 0 &&+ (state.lastRequestStartedAtMs === null || state.lastRequestStartedAtMs + state.crawlDelayMs <= nowMs)+ if (eligible) {+ this.origins.delete(origin)+ return true}+ this.origins.delete(origin)+ this.origins.set(origin, state)+ }+ return false+ }++ private removeReservation(state: OriginState, reservedStartAtMs: number | null): void {+ if (reservedStartAtMs === null) {+ return+ }+ const index = state.reservedStartTimesMs.indexOf(reservedStartAtMs)+ if (index >= 0) {+ state.reservedStartTimesMs.splice(index, 1)}}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.tsindex d121b3bd4032..988434a90097 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts@@ -17,8 +17,10 @@ const OPTIONS: ImageFetchOptions = {maxBytes: 1000,timeoutMs: 5000,maxRedirects: 3,- isOffsite: () => false,- authorizeRedirect: () => Promise.resolve('allow' as const),+ isDifferentOrigin: () => false,+ scheduleRequest: async (_url, _deadlineMs, request) => ({ ran: true as const, value: await request() }),+ checkRedirectPolicy: () => Promise.resolve({ allowed: true as const, tdmrepReservation: false }),+ tdmrepReservation: false,}function respond(@@ -29,6 +31,7 @@ function respond(return {status,headers,+ headerLines: Object.entries(headers).map(([name, value]) => ({ name, value })),read: jest.fn().mockResolvedValue(body),discard: jest.fn(),}@@ -72,20 +75,68 @@ describe('HttpImageFetcher', () => {const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)- expect(result).toEqual({ outcome: 'ok', status: 200, bytes: PNG, contentType: 'image/png', redirects: 0 })+ expect(result).toMatchObject({+ outcome: 'ok',+ status: 200,+ bytes: PNG,+ contentType: 'image/png',+ redirects: 0,+ currentUrl: 'https://cdn.example.com/a.png',+ })+ })++ it('uses an ETag validator and accepts the resulting 304', async () => {+ fetchStreamedMock.mockResolvedValue(respond(304, { etag: '"v1"' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ cache: {+ requestTimeMs: Date.now() - 1_000,+ responseTimeMs: Date.now() - 500,+ etag: '"v1"',+ lastModified: 'yesterday',+ },+ })++ expect(fetchStreamedMock.mock.calls[0][1].headers).toMatchObject({ 'if-none-match': '"v1"' })+ expect(fetchStreamedMock.mock.calls[0][1].headers).not.toHaveProperty('if-modified-since')+ expect(result).toMatchObject({ outcome: 'not_modified', status: 304 })+ })++ it('does not accept an unsolicited 304', async () => {+ fetchStreamedMock.mockResolvedValue(respond(304, {}))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'unexpected_status', status: 304 })+ })++ it('does not send an original URL validator to a redirect target', async () => {+ fetchStreamedMock+ .mockResolvedValueOnce(respond(302, { location: '/moved.png' }))+ .mockResolvedValueOnce(image(PNG, 'image/png'))++ await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ cache: { requestTimeMs: Date.now() - 1_000, responseTimeMs: Date.now() - 500, etag: '"v1"' },+ })++ expect(fetchStreamedMock.mock.calls[0][1].headers).toMatchObject({ 'if-none-match': '"v1"' })+ expect(fetchStreamedMock.mock.calls[1][1].headers).not.toHaveProperty('if-none-match')})it.each([- ['a type that is not an image', 'text/html', PNG],- ['a type outside the raster set', 'image/svg+xml', PNG],- ['a payload that is not the declared format', 'image/gif', PNG],- ['a payload of the wrong raster format', 'image/png', GIF],- ])('refuses %s', async (_name, contentType, bytes) => {+ ['a type that is not an image', 'text/html', PNG, 'not_image'],+ ['a type outside the raster set', 'image/svg+xml', PNG, 'not_image'],+ ['the BMP format', 'image/bmp', Buffer.from('BM'), 'not_image'],+ ['a payload that is not the declared format', 'image/gif', PNG, 'ok'],+ ['a payload of the wrong raster format', 'image/png', GIF, 'ok'],+ ])('handles %s', async (_name, contentType, bytes, outcome) => {fetchStreamedMock.mockResolvedValue(image(bytes, contentType))const result = await fetcher().fetch('https://cdn.example.com/a', OPTIONS)- expect(result).toMatchObject({ outcome: 'not_image' })+ expect(result).toMatchObject({ outcome })})it('refuses a declared size over the limit without reading the body', async () => {@@ -139,6 +190,29 @@ describe('HttpImageFetcher', () => {expect(result.retryAfterMs).toBeLessThanOrEqual(expectedMs)})+ it('uses the longest valid value from repeated Retry-After field lines', async () => {+ const response = respond(429, {})+ response.headerLines = [+ { name: 'retry-after', value: '10' },+ { name: 'retry-after', value: 'invalid' },+ { name: 'retry-after', value: '30' },+ ]+ fetchStreamedMock.mockResolvedValue(response)++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result.retryAfterMs).toBe(30_000)+ })++ it.each([408, 425])('ignores Retry-After on status %s', async (status) => {+ fetchStreamedMock.mockResolvedValue(respond(status, { 'retry-after': '120' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'rate_limited', status })+ expect(result.retryAfterMs).toBeUndefined()+ })+it('follows a redirect and reports how many hops it took', async () => {fetchStreamedMock.mockResolvedValueOnce(respond(302, { location: '/moved.png' }))@@ -150,6 +224,20 @@ describe('HttpImageFetcher', () => {expect(fetchStreamedMock.mock.calls[1][0]).toBe('https://cdn.example.com/moved.png')})+ it('refuses a redirect with repeated Location field lines', async () => {+ const response = respond(302, {})+ response.headerLines = [+ { name: 'location', value: '/first.png' },+ { name: 'location', value: '/second.png' },+ ]+ fetchStreamedMock.mockResolvedValue(response)++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'bad_redirect' })+ expect(fetchStreamedMock).toHaveBeenCalledTimes(1)+ })+it('signs each redirect hop for its target URL', async () => {fetchStreamedMock.mockResolvedValueOnce(respond(302, { location: 'https://images.example.net/moved.png' }))@@ -170,17 +258,13 @@ describe('HttpImageFetcher', () => {})it.each([- ['the target is one this lane never follows', 'https://other.example/a.png', 'refuse' as const],- ['it leaves HTTP for another scheme', 'javascript:alert(1)', 'allow' as const],- ['it carries credentials for the next hop', 'https://user:[email protected]/a.png', 'allow' as const],- ['it downgrades from HTTPS to plain HTTP', 'http://other.example/a.png', 'allow' as const],- ])('refuses a redirect when %s', async (_name, location, decision) => {+ ['it leaves HTTP for another scheme', 'javascript:alert(1)'],+ ['it carries credentials for the next hop', 'https://user:[email protected]/a.png'],+ ['it downgrades from HTTPS to plain HTTP', 'http://other.example/a.png'],+ ])('refuses a redirect when %s', async (_name, location) => {fetchStreamedMock.mockResolvedValue(respond(302, { location }))- const result = await fetcher().fetch('https://cdn.example.com/a.png', {- ...OPTIONS,- authorizeRedirect: () => Promise.resolve(decision),- })+ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)expect(result).toMatchObject({ outcome: 'bad_redirect' })expect(fetchStreamedMock).toHaveBeenCalledTimes(1)@@ -222,7 +306,7 @@ describe('HttpImageFetcher', () => {const result = await fetcher().fetch('https://cdn.example.com/a.png', {...OPTIONS,maxRedirects: 0,- isOffsite: () => true,+ isDifferentOrigin: () => true,})expect(result).toMatchObject({@@ -231,12 +315,15 @@ describe('HttpImageFetcher', () => {})})- it('stops at the redirect limit for a target on the same domain', async () => {+ it('stops at the redirect limit for a target on the same origin', async () => {fetchStreamedMock.mockResolvedValue(respond(302, { location: 'https://cdn.example.com/b.png' }))const result = await fetcher().fetch('https://cdn.example.com/a.png', { ...OPTIONS, maxRedirects: 0 })- expect(result).toMatchObject({ outcome: 'too_many_redirects' })+ expect(result).toMatchObject({+ outcome: 'redirect_continuation',+ redirectTarget: { url: 'https://cdn.example.com/b.png', host: 'cdn.example.com' },+ })})it('defers a redirect whose target has no budget left, so nothing is written to the crawl history for it', async () => {@@ -245,73 +332,237 @@ describe('HttpImageFetcher', () => {// the URL.fetchStreamedMock.mockResolvedValue(respond(302, { location: 'https://cdn.example.net/a.png' }))+ let requestNumber = 0const result = await fetcher().fetch('https://cdn.example.com/a.png', {...OPTIONS,- authorizeRedirect: () => Promise.resolve('defer' as const),+ scheduleRequest: async (_url, _deadlineMs, request) => {+ requestNumber += 1+ return requestNumber === 1+ ? { ran: true as const, value: await request() }+ : { ran: false as const, reason: 'backoff' as const, waitMs: 90_000 }+ },})- expect(result).toMatchObject({ outcome: 'redirect_deferred' })+ expect(result).toMatchObject({+ outcome: 'request_deferred',+ redirects: 1,+ currentUrl: 'https://cdn.example.net/a.png',+ schedulingReason: 'backoff',+ schedulingWaitMs: 90_000,+ })+ expect(fetchStreamedMock).toHaveBeenCalledTimes(1)})- it('refuses a response that arrives compressed, under its own outcome', async () => {- // The byte limit counts bytes on the wire, and a compressed body expands past it. The image- // may be perfectly good, so the lane must not report it, or record it, as "not an image".+ it('keeps an accepted response coding for the scrubber', async () => {fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png', { 'content-encoding': 'gzip' }))const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)+ expect(result).toMatchObject({ outcome: 'ok', contentEncoding: 'gzip' })+ })++ it('keeps repeated content codings in received order', async () => {+ const response = image(PNG, 'image/png')+ response.headerLines = [+ { name: 'content-type', value: 'image/png' },+ { name: 'content-encoding', value: 'gzip' },+ { name: 'content-encoding', value: 'br, zstd' },+ ]+ fetchStreamedMock.mockResolvedValue(response)++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'ok', contentEncoding: 'gzip, br, zstd' })+ })++ it('refuses conflicting repeated Content-Type field lines', async () => {+ const response = image(PNG, 'image/png')+ response.headerLines = [+ { name: 'content-type', value: 'image/png' },+ { name: 'content-type', value: 'image/jpeg' },+ ]+ fetchStreamedMock.mockResolvedValue(response)++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'not_image' })+ })++ it('combines repeated Cache-Control field lines in received order', async () => {+ const response = image(PNG, 'image/png')+ response.headerLines.push(+ { name: 'cache-control', value: 'public, max-age=86400' },+ { name: 'cache-control', value: 'no-store' }+ )+ fetchStreamedMock.mockResolvedValue(response)++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result.cache?.cacheControl).toBe('public, max-age=86400, no-store')+ })++ it('refuses an unsupported response coding', async () => {+ fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png', { 'content-encoding': 'compress' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)+expect(result).toMatchObject({ outcome: 'unsupported_encoding' })})- it('defers a redirect whose politeness wait would outlive the request', async () => {- // The wait comes out of this request's clock. A wait that cannot land would report the site- // as slow when our own budget ran out.- fetchStreamedMock.mockResolvedValue(respond(302, { location: '/moved.png' }))- const authorizeRedirect = jest.fn().mockResolvedValue('allow')+ it.each(['gzip,', 'gzip, br, deflate, zstd, identity'])(+ 'refuses a malformed or excessive response coding list: %s',+ async (contentEncoding) => {+ fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png', { 'content-encoding': contentEncoding }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'unsupported_encoding' })+ }+ )++ it('applies a refusal from any repeated opt-out field line', async () => {+ const response = image(PNG, 'image/png')+ response.headerLines = [+ { name: 'content-type', value: 'image/png' },+ { name: 'x-robots-tag', value: 'all' },+ { name: 'x-robots-tag', value: 'PostHogImageFetcherBot: noimageai' },+ ]+ fetchStreamedMock.mockResolvedValue(response)++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)++ expect(result).toMatchObject({ outcome: 'opt_out', refusalReason: 'x_robots_tag' })+ })++ it('lets a response header override a TDMRep reservation', async () => {+ fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png', { 'tdm-reservation': '0' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ tdmrepReservation: true,+ })++ expect(result).toMatchObject({ outcome: 'ok' })+ })++ it('applies a TDMRep reservation when the response does not override it', async () => {+ fetchStreamedMock.mockResolvedValue(image(PNG, 'image/png'))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ tdmrepReservation: true,+ })++ expect(result).toMatchObject({ outcome: 'opt_out', refusalReason: 'tdm_reservation' })+ })++ it('checks path policy again before a same-origin redirect target is requested', async () => {+ fetchStreamedMock.mockResolvedValue(respond(302, { location: '/private/image.png' }))- await fetcher().fetch('https://cdn.example.com/a.png', { ...OPTIONS, authorizeRedirect })+ const result = await fetcher().fetch('https://cdn.example.com/public/image.png', {+ ...OPTIONS,+ checkRedirectPolicy: () =>+ Promise.resolve({ allowed: false as const, transient: false, reason: 'robots_disallow' }),+ })- const remainingMs = authorizeRedirect.mock.calls[0][1]- expect(remainingMs).toBeGreaterThan(0)- expect(remainingMs).toBeLessThanOrEqual(OPTIONS.timeoutMs)+ expect(result).toMatchObject({+ outcome: 'redirect_policy_refused',+ redirects: 1,+ currentUrl: 'https://cdn.example.com/private/image.png',+ refusalReason: 'robots_disallow',+ policyTransient: false,+ })+ expect(fetchStreamedMock).toHaveBeenCalledTimes(1)+ })++ it('applies the redirected path TDM policy to the next response', async () => {+ fetchStreamedMock+ .mockResolvedValueOnce(respond(302, { location: '/reserved/image.png' }))+ .mockResolvedValueOnce(image(PNG, 'image/png'))++ const result = await fetcher().fetch('https://cdn.example.com/public/image.png', {+ ...OPTIONS,+ checkRedirectPolicy: () => Promise.resolve({ allowed: true as const, tdmrepReservation: true }),+ })++ expect(result).toMatchObject({ outcome: 'opt_out', refusalReason: 'tdm_reservation', redirects: 1 })+ })++ it('uses one request deadline for every redirect hop', async () => {+ fetchStreamedMock+ .mockResolvedValueOnce(respond(302, { location: '/moved.png' }))+ .mockResolvedValueOnce(image(PNG, 'image/png'))+ const deadlines: number[] = []++ await fetcher().fetch('https://cdn.example.com/a.png', {+ ...OPTIONS,+ scheduleRequest: async (_url, deadlineMs, request) => {+ deadlines.push(deadlineMs)+ return { ran: true as const, value: await request() }+ },+ })++ expect(deadlines).toHaveLength(2)+ expect(new Set(deadlines).size).toBe(1)+ expect(deadlines[0] - Date.now()).toBeGreaterThan(0)+ expect(deadlines[0] - Date.now()).toBeLessThanOrEqual(OPTIONS.timeoutMs)})it('gives up on a redirect chain longer than the limit', async () => {fetchStreamedMock.mockResolvedValue(respond(302, { location: '/again.png' }))- const authorizeRedirect = jest.fn().mockResolvedValue('allow')+ let scheduledRequests = 0const result = await fetcher().fetch('https://cdn.example.com/a.png', {...OPTIONS,maxRedirects: 2,- authorizeRedirect,+ scheduleRequest: async (_url, _deadlineMs, request) => {+ scheduledRequests += 1+ return { ran: true as const, value: await request() }+ },})- expect(result).toEqual({ outcome: 'too_many_redirects', redirects: 2, status: 302 })+ expect(result).toMatchObject({+ outcome: 'redirect_continuation',+ redirects: 2,+ status: 302,+ redirectTarget: { url: 'https://cdn.example.com/again.png' },+ })// Three requests carry two redirects. The third response is read and refused, and the// budget of whatever it points at is never asked for a token.expect(fetchStreamedMock).toHaveBeenCalledTimes(3)- expect(authorizeRedirect).toHaveBeenCalledTimes(2)+ expect(scheduledRequests).toBe(3)})- it('reports a redirect authorizer that threw rather than letting it escape', async () => {- // The authorizer reaches into the host budget, which the fetcher does not own. A throw there- // would leave the sibling domains of the batch running while the partition replayed them.- fetchStreamedMock.mockResolvedValue(respond(302, { location: '/moved.png' }))-+ it('reports a request scheduler that threw rather than letting it escape', async () => {const result = await fetcher().fetch('https://cdn.example.com/a.png', {...OPTIONS,- authorizeRedirect: () => Promise.reject(new Error('budget exploded')),+ scheduleRequest: () => Promise.reject(new Error('budget exploded')),+ })++ expect(result).toEqual({+ outcome: 'error',+ redirects: 0,+ currentUrl: 'https://cdn.example.com/a.png',})+ })++ it('accepts a Retry-After period of zero as a non-negative integer', async () => {+ fetchStreamedMock.mockResolvedValue(respond(429, { 'retry-after': '0' }))++ const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)- expect(result).toEqual({ outcome: 'error', redirects: 0 })+ expect(result.retryAfterMs).toBe(0)})it.each([- ['a period of zero', '0'],['a negative period', '-5'],+ ['a decimal period', '1.5'],+ ['an exponent', '1e3'],+ ['a signed period', '+5'],+ ['an unsafe period', '9007199254740991'],['whitespace', ' '],['a date already past', new Date(Date.now() - 60_000).toUTCString()],- ])('reports no Retry-After period for %s, so the caller applies its own default', async (_name, header) => {+ ])('reports no Retry-After period for %s, so exponential backoff has no minimum', async (_name, header) => {fetchStreamedMock.mockResolvedValue(respond(429, { 'retry-after': header }))const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)@@ -329,6 +580,6 @@ describe('HttpImageFetcher', () => {const result = await fetcher().fetch('https://cdn.example.com/a.png', OPTIONS)- expect(result).toEqual({ outcome, redirects: 0 })+ expect(result).toMatchObject({ outcome, redirects: 0, currentUrl: 'https://cdn.example.com/a.png' })})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.tsindex 8b8f4b88f485..b3aea833d0f3 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts@@ -1,15 +1,18 @@import { InvalidRequestError, ResolutionError, SecureRequestError, fetchStreamed } from '~/common/utils/request'+import { OriginPolicyReason, ResponseOptOutReason, responseOptOutReason } from './configuration-policy'+import { HttpCacheMetadata } from './crawl-history'+import { ImageFetchRequestMetrics } from './metrics'+import { canonicalizeUrl } from './politeness-key'import { WebBotAuthRequestSigner } from './web-bot-auth'/**- * The raster set the anonymizer keeps on a collected ref, so a fetched image and an inline one reach- * the scrub lane as the same kind of thing.+ * The raster formats that the fetch lane and image scrubber accept.** SVG is absent on purpose. It is a text format that can carry the page's own data, so its redaction* belongs on the inline path rather than on an image model.*/-const ALLOWED_CONTENT_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/avif'] as const+const ALLOWED_CONTENT_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif'] as constexport type ImageContentType = (typeof ALLOWED_CONTENT_TYPES)[number]@@ -20,25 +23,38 @@ export type FetchOutcome =| 'rate_limited'| 'server_error'| 'unexpected_status'- | 'too_many_redirects'| 'bad_redirect'- | 'redirect_deferred'+ | 'request_deferred'+ | 'redirect_policy_refused'| 'redirect_offsite'+ | 'redirect_continuation'| 'too_large'| 'not_image'| 'unsupported_encoding'| 'blocked'+ | 'opt_out'+ | 'not_modified'| 'timeout'| 'error'+export type TransientFetchOutcome = Extract<FetchOutcome, 'timeout' | 'error' | 'rate_limited' | 'server_error'>+export type FetchRefusalReason = OriginPolicyReason | ResponseOptOutReason | 'configuration_refused'+export interface ImageFetchResult {outcome: FetchOutcomeredirects: number+ currentUrl: stringstatus?: numberbytes?: BuffercontentType?: ImageContentType- /** Set by a 429 or a 503 that named a period. The caller holds the whole domain for that period. */+ contentEncoding?: string+ cache?: HttpCacheMetadata+ refusalReason?: FetchRefusalReason+ /** Set by a 429 or a 503 that named a period. The caller holds the registrable domain for that period. */retryAfterMs?: number+ schedulingReason?: RequestScheduleBlockReason+ schedulingWaitMs?: number+ policyTransient?: boolean/** Where a redirect this lane did not follow points. The caller republishes it rather than fetching it. */redirectTarget?: { url: string; host: string }}@@ -48,30 +64,29 @@ export interface ImageFetchOptions {/** Covers the redirect chain as a whole, so a chain of slow hops cannot outlive one hop's budget. */timeoutMs: numbermaxRedirects: number- /**- * The fetch asks this for every redirect target it will follow, so each hop spends a token.- *- * `remainingMs` is what is left of this request, so a wait longer than that must `defer`.- *- * A `defer` must not read as a `refuse`, because the caller writes a refusal to the crawl- * history and writes nothing for a deferral.- */- authorizeRedirect: (url: URL, remainingMs: number) => Promise<RedirectDecision>- /**- * True when the target belongs to another operator, so this fetch must not follow it.- *- * The fetch asks this before it applies the redirect limit, and the question spends nothing. The- * limit bounds the hops this request follows itself. Nobody here follows a target for another- * operator, so it goes back to Kafka and costs one hop instead. Requirement 7.- */- isOffsite: (url: URL) => boolean+ scheduleRequest: <T>(+ url: URL,+ deadlineMs: number,+ request: () => Promise<T>+ ) => Promise<{ ran: true; value: T } | { ran: false; reason: RequestScheduleBlockReason; waitMs: number }>+ checkRedirectPolicy: (url: string) => Promise<RedirectTargetPolicy>+ isDifferentOrigin: (url: URL) => boolean+ cache?: HttpCacheMetadata+ tdmrepReservation: boolean+ onRedirectResponse?: () => void}-/**- * `allow` follows the target here. `defer` means the budget is spent or the breaker is open.- * `refuse` means this lane will never follow the target.- */-export type RedirectDecision = 'allow' | 'refuse' | 'defer'+export type RequestScheduleBlockReason =+ | 'breaker_open'+ | 'backoff'+ | 'deadline'+ | 'origin_map_full'+ | 'registrable_domain_map_full'+ | 'connection_limit'++export type RedirectTargetPolicy =+ | { allowed: true; tdmrepReservation: boolean }+ | { allowed: false; transient: boolean; reason: OriginPolicyReason | 'configuration_refused' }export interface ImageFetcher {fetch(url: string, options: ImageFetchOptions): Promise<ImageFetchResult>@@ -82,9 +97,7 @@ const USER_AGENT = 'PostHogImageFetcherBot/1.0 (+https://posthog.com/docs/ai-resconst REQUEST_HEADERS: Record<string, string> = {'user-agent': USER_AGENT,accept: 'image/*',- // Every type this lane accepts is compressed already, so gzip saves the origin almost nothing,- // and the byte limit can count what arrives rather than what a decoder would produce from it.- 'accept-encoding': 'identity',+ 'accept-encoding': 'gzip, deflate, br, zstd',}const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])@@ -106,119 +119,186 @@ export class HttpImageFetcher implements ImageFetcher {public async fetch(url: string, options: ImageFetchOptions): Promise<ImageFetchResult> {const deadlineMs = Date.now() + options.timeoutMslet target = url+ let currentCache = options.cache+ let tdmrepReservation = options.tdmrepReservationfor (let redirects = 0; ; redirects++) {const remainingMs = deadlineMs - Date.now()if (remainingMs <= 0) {- return { outcome: 'timeout', redirects }+ return { outcome: 'timeout', redirects, currentUrl: target }}- let hop: HopResult+ let scheduled:+ | { ran: true; value: HopResult }+ | { ran: false; reason: RequestScheduleBlockReason; waitMs: number }try {- hop = await this.hop(target, remainingMs, options.maxBytes)+ scheduled = await options.scheduleRequest(new URL(target), deadlineMs, () =>+ this.hop(+ target,+ Math.max(1, deadlineMs - Date.now()),+ options.maxBytes,+ currentCache,+ tdmrepReservation+ )+ )} catch (error) {- return { outcome: classifyError(error), redirects }+ return { outcome: classifyError(error), redirects, currentUrl: target }}+ if (!scheduled.ran) {+ return {+ outcome: 'request_deferred',+ redirects,+ currentUrl: target,+ schedulingReason: scheduled.reason,+ schedulingWaitMs: scheduled.waitMs,+ }+ }+ const hop = scheduled.valueif (hop.kind !== 'redirect') {- return { ...hop.result, redirects }+ return { ...hop.result, redirects, currentUrl: target }}const next = resolveRedirect(target, hop.location, this.policy)if (!next) {- return { outcome: 'bad_redirect', redirects, status: hop.status }+ return { outcome: 'bad_redirect', redirects, currentUrl: target, status: hop.status }}- if (options.isOffsite(next)) {- // The budget, the breaker, and the connection count for that domain belong to the- // consumer that owns its partition.+ options.onRedirectResponse?.()+ if (options.isDifferentOrigin(next)) {return {outcome: 'redirect_offsite',redirects,+ currentUrl: target,status: hop.status,redirectTarget: { url: next.toString(), host: next.hostname },}}- // After the offsite test and before authorization, so a hop this lane refuses spends no- // token from the budget of the site it would have landed on.if (redirects >= options.maxRedirects) {- return { outcome: 'too_many_redirects', redirects, status: hop.status }- }- let decision: RedirectDecision- try {- decision = await options.authorizeRedirect(next, deadlineMs - Date.now())- } catch (error) {- return { outcome: classifyError(error), redirects }+ return {+ outcome: 'redirect_continuation',+ redirects,+ currentUrl: target,+ status: hop.status,+ redirectTarget: { url: next.toString(), host: next.hostname },+ cache: hop.cache,+ }}- if (decision !== 'allow') {- const outcome = decision === 'defer' ? 'redirect_deferred' : 'bad_redirect'- return { outcome, redirects, status: hop.status }+ const redirectPolicy = await options.checkRedirectPolicy(next.toString())+ if (!redirectPolicy.allowed) {+ return {+ outcome: 'redirect_policy_refused',+ redirects: redirects + 1,+ currentUrl: next.toString(),+ status: hop.status,+ refusalReason: redirectPolicy.reason,+ policyTransient: redirectPolicy.transient,+ cache: hop.cache,+ }}target = next.toString()+ currentCache = undefined+ tdmrepReservation = redirectPolicy.tdmrepReservation}}- private async hop(url: string, timeoutMs: number, maxBytes: number): Promise<HopResult> {- const headers = { ...REQUEST_HEADERS, ...this.webBotAuthSigner.headersForGet(url) }- const response = await fetchStreamed(url, { headers, timeoutMs })- const status = response.status-- if (REDIRECT_STATUSES.has(status)) {- response.discard()- const location = response.headers['location']- return location- ? { kind: 'redirect', status, location }- : { kind: 'done', result: { outcome: 'bad_redirect', status } }- }- if (status !== 200) {- response.discard()- return { kind: 'done', result: statusResult(status, response.headers['retry-after']) }+ private async hop(+ url: string,+ timeoutMs: number,+ maxBytes: number,+ previousCache: HttpCacheMetadata | undefined,+ tdmrepReservation: boolean+ ): Promise<HopResult> {+ const requestTimeMs = Date.now()+ const canonical = canonicalizeUrl(url)+ let requestOutcome = ImageFetchRequestMetrics.outcomeForHttpStatus()+ const headers: Record<string, string> = { ...REQUEST_HEADERS, ...this.webBotAuthSigner.headersForGet(url) }+ if (previousCache?.etag) {+ headers['if-none-match'] = previousCache.etag+ } else if (previousCache?.lastModified) {+ headers['if-modified-since'] = previousCache.lastModified}+ try {+ const response = await fetchStreamed(url, { headers, timeoutMs })+ const status = response.status+ requestOutcome = ImageFetchRequestMetrics.outcomeForHttpStatus(status)+ const cache = cacheMetadata(requestTimeMs, Date.now(), response.headerLines)+ const optOut = responseOptOutReason(response.headerLines, tdmrepReservation)+ if (optOut) {+ response.discard()+ return { kind: 'done', result: { outcome: 'opt_out', status, refusalReason: optOut, cache } }+ }- const contentType = normalizeContentType(response.headers['content-type'])- if (!contentType) {- response.discard()- return { kind: 'done', result: { outcome: 'not_image', status } }- }- // An origin that compresses anyway makes the byte limit count compressed bytes, and the- // payload behind them can be far larger. This is a refusal by this lane rather than a fact- // about the image, so it gets its own outcome and does not write the URL off.- const encoding = response.headers['content-encoding']?.trim().toLowerCase()- if (encoding && encoding !== 'identity') {- response.discard()- return { kind: 'done', result: { outcome: 'unsupported_encoding', status } }- }- // Before the body, so a declared size over the limit costs one header exchange.- const declaredBytes = Number(response.headers['content-length'])- if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {- response.discard()- return { kind: 'done', result: { outcome: 'too_large', status } }- }+ if (REDIRECT_STATUSES.has(status)) {+ response.discard()+ const locations = headerValues(response.headerLines, 'location')+ const location = locations.length === 1 ? locations[0] : undefined+ return location+ ? { kind: 'redirect', status, location, cache }+ : { kind: 'done', result: { outcome: 'bad_redirect', status, cache } }+ }+ if (status === 304) {+ response.discard()+ const outcome =+ previousCache?.etag || previousCache?.lastModified ? 'not_modified' : 'unexpected_status'+ return { kind: 'done', result: { outcome, status, cache } }+ }+ if (status !== 200) {+ response.discard()+ return {+ kind: 'done',+ result: { ...statusResult(status, headerValues(response.headerLines, 'retry-after')), cache },+ }+ }- const { bytes, overLimit } = await response.read(maxBytes)- if (overLimit) {- return { kind: 'done', result: { outcome: 'too_large', status } }- }- // A payload that disagrees with its declared type would reach the scrub lane as an image no- // model can read, and by then the URL that produced it is gone.- if (!magicBytesMatch(bytes, contentType)) {- return { kind: 'done', result: { outcome: 'not_image', status } }+ const contentTypes = headerValues(response.headerLines, 'content-type').map(normalizeContentType)+ const contentType = contentTypes[0]+ if (!contentType || contentTypes.some((candidate) => candidate !== contentType)) {+ response.discard()+ return { kind: 'done', result: { outcome: 'not_image', status, cache } }+ }+ const contentEncoding = normalizeContentEncoding(headerValues(response.headerLines, 'content-encoding'))+ if (contentEncoding === null) {+ response.discard()+ return { kind: 'done', result: { outcome: 'unsupported_encoding', status, cache } }+ }+ const declaredTooLarge = headerValues(response.headerLines, 'content-length').some((value) => {+ const declaredBytes = Number(value)+ return Number.isFinite(declaredBytes) && declaredBytes > maxBytes+ })+ if (declaredTooLarge) {+ response.discard()+ return { kind: 'done', result: { outcome: 'too_large', status, cache } }+ }++ const { bytes, overLimit } = await response.read(maxBytes, false)+ if (overLimit) {+ return { kind: 'done', result: { outcome: 'too_large', status, cache } }+ }+ return { kind: 'done', result: { outcome: 'ok', status, bytes, contentType, contentEncoding, cache } }+ } finally {+ if (canonical) {+ ImageFetchRequestMetrics.observeRequest(requestOutcome, (Date.now() - requestTimeMs) / 1000)+ }}- return { kind: 'done', result: { outcome: 'ok', status, bytes, contentType } }}}type HopResult =- | { kind: 'redirect'; status: number; location: string }- | { kind: 'done'; result: Omit<ImageFetchResult, 'redirects'> }+ | { kind: 'redirect'; status: number; location: string; cache: HttpCacheMetadata }+ | { kind: 'done'; result: Omit<ImageFetchResult, 'redirects' | 'currentUrl'> }-function statusResult(status: number, retryAfter: string | undefined): Omit<ImageFetchResult, 'redirects'> {+function statusResult(status: number, retryAfterValues: string[]): Omit<ImageFetchResult, 'redirects' | 'currentUrl'> {+ const retryAfterMs = maximumRetryAfterMs(retryAfterValues)if (status === 404 || status === 410) {return { outcome: 'not_found', status }}if (status === 401 || status === 403) {return { outcome: 'forbidden', status }}+ if (status === 408 || status === 425) {+ return { outcome: 'rate_limited', status }+ }if (status === 429) {- return { outcome: 'rate_limited', status, retryAfterMs: parseRetryAfterMs(retryAfter) }+ return { outcome: 'rate_limited', status, retryAfterMs }}if (status === 503) {- return { outcome: 'server_error', status, retryAfterMs: parseRetryAfterMs(retryAfter) }+ return { outcome: 'server_error', status, retryAfterMs }}if (status >= 500) {return { outcome: 'server_error', status }@@ -226,17 +306,23 @@ function statusResult(status: number, retryAfter: string | undefined): Omit<Imagreturn { outcome: 'unexpected_status', status }}+function maximumRetryAfterMs(values: string[]): number | undefined {+ const parsed = values.flatMap((value) => {+ const retryAfterMs = parseRetryAfterMs(value)+ return retryAfterMs === undefined ? [] : [retryAfterMs]+ })+ return parsed.length > 0 ? Math.max(...parsed) : undefined+}+/** RFC 9110 allows a count of seconds or an HTTP date. Real responses use both. */export function parseRetryAfterMs(value: string | undefined): number | undefined {if (!value) {return undefined}- // An absent, zero, or past period returns undefined, so the caller applies its own default- // rather than reading zero as a site that wants no pause.const trimmed = value.trim()- const seconds = trimmed === '' ? NaN : Number(trimmed)- if (Number.isFinite(seconds)) {- return seconds > 0 ? seconds * 1000 : undefined+ if (/^\d+$/.test(trimmed)) {+ const seconds = Number(trimmed)+ return Number.isSafeInteger(seconds) && seconds <= Number.MAX_SAFE_INTEGER / 1000 ? seconds * 1000 : undefined}const dateMs = Date.parse(trimmed)if (Number.isNaN(dateMs)) {@@ -281,14 +367,14 @@ function resolveRedirect(from: string, location: string, policy: RedirectPolicy)if (next.port !== '') {return null}- const target = next.toString()- if (target.length > policy.maxUrlLength) {+ const canonical = canonicalizeUrl(next.toString())+ if (!canonical || canonical.fetch.length > policy.maxUrlLength) {return null}- if (!policy.isPublicHost(next.hostname)) {+ if (!policy.isPublicHost(canonical.host)) {return null}- return next+ return new URL(canonical.fetch)}function normalizeContentType(header: string | undefined): ImageContentType | undefined {@@ -299,50 +385,52 @@ function normalizeContentType(header: string | undefined): ImageContentType | unreturn ALLOWED_CONTENT_TYPES.find((allowed) => allowed === type)}-function startsWith(bytes: Buffer, signature: number[], offset = 0): boolean {- if (bytes.length < offset + signature.length) {- return false+const ALLOWED_CONTENT_ENCODINGS = new Set(['gzip', 'deflate', 'br', 'zstd'])+const MAX_CONTENT_ENCODING_LAYERS = 4++function normalizeContentEncoding(values: string[]): string | undefined | null {+ const declaredCodings = values.flatMap((value) => value.split(',')).map((coding) => coding.trim().toLowerCase())+ if (declaredCodings.length > MAX_CONTENT_ENCODING_LAYERS || declaredCodings.some((coding) => coding === '')) {+ return null+ }+ const codings = declaredCodings.filter((coding) => coding !== 'identity')+ if (codings.some((coding) => !ALLOWED_CONTENT_ENCODINGS.has(coding))) {+ return null}- return signature.every((byte, index) => bytes[offset + index] === byte)+ return codings.length > 0 ? codings.join(', ') : undefined}-function asciiAt(bytes: Buffer, offset: number, text: string): boolean {- return startsWith(- bytes,- [...text].map((char) => char.charCodeAt(0)),- offset- )+function headerValues(headerLines: Array<{ name: string; value: string }>, name: string): string[] {+ return headerLines.filter((line) => line.name === name).map((line) => line.value)}-/**- * This checks agreement rather than format. Anything that passes still reaches an image decoder- * later, so this only has to catch a payload that is not the format it claims.- */-export function magicBytesMatch(bytes: Buffer, contentType: ImageContentType): boolean {- switch (contentType) {- case 'image/png':- return startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])- case 'image/jpeg':- return startsWith(bytes, [0xff, 0xd8, 0xff])- case 'image/gif':- return asciiAt(bytes, 0, 'GIF87a') || asciiAt(bytes, 0, 'GIF89a')- case 'image/webp':- return asciiAt(bytes, 0, 'RIFF') && asciiAt(bytes, 8, 'WEBP')- case 'image/bmp':- return asciiAt(bytes, 0, 'BM')- case 'image/avif':- // An ISO base media file names its brand after the `ftyp` box header, and AVIF still- // ships under the `mif1` and `msf1` brands that came before the AVIF ones.- return (- asciiAt(bytes, 4, 'ftyp') &&- (asciiAt(bytes, 8, 'avif') ||- asciiAt(bytes, 8, 'avis') ||- asciiAt(bytes, 8, 'mif1') ||- asciiAt(bytes, 8, 'msf1'))- )+function cacheMetadata(+ requestTimeMs: number,+ responseTimeMs: number,+ headerLines: Array<{ name: string; value: string }>+): HttpCacheMetadata {+ return {+ requestTimeMs,+ responseTimeMs,+ etag: singletonHeader(headerLines, 'etag'),+ lastModified: singletonHeader(headerLines, 'last-modified'),+ date: singletonHeader(headerLines, 'date'),+ age: singletonHeader(headerLines, 'age'),+ cacheControl: combinedHeader(headerLines, 'cache-control'),+ expires: singletonHeader(headerLines, 'expires'),}}+function singletonHeader(headerLines: Array<{ name: string; value: string }>, name: string): string | undefined {+ const values = headerValues(headerLines, name)+ return values.length === 1 ? values[0] : undefined+}++function combinedHeader(headerLines: Array<{ name: string; value: string }>, name: string): string | undefined {+ const values = headerValues(headerLines, name)+ return values.length > 0 ? values.join(', ') : undefined+}+export function classifyError(error: unknown): FetchOutcome {// `blocked` is terminal, so it must only cover a permanent property of the URL. A refused// address and an unparsable URL are permanent. A name that did not resolve is not, because thediff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.tsnew file mode 100644index 000000000000..3d94d3b74189--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.test.ts@@ -0,0 +1,37 @@+import { register } from 'prom-client'++import { ImageFetchRequestMetrics } from './metrics'++describe('ImageFetchRequestMetrics', () => {+ beforeEach(() => register.resetMetrics())++ test.each([+ [undefined, 'network_error'],+ [199, 'other'],+ [200, '2xx'],+ [299, '2xx'],+ [300, '3xx'],+ [399, '3xx'],+ [400, '4xx'],+ [499, '4xx'],+ [500, '5xx'],+ [599, '5xx'],+ [600, 'other'],+ ] as const)('maps HTTP status %s to the bounded %s outcome', (status, expected) => {+ expect(ImageFetchRequestMetrics.outcomeForHttpStatus(status)).toBe(expected)+ })++ it('records retry causes with fixed semantic labels', async () => {+ ImageFetchRequestMetrics.incRetryCause('rate_limited')+ ImageFetchRequestMetrics.incRetryCause('server_error')+ ImageFetchRequestMetrics.incRetryCause('timeout')+ ImageFetchRequestMetrics.incRetryCause('error')++ const metric = (await register.getMetricsAsJSON()).find(+ (candidate) => candidate.name === 'ml_image_fetch_retry_causes_total'+ )+ const causes = metric?.values.map((value) => value.labels.cause)++ expect(causes).toEqual(['rate_limited', 'server_error', 'timeout', 'error'])+ })+})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.tsindex 197a3abfe548..1d21195b7b58 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@@ -1,6 +1,8 @@import { Counter, Gauge, Histogram } from 'prom-client'-import type { TeamVolume } from './team-volume'+import type { RepublishReason, UrlDropReason } from './collected-urls-record'+import type { AttemptOutcome } from './fetch-runner'+import type { FetchRefusalReason, RequestScheduleBlockReason, TransientFetchOutcome } from './image-fetcher'/** What the in-flight gauge reads. Narrower than `ConcurrencyController`, so the metrics do not depend on the whole of it. */export interface InFlightCount {@@ -9,22 +11,17 @@ export interface InFlightCount {/** What the budget gauges read. Narrower than `HostBudget`, so the metrics do not depend on the whole of it. */export interface BudgetCounts {- readonly trackedDomains: number+ readonly trackedRegistrableDomains: number+ readonly trackedOrigins: numberreadonly evictedWhileBlocked: number- blockedDomains(nowMs: number): number+ blockedRegistrableDomains(nowMs: number): number}-export type UrlDropReason =- | 'malformed'- | 'unsupported_version'- | 'stale'- | 'bad_ref'- | 'bad_url'- | 'foreign_domain'- | 'private_host'- | 'oversized_record'--export type DedupScope = 'batch' | 'pod' | 'store'+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'+type PolicyAndBudgetReason = FetchRefusalReason | RequestScheduleBlockReason | 'none'export class ImageFetchConsumerMetrics {private static readonly fetchable = new Counter({@@ -32,32 +29,27 @@ export class ImageFetchConsumerMetrics {help: 'URLs that passed every check and would have been fetched. In dry run no request is sent, so this is the offered rate rather than the sent rate',})/**- * `batch` and `pod` cost only memory, and `store` costs a shared-store read, so the split is the- * measurement rather than the total. A high `store` share against a full pod cache says the pod- * cache is too small. A low one says the pod cache already holds the working set.+ * `batch` costs only memory, while `store` costs a shared-store read.*/private static readonly deduped = new Counter({name: 'ml_image_fetch_consumer_deduped_total',- help: 'URLs skipped as already known, by the layer that caught them: "batch" (another copy in the same poll batch), "pod" (this pod saw it earlier), "store" (another pod saw it, or this pod before a restart)',+ help: 'URLs skipped as already known, by the layer that caught them: "batch" (another copy in the same poll batch) or "store" (a durable crawl-history result)',labelNames: ['scope'],})/**- * `stale` is the expected reason under a backlog. The others mean the producer and this consumer- * disagree about the wire format, so a sustained rate on any of them takes the lane to zero while- * the Kafka side still looks healthy.+ * A sustained rate means the producer and consumer disagree about the wire format.*/private static readonly dropped = new Counter({name: 'ml_image_fetch_consumer_dropped_total',- help: 'URLs refused before dedup, by reason: "stale" (older than the age limit), "malformed" / "unsupported_version" / "oversized_record" (the record did not parse), "bad_ref" / "bad_url" (an entry inside a record did not parse), "foreign_domain" (the key is not the registrable domain of the host), "private_host" (the host is a private address or a name that only resolves inside a network)',+ help: 'URLs refused before dedup because the versioned record, URL, ref, or registrable-domain key was invalid',labelNames: ['reason'],})/**- * A batch that spans many domains means the key spreads work more finely than the partition count- * can express, which is what would let one pod pass the budget of a single site.+ * This distribution shows how much independent origin state one poll can activate.*/- private static readonly domainsPerBatch = new Histogram({- name: 'ml_image_fetch_consumer_domains_per_batch',- help: 'Distinct registrable domains in one poll batch. The politeness budget is per domain and held by the pod owning the partition, so this bounds how many budgets one pod runs at once',+ private static readonly originsPerBatch = new Histogram({+ name: 'ml_image_fetch_consumer_origins_per_batch',+ help: 'Distinct origins in one poll batch',buckets: [1, 2, 4, 8, 16, 32, 64],})private static readonly urlsPerRecord = new Histogram({@@ -67,17 +59,32 @@ export class ImageFetchConsumerMetrics {})private static readonly storeErrors = new Counter({name: 'ml_image_fetch_consumer_store_errors_total',- help: 'Crawl-history keys that failed, by operation. A failed read makes the lane treat a known URL as new, so the measured hit rate understates the real one. A failed write leaves the URL unrecorded, so the next pod to see it counts it again',+ help: 'Crawl-history keys in a failed read or write. Either failure stops the batch before Kafka offsets advance',labelNames: ['operation'],})+ private static readonly storeDuration = new Histogram({+ name: 'ml_image_fetch_consumer_store_duration_seconds',+ help: 'Crawl-history operation wall time by bounded operation and outcome',+ labelNames: ['operation', 'outcome'],+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120],+ })private static readonly batchDuration = new Histogram({name: 'ml_image_fetch_consumer_batch_duration_seconds',- help: 'Wall time per poll batch. Read against CONSUMER_MAX_HEARTBEAT_INTERVAL_MS (30s), which binds long before max.poll.interval.ms: the batch refreshes the heartbeat from inside itself, so a batch past this means that refresh stopped',- buckets: [0.01, 0.05, 0.1, 0.5, 1, 5, 15, 30, 60],+ help: 'Wall time per completed poll batch. Read against Kafka max.poll.interval.ms (300s)',+ buckets: [0.01, 0.05, 0.1, 0.5, 1, 5, 15, 30, 60, 120, 240, 300, 600],+ })+ private static activeBatchStartedAtMs: number | undefined+ private static readonly activeBatchElapsed = new Gauge({+ name: 'ml_image_fetch_consumer_active_batch_elapsed_seconds',+ help: 'Elapsed wall time of the active non-empty poll batch, or zero between batches. This exposes a stuck batch before Kafka max.poll.interval.ms revokes it',+ collect() {+ const startedAtMs = ImageFetchConsumerMetrics.activeBatchStartedAtMs+ this.set(startedAtMs === undefined ? 0 : Math.max(0, performance.now() - startedAtMs) / 1000)+ },})private static readonly ageSeconds = new Histogram({name: 'ml_image_fetch_consumer_url_age_seconds',- help: 'Age of a URL when this lane reached it, measured from capture rather than from produce. The tail against the configured age limit says how much of a backlog would be dropped rather than fetched',+ help: 'Age of a URL when this lane reached it, measured from capture rather than from produce. The tail shows the age of the backlog',buckets: [1, 10, 60, 300, 900, 3600, 6 * 3600, 24 * 3600],})private static readonly dryRun = new Gauge({@@ -100,10 +107,23 @@ export class ImageFetchConsumerMetrics {public static incStoreError(operation: 'read' | 'write', count: number): void {this.storeErrors.labels(operation).inc(count)}- public static observeBatch(domains: number, durationSeconds: number): void {- this.domainsPerBatch.observe(domains)+ public static observeStoreDuration(+ operation: 'read' | 'write',+ outcome: 'success' | 'error',+ durationSeconds: number+ ): void {+ this.storeDuration.labels(operation, outcome).observe(durationSeconds)+ }+ public static observeBatch(origins: number, durationSeconds: number): void {+ this.originsPerBatch.observe(origins)this.batchDuration.observe(durationSeconds)}+ public static startBatch(nowMs = performance.now()): void {+ this.activeBatchStartedAtMs = nowMs+ }+ public static finishBatch(): void {+ this.activeBatchStartedAtMs = undefined+ }public static observeRecord(urls: number): void {this.urlsPerRecord.observe(urls)}@@ -119,82 +139,158 @@ export class ImageFetchConsumerMetrics {* logs of the runner. A URL is page content and belongs in no metric, log, or trace.*/export class ImageFetchRequestMetrics {+ private static readonly completedUrls = new Counter({+ name: 'ml_image_fetch_completed_urls_total',+ help: 'Completed URLs by final outcome and refusal reason',+ labelNames: ['outcome', 'refusal_reason'],+ })+ private static readonly completedUrlSystemTime = new Histogram({+ name: 'ml_image_fetch_completed_url_system_time_seconds',+ help: 'Time from first collection until the URL reaches a terminal outcome',+ buckets: [1, 60, 600, 3600, 6 * 3600, 24 * 3600, 7 * 24 * 3600, 30 * 24 * 3600],+ })+ private static readonly completedUrlFetches = new Histogram({+ name: 'ml_image_fetch_completed_url_fetches',+ help: 'Image HTTP requests made before a URL reaches a terminal outcome',+ buckets: [0, 1, 2, 3, 5, 10],+ })+ private static readonly completedUrlRepublishes = new Histogram({+ name: 'ml_image_fetch_completed_url_republishes',+ help: 'Frontier and delay-topic republishes before a URL reaches a terminal outcome',+ buckets: [0, 1, 2, 3, 5, 10],+ })+ private static readonly policyAndBudgetDecisions = new Counter({+ name: 'ml_image_fetch_policy_and_budget_decisions_total',+ help: 'Origin-policy and registrable-domain request-control decisions after block state is known',+ labelNames: ['blocked', 'reason'],+ })/**- * `ok` against the sum is the yield of the lane. The site answers `not_found`, `forbidden`,- * `rate_limited`, and `server_error`. This lane refuses `too_large`, `not_image`, `blocked`,- * `bad_redirect`, and `too_many_redirects`. Only `breaker_open` and `deadline` come back in a- * later batch.+ * `ok` against the sum is the yield of the lane.*/private static readonly outcomes = new Counter({name: 'ml_image_fetch_requests_total',- help: 'URLs that reached the request stage, by outcome. "deadline", "breaker_open", "connection_limit" and "rate_limited" cover URLs the lane never sent, so they say the lane wants more pods or the site wants less traffic, rather than that a fetch failed',+ help: 'Completed external HTTP requests by status class or network failure',labelNames: ['outcome'],})private static readonly duration = new Histogram({name: 'ml_image_fetch_request_duration_seconds',- help: 'Time from the first request of a URL to its outcome, redirects included. It excludes the wait for a rate-limit token, which ml_image_fetch_budget_wait_seconds holds',+ help: 'Time for one completed external HTTP request, including its response body',labelNames: ['outcome'],buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],})+ private static readonly retryCauses = new Counter({+ name: 'ml_image_fetch_retry_causes_total',+ help: 'Transient fetch outcomes that caused the URL to be scheduled for another attempt',+ labelNames: ['cause'],+ })/**- * A rising tail means one domain offers more URLs than its rate carries. Past the pass deadline- * the wait becomes a `deadline` shed, so read this against that outcome: a growing wait with no- * sheds is headroom, and a growing wait with sheds is a domain the lane cannot keep up with.+ * Read a rising tail with the `deadline` outcome to distinguish headroom from load that an+ * origin's allowed rate cannot carry within one pass.*/- private static readonly budgetWait = new Histogram({- name: 'ml_image_fetch_budget_wait_seconds',- help: 'Time a URL waited for its domain rate limit before its request went out',+ private static readonly schedulerWait = new Histogram({+ name: 'ml_image_fetch_scheduler_wait_seconds',+ help: 'Time a request waited for an origin crawl delay, registrable-domain rate, or pod request slot',+ labelNames: ['scope'],buckets: [0, 0.1, 0.5, 1, 2, 5, 10, 20],})private static readonly responseBytes = new Histogram({name: 'ml_image_fetch_response_bytes',help: 'Size of a downloaded image. The tail against the configured byte limit says how much of the catalog the limit refuses',- buckets: [1024, 8 * 1024, 32 * 1024, 128 * 1024, 512 * 1024, 1024 * 1024, 2 * 1024 * 1024],+ buckets: [+ 1024,+ 8 * 1024,+ 32 * 1024,+ 128 * 1024,+ 512 * 1024,+ 1024 * 1024,+ 2 * 1024 * 1024,+ 10 * 1024 * 1024,+ 20 * 1024 * 1024,+ ],})private static readonly redirects = new Histogram({name: 'ml_image_fetch_redirects',- help: 'Redirects followed for one URL. Each hop is a separate request against the budget of whichever domain it lands on',+ help: 'Redirects followed for one URL. Each hop uses its registrable-domain budget and origin crawl delay',buckets: [0, 1, 2, 3],})/**- * The tracked count against the configured maximum says whether the map evicts, and an eviction- * forgets that a domain is blocked.- ** Both gauges read the budget at scrape time. A hold expires by the clock, so a count taken at- * the end of a batch would report blocked domains until the next batch arrives.+ * the end of a batch would report blocked origins until the next batch arrives.*/- private static readonly trackedDomains = new Gauge({- name: 'ml_image_fetch_tracked_domains',- help: 'Registrable domains this pod holds rate-limit state for',+ private static readonly trackedRegistrableDomains = new Gauge({+ name: 'ml_image_fetch_tracked_registrable_domains',+ help: 'Registrable domains this pod holds request-control state for',collect() {- this.set(ImageFetchRequestMetrics.budget?.trackedDomains ?? 0)+ this.set(ImageFetchRequestMetrics.budget?.trackedRegistrableDomains ?? 0)},})- private static readonly blockedDomains = new Gauge({- name: 'ml_image_fetch_blocked_domains',- help: 'Domains this pod is currently sending nothing to, because a breaker opened or a Retry-After header is still in force',+ private static readonly trackedOrigins = new Gauge({+ name: 'ml_image_fetch_tracked_origins',+ help: 'Origins this pod holds configuration and crawl-delay state for',collect() {- this.set(ImageFetchRequestMetrics.budget?.blockedDomains(Date.now()) ?? 0)+ this.set(ImageFetchRequestMetrics.budget?.trackedOrigins ?? 0)+ },+ })+ private static readonly blockedRegistrableDomains = new Gauge({+ name: 'ml_image_fetch_blocked_registrable_domains',+ help: 'Registrable domains held by transient back-off, Retry-After, or an open circuit breaker',+ collect() {+ this.set(ImageFetchRequestMetrics.budget?.blockedRegistrableDomains(Date.now()) ?? 0)},})- public static incOutcome(outcome: string, count = 1): void {- this.outcomes.labels(outcome).inc(count)+ public static outcomeForHttpStatus(status?: number): HttpRequestOutcome {+ if (status === undefined) {+ return 'network_error'+ }+ if (status >= 200 && status < 300) {+ return '2xx'+ }+ if (status >= 300 && status < 400) {+ return '3xx'+ }+ if (status >= 400 && status < 500) {+ return '4xx'+ }+ if (status >= 500 && status < 600) {+ return '5xx'+ }+ return 'other'}- public static observeRequest(outcome: string, durationSeconds: number, redirects: number): void {+ public static observeRequest(outcome: HttpRequestOutcome, durationSeconds: number): void {this.outcomes.labels(outcome).inc()this.duration.labels(outcome).observe(durationSeconds)+ }+ public static incRetryCause(cause: TransientFetchOutcome): void {+ this.retryCauses.labels(cause).inc()+ }+ public static observeRedirectCount(redirects: number): void {this.redirects.observe(redirects)}- public static observeBudgetWait(waitSeconds: number): void {- this.budgetWait.observe(waitSeconds)+ public static observeCompletedUrl(+ outcome: AttemptOutcome,+ refusalReason: FetchRefusalReason | 'none',+ systemTimeSeconds: number,+ fetches: number,+ republishes: number+ ): void {+ this.completedUrls.labels(outcome, refusalReason).inc()+ this.completedUrlSystemTime.observe(systemTimeSeconds)+ this.completedUrlFetches.observe(fetches)+ this.completedUrlRepublishes.observe(republishes)+ }+ public static observePolicyAndBudgetDecision(blocked: boolean, reason: PolicyAndBudgetReason = 'none'): void {+ this.policyAndBudgetDecisions.labels(blocked ? 'true' : 'false', reason).inc()+ }+ public static observeSchedulerWait(scope: SchedulerWaitScope, waitSeconds: number): void {+ this.schedulerWait.labels(scope).observe(waitSeconds)}public static observeBytes(bytes: number): void {this.responseBytes.observe(bytes)}private static readonly evictedWhileBlocked = new Gauge({- name: 'ml_image_fetch_domains_evicted_while_blocked',- help: 'Domains dropped from the rate-limit map while they were still blocked. Each one resumes traffic to a site that asked us to wait, so a rising value means the tracked-domain limit is too low',+ name: 'ml_image_fetch_registrable_domains_evicted_while_blocked',+ help: 'Registrable domains removed from request-control state while still blocked. This must stay zero',collect() {this.set(ImageFetchRequestMetrics.budget?.evictedWhileBlocked ?? 0)},@@ -208,7 +304,7 @@ export class ImageFetchRequestMetrics {*/private static readonly inFlight = new Gauge({name: 'ml_image_fetch_requests_in_flight',- help: "Image requests this pod holds open right now. A URL waiting for its domain's rate limit is not counted, because it holds no socket",+ help: 'External requests this pod holds open. A URL waiting for its registrable-domain rate limit holds no socket and is not counted',collect() {this.set(ImageFetchRequestMetrics.requests?.running ?? 0)},@@ -217,23 +313,7 @@ export class ImageFetchRequestMetrics {private static budget: BudgetCounts | undefinedprivate static requests: InFlightCount | undefined- /**- * URLs a shed left in the back queue, which the lane will not put back.- *- * A pass sheds whatever it did not reach, and one back queue can hold far more than a delay- * tier can carry. Republishing all of them answers overload with more Kafka traffic, and the- * same URLs come round again a minute later, each having spent a hop.- */- private static readonly shedDropped = new Counter({- name: 'ml_image_fetch_shed_dropped_total',- help: 'URLs a shed did not put back, because one pass republishes at most a fixed number for one domain. They return when a session refers to the same image',- })-- public static incShedDropped(count: number): void {- this.shedDropped.inc(count)- }-- /** The runner owns both. Requirement 28. */+ /** The runner owns both. */public static trackBudget(budget: BudgetCounts, requests: InFlightCount): void {this.budget = budgetthis.requests = requests@@ -242,11 +322,11 @@ export class ImageFetchRequestMetrics {/*** Read against `ml_image_fetch_requests_total` this is the amplification factor, because the lane* reads every republished message again. A rate that approaches the request rate means most work- * goes around rather than completes. Requirement 27.+ * goes around rather than completes.*/private static readonly republished = new Counter({name: 'ml_image_fetch_republished_total',- help: 'URLs published back to Kafka, by why and to which topic. "redirect" left the registrable domain, so another consumer owns its budget. "retry" hit a transient failure and waits in a delay topic. "not_ready" arrived before the period it was waiting out had passed',+ help: 'URLs published back to Kafka by bounded reason and destination class. "redirect" left the origin. "retry" hit a transient failure and waits in a delay topic. "not_ready" arrived before its wait ended',labelNames: ['reason', 'topic'],})private static readonly republishFailed = new Counter({@@ -255,19 +335,18 @@ export class ImageFetchRequestMetrics {labelNames: ['reason'],})/**- * Zero is the common case, which is a URL fetched on first sight. The tail shows redirect chains- * and retries, and a value at the budget is a URL the lane gave up on. Requirement 26.+ * Zero is the common case. The tail shows redirect chains and retries.*/private static readonly hopsUsed = new Histogram({name: 'ml_image_fetch_hops_used',- help: 'Moves one URL made before the lane finished with it. A republish and a retry each count one. A redirect that stays on the same domain is bounded separately and counts none',+ help: 'Redirects and retries spent from one URL job before the lane finished it',buckets: [0, 1, 2, 3, 5, 10],})- public static incRepublished(reason: string, topic: string): void {- this.republished.labels(reason, topic).inc()+ public static incRepublished(reason: RepublishReason, destination: RepublishDestination): void {+ this.republished.labels(reason, destination).inc()}- public static incRepublishFailed(reason: string): void {+ public static incRepublishFailed(reason: RepublishReason): void {this.republishFailed.labels(reason).inc()}public static observeHops(hops: number): void {@@ -286,7 +365,7 @@ export class ImageFetchRequestMetrics {export class RetryDelayMetrics {private static readonly released = new Counter({name: 'ml_image_fetch_retry_released_total',- help: 'Records this delay consumer finished with, by what happened: "released" back to the frontier, "failed" to publish, or "malformed" and dropped',+ help: 'Records this delay consumer handled by outcome. A malformed record is dropped, while an invalid timestamp or failed publish leaves the offset uncommitted',labelNames: ['outcome'],})private static readonly waitSeconds = new Histogram({@@ -295,49 +374,13 @@ export class RetryDelayMetrics {buckets: [1, 10, 60, 300, 600, 1800, 3600],})- public static incReleased(outcome: 'released' | 'failed' | 'malformed' | 'abandoned'): void {- this.released.labels(outcome).inc()+ public static incReleased(+ outcome: 'released' | 'failed' | 'malformed' | 'invalid_timestamp' | 'abandoned',+ count = 1+ ): void {+ this.released.labels(outcome).inc(count)}public static observeWait(waitSeconds: number): void {this.waitSeconds.observe(waitSeconds)}}--/**- * How the lane's work divides between teams, without an unbounded label.- *- * The team ID space is in the low millions, so this bounds `pseudo_team` here rather than at the- * database. The busiest teams keep their name, everything else is one `other` row, and the count of- * distinct teams is an estimate in a single series. Requirements 29, 30, and 31.- *- * Nothing on this path holds the team ID, so a team ID label here would need the mirror to send it.- */-export class ImageFetchTeamMetrics {- private static source: TeamVolume | undefined-- private static readonly urlsByTeam = new Gauge({- name: 'ml_image_fetch_team_urls',- help: 'URLs handled for each of the busiest teams, with the rest summed as "other". The label is the team pseudonym the topic carries, not the team ID',- labelNames: ['pseudo_team'],- collect() {- // Rebuilt at scrape rather than kept in step with the counts, so a team that drops out- // of the top list loses its series instead of holding its last value.- this.reset()- for (const { team, count } of ImageFetchTeamMetrics.source?.top() ?? []) {- this.labels(team).set(count)- }- },- })- private static readonly distinctTeams = new Gauge({- name: 'ml_image_fetch_distinct_teams',- help: 'About how many distinct teams this pod has handled URLs for, estimated rather than counted, because an exact set of a million team pseudonyms costs hundreds of megabytes',- collect() {- this.set(ImageFetchTeamMetrics.source?.distinctTeams() ?? 0)- },- })-- /** The consumer owns the counts. These gauges read them at scrape time. */- public static track(volume: TeamVolume): void {- this.source = volume- }-}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.test.tsnew file mode 100644index 000000000000..14eed6b3a041--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.test.ts@@ -0,0 +1,185 @@+import { HostBudget, HostBudgetOptions } from './host-budget'+import { ImageFetchRequestMetrics } from './metrics'+import { OriginRequestScheduler } from './origin-request-scheduler'++const OPTIONS: HostBudgetOptions = {+ requestsPerSecond: 1,+ burst: 5,+ maxConcurrent: 6,+ breakerFailures: 2,+ breakerCooldownMs: 60_000,+ breakerMaxCooldownMs: 3_600_000,+ maxTrackedRegistrableDomains: 20_000,+ maxTrackedOrigins: 20_000,+ random: () => 1,+}+const ORIGIN = new URL('https://example.com')+const REGISTRABLE_DOMAIN = 'example.com'++describe('OriginRequestScheduler', () => {+ beforeEach(() => jest.useFakeTimers().setSystemTime(1_700_000_000_000))+ afterEach(() => {+ jest.restoreAllMocks()+ jest.useRealTimers()+ })++ it('keeps concurrent request start times at least one second apart', async () => {+ const scheduler = new OriginRequestScheduler(new HostBudget(OPTIONS), 300)+ const observeSchedulerWait = jest.spyOn(ImageFetchRequestMetrics, 'observeSchedulerWait')+ const startedAtMs: number[] = []+ const deadlineMs = Date.now() + 10_000++ const requests = [0, 1, 2].map(() =>+ scheduler.runImage(ORIGIN, deadlineMs, () => {+ startedAtMs.push(Date.now())+ return Promise.resolve()+ })+ )+ await jest.runAllTimersAsync()++ expect(await Promise.all(requests)).toEqual([+ { ran: true, value: undefined },+ { ran: true, value: undefined },+ { ran: true, value: undefined },+ ])+ expect(startedAtMs).toEqual([1_700_000_000_000, 1_700_000_001_000, 1_700_000_002_000])+ expect(observeSchedulerWait).toHaveBeenCalledWith('origin_crawl_delay', 1)+ expect(observeSchedulerWait).toHaveBeenCalledWith('request_capacity', 0)+ })++ it('runs one half-open probe while later requests remain blocked', async () => {+ const budget = new HostBudget(OPTIONS)+ budget.recordTransientFailure(REGISTRABLE_DOMAIN, Date.now())+ budget.recordTransientFailure(REGISTRABLE_DOMAIN, Date.now())+ jest.setSystemTime(Date.now() + 120_001)+ const scheduler = new OriginRequestScheduler(budget, 300)+ let finishProbe: (() => void) | undefined+ const probe = scheduler.runImage(+ ORIGIN,+ Date.now() + 10_000,+ () =>+ new Promise<void>((resolve) => {+ finishProbe = resolve+ })+ )++ await Promise.resolve()+ await expect(scheduler.runImage(ORIGIN, Date.now() + 10_000, () => Promise.resolve())).resolves.toEqual({+ ran: false,+ reason: 'breaker_open',+ waitMs: OPTIONS.breakerCooldownMs,+ })+ expect(finishProbe).toBeDefined()+ finishProbe?.()+ await expect(probe).resolves.toEqual({ ran: true, value: undefined })+ })++ it('returns a queued request to the caller when its pass deadline expires', async () => {+ const scheduler = new OriginRequestScheduler(new HostBudget(OPTIONS), 1)+ let releaseFirst: (() => void) | undefined+ const first = scheduler.runImage(+ new URL('https://first.example'),+ Date.now() + 10_000,+ () =>+ new Promise<void>((resolve) => {+ releaseFirst = resolve+ })+ )+ const second = scheduler.runImage(new URL('https://second.example'), Date.now() + 500, () => Promise.resolve())++ await Promise.resolve()+ jest.advanceTimersByTime(501)+ releaseFirst?.()++ await expect(first).resolves.toEqual({ ran: true, value: undefined })+ await expect(second).resolves.toEqual({ ran: false, reason: 'deadline', waitMs: 0 })+ })++ it('checks the registrable-domain token bucket after a pod-capacity wait', async () => {+ const scheduler = new OriginRequestScheduler(new HostBudget({ ...OPTIONS, burst: 2 }), 1)+ const startedAtMs: number[] = []+ let releaseFirst: (() => void) | undefined+ const startRequest = (origin: string, hold = false): Promise<unknown> =>+ scheduler.runImage(new URL(origin), Date.now() + 30_000, () => {+ startedAtMs.push(Date.now())+ if (!hold) {+ return Promise.resolve()+ }+ return new Promise<void>((resolve) => {+ releaseFirst = resolve+ })+ })++ const requests = [+ startRequest('https://a.example.com/image.png', true),+ startRequest('https://b.example.com/image.png'),+ startRequest('https://c.example.com/image.png'),+ startRequest('https://d.example.com/image.png'),+ ]+ await Promise.resolve()+ jest.advanceTimersByTime(10_000)+ releaseFirst?.()+ await jest.runAllTimersAsync()+ await Promise.all(requests)++ expect(startedAtMs).toEqual([1_700_000_000_000, 1_700_000_010_000, 1_700_000_010_000, 1_700_000_011_000])+ })++ it('returns a crawl wait that is longer than the pass deadline', async () => {+ const budget = new HostBudget(OPTIONS)+ budget.setCrawlDelay(ORIGIN.origin, 600_000, Date.now())+ const scheduler = new OriginRequestScheduler(budget, 300)+ await expect(scheduler.runImage(ORIGIN, Date.now() + 10_000, () => Promise.resolve())).resolves.toMatchObject({+ ran: true,+ })++ await expect(scheduler.runImage(ORIGIN, Date.now() + 20_000, () => Promise.resolve())).resolves.toEqual({+ ran: false,+ reason: 'deadline',+ waitMs: 600_000,+ })+ })++ it('shares the connection limit across sibling origins', async () => {+ const scheduler = new OriginRequestScheduler(new HostBudget({ ...OPTIONS, maxConcurrent: 1 }), 300)+ let releaseFirst: (() => void) | undefined+ const first = scheduler.runImage(+ new URL('https://a.example.com/image.png'),+ Date.now() + 10_000,+ () =>+ new Promise<void>((resolve) => {+ releaseFirst = resolve+ })+ )++ await Promise.resolve()+ await expect(+ scheduler.runImage(new URL('https://b.example.com/image.png'), Date.now() + 10_000, () => Promise.resolve())+ ).resolves.toEqual({ ran: false, reason: 'connection_limit', waitMs: 0 })++ releaseFirst?.()+ await expect(first).resolves.toEqual({ ran: true, value: undefined })+ })++ it('counts a configuration request against the registrable-domain connection limit', async () => {+ const scheduler = new OriginRequestScheduler(new HostBudget({ ...OPTIONS, maxConcurrent: 1 }), 300)+ let releaseConfiguration: (() => void) | undefined+ const configuration = scheduler.run(+ new URL('https://a.example.com/robots.txt'),+ Date.now() + 10_000,+ () =>+ new Promise<void>((resolve) => {+ releaseConfiguration = resolve+ })+ )++ await Promise.resolve()+ await expect(+ scheduler.runImage(new URL('https://b.example.com/image.png'), Date.now() + 10_000, () => Promise.resolve())+ ).resolves.toEqual({ ran: false, reason: 'connection_limit', waitMs: 0 })++ expect(releaseConfiguration).toBeDefined()+ releaseConfiguration?.()+ await expect(configuration).resolves.toEqual({ ran: true, value: undefined })+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.tsnew file mode 100644index 000000000000..9b0175806477--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler.ts@@ -0,0 +1,123 @@+import { ConcurrencyController } from '~/common/utils/concurrencyController'+import { delay } from '~/common/utils/utils'++import { ConfigurationRequestScheduler } from './configuration-policy'+import { BudgetBlockReason, HostBudget } from './host-budget'+import { ImageFetchRequestMetrics } from './metrics'+import { politenessKey } from './politeness-key'++export type ScheduledRequest<T> =+ | { ran: true; value: T }+ | { ran: false; reason: BudgetBlockReason | 'connection_limit'; waitMs: number }++export class OriginRequestScheduler implements ConfigurationRequestScheduler {+ private readonly inFlight: ConcurrencyController++ constructor(+ private readonly budget: HostBudget,+ maxInFlightRequests: number+ ) {+ this.inFlight = new ConcurrencyController(maxInFlightRequests)+ }++ public run<T>(url: URL, deadlineMs: number, request: () => Promise<T>): Promise<ScheduledRequest<T>> {+ return this.runScheduled(url, deadlineMs, true, request)+ }++ public runImage<T>(url: URL, deadlineMs: number, request: () => Promise<T>): Promise<ScheduledRequest<T>> {+ return this.runScheduled(url, deadlineMs, false, request)+ }++ public get running(): number {+ return this.inFlight.running+ }++ private async runScheduled<T>(+ url: URL,+ deadlineMs: number,+ configurationRequest: boolean,+ request: () => Promise<T>+ ): Promise<ScheduledRequest<T>> {+ const origin = url.origin+ const registrableDomain = politenessKey(url.hostname)+ const nowMs = Date.now()+ if (!this.budget.requestScheduled(origin, nowMs)) {+ return { ran: false, reason: 'origin_map_full', waitMs: 0 }+ }+ try {+ for (;;) {+ const capacityWaitStartedAtMs = Date.now()+ const scheduled = await this.inFlight.run({+ debugTag: registrableDomain,+ fn: async () => {+ const checkedAtMs = Date.now()+ ImageFetchRequestMetrics.observeSchedulerWait(+ 'request_capacity',+ Math.max(0, checkedAtMs - capacityWaitStartedAtMs) / 1000+ )+ const grant = this.budget.take(+ registrableDomain,+ origin,+ checkedAtMs,+ deadlineMs,+ configurationRequest+ )+ if (!grant.granted) {+ return {+ kind: 'stopped',+ reason: grant.reason,+ waitMs: grant.waitMs,+ } as const+ }+ if (grant.waitMs > 0) {+ return {+ kind: 'wait',+ waitMs: grant.waitMs,+ waitScope: grant.waitScope ?? 'registrable_domain_rate',+ } as const+ }+ if (!this.budget.acquireConnection(registrableDomain, origin)) {+ this.budget.returnGrant(+ registrableDomain,+ origin,+ checkedAtMs,+ grant.reservedStartAtMs,+ grant.halfOpenProbe+ )+ return { kind: 'stopped', reason: 'connection_limit' as const, waitMs: 0 } as const+ }+ try {+ this.budget.markRequestStarted(+ registrableDomain,+ origin,+ Date.now(),+ grant.reservedStartAtMs,+ configurationRequest ? 'configuration' : 'image'+ )+ return { kind: 'ran', value: await request() } as const+ } finally {+ this.budget.releaseConnection(registrableDomain, origin)+ }+ },+ })+ if (scheduled.kind === 'ran') {+ return { ran: true, value: scheduled.value }+ }+ if (scheduled.kind === 'stopped') {+ return {+ ran: false,+ reason: scheduled.reason,+ waitMs: scheduled.waitMs,+ }+ }+ if (Date.now() + scheduled.waitMs > deadlineMs) {+ return { ran: false, reason: 'deadline', waitMs: scheduled.waitMs }+ }+ ImageFetchRequestMetrics.observeSchedulerWait(scheduled.waitScope, scheduled.waitMs / 1000)+ await delay(scheduled.waitMs)+ }+ } finally {+ this.budget.requestFinished(origin)+ }+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.tsindex 69e252f813fb..5d5d00aa1ac0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key.ts@@ -1,7 +1,6 @@/**- * The URL policy of the collector, reached through the node addon rather than reimplemented here. One- * public suffix list answers for the producer and for this lane, so the key a record arrives under- * and the key its budget is scoped to cannot drift.+ * The URL policy of the collector, reached through the node addon rather than reimplemented here.+ * One public suffix list keeps producer and consumer canonicalization aligned.** The addon holds a 15 MB native library, and `index.ts` imports every server whatever mode the pod* runs. This loads the addon on first use rather than at import, so only a pod in this lane pays for@@ -12,7 +11,11 @@ let cached: typeof import('@posthog/replay-anonymizer') | undefinedfunction addon(): typeof import('@posthog/replay-anonymizer') {if (!cached) {const loaded = require('@posthog/replay-anonymizer') as typeof import('@posthog/replay-anonymizer')- if (typeof loaded.politenessKey !== 'function' || typeof loaded.isPublicHost !== 'function') {+ if (+ typeof loaded.politenessKey !== 'function' ||+ typeof loaded.isPublicHost !== 'function' ||+ typeof loaded.canonicalizeUrl !== 'function'+ ) {throw new Error('the replay-anonymizer addon is missing the url policy: rebuild index.node')}cached = loaded@@ -23,9 +26,7 @@ function addon(): typeof import('@posthog/replay-anonymizer') {/*** Load the addon now, so a stale `index.node` stops the pod at startup.*- * The parser calls into it for every URL, and requirement 23 says a record is counted and dropped- * rather than thrown. A throw from there would crash loop on the first batch and stall the- * partition for every site on it.+ * The parser calls into it for every URL. A stale addon must stop the pod before it reads a batch.*/export function assertUrlPolicyLoaded(): void {addon()@@ -36,13 +37,16 @@ export function politenessKey(host: string): string {}/**- * False for a host the collector would have declined: a private or reserved address, and a name- * that only resolves inside a network.+ * False for a host the collector would decline, including private and reserved names.** The connection layer refuses a private address, so this is not the only guard against one. It is* the only guard against a name that looks internal and whose DNS answer is public, because no- * address check can refuse that. Requirement 35.+ * address check can refuse that.*/export function isPublicHost(host: string): boolean {return addon().isPublicHost(host)}++export function canonicalizeUrl(url: string): import('@posthog/replay-anonymizer').CanonicalUrl | null {+ return addon().canonicalizeUrl(url)+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.test.tsindex cf465377f1b0..0acc4f6fe122 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.test.ts@@ -2,165 +2,181 @@ import { Message } from 'node-rdkafka'import { KafkaProducerWrapper } from '~/common/kafka/producer'+import { RetryDelayMetrics } from './metrics'import { RetryDelayConsumer } from './retry-delay-consumer'+const NOW_MS = 1_700_000_000_000const DELAY_MS = 60_000const FRONTIER = 'session_replay_image_fetch'-function message(writtenAtMs: number, overrides: Partial<Message> = {}): Message {+function message(timestamp: number | undefined, overrides: Partial<Message> = {}): Message {return {value: Buffer.from('{"v":1}'),key: Buffer.from('example.com'),size: 7,- topic: 'session_replay_image_fetch_retry_1m',+ topic: 'ai_research_session_replay_image_fetch_retry_1m',partition: 0,offset: 0,- timestamp: writtenAtMs,+ timestamp,...overrides,}}-function build(overrides: { isStopping?: () => boolean; produce?: () => Promise<void>; delayMs?: number } = {}): {+interface Harness {consumer: RetryDelayConsumer- published: string[]- stored: number[]- beats: () => number-} {- const published: string[] = []- const stored: number[] = []- let beats = 0- const producer = {- produce: async ({ topic }: { topic: string }) => {- await (overrides.produce?.() ?? Promise.resolve())- published.push(topic)- },- } as unknown as KafkaProducerWrapper- const consumer = new RetryDelayConsumer(producer, {+ produce: jest.Mock<Promise<void>, any[]>+ storeOffsets: jest.Mock<void, [Message[]]>+ heartbeat: jest.Mock<void, []>+}++function build(overrides: { isStopping?: () => boolean; delayMs?: number } = {}): Harness {+ const produce = jest.fn(() => Promise.resolve())+ const storeOffsets = jest.fn()+ const heartbeat = jest.fn()+ const consumer = new RetryDelayConsumer({ produce } as unknown as KafkaProducerWrapper, {frontierTopic: FRONTIER,delayMs: overrides.delayMs ?? DELAY_MS,- heartbeat: () => beats++,- heartbeatIntervalMs: 1,- storeOffset: (m) => stored.push(m.offset),+ heartbeat,+ heartbeatIntervalMs: 10_000,isStopping: overrides.isStopping,+ storeOffsets,})- return { consumer, published, stored, beats: () => beats }+ return { consumer, produce, storeOffsets, heartbeat }}describe('RetryDelayConsumer', () => {- it('publishes a record whose period has already passed, without waiting', async () => {- const { consumer, published, stored } = build()-- await consumer.handleBatch([message(Date.now() - DELAY_MS - 1000)])+ beforeEach(() => jest.useFakeTimers().setSystemTime(NOW_MS))+ afterEach(() => {+ jest.restoreAllMocks()+ jest.useRealTimers()+ })- expect(published).toEqual([FRONTIER])- expect(stored).toEqual([0])+ it.each([0, -1, Number.NaN])('refuses an invalid delay of %p', (delayMs) => {+ expect(() => build({ delayMs })).toThrow('positive delay')})- it('waits out what is left of the period, measured from when the record was written', async () => {- // A consumer that restarts must not begin the wait again, or a record could be held for- // several periods by a rolling deploy.- const { consumer, published, beats } = build()+ it('does nothing for an empty batch', async () => {+ const harness = build()- await consumer.handleBatch([message(Date.now() - DELAY_MS + 20)])+ await harness.consumer.handleBatch([])- expect(published).toEqual([FRONTIER])- expect(beats()).toBeGreaterThan(0)+ expect(harness.produce).not.toHaveBeenCalled()+ expect(harness.storeOffsets).not.toHaveBeenCalled()})- it('waits no longer than the period of its topic, whatever the record timestamp says', async () => {- // The timestamp comes from whichever pod wrote the record. A clock ahead of this one would- // otherwise hold the record for longer than the tier it is in.- const { consumer, published } = build({ delayMs: 50 })+ it('publishes a ripe batch and stores its offsets once', async () => {+ const harness = build()+ const messages = [message(NOW_MS - DELAY_MS, { offset: 1 }), message(NOW_MS - DELAY_MS, { offset: 2 })]- const startedAt = Date.now()- await consumer.handleBatch([message(Date.now() + 60 * 60 * 1000, { offset: 1 })])+ await harness.consumer.handleBatch(messages)- expect(published).toEqual([FRONTIER])- expect(Date.now() - startedAt).toBeLessThan(DELAY_MS)+ expect(harness.produce).toHaveBeenCalledTimes(2)+ expect(harness.produce.mock.calls[0][0]).toMatchObject({+ topic: FRONTIER,+ key: messages[0].key,+ value: messages[0].value,+ })+ expect(harness.storeOffsets).toHaveBeenCalledTimes(1)+ expect(harness.storeOffsets).toHaveBeenCalledWith(messages)})- it('abandons a record when the pod is shutting down before the wait starts', async () => {- const { consumer, published, stored } = build({ isStopping: () => true })+ it('waits once for the newest append timestamp in the batch', async () => {+ const harness = build()+ const older = message(NOW_MS - 30_000, { offset: 1 })+ const newer = message(NOW_MS - 10_000, { offset: 2 })- await consumer.handleBatch([message(Date.now())])+ const handled = harness.consumer.handleBatch([older, newer])+ await jest.advanceTimersByTimeAsync(30_000)+ expect(harness.produce).not.toHaveBeenCalled()+ await jest.advanceTimersByTimeAsync(20_000)+ await handled- expect(published).toEqual([])- expect(stored).toEqual([])+ expect(harness.produce).toHaveBeenCalledTimes(2)+ expect(harness.storeOffsets).toHaveBeenCalledTimes(1)})- it('gives up a wait in progress rather than finishing it', async () => {- // A record with a full period left would otherwise hold a rolling deploy for that period,- // until Kubernetes killed the pod. The offset stays uncommitted, so the next pod reads the- // record and waits out what remains.- let stopping = false- const { consumer, published, stored } = build({ isStopping: () => stopping })- setTimeout(() => (stopping = true), 20)+ it('reports health while a batch is deliberately waiting', async () => {+ const harness = build()- const startedAt = Date.now()- await consumer.handleBatch([message(Date.now())])- const elapsed = Date.now() - startedAt+ const handled = harness.consumer.handleBatch([message(NOW_MS)])+ await jest.advanceTimersByTimeAsync(DELAY_MS)+ await handled- expect(published).toEqual([])- expect(stored).toEqual([])- // The record had the whole period left. Returning anywhere near it means the wait ran on.- expect(elapsed).toBeLessThan(DELAY_MS / 10)+ expect(harness.heartbeat).toHaveBeenCalledTimes(7)})- it('fails the batch for a record it could not publish, so no later offset commits past it', async () => {- // Storing nothing is not enough on its own. The next poll would read the records after this- // one and store one of their offsets, and an offset is a high water mark.- const { consumer, published, stored } = build({- produce: () => Promise.reject(new Error('broker down')),- })+ it.each([undefined, Number.NaN, 0, -1])(+ 'throws for an invalid broker append timestamp of %p',+ async (timestamp) => {+ const harness = build()+ const incReleased = jest.spyOn(RetryDelayMetrics, 'incReleased')++ await expect(harness.consumer.handleBatch([message(timestamp)])).rejects.toThrow(+ 'requires broker append timestamps'+ )+ expect(incReleased).toHaveBeenCalledWith('invalid_timestamp', 1)+ expect(harness.produce).not.toHaveBeenCalled()+ expect(harness.storeOffsets).not.toHaveBeenCalled()+ }+ )++ it('throws and stores no offset when any frontier publish fails', async () => {+ const harness = build()+ harness.produce.mockRejectedValueOnce(new Error('broker unavailable'))++ await expect(harness.consumer.handleBatch([message(NOW_MS - DELAY_MS)])).rejects.toThrow(+ 'could not publish a record back to the frontier'+ )+ expect(harness.storeOffsets).not.toHaveBeenCalled()+ })- await expect(consumer.handleBatch([message(Date.now() - DELAY_MS - 1000)])).rejects.toThrow(+ it('stops publishing the batch after the first frontier failure', async () => {+ const harness = build()+ harness.produce.mockResolvedValueOnce().mockRejectedValueOnce(new Error('broker unavailable'))+ const messages = [+ message(NOW_MS - DELAY_MS, { offset: 1 }),+ message(NOW_MS - DELAY_MS, { offset: 2 }),+ message(NOW_MS - DELAY_MS, { offset: 3 }),+ ]++ await expect(harness.consumer.handleBatch(messages)).rejects.toThrow('could not publish a record back to the frontier')- expect(published).toEqual([])- expect(stored).toEqual([])+ expect(harness.produce).toHaveBeenCalledTimes(2)+ expect(harness.storeOffsets).not.toHaveBeenCalled()})- it('stores the offset of a record it can never publish, so the partition still moves', async () => {- const { consumer, published, stored } = build()+ it('stores the batch offset after it skips a malformed record', async () => {+ const harness = build()+ const malformed = message(NOW_MS - DELAY_MS, { value: null })- await consumer.handleBatch([message(Date.now() - DELAY_MS - 1000, { offset: 7, value: null })])+ await harness.consumer.handleBatch([malformed])- expect(published).toEqual([])- expect(stored).toEqual([7])+ expect(harness.produce).not.toHaveBeenCalled()+ expect(harness.storeOffsets).toHaveBeenCalledWith([malformed])})- it('stores each offset as it goes, so a shutdown keeps only the records it did not reach', async () => {- // Requirement 21. The consumer that owns this one stores offsets for a whole batch once the- // handler returns, so anything left unstored here must stay unstored there.- let releasedSoFar = 0- const { consumer, published, stored } = build({- produce: () => Promise.resolve(releasedSoFar++).then(() => {}),- isStopping: () => releasedSoFar >= 2,- })- const ripe = Date.now() - DELAY_MS - 1000+ it('abandons the batch without storing offsets when shutdown has started', async () => {+ const harness = build({ isStopping: () => true })- await consumer.handleBatch([- message(ripe, { offset: 4 }),- message(ripe, { offset: 5 }),- message(ripe, { offset: 6 }),- ])+ await harness.consumer.handleBatch([message(NOW_MS)])- expect(published).toEqual([FRONTIER, FRONTIER])- expect(stored).toEqual([4, 5])+ expect(harness.produce).not.toHaveBeenCalled()+ expect(harness.storeOffsets).not.toHaveBeenCalled()})- it.each([[0], [-1], [NaN]])('refuses to start with a delay of %p', (delayMs) => {- const producer = {} as KafkaProducerWrapper-- expect(- () =>- new RetryDelayConsumer(producer, {- frontierTopic: FRONTIER,- delayMs,- heartbeat: () => {},- storeOffset: () => {},- })- ).toThrow('positive delay')+ it('abandons an active wait when shutdown starts', async () => {+ let stopping = false+ const harness = build({ isStopping: () => stopping })+ const handled = harness.consumer.handleBatch([message(NOW_MS)])++ await jest.advanceTimersByTimeAsync(10_000)+ stopping = true+ await jest.advanceTimersByTimeAsync(10_000)+ await handled++ expect(harness.produce).not.toHaveBeenCalled()+ expect(harness.storeOffsets).not.toHaveBeenCalled()})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.tsindex 416e312dc46e..2f812046d8a9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer.ts@@ -16,12 +16,7 @@ export interface RetryDelayConsumerOptions {heartbeatIntervalMs?: number/** True once the pod is shutting down. A wait of an hour would otherwise hold the rolling deploy until Kubernetes killed it. */isStopping?: () => boolean- /**- * Called only for a record this consumer finished with. The consumer that owns this one stores- * offsets for a whole batch once the handler returns, whatever the handler did with the- * records, so a record abandoned mid-wait would commit and never be seen again. Requirement 21.- */- storeOffset: (message: Message) => void+ storeOffsets: (messages: Message[]) => void}const DEFAULT_HEARTBEAT_INTERVAL_MS = 10_000@@ -50,31 +45,33 @@ export class RetryDelayConsumer {}public async handleBatch(messages: Message[]): Promise<void> {- for (const message of messages) {- if (this.stopping()) {- // The record stays where it is, with no offset stored. The next pod to own this- // partition reads it again and waits out what is left of its period, measured from- // when it was written. Requirement 21.- RetryDelayMetrics.incReleased('abandoned')+ if (messages.length === 0) {+ return+ }+ if (this.stopping()) {+ RetryDelayMetrics.incReleased('abandoned', messages.length)+ return+ }+ const invalidTimestampCount = messages.filter(+ (message) =>+ message.timestamp === undefined || !Number.isFinite(message.timestamp) || message.timestamp <= 0+ ).length+ if (invalidTimestampCount > 0) {+ RetryDelayMetrics.incReleased('invalid_timestamp', invalidTimestampCount)+ throw new Error('the image fetch retry lane requires broker append timestamps')+ }+ const waitMs = this.remainingBatchWaitMs(messages)+ if (waitMs > 0) {+ RetryDelayMetrics.observeWait(waitMs / 1000)+ if (!(await this.sleepWithHeartbeat(waitMs))) {+ RetryDelayMetrics.incReleased('abandoned', messages.length)return}- const waitMs = this.remainingWaitMs(message)- if (waitMs > 0) {- RetryDelayMetrics.observeWait(waitMs / 1000)- if (!(await this.sleepWithHeartbeat(waitMs))) {- RetryDelayMetrics.incReleased('abandoned')- return- }- }- if (!(await this.release(message))) {- // Thrown, not returned. Returning holds this batch and no more: the next poll reads- // the records after it and stores one of their offsets, and an offset is a high- // water mark, so that commits this record too. A throw leaves the poll loop, so- // nothing is stored and the record is read again. Requirement 21.- throw new Error('the image fetch retry lane could not publish a record back to the frontier')- }- this.options.storeOffset(message)}+ for (const message of messages) {+ await this.release(message)+ }+ this.options.storeOffsets(messages)}private stopping(): boolean {@@ -86,12 +83,9 @@ export class RetryDelayConsumer {* that restarts does not begin the wait again. librdkafka reports an absent timestamp as -1,* which is not nullish, so a plain `??` would make the whole period look already spent.*/- private remainingWaitMs(message: Message): number {- const writtenAtMs = message.timestamp !== undefined && message.timestamp > 0 ? message.timestamp : Date.now()- // Clamped to the period, because the timestamp comes from whichever pod wrote the record.- // A clock ahead of this one would otherwise hold the record for longer than its tier, and- // the tier period is the whole reason a record can be held here at all.- return Math.min(this.options.delayMs, writtenAtMs + this.options.delayMs - Date.now())+ private remainingBatchWaitMs(messages: Message[]): number {+ const latestReadyAtMs = Math.max(...messages.map((message) => message.timestamp! + this.options.delayMs))+ return Math.max(0, latestReadyAtMs - Date.now())}/** False when the pod started shutting down during the wait, so the caller abandons the record. */@@ -115,12 +109,10 @@ export class RetryDelayConsumer {* A failed produce returns false, because reading the record again is the only way it comes* back. Nothing else holds it.*/- private async release(message: Message): Promise<boolean> {+ private async release(message: Message): Promise<void> {if (!message.value || !message.key) {- // The offset stores anyway. This record can never be released, and holding its offset- // would stop the partition rather than fix it.RetryDelayMetrics.incReleased('malformed')- return true+ return}try {await this.producer.produce({@@ -133,9 +125,10 @@ export class RetryDelayConsumer {error: error instanceof Error ? error.name : 'unknown',})RetryDelayMetrics.incReleased('failed')- return false+ throw new Error('the image fetch retry lane could not publish a record back to the frontier', {+ cause: error,+ })}RetryDelayMetrics.incReleased('released')- return true}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.test.tsdeleted file mode 100644index dccee6597632..000000000000--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.test.ts+++ /dev/null@@ -1,96 +0,0 @@-import { TeamVolume } from './team-volume'--/**- * These tests pin the bound, the accounting, and the estimate. They do not pin the count inheritance- * on eviction, which is the step that guarantees the map always holds a team above total over- * capacity. A change that drops it makes this a random-eviction cache, which still finds a heavy team- * often enough that no small test fails.- */-describe('TeamVolume', () => {- it('names the busiest teams and sums the rest into one bucket (requirement 29)', () => {- const volume = new TeamVolume(2)- volume.record('busiest', 100)- volume.record('second', 50)- volume.record('third', 7)- volume.record('fourth', 3)-- expect(volume.top()).toEqual([- { team: 'busiest', count: 100 },- { team: 'second', count: 50 },- { team: 'other', count: 10 },- ])- })-- it('names every team when there are fewer than the limit', () => {- const volume = new TeamVolume(20)- volume.record('only', 5)-- // No `other` row: an empty bucket would be a series carrying nothing.- expect(volume.top()).toEqual([{ team: 'only', count: 5 }])- })-- it.each([- [1, 1],- [10, 10],- [500, 500],- [50_000, 50_000],- ])('estimates %i distinct teams (requirement 30)', (teams, expected) => {- // A reader takes the order of magnitude, so a few percent of error costs nothing. A set would- // be exact and would cost hundreds of megabytes at the top of this range.- const volume = new TeamVolume()- for (let i = 0; i < teams; i++) {- volume.record(`team-${i}`)- }-- const estimate = volume.distinctTeams()-- expect(estimate).toBeGreaterThan(expected * 0.9)- expect(estimate).toBeLessThan(expected * 1.1)- })-- it('holds a bounded number of counters however many teams arrive', () => {- // Someone who spreads traffic over many project tokens must not grow this map for the life- // of the pod. The map keeps the metric label bounded, so the map must stay bounded itself.- const volume = new TeamVolume(20)-- for (let i = 0; i < 100_000; i++) {- volume.record(`team-${i}`)- }-- expect(volume.trackedTeams).toBeLessThanOrEqual(200)- })-- it('keeps a busy team named through a flood of teams seen once (requirement 29)', () => {- // Space-Saving holds any team whose share is above total divided by the counters kept. Here- // that is 15000 over 20, so 750, and a team at a third of all volume sits far above it.- // Someone who spreads traffic over many tokens therefore cannot hide a heavy team.- const volume = new TeamVolume(2)- volume.record('busy', 5_000)-- for (let i = 0; i < 10_000; i++) {- volume.record(`noise-${i}`)- }-- expect(volume.top()[0].team).toBe('busy')- })-- it('accounts for every URL it was given, named or not', () => {- const volume = new TeamVolume(2)- volume.record('a', 10)- volume.record('b', 5)- volume.record('c', 3)- volume.record('d', 2)-- expect(volume.top().reduce((sum, { count }) => sum + count, 0)).toBe(20)- })-- it('counts a repeated team once', () => {- const volume = new TeamVolume()- for (let i = 0; i < 1000; i++) {- volume.record('same')- }-- expect(volume.distinctTeams()).toBe(1)- expect(volume.top()).toEqual([{ team: 'same', count: 1000 }])- })-})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.tsdeleted file mode 100644index e03dfa2dbdcc..000000000000--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/team-volume.ts+++ /dev/null@@ -1,138 +0,0 @@-import { createHash } from 'node:crypto'--/** This many teams keep their name. The class sums everything else into `other`. */-const DEFAULT_TOP_N = 20--/**- * Counters held to find those teams, wider than the reported list so that the reported list is- * right. Space-Saving holds any team whose share is above one over this number of counters. At 200- * counters that is half a percent of the lane's volume.- *- * The count is bounded because the team ID space is in the low millions. A map of every team ever- * seen is the unbounded growth this class exists to avoid.- */-const TRACKED_MULTIPLE = 10--/**- * Registers of the estimator. 2^12 gives about 1.6% error for a few kilobytes, which is far finer- * than any decision this number feeds.- */-const HLL_REGISTER_BITS = 12-const HLL_REGISTERS = 1 << HLL_REGISTER_BITS--/**- * How much of the lane one team uses, without a `team_id` label on anything.- *- * The team ID space is in the low millions. A label of that cardinality is unbounded twice over: in- * the time series database, and in the memory of this process, because prom-client holds every label- * combination for the life of the pod. So this class holds the identities of the busiest teams,- * bounded, and counts everything else without a name.- *- * Requirements 29, 30, and 31.- */-export class TeamVolume {- private readonly counts = new Map<string, number>()- private readonly registers = new Uint8Array(HLL_REGISTERS)- private readonly capacity: number- private total = 0-- constructor(private readonly topN: number = DEFAULT_TOP_N) {- this.capacity = topN * TRACKED_MULTIPLE- }-- /**- * Space-Saving: a full map replaces its smallest counter rather than grows.- *- * The replacement inherits the count it displaced, so a team that keeps arriving climbs past the- * churn of teams seen once. A flood of quiet teams therefore cannot push a busy team out, and- * that flood is what someone who spreads traffic over many project tokens produces.- */- public record(team: string, count = 1): void {- this.total += count- this.observeDistinct(team)-- const seen = this.counts.get(team)- if (seen !== undefined) {- this.counts.set(team, seen + count)- return- }- if (this.counts.size < this.capacity) {- this.counts.set(team, count)- return- }- const smallest = this.smallest()- this.counts.delete(smallest.team)- this.counts.set(team, smallest.count + count)- }-- private smallest(): { team: string; count: number } {- let team = ''- let count = Infinity- for (const [candidate, candidateCount] of this.counts) {- if (candidateCount < count) {- team = candidate- count = candidateCount- }- }- return { team, count }- }-- /**- * The busiest teams by name, and everything else summed as `other`.- *- * This sorts on each read rather than keeps an order on each record, because a read happens once- * for each scrape and a record happens once for each URL.- */- public top(): { team: string; count: number }[] {- const sorted = [...this.counts].sort((left, right) => right[1] - left[1])- const named = sorted.slice(0, this.topN).map(([team, count]) => ({ team, count }))- // Everything this pod handled, less what the named rows account for. This reads the running- // total, because the counters of the untracked teams no longer exist.- const rest = this.total - named.reduce((sum, { count }) => sum + count, 0)- return rest > 0 ? [...named, { team: 'other', count: rest }] : named- }-- /**- * About how many distinct teams this pod saw. HyperLogLog rather than a set, because a set of a- * million team IDs is hundreds of megabytes, and a reader only ever takes the order of magnitude.- */- public distinctTeams(): number {- let sum = 0- let empty = 0- for (const rank of this.registers) {- sum += 2 ** -rank- if (rank === 0) {- empty++- }- }- const estimate = (ALPHA * HLL_REGISTERS * HLL_REGISTERS) / sum- // The estimator is biased below this point, and a count of the untouched registers is exact there.- if (estimate <= 2.5 * HLL_REGISTERS && empty > 0) {- return Math.round(HLL_REGISTERS * Math.log(HLL_REGISTERS / empty))- }- return Math.round(estimate)- }-- /** Counters held right now, which never pass the capacity. */- public get trackedTeams(): number {- return this.counts.size- }-- private observeDistinct(team: string): void {- // The team ID is already an HMAC on this topic, but it is not uniform across the register- // index and the leading zero count, and the estimator needs both of them to be uniform.- const digest = createHash('sha1').update(team).digest()- const index = digest.readUInt16BE(0) % HLL_REGISTERS- const rank = leadingZeros(digest.readUInt32BE(2)) + 1- if (rank > this.registers[index]) {- this.registers[index] = rank- }- }-}--/** The bias constant for this register count, from the HyperLogLog paper. */-const ALPHA = 0.7213 / (1 + 1.079 / HLL_REGISTERS)--function leadingZeros(value: number): number {- return value === 0 ? 32 : Math.clz32(value)-}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.tsindex 04f1dc474989..7bf3e39d4cb6 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@@ -1,409 +1,353 @@import { Message } from 'node-rdkafka'-import { FetchCandidate } from './collected-urls-record'-import { CrawlHistoryReadResult, CrawlHistoryStore, crawlHistoryKey } from './crawl-history'-import { AttemptOutcome, FetchPass, isTerminal } from './fetch-runner'-import { FrontierPublisher } from './frontier-publisher'+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 { UrlFetchConsumer } from './url-fetch-consumer'-const TEAM = '0123456789abcdef0123456789abcdef'-const OTHER_TEAM = 'fedcba9876543210fedcba9876543210'-const NOW = 1_700_000_000_000+const NOW_MS = 1_700_000_000_000-/** The ref format fixes the hash at 22 base64url characters, so a short test name needs padding. */-const hash = (name: string): string => name.padEnd(22, '0')+function candidate(name: string, overrides: Partial<FetchCandidate> = {}): FetchCandidate {+ const hash = name.padEnd(22, '0')+ return {+ originalRef: `imageurl:${hash}`,+ currentUrl: `https://cdn.example.com/${name}.png`,+ host: 'cdn.example.com',+ origin: 'https://cdn.example.com',+ registrableDomain: 'example.com',+ remainingHops: MAX_HOPS,+ notBeforeMs: 0,+ firstSeenAtMs: NOW_MS,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,+ ...overrides,+ }+}-function ref(name: string, team: string = TEAM): string {- return `imageurl:${team}:${hash(name)}`+function message(candidates: FetchCandidate[], key = 'example.com'): Message {+ const value = serializeFrontierRecord(candidates)+ return {+ value,+ key: Buffer.from(key),+ size: value.length,+ topic: 'session_replay_image_fetch',+ partition: 0,+ offset: 0,+ }}class FakeCrawlHistory implements CrawlHistoryStore {- public readonly stored = new Map<string, number>()- public readFailure: Error | null = null- public writeFailure: Error | null = null- /** Keys whose individual write reports a failure. */- public partialWriteFailures = new Set<string>()- /** Keys whose read did not complete, so the store can say nothing about them. */- public partialReadFailures = new Set<string>()- public reads = 0-- read(keys: string[], _nowMs: number): Promise<CrawlHistoryReadResult> {- this.reads++- if (this.readFailure) {- return Promise.reject(this.readFailure)+ public readonly items = new Map<string, CrawlHistoryItem>()+ public readKeys: string[][] = []+ public writes: CrawlHistoryItem[][] = []+ public readError: Error | undefined+ public writeError: Error | undefined++ read(keys: string[]): Promise<Map<string, CrawlHistoryItem>> {+ this.readKeys.push(keys)+ if (this.readError) {+ return Promise.reject(this.readError)}- const known = new Set<number>()- const failed = new Set<number>()- keys.forEach((key, index) => {- if (this.partialReadFailures.has(key)) {- failed.add(index)- } else if (this.stored.has(key)) {- known.add(index)- }- })- return Promise.resolve({ known, failed })+ return Promise.resolve(+ new Map(keys.flatMap((key) => (this.items.has(key) ? [[key, this.items.get(key)!] as const] : [])))+ )}- record(keys: string[], nowMs: number): Promise<{ failed: Set<number> }> {- if (this.writeFailure) {- return Promise.reject(this.writeFailure)+ write(items: CrawlHistoryItem[]): Promise<void> {+ this.writes.push(items)+ if (this.writeError) {+ return Promise.reject(this.writeError)}- const failed = new Set<number>()- keys.forEach((key, index) => {- if (this.partialWriteFailures.has(key)) {- failed.add(index)- return- }- this.stored.set(key, nowMs)- })- return Promise.resolve({ failed })+ for (const item of items) {+ this.items.set(item.key, item)+ }+ return Promise.resolve()}}-/** A real Message, so the type fails if the consumer starts to read a field this omits. */-function message(value: Buffer | null, key: string | null): Message {+function terminal(candidate: FetchCandidate, outcome: AttemptOutcome = 'ok'): FetchAttempt {return {- value,- key: key === null ? null : Buffer.from(key),- size: value?.length ?? 0,- topic: 'session_replay_image_fetch',- partition: 0,- offset: 0,+ candidate,+ outcome,+ finished: true,+ lost: false,+ history: {+ kind: 'url',+ key: candidate.originalRef,+ nextFetchAtMs: NOW_MS + 30 * 24 * 60 * 60 * 1000,+ storageExpiresAtMs: NOW_MS + 30 * 24 * 60 * 60 * 1000,+ outcome,+ },+ configurationUpdates: [],}}-function record(- urls: { ref: string; url: string; host: string }[],- overrides: { v?: unknown; pseudoTeam?: string; capturedAtMs?: number; key?: string | null } = {}-): Message {- const body = {- v: overrides.v ?? 1,- pseudoTeam: overrides.pseudoTeam ?? TEAM,- capturedAtMs: overrides.capturedAtMs ?? NOW,- urls,- }- return message(Buffer.from(JSON.stringify(body)), overrides.key === null ? null : (overrides.key ?? 'example.com'))+interface Harness {+ consumer: UrlFetchConsumer+ history: FakeCrawlHistory+ run: jest.Mock<Promise<FetchAttempt[]>, [FetchCandidate[], Map<string, CrawlHistoryItem>]>+ republish: jest.Mock<Promise<RepublishResult>, any[]>}-function url(name: string, host = 'cdn.example.com'): { ref: string; url: string; host: string } {- return { ref: ref(name), url: `https://${host}/${name}.png`, host }+function build(dryRun = false): Harness {+ const history = new FakeCrawlHistory()+ 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 consumer = new UrlFetchConsumer(+ history,+ { republish } as unknown as FrontierPublisher,+ { seenTtlSeconds: 30 * 24 * 60 * 60, dryRun },+ dryRun ? undefined : ({ run } as FetchPass)+ )+ return { consumer, history, run, republish }}describe('UrlFetchConsumer', () => {- let crawlHistory: FakeCrawlHistory- let consumer: UrlFetchConsumer- let republished: { reason: string; waitMs: number }[]- let publisher: FrontierPublisher-- const build = (dedupMaxRefs = 1000): UrlFetchConsumer =>- new UrlFetchConsumer(crawlHistory, publisher, {- maxAgeMs: 6 * 60 * 60 * 1000,- dedupMaxRefs,- seenTtlSeconds: 7 * 24 * 60 * 60,- dryRun: true,- })-- beforeEach(() => {- crawlHistory = new FakeCrawlHistory()- republished = []- publisher = {- republish: (_c: unknown, _t: unknown, reason: string, waitMs: number) => {- republished.push({ reason, waitMs })- return Promise.resolve(true)- },- } as unknown as FrontierPublisher- consumer = build()- })+ afterEach(() => jest.restoreAllMocks())- const hashOf = (key: string): string => key.split(':').pop() as string-- it.each([NaN, 0, -1])('refuses to start with an age limit of %p', (maxAgeMs) => {- // The limit arrives from env, where a typo parses to NaN. A NaN limit makes every comparison- // false, so the lane stops shedding a backlog rather than fails.+ it.each([Number.NaN, 0, 3_599, 3_600.5])('refuses an invalid crawl-history TTL of %p', (seenTtlSeconds) => {expect(() =>- new UrlFetchConsumer(crawlHistory, publisher, {- maxAgeMs,- dedupMaxRefs: 10,- seenTtlSeconds: 604_800,- dryRun: true,- })- ).toThrow('SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS')+ new UrlFetchConsumer(new FakeCrawlHistory(), {} as FrontierPublisher, { seenTtlSeconds, dryRun: true })+ ).toThrow('AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS')})- it.each([NaN, 0, -1, 1.5, 7, 3599])('refuses to start with a seen TTL of %p', (seenTtlSeconds) => {- // The TTL arrives from env, where a typo parses to NaN and a unit suffix truncates: "7d"- // parses to 7, and a 7-second TTL empties the ledger as fast as it fills. A NaN expiry makes- // every ledger write fail while the lane looks healthy.+ it('refuses active mode without a fetch pass', () => {expect(() =>- new UrlFetchConsumer(crawlHistory, publisher, {- maxAgeMs: 1000,- dedupMaxRefs: 10,- seenTtlSeconds,- dryRun: true,+ new UrlFetchConsumer(new FakeCrawlHistory(), {} as FrontierPublisher, {+ seenTtlSeconds: 3_600,+ dryRun: false,})- ).toThrow('AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS')+ ).toThrow('fetch runner')})- it('writes one ledger entry per URL it would fetch', async () => {- await consumer.handleBatch([record([url('a'), url('b')])], NOW)-- expect([...crawlHistory.stored.keys()].map(hashOf).sort()).toEqual([hash('a'), hash('b')])- })+ it('parses dry-run traffic without reading or writing shared state', async () => {+ const harness = build(true)- it('does not re-record a URL another pod already reached', async () => {- crawlHistory.stored.set(crawlHistoryKey(TEAM, hash('a')), NOW - 1000)+ await harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)- await consumer.handleBatch([record([url('a'), url('b')])], NOW)+ expect(harness.history.readKeys).toEqual([])+ expect(harness.history.writes).toEqual([])+ })- // The earlier entry survives, so the store measures the hit rate rather than the rate of- // first arrivals.- expect(crawlHistory.stored.get(crawlHistoryKey(TEAM, hash('a')))).toBe(NOW - 1000)- expect(crawlHistory.stored.get(crawlHistoryKey(TEAM, hash('b')))).toBe(NOW)+ it('bulk reads URL and per-origin configuration keys', async () => {+ const harness = build()++ await harness.consumer.handleBatch([message([candidate('a'), candidate('b')])], NOW_MS)++ expect(harness.history.readKeys).toEqual([+ [+ candidate('a').originalRef,+ candidate('b').originalRef,+ configurationCacheKey(candidate('a').origin, 'robots'),+ configurationCacheKey(candidate('a').origin, 'tdmrep'),+ ],+ ])+ expect(harness.run.mock.calls[0][0]).toEqual([candidate('a'), candidate('b')])+ expect(harness.history.writes[0]).toHaveLength(2)})- it('collapses a repeated URL inside one batch into a single ledger write', async () => {- await consumer.handleBatch([record([url('a')]), record([url('a')]), record([url('a')])], NOW)+ it('deduplicates one global ref within the batch', async () => {+ const harness = build()++ await harness.consumer.handleBatch([message([candidate('a')]), message([candidate('a')])], NOW_MS)- expect([...crawlHistory.stored.keys()]).toEqual([crawlHistoryKey(TEAM, hash('a'))])+ expect(harness.run.mock.calls[0][0]).toEqual([candidate('a')])})- it('does not consult the store for a URL this pod already handled', async () => {- await consumer.handleBatch([record([url('a')])], NOW)- const readsAfterFirst = crawlHistory.reads+ it('keeps the most conservative durable state from duplicate jobs', async () => {+ const harness = build()+ const stale = candidate('a')+ const advanced = candidate('a', {+ currentUrl: 'https://cdn.example.com/moved.png',+ remainingHops: 7,+ firstSeenAtMs: NOW_MS - 5_000,+ fetchCount: 4,+ republishCount: 3,+ lastRepublishReason: 'retry',+ })- await consumer.handleBatch([record([url('a')])], NOW)+ await harness.consumer.handleBatch([message([stale]), message([advanced])], NOW_MS)- expect(crawlHistory.reads).toBe(readsAfterFirst)+ expect(harness.run.mock.calls[0][0]).toEqual([advanced])})- it.each([- ['still waiting out its delay', NOW + 60_000, 0, [{ reason: 'not_ready', waitMs: 60_000 }]],- ['past its delay', NOW - 1, 1, []],- ])(- 'handles a retry that is %s (requirement 15)',- async (_name, notBeforeMs, expectedWrites, expectedRepublishes) => {- // A record can come back before its wait is over, because a wait longer than the longest- // delay topic goes round that topic again. An early fetch would reach a site that asked- // to be left alone, and a crawl history entry would stop the trip the URL still makes.- // It goes back for the rest of the wait, because nothing else holds it.- const body = {- v: 1,- pseudoTeam: TEAM,- capturedAtMs: NOW,- notBeforeMs,- urls: [url('a')],- }- const early = message(Buffer.from(JSON.stringify(body)), 'example.com')-- await consumer.handleBatch([early], NOW)-- expect(crawlHistory.stored.size).toBe(expectedWrites)- expect(republished).toEqual(expectedRepublishes)- }- )-- it('records a URL that is not ready and has no hops left (requirements 12 and 24)', async () => {- // It cannot go round again, and nothing else holds it. Without an entry it comes back on- // every session that refers to the image and is dropped again each time.- const body = {- v: 1,- pseudoTeam: TEAM,- capturedAtMs: NOW,- notBeforeMs: NOW + 60_000,- hopsRemaining: 1,- urls: [url('a')],- }- const spent = message(Buffer.from(JSON.stringify(body)), 'example.com')+ it('keeps the latest not-before time from duplicate jobs', async () => {+ const harness = build()+ const stale = candidate('a')+ const delayed = candidate('a', {+ remainingHops: 9,+ notBeforeMs: NOW_MS + 30_000,+ republishCount: 1,+ lastRepublishReason: 'retry',+ })- await consumer.handleBatch([spent], NOW)+ await harness.consumer.handleBatch([message([stale]), message([delayed])], NOW_MS)- expect([...crawlHistory.stored.keys()].map(hashOf)).toEqual([hash('a')])- expect(republished).toEqual([])+ expect(harness.run.mock.calls[0][0]).toEqual([])+ expect(harness.republish).toHaveBeenCalledWith(+ expect.objectContaining({ remainingHops: 9, notBeforeMs: NOW_MS + 30_000 }),+ expect.any(Object),+ 'not_ready',+ 30_000+ )})- it('fails the batch when a URL that is not ready cannot be sent back (requirement 21)', async () => {- publisher = { republish: () => Promise.resolve(false) } as unknown as FrontierPublisher- const body = { v: 1, pseudoTeam: TEAM, capturedAtMs: NOW, notBeforeMs: NOW + 60_000, urls: [url('a')] }- const early = message(Buffer.from(JSON.stringify(body)), 'example.com')+ it('skips a URL whose crawl-history interval has not ended', async () => {+ const harness = build()+ harness.history.items.set(candidate('a').originalRef, {+ kind: 'url',+ key: candidate('a').originalRef,+ nextFetchAtMs: NOW_MS + 1,+ storageExpiresAtMs: NOW_MS + 1,+ outcome: 'ok',+ })++ await harness.consumer.handleBatch([message([candidate('a'), candidate('b')])], NOW_MS)- await expect(build().handleBatch([early], NOW)).rejects.toThrow('account for 1')- expect(crawlHistory.stored.size).toBe(0)+ expect(harness.run.mock.calls[0][0]).toEqual([candidate('b')])})- it('drops a URL older than the age limit without recording it', async () => {- const sevenHoursAgo = NOW - 7 * 60 * 60 * 1000+ it('republishes a job that arrives before its durable not-before time', async () => {+ const harness = build()+ const early = candidate('a', { notBeforeMs: NOW_MS + 30_000 })- await consumer.handleBatch([record([url('a')], { capturedAtMs: sevenHoursAgo })], NOW)+ await harness.consumer.handleBatch([message([early])], NOW_MS)- expect(crawlHistory.stored.size).toBe(0)+ expect(harness.run.mock.calls[0][0]).toEqual([])+ expect(harness.republish).toHaveBeenCalledWith(+ early,+ {+ currentUrl: early.currentUrl,+ host: early.host,+ origin: early.origin,+ registrableDomain: early.registrableDomain,+ },+ 'not_ready',+ 30_000+ )+ expect(harness.history.writes).toEqual([])})- it.each([- ['an unsupported version', record([url('a')], { v: 2 })],- ['a missing kafka key', record([url('a')], { key: null })],- ['a body that is not json', message(Buffer.from('{oh no'), 'example.com')],- ['an empty value', message(null, 'example.com')],- ])('drops %s without throwing', async (_name, message) => {- await expect(consumer.handleBatch([message], NOW)).resolves.toBeUndefined()+ it('records a terminal refusal when the remaining delay is over one hour', async () => {+ const harness = build()+ harness.republish.mockResolvedValue('refused_delay')+ const early = candidate('a', { notBeforeMs: NOW_MS + 3_600_001 })- expect(crawlHistory.stored.size).toBe(0)- })+ await harness.consumer.handleBatch([message([early])], NOW_MS)- it.each([- [- 'a ref belonging to another team',- { ref: ref('a', OTHER_TEAM), url: 'https://cdn.example.com/a.png', host: 'cdn.example.com' },- ],- [- 'a bytes ref rather than a url ref',- { ref: `image:${TEAM}:${hash('a')}`, url: 'https://cdn.example.com/a.png', host: 'cdn.example.com' },- ],- [- 'a url whose host contradicts the entry',- { ref: ref('a'), url: 'https://evil.example.net/a.png', host: 'cdn.example.com' },- ],- ['a scheme we never fetch', { ref: ref('a'), url: 'ftp://cdn.example.com/a.png', host: 'cdn.example.com' }],- [- 'a port the scheme does not own',- { ref: ref('a'), url: 'https://cdn.example.com:11211/a.png', host: 'cdn.example.com' },- ],- [- 'a url carrying credentials',- { ref: ref('a'), url: 'https://user:[email protected]/a.png', host: 'cdn.example.com' },- ],- ])('rejects %s while keeping the rest of the record', async (_name, bad) => {- await consumer.handleBatch([record([bad as ReturnType<typeof url>, url('good')])], NOW)-- expect([...crawlHistory.stored.keys()].map(hashOf)).toEqual([hash('good')])+ expect(harness.history.writes[0]).toEqual([+ expect.objectContaining({ kind: 'url', key: early.originalRef, outcome: DELAY_TOO_LONG }),+ ])})- it('does not mark the pod cache for a URL whose write failed', async () => {- crawlHistory.partialWriteFailures.add(crawlHistoryKey(TEAM, hash('a')))+ it('records a terminal refusal when a delayed job has no remaining hops', async () => {+ const harness = build()+ const early = candidate('a', { notBeforeMs: NOW_MS + 30_000, remainingHops: 0 })- await consumer.handleBatch([record([url('a')])], NOW)- const readsAfterFirst = crawlHistory.reads- await consumer.handleBatch([record([url('a')])], NOW)+ await harness.consumer.handleBatch([message([early])], NOW_MS)- // No durable store holds the URL, so the next arrival must reach the store again rather than- // stop in this pod and vanish from the measurement.- expect(crawlHistory.reads).toBe(readsAfterFirst + 1)+ expect(harness.republish).not.toHaveBeenCalled()+ expect(harness.history.writes[0]).toEqual([+ expect.objectContaining({ kind: 'url', key: early.originalRef, outcome: HOPS_EXHAUSTED }),+ ])})- it('rejects a host outside the domain the record is keyed by', async () => {- // The key scopes the per-site budget, so a foreign host would spend another site's allowance.- await consumer.handleBatch(- [record([url('a', 'img.other-site.net'), url('good', 'cdn.example.com')], { key: 'example.com' })],- NOW- )+ it('throws when a not-ready republish fails', async () => {+ const harness = build()+ harness.republish.mockResolvedValue('failed')+ const early = candidate('a', { notBeforeMs: NOW_MS + 30_000 })- expect([...crawlHistory.stored.keys()].map(hashOf)).toEqual([hash('good')])+ await expect(harness.consumer.handleBatch([message([early])], NOW_MS)).rejects.toThrow('account for 1 URLs')+ expect(harness.history.writes).toEqual([])})- it('drops a record carrying more URLs than any producer sends', async () => {- const many = Array.from({ length: 1100 }, (_value, index) => url(`u${index}`))-- await consumer.handleBatch([record(many)], NOW)+ it('drops a malformed record without running the fetch pass', async () => {+ const harness = build()+ const invalid = message([candidate('a')])+ invalid.value = Buffer.from('{')- expect(crawlHistory.stored.size).toBe(0)+ await expect(harness.consumer.handleBatch([invalid], NOW_MS)).resolves.toBeUndefined()+ expect(harness.run).not.toHaveBeenCalled()})- it('holds back a URL whose dedup read failed, rather than treating it as new', async () => {- // To count it as new would fetch it. A store outage would then make every batch send the- // full un-deduped volume at customer sites, because our own store is down.- crawlHistory.partialReadFailures.add(crawlHistoryKey(TEAM, hash('a')))+ it('rejects a whole multi-job record when one job belongs to another partition', async () => {+ const harness = build()+ const foreign = candidate('foreign', {+ currentUrl: 'https://img.other.net/foreign.png',+ host: 'img.other.net',+ origin: 'https://img.other.net',+ registrableDomain: 'other.net',+ })- await expect(consumer.handleBatch([record([url('a'), url('b')])], NOW)).resolves.toBeUndefined()+ await harness.consumer.handleBatch([message([candidate('a'), foreign])], NOW_MS)- expect([...crawlHistory.stored.keys()].map(hashOf)).toEqual([hash('b')])+ expect(harness.run).not.toHaveBeenCalled()+ expect(harness.history.readKeys).toEqual([])})- it('commits a batch the store could not answer for, rather than replaying it forever', async () => {- // A store that answers nothing answers nothing for the next batch too, so a replay stops- // the lane instead of saving the URL. Nothing is recorded, so the mirror offers it again.- crawlHistory.readFailure = new Error('store down')-- await expect(consumer.handleBatch([record([url('a')])], NOW)).resolves.toBeUndefined()-- expect(crawlHistory.stored.size).toBe(0)+ it('throws when the bulk read fails', async () => {+ const harness = build()+ harness.history.readError = new Error('read failed')+ const observeBatch = jest.spyOn(ImageFetchConsumerMetrics, 'observeBatch')+ const observeStoreDuration = jest.spyOn(ImageFetchConsumerMetrics, 'observeStoreDuration')+ const startBatch = jest.spyOn(ImageFetchConsumerMetrics, 'startBatch')+ 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(observeStoreDuration).toHaveBeenCalledWith('read', 'error', expect.any(Number))+ expect(startBatch).toHaveBeenCalledTimes(1)+ expect(finishBatch).toHaveBeenCalledTimes(1)})- it('commits a batch whose store write failed, because the URL was fetched', async () => {- // A missing crawl history entry costs one duplicate fetch later, which requirement 22- // allows. A replay would cost the same duplicate and stall the partition too.- crawlHistory.writeFailure = new Error('store down')+ it('throws when the final bulk write fails', async () => {+ const harness = build()+ harness.history.writeError = new Error('write failed')- await expect(consumer.handleBatch([record([url('a')])], NOW)).resolves.toBeUndefined()+ await expect(harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)).rejects.toThrow('write failed')})- it('replays the batch when the pass could not put a URL back, rather than committing past it', async () => {- // Requirement 21. Nothing else holds a URL whose republish failed, so its offset must not- // commit.- const runner: FetchPass = {- run: (candidates: FetchCandidate[]) =>- Promise.resolve(- candidates.map((candidate) => ({- candidate,- outcome: 'timeout' as AttemptOutcome,- finished: false,- lost: true,- }))- ),+ it('keeps publish work before the final history write', async () => {+ const harness = build()+ const order: string[] = []+ harness.run.mockImplementation((candidates) => {+ order.push('published')+ return Promise.resolve(candidates.map((item) => terminal(item)))+ })+ const write = harness.history.write.bind(harness.history)+ harness.history.write = async (items) => {+ order.push('history')+ await write(items)}- const fetching = new UrlFetchConsumer(- crawlHistory,- publisher,- { maxAgeMs: 6 * 60 * 60 * 1000, dedupMaxRefs: 1000, seenTtlSeconds: 604_800, dryRun: false },- runner- )- await expect(fetching.handleBatch([record([url('lost')])], NOW)).rejects.toThrow('account for 1')- // No crawl history entry, so the replay fetches the URL rather than skips it.- expect(crawlHistory.stored.size).toBe(0)- })+ await harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)- it('refuses to leave dry run without a way to send the requests', () => {- expect(- () =>- new UrlFetchConsumer(crawlHistory, publisher, {- maxAgeMs: 1000,- dedupMaxRefs: 10,- seenTtlSeconds: 604_800,- dryRun: false,- })- ).toThrow('fetch runner')+ expect(order).toEqual(['published', 'history'])})- it('records only the URLs the fetch pass finished with', async () => {- const outcomes: Record<string, AttemptOutcome> = {- [hash('done')]: 'ok',- [hash('gone')]: 'not_found',- [hash('later')]: 'deadline',- [hash('slow')]: 'timeout',- }- const runner: FetchPass = {- run: (candidates: FetchCandidate[]) =>- Promise.resolve(- candidates.map((candidate) => ({- candidate,- outcome: outcomes[candidate.urlHash],- finished: isTerminal(outcomes[candidate.urlHash]),- lost: false,- }))- ),- }- const fetching = new UrlFetchConsumer(- crawlHistory,- publisher,- { maxAgeMs: 6 * 60 * 60 * 1000, dedupMaxRefs: 1000, seenTtlSeconds: 604_800, dryRun: false },- runner+ it('throws when the fetch pass reports a lost URL', async () => {+ const harness = build()+ harness.run.mockImplementation((candidates) =>+ Promise.resolve(+ candidates.map((item) => ({+ candidate: item,+ outcome: 'timeout',+ finished: false,+ lost: true,+ configurationUpdates: [],+ }))+ ))- await fetching.handleBatch([record([url('done'), url('gone'), url('later'), url('slow')])], NOW)-- // A crawl history entry stops this lane from ever reading a URL again, so an answered URL- // gets one and a URL that only ran out of time does not.- expect([...crawlHistory.stored.keys()].map(hashOf).sort()).toEqual([hash('done'), hash('gone')])+ await expect(harness.consumer.handleBatch([message([candidate('a')])], NOW_MS)).rejects.toThrow(+ 'account for 1 URLs'+ )})})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.tsindex 783331842ab4..c0343db44876 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@@ -1,169 +1,121 @@import { Message } from 'node-rdkafka'import { logger } from '~/common/utils/logger'-import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'-import { FetchCandidate, MAX_HOPS, parseCollectedUrlsRecord } from './collected-urls-record'-import { CrawlHistoryStore, crawlHistoryKey } from './crawl-history'-import { FetchPass, HOPS_EXHAUSTED } from './fetch-runner'+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 { ImageFetchConsumerMetrics, ImageFetchRequestMetrics, ImageFetchTeamMetrics, UrlDropReason } from './metrics'-import { TeamVolume } from './team-volume'+import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'++const ONE_HOUR_MS = 60 * 60 * 1000export interface UrlFetchConsumerOptions {- /** The lane drops a URL older than this, so a backlog sheds work instead of fetching stale URLs. */- maxAgeMs: number- dedupMaxRefs: number- /** TTL on each crawl history entry, which sets the recrawl interval. */seenTtlSeconds: number- /** While true, no request leaves this process. Everything else still runs, including the crawl history write. */dryRun: boolean}-/**- * The image fetch lane.- *- * The consumer handles a bad record and an unavailable crawl history instead of throwing. This lane- * shares a partition with every site whose URLs key to it, and a throw here stops the consumer, replays the- * same batch, and holds that partition against all of them.- */export class UrlFetchConsumer {- private readonly seenRefs: RefDedupCache- /** Bounded on purpose: one series for each busy team, one for the rest, one estimate. Requirement 31. */- private readonly teamVolume = new TeamVolume()-constructor(private readonly crawlHistory: CrawlHistoryStore,private readonly publisher: FrontierPublisher,private readonly options: UrlFetchConsumerOptions,- /** Absent in dry run, so the dry run sends nothing. The lane reads no flag for each URL. */private readonly runner?: FetchPass) {- // These arrive from env, where a typo parses to NaN. A NaN age limit makes every comparison- // false, which disables the shed that lets the lane drop a backlog.- if (!Number.isFinite(options.maxAgeMs) || options.maxAgeMs <= 0) {- throw new Error(- `SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS must be a positive number, got ${options.maxAgeMs}`- )- }- // A NaN TTL makes every ledger write fail while the lane appears healthy. The hour floor catches- // unit suffixes, which the env parser truncates rather than rejects: "7d" parses to 7, and- // a 7-second TTL empties the ledger as fast as it fills, so nothing dedups.if (!Number.isInteger(options.seenTtlSeconds) || options.seenTtlSeconds < 60 * 60) {- throw new Error(- `AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS must be an integer of at least 3600, got ` +- `${options.seenTtlSeconds} (a unit suffix like "7d" parses as 7: give the value in seconds)`- )+ throw new Error('AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS must be at least 3600')}if (!options.dryRun && !runner) {throw new Error('the image fetch lane needs a fetch runner once dry run is cleared')}- this.seenRefs = new RefDedupCache('image_fetch_consumer', options.dedupMaxRefs)ImageFetchConsumerMetrics.setDryRun(options.dryRun)- ImageFetchTeamMetrics.track(this.teamVolume)}public async handleBatch(messages: Message[], nowMs: number): Promise<void> {- // Wall clock, not the caller's nowMs: nowMs dates the URLs, and a test can set it far from- // the present, which would make the duration meaningless.const startedAt = process.hrtime.bigint()const drops = new Map<UrlDropReason, number>()- const countDrop = (reason: UrlDropReason, count = 1): void => {- drops.set(reason, (drops.get(reason) ?? 0) + count)- }-- const domains = new Set<string>()- const seenInBatch = new Set<string>()- const candidates: FetchCandidate[] = []- const notReady: FetchCandidate[] = []+ const candidatesByRef = new Map<string, FetchCandidate>()let dedupedInBatch = 0- let dedupedInPod = 0+ let originCount = 0+ ImageFetchConsumerMetrics.startBatch()- for (const message of messages) {- const parsed = parseCollectedUrlsRecord(message.value, message.key?.toString() ?? null)- if (!parsed.ok) {- countDrop(parsed.reason)- continue+ try {+ for (const message of messages) {+ const parsed = this.parse(message)+ if (!parsed.ok) {+ drops.set(parsed.reason, (drops.get(parsed.reason) ?? 0) + 1)+ continue+ }+ ImageFetchConsumerMetrics.observeRecord(parsed.urlCount)+ for (const rejected of parsed.rejected) {+ drops.set(rejected.reason, (drops.get(rejected.reason) ?? 0) + 1)+ }+ for (const candidate of parsed.candidates) {+ const existing = candidatesByRef.get(candidate.originalRef)+ if (existing) {+ dedupedInBatch += 1+ candidatesByRef.set(candidate.originalRef, foldDuplicateCandidate(existing, candidate))+ continue+ }+ ImageFetchConsumerMetrics.observeAge(Math.max(0, nowMs - candidate.firstSeenAtMs) / 1000)+ candidatesByRef.set(candidate.originalRef, candidate)+ }}- ImageFetchConsumerMetrics.observeRecord(parsed.urlCount)- for (const { reason } of parsed.rejected) {- countDrop(reason)+ const candidates = [...candidatesByRef.values()]+ const origins = new Set(candidates.map((candidate) => candidate.origin))+ originCount = origins.size++ if (this.options.dryRun || candidates.length === 0) {+ return}- for (const candidate of parsed.candidates) {- domains.add(candidate.domain)- if (nowMs - candidate.capturedAtMs > this.options.maxAgeMs) {- countDrop('stale')++ const keys = [+ ...candidates.map((candidate) => candidate.originalRef),+ ...[...origins].flatMap((origin) => [+ configurationCacheKey(origin, 'robots'),+ configurationCacheKey(origin, 'tdmrep'),+ ]),+ ]+ const stored = await this.runCrawlHistoryOperation('read', keys.length, () => this.crawlHistory.read(keys))++ const fetchable: FetchCandidate[] = []+ const notReady: FetchCandidate[] = []+ for (const candidate of candidates) {+ const history = stored.get(candidate.originalRef)+ if (history?.kind === 'url' && history.nextFetchAtMs > nowMs) {+ ImageFetchConsumerMetrics.incDeduped('store', 1)continue}if (candidate.notBeforeMs > nowMs) {- // A wait longer than the longest tier, so the tier it came out of covered only- // part of it. It goes back for the rest and spends a hop. Requirement 15.notReady.push(candidate)- continue- }- if (seenInBatch.has(candidate.ref)) {- dedupedInBatch++- continue+ } else {+ fetchable.push(candidate)}- seenInBatch.add(candidate.ref)- if (this.seenRefs.has(candidate.ref)) {- dedupedInPod++- continue- }- // After dedup, so the distribution describes the URLs this lane acts on rather than- // how often a popular image reappears.- ImageFetchConsumerMetrics.observeAge(Math.max(0, nowMs - candidate.capturedAtMs) / 1000)- this.teamVolume.record(candidate.pseudoTeam)- candidates.push(candidate)}- }-- const fetchable = await this.removeAlreadySeen(candidates, nowMs)- if (fetchable.length > 0) {ImageFetchConsumerMetrics.incFetchable(fetchable.length)- }- const pass = this.runner ? await this.fetchAll(this.runner, fetchable) : { finished: fetchable, lost: 0 }- const held = await this.rescheduleNotReady(notReady, nowMs)- const finished = [...pass.finished, ...held.exhausted]- if (finished.length > 0) {- await this.recordFetched(finished, nowMs)- }- const lost = pass.lost + held.lost-- if (dedupedInBatch > 0) {- ImageFetchConsumerMetrics.incDeduped('batch', dedupedInBatch)- }- if (dedupedInPod > 0) {- ImageFetchConsumerMetrics.incDeduped('pod', dedupedInPod)- }- for (const [reason, count] of drops) {- ImageFetchConsumerMetrics.incDropped(reason, count)- }- ImageFetchConsumerMetrics.observeBatch(domains.size, Number(process.hrtime.bigint() - startedAt) / 1e9)- if (lost > 0) {- // Thrown last, so the counts above publish first. The consumer stores offsets only after- // this returns, so a throw replays the batch on the pod that takes the partition next.- // Requirement 21.- //- // The replay costs little: the URLs already fetched carry a crawl history entry now, and- // the read at the top of the batch removes them. A URL is a duplicate at worst, which- // requirement 22 allows, and the alternative is a lost URL.- throw new Error(`the image fetch lane could not account for ${lost} URLs`)+ const attempts = await this.runner!.run(fetchable, stored)+ attempts.push(...(await Promise.all(notReady.map((candidate) => this.republishNotReady(candidate, nowMs)))))+ const updates: CrawlHistoryItem[] = []+ for (const attempt of attempts) {+ updates.push(...attempt.configurationUpdates)+ if (attempt.history) {+ updates.push(attempt.history)+ }+ }+ if (updates.length > 0) {+ await this.runCrawlHistoryOperation('write', updates.length, () => this.crawlHistory.write(updates))+ }+ const lost = attempts.filter((attempt) => attempt.lost).length+ if (lost > 0) {+ throw new Error(`the image fetch lane could not account for ${lost} URLs`)+ }+ } finally {+ ImageFetchConsumerMetrics.finishBatch()+ this.recordMetrics(drops, dedupedInBatch, originCount, startedAt)}}- /**- * A URL left out of `finished` and not counted in `lost` is on its way back through Kafka, so- * nothing here has to hold it.- */- /**- * Never throws. Requirement 23.- *- * The parser reads the url policy out of a native addon, so a build that shipped without it- * raises rather than returning a reason. That must read as a record this lane cannot use, not- * as a reason to stop the partition.- */private parse(message: Message): ReturnType<typeof parseCollectedUrlsRecord> {try {return parseCollectedUrlsRecord(message.value, message.key?.toString() ?? null)@@ -175,120 +127,121 @@ export class UrlFetchConsumer {}}- private async fetchAll(- runner: FetchPass,- candidates: FetchCandidate[]- ): Promise<{ finished: FetchCandidate[]; lost: number }> {- let attempts+ private async runCrawlHistoryOperation<T>(+ operation: 'read' | 'write',+ affectedKeys: number,+ run: () => Promise<T>+ ): Promise<T> {+ const startedAt = process.hrtime.bigint()+ let outcome: 'success' | 'error' = 'success'try {- attempts = await runner.run(candidates)+ return await run()} catch (error) {- // The pass answers with outcomes rather than a throw, so reaching here means a defect.- // The log holds the error name only, because an error from the pass can carry a URL.- logger.error('🌐', 'ml_image_fetch_pass_failed', {- count: candidates.length,- error: error instanceof Error ? error.name : 'unknown',- })- // The batch commits rather than replays, unlike a failed republish. A defect here is the- // same on every read, so a replay would stop the partition rather than recover it.- return { finished: [], lost: 0 }- }- return {- finished: attempts.filter((attempt) => attempt.finished).map((attempt) => attempt.candidate),- lost: attempts.filter((attempt) => attempt.lost).length,+ outcome = 'error'+ ImageFetchConsumerMetrics.incStoreError(operation, affectedKeys)+ throw error+ } finally {+ ImageFetchConsumerMetrics.observeStoreDuration(+ operation,+ outcome,+ Number(process.hrtime.bigint() - startedAt) / 1e9+ )}}- /**- * A URL whose read failed is neither fetched nor counted as new. To count it as new would fetch- * it, and a store outage would then send the full un-deduped volume at customer sites, in every- * batch, because our own store is down. It counts as unaccounted instead, which holds the batch- * rather than loses it. Requirement 21.- */- private async removeAlreadySeen(candidates: FetchCandidate[], nowMs: number): Promise<FetchCandidate[]> {- if (candidates.length === 0) {- return []- }- const keys = candidates.map((candidate) => crawlHistoryKey(candidate.pseudoTeam, candidate.urlHash))- let result- try {- result = await this.crawlHistory.read(keys, nowMs)- } catch (error) {- ImageFetchConsumerMetrics.incStoreError('read', keys.length)- logger.warn('🌐', 'ml_image_fetch_crawl_history_read_failed', { count: keys.length, error: String(error) })- return []+ private async republishNotReady(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(+ candidate,+ {+ currentUrl: candidate.currentUrl,+ host: candidate.host,+ origin: candidate.origin,+ registrableDomain: candidate.registrableDomain,+ },+ 'not_ready',+ waitMs+ )+ if (result === 'refused_delay' || waitMs > ONE_HOUR_MS) {+ return this.terminalAttempt(candidate, DELAY_TOO_LONG, nowMs)}- if (result.failed.size > 0) {- ImageFetchConsumerMetrics.incStoreError('read', result.failed.size)+ return {+ candidate,+ outcome: 'backoff',+ finished: false,+ lost: result === 'failed',+ configurationUpdates: [],}- if (result.known.size > 0) {- ImageFetchConsumerMetrics.incDeduped('store', result.known.size)+ }++ private terminalAttempt(candidate: FetchCandidate, outcome: AttemptOutcome, nowMs: number): FetchAttempt {+ ImageFetchRequestMetrics.observeCompletedUrl(+ outcome,+ 'none',+ Math.max(0, nowMs - candidate.firstSeenAtMs) / 1000,+ candidate.fetchCount,+ candidate.republishCount+ )+ ImageFetchRequestMetrics.observeHops(MAX_HOPS - candidate.remainingHops)+ return {+ candidate,+ outcome,+ finished: true,+ lost: false,+ history: this.terminalHistory(candidate, outcome, nowMs),+ configurationUpdates: [],}- return candidates.filter((_candidate, index) => !result.known.has(index) && !result.failed.has(index))}- /**- * A URL waiting out a delay has no crawl history entry and no other copy in Kafka, so a drop- * here loses it until a session refers to the same image again. Requirements 15 and 21.- *- * One with no hops left cannot go round again. The lane records it and stops, exactly as the- * fetch pass does with a URL that runs out mid-chain. Requirements 12 and 24.- */- private async rescheduleNotReady(- candidates: FetchCandidate[],- nowMs: number- ): Promise<{ lost: number; exhausted: FetchCandidate[] }> {- const exhausted: FetchCandidate[] = []- const held: FetchCandidate[] = []- for (const candidate of candidates) {- if (candidate.hopsRemaining <= 1) {- ImageFetchRequestMetrics.incOutcome(HOPS_EXHAUSTED)- ImageFetchRequestMetrics.observeHops(MAX_HOPS)- exhausted.push(candidate)- } else {- held.push(candidate)- }+ private terminalHistory(candidate: FetchCandidate, outcome: AttemptOutcome, nowMs: number): UrlCrawlHistoryItem {+ const nextFetchAtMs = nowMs + this.options.seenTtlSeconds * 1000+ return {+ kind: 'url',+ key: candidate.originalRef,+ nextFetchAtMs,+ storageExpiresAtMs: nextFetchAtMs,+ outcome,}- // Together rather than one after another. A batch can carry a whole delay tier's worth of- // records that arrived early, and one awaited produce for each would run past- // `max.poll.interval.ms` and lose the partition in the middle of the batch.- const sent = await Promise.all(- held.map((candidate) =>- this.publisher.republish(- candidate,- { url: candidate.url, host: candidate.host, domain: candidate.domain },- 'not_ready',- candidate.notBeforeMs - nowMs- )- )- )- return { lost: sent.filter((ok) => !ok).length, exhausted }}- /**- * This marks the pod cache only for a URL whose crawl history entry reached the store.- *- * A URL held only in this pod is invisible to every other pod, and to this one after a restart.- * A mark before the store confirms the write would drop the URL from the measurement, and later- * from fetching.- */- private async recordFetched(candidates: FetchCandidate[], nowMs: number): Promise<void> {- const keys = candidates.map((candidate) => crawlHistoryKey(candidate.pseudoTeam, candidate.urlHash))- let failed: Set<number>- try {- failed = (await this.crawlHistory.record(keys, nowMs, this.options.seenTtlSeconds)).failed- } catch (error) {- ImageFetchConsumerMetrics.incStoreError('write', keys.length)- logger.warn('🌐', 'ml_image_fetch_crawl_history_write_failed', { count: keys.length, error: String(error) })- return+ private recordMetrics(+ drops: Map<UrlDropReason, number>,+ dedupedInBatch: number,+ origins: number,+ startedAt: bigint+ ): void {+ if (dedupedInBatch > 0) {+ ImageFetchConsumerMetrics.incDeduped('batch', dedupedInBatch)}- if (failed.size > 0) {- ImageFetchConsumerMetrics.incStoreError('write', failed.size)+ for (const [reason, count] of drops) {+ ImageFetchConsumerMetrics.incDropped(reason, count)}- candidates.forEach((candidate, index) => {- if (!failed.has(index)) {- this.seenRefs.add(candidate.ref)- }- })+ ImageFetchConsumerMetrics.observeBatch(origins, Number(process.hrtime.bigint() - startedAt) / 1e9)+ }+}++function foldDuplicateCandidate(left: FetchCandidate, right: FetchCandidate): FetchCandidate {+ let preferredRoute = left+ if (+ right.remainingHops < left.remainingHops ||+ (right.remainingHops === left.remainingHops && right.republishCount > left.republishCount) ||+ (right.remainingHops === left.remainingHops &&+ right.republishCount === left.republishCount &&+ right.fetchCount > left.fetchCount)+ ) {+ preferredRoute = right+ }+ const latestState = left.republishCount >= right.republishCount ? left : right+ return {+ ...preferredRoute,+ remainingHops: Math.min(left.remainingHops, right.remainingHops),+ notBeforeMs: Math.max(left.notBeforeMs, right.notBeforeMs),+ firstSeenAtMs: Math.min(left.firstSeenAtMs, right.firstSeenAtMs),+ fetchCount: Math.max(left.fetchCount, right.fetchCount),+ republishCount: Math.max(left.republishCount, right.republishCount),+ lastRepublishReason: latestState.lastRepublishReason,}}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 0fe52da2c649..b92894b8ebeb 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@@ -86,14 +86,15 @@ That matters because the consumer's per-request timeout is an inactivity timeoutGiven an image, `advancedScrub` (`src/scrub.ts`):-1. **Plan the sizes**: `planScales` (`src/scale-plan.ts`) decides every resize from the source dimensions alone, before a pixel is read — the decoded frame, what each detector sees, and what gets stored.+1. **Apply the image policy**: reject an image when its XMP `plus:DataMining` value prohibits AI training.+2. **Plan the sizes**: `planScales` (`src/scale-plan.ts`) decides every resize from the source dimensions alone, before a pixel is read — the decoded frame, what each detector sees, and what gets stored.An area budget rather than a long-side cap, so tall pages keep legible native resolution instead of being squashed.Faces are detected on a letterboxed (never squashed) 640×640 input; frames beyond 3:1 aspect are tiled along their long axis (overlapping windows) so a face on a tall page stays above the detector's minimum size instead of shrinking past it.-2. **NSFW/gore gate**: if the image is explicit or gory (NSFL + NSFW probability over `NSFW_THRESHOLD`), it collapses to a 1x1 blank.-3. **Face redaction**: every detected face (YuNet) is filled with its **mean colour**.-4. **Text redaction**: every detected text region (DBNet) gets the same fill, with a margin scaled to the box height (= font size).+3. **NSFW/gore gate**: if the image is explicit or gory (NSFL + NSFW probability over `NSFW_THRESHOLD`), it collapses to a 1x1 blank.+4. **Face redaction**: every detected face (YuNet) is filled with its **mean colour**.+5. **Text redaction**: every detected text region (DBNet) gets the same fill, with a margin scaled to the box height (= font size).We detect _where_ text is and never read it.-5. **Code redaction**: every decodable QR/barcode (zxing) gets the same fill — a TOTP provisioning QR or ticket barcode is machine-readable PII that the face/text detectors can't see.+6. **Code redaction**: every decodable QR/barcode (zxing) gets the same fill — a TOTP provisioning QR or ticket barcode is machine-readable PII that the face/text detectors can't see.The goal is to protect data labellers and reduce PII exposure.It does not need to be perfect; the self-verifying test (below) keeps it honest.@@ -146,6 +147,8 @@ src/ (production — ships)smoke.ts image-build-time smoke test: models load + one scrub, with networking disabledenv.ts validated numeric env knobs — invalid values refuse to start (never fail open)metrics.ts Prometheus registry: HTTP outcomes + scrub outcome signals+ image-input.ts accepted image decoders, pixel limits, and embedded metadata policy+ xmp.ts PLUS Data Mining metadata parserdev/ (non-production)scrub-eval.ts OCR + face-redaction eval over downloaded images (npm run eval)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.jsonindex a556c3d02f09..3bd277a292bb 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json@@ -23,6 +23,7 @@"express": "^4.21.1","onnxruntime-node": "^1.27.0","prom-client": "^15.1.3",+ "saxes": "^6.0.0","sharp": "^0.35.3","tsx": "^4.19.2","zxing-wasm": "^2.2.0"diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/pnpm-lock.yaml b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/pnpm-lock.yamlindex 1b000300c7da..23b8930e8bb6 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/pnpm-lock.yaml+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/pnpm-lock.yaml@@ -17,6 +17,9 @@ importers:prom-client:specifier: ^15.1.3version: 15.1.3+ saxes:+ specifier: ^6.0.0+ version: 6.0.0sharp:specifier: ^0.35.3version: 0.35.3(@types/[email protected])@@ -2384,6 +2387,10 @@ packages:resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}+ resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}+ engines: {node: '>=v12.22.7'}+resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}hasBin: true@@ -2642,6 +2649,9 @@ packages:resolution: {integrity: sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==}engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0}+ resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}+resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}engines: {node: '>=10'}@@ -5240,6 +5250,10 @@ snapshots:+ dependencies:+ xmlchars: 2.2.0+@@ -5523,6 +5537,8 @@ snapshots:imurmurhash: 0.1.4signal-exit: 3.0.7+ [email protected]: {}+diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.test.tsindex 1646013d9de8..48d4600eaf4e 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.test.ts@@ -7,29 +7,24 @@ describe('blur', () => {// A capture can name a data URI `image/png` and put any bytes after the comma, and libvips// dispatches on magic bytes rather than that name, so the loader set is what actually bounds- // which decoders user content can reach. TIFF is blocked in blur.ts; GIF is deliberately not,- // because pages really do inline GIFs and blocking it would send every one of them to the- // dead-letter topic.+ // which decoders user content can reach. TIFF is blocked; the fetcher formats stay reachable.//- // The native VIPS format (`VipsForeignLoadVips`, also blocked in blur.ts) has no row here: a+ // The native VIPS format (`VipsForeignLoadVips`, also blocked in image-input.ts) has no row here: a// real `.v`/`.vips` buffer, built with the `vips` CLI, fails to decode with the identical// "unsupported image format" error whether or not the block is applied, so there is no buffer// that can exercise that branch either way. Blocking it only guards a call path that loads// from a file path, which nothing in this sidecar does today.- it.each([- ['tiff', true],- ['gif', false],- ['png', false],- ['jpeg', false],- ])('%s input is rejected: %s', async (format, blocked) => {+ it.each(['gif', 'png', 'jpeg', 'webp', 'avif'])('decodes %s input', async (format) => {const bytes = await swatch().toFormat(format as keyof FormatEnum).toBuffer()- const decode = blurOnly(bytes)- if (blocked) {- await expect(decode).rejects.toBeInstanceOf(UndecodableImageError)- } else {- await expect(decode).resolves.toBeInstanceOf(Buffer)- }++ await expect(blurOnly(bytes)).resolves.toBeInstanceOf(Buffer)+ })++ it('rejects TIFF input because it is not an accepted fetcher format', async () => {+ const bytes = await swatch().tiff().toBuffer()++ await expect(blurOnly(bytes)).rejects.toBeInstanceOf(UndecodableImageError)})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.tsindex ce1c8b3eeda3..04726ec71636 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts@@ -1,35 +1,17 @@// These params must stay in sync with rust/replay-anonymizer/src/blur.rs, or the mirror diverges from the inline anonymizer.-import sharp from 'sharp'+import { PermanentImageError, UndecodableImageError, inspectImage, sharpForImage } from './image-input.ts'-// One libvips thread per op and no cross-request cache, so N concurrent scrubs cost ~N threads (not N x CPU)-// and no shared cache: bounds sidecar CPU/RSS under the concurrency ceiling.-sharp.concurrency(1)-sharp.cache(false)--// The producer decides an image is collectable from the MIME type written in its data URI, but libvips-// picks a decoder by sniffing magic bytes, so `data:image/png;base64,<anything>` reaches whichever loader-// the bytes actually match. Narrow that to the formats a browser can inline: no page emits TIFF or the-// native VIPS format, so anything arriving as one is already anomalous and belongs on the dead-letter-// topic rather than in a decoder. Blocked loaders make the whole class of libvips decoder CVEs in these-// two formats unreachable, independent of the pinned version. GIF is deliberately absent: pages do inline-// GIFs, and blocking it would dead-letter every one of them.-sharp.block({ operation: ['VipsForeignLoadTiff', 'VipsForeignLoadVips'] })+export { LIMIT_INPUT_PIXELS, UndecodableImageError } from './image-input.ts'const DOWNSAMPLE_RATIO = 0.12const BLUR_SIGMA = 2.34const MAX_LONG_SIDE = 96-// Cap decoded pixels: compressed bytes expand many-fold in libvips, so this guards RSS, not input size.-// Every sharp() decode of raw request bytes (here and in the ML path's src-image.ts) must pass this.-export const LIMIT_INPUT_PIXELS = 50_000_000-// 1x1 transparent PNG: the output substituted for an image the NSFW/gore gate rejects (see advancedScrub).export const BLANK_PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==','base64')-export class UndecodableImageError extends Error {}-function targetDims(w: number, h: number): [number, number] {const scale = Math.min(DOWNSAMPLE_RATIO, MAX_LONG_SIDE / Math.max(w, h))return [Math.max(1, Math.round(w * scale)), Math.max(1, Math.round(h * scale))]@@ -39,22 +21,10 @@ export async function blurOnly(input: Buffer): Promise<Buffer> {// Any libvips failure — bad header OR a corrupt/truncated body that fails mid-decode — is permanent for// these bytes, so map it all to UndecodableImageError (422/skip). A 500 here would poison the partition.try {- const meta = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS }).metadata()- if (!meta.width || !meta.height) {- throw new UndecodableImageError('image has invalid dimensions')- }- // Reject oversized images from the cheap header read, before the full-resolution decode allocates- // ~4 bytes/pixel. (The decode enforces the same cap, but only after starting to allocate.)- if (meta.width * meta.height > LIMIT_INPUT_PIXELS) {- throw new UndecodableImageError('image exceeds the pixel limit')- }- const [tw, th] = targetDims(meta.width, meta.height)- return await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS })- .resize(tw, th, { fit: 'fill' })- .blur(BLUR_SIGMA)- .png()- .toBuffer()+ const description = await inspectImage(input)+ const [tw, th] = targetDims(description.width, description.height)+ return await sharpForImage(input).resize(tw, th, { fit: 'fill' }).blur(BLUR_SIGMA).png().toBuffer()} catch (e) {- throw e instanceof UndecodableImageError ? e : new UndecodableImageError(String(e))+ throw e instanceof PermanentImageError ? e : new UndecodableImageError(String(e))}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjsindex cd571e3b5bb2..66f696e6894c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs@@ -30,7 +30,11 @@ parentPort.on('message', async (job) => {return}if (kind === 'undecodable') {- parentPort.postMessage({ id: job.id, failure: { message: 'bad bytes', undecodable: true } })+ parentPort.postMessage({ id: job.id, failure: { message: 'bad bytes', kind: 'undecodable' } })+ return+ }+ if (kind === 'opt-out') {+ parentPort.postMessage({ id: job.id, failure: { message: 'training prohibited', kind: 'opt-out' } })return}// Reports its own interval so the test can assert overlap directly rather than inferringdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.tsnew file mode 100644index 000000000000..d9924c16adcc--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.ts@@ -0,0 +1,44 @@+import sharp, { type Sharp } from 'sharp'++import { imageMetadataProhibitsAiTraining } from './xmp.ts'++// One libvips thread per operation and no shared cache bound CPU and memory to the request concurrency limit.+sharp.concurrency(1)+sharp.cache(false)+// The accepted image types do not need TIFF or native VIPS loaders, so blocking them removes unnecessary decoder paths.+sharp.block({ operation: ['VipsForeignLoadTiff', 'VipsForeignLoadVips'] })++// Compressed image bytes can expand many times in memory, so every decoder applies this pixel limit before allocation.+export const LIMIT_INPUT_PIXELS = 50_000_000++export class PermanentImageError extends Error {}+export class UndecodableImageError extends PermanentImageError {}+export class ImageOptOutError extends PermanentImageError {}++export interface ImageDescription {+ width: number+ height: number+ format: string+}++export async function inspectImage(input: Buffer): Promise<ImageDescription> {+ const metadata = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS }).metadata()+ if (!metadata.width || !metadata.height) {+ throw new UndecodableImageError('image has invalid dimensions')+ }+ if (metadata.width * metadata.height > LIMIT_INPUT_PIXELS) {+ throw new UndecodableImageError('image exceeds the pixel limit')+ }+ if (imageMetadataProhibitsAiTraining(input, metadata.xmp)) {+ throw new ImageOptOutError('image metadata prohibits AI training')+ }+ return {+ width: metadata.width,+ height: metadata.height,+ format: metadata.format === 'heif' ? 'avif' : (metadata.format ?? 'unknown'),+ }+}++export function sharpForImage(input: Buffer): Sharp {+ return sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS })+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.tsindex acf32610ecb4..e06a9dad48f8 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts@@ -33,7 +33,16 @@ async function stageCount(stage: string): Promise<number> {return values.find((v) => v.metricName?.endsWith('_count') && v.labels.stage === stage)?.value ?? 0}+async function sourceFormatLabels(): Promise<string[]> {+ const metric = (await register.getMetricsAsJSON()).find(+ (candidate) => candidate.name === 'ml_mirror_image_scrub_source_format_total'+ )+ return (metric as { values: { labels: Record<string, string> }[] }).values.map((value) => value.labels.format)+}+describe('observeScrubOutcome', () => {+ beforeEach(() => register.resetMetrics())+// A frame that returned early never ran the stages below its exit, so recording their zeros// reports work that did not happen and pulls every one of those quantiles toward zero. The// damage scales with how common the early exit is, so it lands hardest exactly when the@@ -54,4 +63,13 @@ describe('observeScrubOutcome', () => {expect(await stageCount(skipped)).toBe(0)}})++ it.each(['bmp', 'vendor-specific'])(+ 'coalesces unsupported source format %s into the bounded other label',+ async (format) => {+ ScrubMetrics.observeScrubOutcome(timings({ format }))++ expect(await sourceFormatLabels()).toEqual(['other'])+ }+ )})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.tsindex 40ee016041d1..d5de0c91fab4 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts@@ -4,6 +4,26 @@ import { type StageTimings } from './scrub.ts'export const register = new Registry()+type SourceFormatLabel = 'avif' | 'gif' | 'heif' | 'jpeg' | 'jp2' | 'png' | 'raw' | 'svg' | 'tiff' | 'webp' | 'other'++function sourceFormatLabel(format: string): SourceFormatLabel {+ switch (format) {+ case 'avif':+ case 'gif':+ case 'heif':+ case 'jpeg':+ case 'jp2':+ case 'png':+ case 'raw':+ case 'svg':+ case 'tiff':+ case 'webp':+ return format+ default:+ return 'other'+ }+}+const scrubbed = new Counter({name: 'ml_mirror_image_scrub_scrubbed_total',help: 'Images scrubbed',@@ -19,6 +39,11 @@ const undecodable = new Counter({help: 'Inputs sharp could not decode (422) — permanently skipped, never retried',registers: [register],})+const optedOut = new Counter({+ name: 'ml_mirror_image_scrub_opted_out_total',+ help: 'Images skipped because embedded PLUS metadata prohibits AI training',+ registers: [register],+})const rejected = new Counter({name: 'ml_mirror_image_scrub_rejected_total',help: 'Requests shed for concurrency (503)',@@ -69,7 +94,7 @@ const stageDuration = new Histogram({// decode-side optimization is bounded by this distribution.const sourceFormat = new Counter({name: 'ml_mirror_image_scrub_source_format_total',- help: 'Decoded images by source container format',+ help: 'Decoded images by bounded source container format',labelNames: ['format'],registers: [register],})@@ -83,7 +108,7 @@ const storedMegapixels = new Histogram({})const sourceMegapixels = new Histogram({name: 'ml_mirror_image_scrub_source_megapixels',- help: 'Source megapixels before the SCRUB_MAX_PIXELS downscale, by format. Mass above the SCRUB_MAX_PIXELS budget is the traffic that actually gets downscaled',+ help: 'Source megapixels before the SCRUB_MAX_PIXELS downscale, by bounded format. Mass above the SCRUB_MAX_PIXELS budget is the traffic that actually gets downscaled',labelNames: ['format'],buckets: [0.1, 0.25, 0.5, 1, 2, 2.56, 4, 8, 16, 50],registers: [register],@@ -182,6 +207,7 @@ export const ScrubMetrics = {incScrubbed: () => scrubbed.inc(),incFailed: () => failed.inc(),incUndecodable: () => undecodable.inc(),+ incOptedOut: () => optedOut.inc(),incRejected: () => rejected.inc(),incTooLarge: () => tooLarge.inc(),incAborted: () => aborted.inc(),@@ -201,8 +227,9 @@ export const ScrubMetrics = {textBoxesRedacted.inc(t.textBoxes)codesRedacted.inc(t.codes)- sourceFormat.labels(t.format).inc()- sourceMegapixels.labels(t.format).observe(t.inputPixels / 1e6)+ const format = sourceFormatLabel(t.format)+ sourceFormat.labels(format).inc()+ sourceMegapixels.labels(format).observe(t.inputPixels / 1e6)stageDuration.labels('decode').observe(t.decodeMs / 1000)// Each early return skips the stages below it, and recording their zeros would drag those// quantiles toward zero rather than describing the work they do. A uniform frame returnsdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.tsindex 4b1ab40531d5..7317777e889b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts@@ -4,6 +4,7 @@ import { join } from 'node:path'import { pathToFileURL } from 'node:url'import { UndecodableImageError } from './blur.ts'+import { ImageOptOutError } from './image-input.ts'import { ScrubAbandonedError, type ScrubPool, type ScrubResult, startPool } from './pool.ts'// cwd-relative rather than import.meta, which jest's CJS transform cannot load (see qr.ts).@@ -108,6 +109,12 @@ describe('startPool', () => {await expect(pool.scrub(Buffer.from('undecodable'))).rejects.toBeInstanceOf(UndecodableImageError)})+ it('rebuilds an ImageOptOutError from the wire', async () => {+ pool = await startPool(1, FAKE_WORKER)++ await expect(pool.scrub(Buffer.from('opt-out'))).rejects.toBeInstanceOf(ImageOptOutError)+ })+it('drops a queued job whose caller has hung up, without occupying a worker', async () => {// The consumer gives up after 10s and retries, but its queue entry outlives it. Dispatching// it anyway spends a full scrub on a response nobody reads, and the server holds one of itsdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.tsindex 8a0acfc54920..bfec2abc9eb4 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts@@ -3,6 +3,7 @@ import { Worker } from 'node:worker_threads'import { UndecodableImageError } from './blur.ts'import { WORKER_HEAP_MB } from './cores.ts'+import { ImageOptOutError } from './image-input.ts'import { ScrubMetrics } from './metrics.ts'import { type StageTimings } from './scrub.ts'import { type ScrubReply } from './worker-protocol.ts'@@ -194,9 +195,12 @@ export async function startPool(restartFailures[index] = 0}if ('failure' in msg) {- const error = msg.failure.undecodable- ? new UndecodableImageError(msg.failure.message)- : new Error(msg.failure.message)+ const error =+ msg.failure.kind === 'undecodable'+ ? new UndecodableImageError(msg.failure.message)+ : msg.failure.kind === 'opt-out'+ ? new ImageOptOutError(msg.failure.message)+ : new Error(msg.failure.message)pending.reject(error)} else {pending.resolve({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.tsindex f26915a0c635..03f32a4924db 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts@@ -8,6 +8,7 @@import { parentPort } from 'node:worker_threads'import { UndecodableImageError } from './blur.ts'+import { ImageOptOutError } from './image-input.ts'import { advancedScrub, loadModels } from './scrub.ts'import { type ScrubJob, type ScrubReply } from './worker-protocol.ts'@@ -41,7 +42,12 @@ port.on('message', (job: ScrubJob) => {id: job.id,failure: {message: error instanceof Error ? error.message : String(error),- undecodable: error instanceof UndecodableImageError,+ kind:+ error instanceof ImageOptOutError+ ? 'opt-out'+ : error instanceof UndecodableImageError+ ? 'undecodable'+ : 'failed',},} satisfies ScrubReply)})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.tsindex 3a978d5fa628..c41821e722a5 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts@@ -16,6 +16,7 @@ import { BLANK_PNG, LIMIT_INPUT_PIXELS, UndecodableImageError, blurOnly } from 'import { type DbnetModel, detectTextDbnet, loadDbnet } from './dbnet.ts'import { numFromEnv } from './env.ts'import { type Box } from './geometry.ts'+import { PermanentImageError } from './image-input.ts'import { detectCodes } from './qr.ts'import { type SafetyModel, classifySafety, loadSafety } from './safety.ts'import { type Dims, type ScalePlan, limitsFromEnv, planScales } from './scale-plan.ts'@@ -146,7 +147,7 @@ export async function advancedScrub(plan = planScales(meta, limitsFromEnv())src = await decodeSrc(input, plan.frame)} catch (e) {- throw e instanceof UndecodableImageError ? e : new UndecodableImageError(String(e))+ throw e instanceof PermanentImageError ? e : new UndecodableImageError(String(e))}const { W, H } = srctimings.decodeMs = performance.now() - tDecdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.tsindex 3e23d0fbd2fe..c8c860f00597 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts@@ -1,5 +1,6 @@import { once } from 'node:events'import type { AddressInfo } from 'node:net'+import sharp from 'sharp'import { blurOnly } from './blur.ts'import { startServer } from './server.ts'@@ -58,6 +59,25 @@ describe('image-scrub sidecar server', () => {expect(res.status).toBe(422)})+ it('422s an image whose PLUS metadata prohibits AI training', async () => {+ const optedOut = await sharp(PNG)+ .withXmp(+ `+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"+ xmlns:plus="http://ns.useplus.org/ldf/xmp/1.0/">+ <rdf:Description plus:DataMining="http://ns.useplus.org/ldf/vocab/DMI-PROHIBITED-AIMLTRAINING" />+ </rdf:RDF>+ `+ )+ .png()+ .toBuffer()++ const res = await fetch(`${base}/scrub`, { method: 'POST', body: optedOut })++ expect(res.status).toBe(422)+ expect(await res.text()).toBe('image metadata prohibits AI training')+ })+it('serves health + metrics on the metrics listener, not the scrub listener', async () => {expect((await fetch(`${metricsBase}/_health`)).status).toBe(200)const metrics = await fetch(`${metricsBase}/metrics`)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.tsindex 74f483071dc6..3e6127f87ee3 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts@@ -3,6 +3,7 @@ import express, { type NextFunction, type Request, type Response } from 'expressimport { type Server } from 'node:http'import { UndecodableImageError } from './blur.ts'+import { ImageOptOutError } from './image-input.ts'import { ScrubMetrics, register } from './metrics.ts'import { ScrubAbandonedError } from './pool.ts'@@ -126,6 +127,11 @@ export function startServer(res.status(422).send('undecodable image')return}+ if (err instanceof ImageOptOutError) {+ ScrubMetrics.incOptedOut()+ res.status(422).send('image metadata prohibits AI training')+ return+ }ScrubMetrics.incFailed()console.error(`scrub failed: ${String(err)}`)res.status(500).send('scrub failed')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.tsindex 65b5f77cd8e4..1ffe6d7a312e 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts@@ -2,7 +2,7 @@* Decoding a multi-megapixel PNG is tens of ms; the pipeline touches the source 4-5 times. */import sharp, { type Sharp } from 'sharp'-import { LIMIT_INPUT_PIXELS } from './blur.ts'+import { inspectImage, sharpForImage } from './image-input.ts'import { type Dims, limitsFromEnv, planScales } from './scale-plan.ts'export interface Src {@@ -16,11 +16,8 @@ export interface Src {/** Source dimensions from the header alone, so the plan can be made before any pixel is decoded. */export async function probeDims(input: Buffer): Promise<Dims> {- const meta = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS }).metadata()- if (!meta.width || !meta.height) {- throw new Error('image has invalid dimensions')- }- return { width: meta.width, height: meta.height }+ const description = await inspectImage(input)+ return { width: description.width, height: description.height }}/**@@ -31,17 +28,14 @@ export async function probeDims(input: Buffer): Promise<Dims> {* modules that happen to apply it.*/export async function decodeSrc(input: Buffer, frame?: Dims): Promise<Src> {- const meta = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS }).metadata()- if (!meta.width || !meta.height) {- throw new Error('image has invalid dimensions')- }- const target = frame ?? planScales({ width: meta.width, height: meta.height }, limitsFromEnv()).frame+ const description = await inspectImage(input)+ const target = frame ?? planScales(description, limitsFromEnv()).frameconst targetW = target.widthconst targetH = target.height// flatten, NOT removeAlpha: removeAlpha discards the alpha channel but keeps the RGB underneath,// so content hidden under fully transparent pixels (invisible in the replay) would surface in// the scrubbed output. Flatten composites over a background, destroying hidden RGB.- const { data, info } = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS })+ const { data, info } = await sharpForImage(input).resize(targetW, targetH, { fit: 'fill' }).flatten({ background: '#fff' }).raw()@@ -50,8 +44,8 @@ export async function decodeSrc(input: Buffer, frame?: Dims): Promise<Src> {data,W: info.width,H: info.height,- format: meta.format ?? 'unknown',- inputPixels: meta.width * meta.height,+ format: description.format,+ inputPixels: description.width * description.height,}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.tsindex 632c83984c2d..6b7ed16e55a1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts@@ -9,4 +9,4 @@ export interface ScrubJob {export type ScrubReply =| { ready: true }| { id: number; out: Uint8Array; timings: StageTimings }- | { id: number; failure: { message: string; undecodable: boolean } }+ | { id: number; failure: { message: string; kind: 'undecodable' | 'opt-out' | 'failed' } }diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/xmp.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/xmp.test.tsnew file mode 100644index 000000000000..08ffaaafe211--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/xmp.test.ts@@ -0,0 +1,64 @@+import { imageMetadataProhibitsAiTraining, xmpProhibitsAiTraining } from './xmp.ts'++const packet = (description: string): Buffer =>+ Buffer.from(`+ <x:xmpmeta xmlns:x="adobe:ns:meta/">+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">+ <rdf:Description xmlns:rights="http://ns.useplus.org/ldf/xmp/1.0/" ${description} />+ </rdf:RDF>+ </x:xmpmeta>+ `)++describe('PLUS Data Mining metadata', () => {+ it.each([+ 'DMI-PROHIBITED',+ 'DMI-PROHIBITED-AIMLTRAINING',+ 'DMI-PROHIBITED-EXCEPTSEARCHENGINEINDEXING',+ 'DMI-PROHIBITED-GENAIMLTRAINING',+ 'DMI-PROHIBITED-SEECONSTRAINT',+ 'DMI-PROHIBITED-SEEEMBEDDEDRIGHTSEXPR',+ 'DMI-PROHIBITED-SEELINKEDRIGHTSEXPR',+ ])('recognizes %s in an attribute with any valid namespace prefix', (value) => {+ expect(xmpProhibitsAiTraining(packet(`rights:DataMining="http://ns.useplus.org/ldf/vocab/${value}"`))).toBe(+ true+ )+ })++ it('recognizes the RDF resource form', () => {+ expect(+ xmpProhibitsAiTraining(+ Buffer.from(`+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"+ xmlns:plus="http://ns.useplus.org/ldf/xmp/1.0/">+ <rdf:Description>+ <plus:DataMining rdf:resource="http://ns.useplus.org/ldf/vocab/DMI-PROHIBITED" />+ </rdf:Description>+ </rdf:RDF>+ `)+ )+ ).toBe(true)+ })++ it('does not reject an allowed value or the same property name in another namespace', () => {+ expect(xmpProhibitsAiTraining(packet('rights:DataMining="http://ns.useplus.org/ldf/vocab/DMI-ALLOWED"'))).toBe(+ false+ )+ expect(+ xmpProhibitsAiTraining(Buffer.from('<DataMining xmlns="https://example.com/">DMI-PROHIBITED</DataMining>'))+ ).toBe(false)+ })++ it('recognizes an XMP packet in a GIF application extension', () => {+ const xmp = packet('rights:DataMining="http://ns.useplus.org/ldf/vocab/DMI-PROHIBITED"')+ const trailer = Buffer.from([0x01, ...Array.from({ length: 255 }, (_, index) => 0xff - index), 0x00, 0x00])+ const gif = Buffer.concat([+ Buffer.from('GIF89a', 'ascii'),+ Buffer.from([0x21, 0xff, 0x0b]),+ Buffer.from('XMP DataXMP', 'ascii'),+ xmp,+ trailer,+ ])++ expect(imageMetadataProhibitsAiTraining(gif, undefined)).toBe(true)+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/xmp.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/xmp.tsnew file mode 100644index 000000000000..ce57924e8254--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/xmp.ts@@ -0,0 +1,103 @@+import { type SaxesAttributeNS, SaxesParser, type SaxesTagNS } from 'saxes'++const PLUS_NAMESPACE = 'http://ns.useplus.org/ldf/xmp/1.0/'+const RDF_NAMESPACE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'+const GIF_XMP_MARKER = Buffer.concat([Buffer.from([0x21, 0xff, 0x0b]), Buffer.from('XMP DataXMP', 'ascii')])+const GIF_XMP_TRAILER = Buffer.from([0x01, ...Array.from({ length: 255 }, (_, index) => 0xff - index), 0x00, 0x00])+const PROHIBITED_DATA_MINING_VALUES = new Set([+ 'DMI-PROHIBITED',+ 'DMI-PROHIBITED-AIMLTRAINING',+ 'DMI-PROHIBITED-EXCEPTSEARCHENGINEINDEXING',+ 'DMI-PROHIBITED-GENAIMLTRAINING',+ 'DMI-PROHIBITED-SEECONSTRAINT',+ 'DMI-PROHIBITED-SEEEMBEDDEDRIGHTSEXPR',+ 'DMI-PROHIBITED-SEELINKEDRIGHTSEXPR',+])++function isProhibitedDataMiningValue(value: string): boolean {+ const identifier = value.trim().split('/').at(-1)+ return identifier !== undefined && PROHIBITED_DATA_MINING_VALUES.has(identifier)+}++function isDataMiningProperty(value: { uri: string; local: string }): boolean {+ return value.uri === PLUS_NAMESPACE && value.local === 'DataMining'+}++function resourceValue(tag: SaxesTagNS): string | undefined {+ return Object.values(tag.attributes).find(+ (attribute: SaxesAttributeNS) => attribute.uri === RDF_NAMESPACE && attribute.local === 'resource'+ )?.value+}++export function xmpProhibitsAiTraining(xmp: Buffer): boolean {+ const parser = new SaxesParser({ xmlns: true })+ let prohibited = false+ let dataMiningDepth = 0+ let dataMiningText = ''++ parser.on('opentag', (tag) => {+ for (const attribute of Object.values(tag.attributes)) {+ if (isDataMiningProperty(attribute) && isProhibitedDataMiningValue(attribute.value)) {+ prohibited = true+ }+ }+ if (dataMiningDepth > 0) {+ dataMiningDepth += 1+ return+ }+ if (isDataMiningProperty(tag)) {+ dataMiningDepth = 1+ dataMiningText = ''+ const resource = resourceValue(tag)+ if (resource && isProhibitedDataMiningValue(resource)) {+ prohibited = true+ }+ }+ })+ const collectText = (text: string): void => {+ if (dataMiningDepth > 0) {+ dataMiningText += text+ }+ }+ parser.on('text', collectText)+ parser.on('cdata', collectText)+ parser.on('closetag', () => {+ if (dataMiningDepth === 0) {+ return+ }+ dataMiningDepth -= 1+ if (dataMiningDepth === 0 && isProhibitedDataMiningValue(dataMiningText)) {+ prohibited = true+ }+ })+ parser.write(xmp.toString('utf8')).close()+ return prohibited+}++function gifXmpPackets(input: Buffer): Buffer[] {+ if (input.toString('ascii', 0, 6) !== 'GIF89a') {+ return []+ }+ const packets: Buffer[] = []+ let searchFrom = 0+ for (;;) {+ const markerOffset = input.indexOf(GIF_XMP_MARKER, searchFrom)+ if (markerOffset === -1) {+ return packets+ }+ const packetOffset = markerOffset + GIF_XMP_MARKER.length+ const trailerOffset = input.indexOf(GIF_XMP_TRAILER, packetOffset)+ if (trailerOffset === -1) {+ throw new Error('GIF XMP extension has no valid trailer')+ }+ packets.push(input.subarray(packetOffset, trailerOffset))+ searchFrom = trailerOffset + GIF_XMP_TRAILER.length+ }+}++export function imageMetadataProhibitsAiTraining(input: Buffer, decodedXmp: Buffer | undefined): boolean {+ if (decodedXmp && xmpProhibitsAiTraining(decodedXmp)) {+ return true+ }+ return gifXmpPackets(input).some(xmpProhibitsAiTraining)+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.tsindex 70c2ffff96fb..331dcb5cdcd9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref.ts@@ -1,6 +1,6 @@-// The shared ref format between the producer, this consumer, and training joins; pseudo_team is the-// non-reversible HMAC team pseudonym from ml-mirror/pseudonymize.ts (keeps raw team ids out of the-// ML bucket). The hash half is keyed (per-team HMAC, derived alongside the pseudonym) so the+// The inline-image ref format shared by the producer, this consumer, and training joins.+// pseudo_team is the non-reversible HMAC team pseudonym from ml-mirror/pseudonymize.ts. The hash+// half is keyed with a per-team HMAC, derived alongside the pseudonym, so the// unencrypted bucket carries no unkeyed content digest — a plain sha256 would let a bucket reader// confirm whether specific known bytes appeared in a session, and correlate identical images across// teams. The consumer trusts the producer's ref (it is the only writer) and never recomputes the@@ -17,7 +17,9 @@ const PREFIX = 'image'* silent mis-join rather than an error.*/const URL_PREFIX = 'imageurl'-const REF_RE = /^(image|imageurl):([0-9a-f]{32}):([A-Za-z0-9_-]{22})$/+const CONTENT_REF_RE = /^image:([0-9a-f]{32}):([A-Za-z0-9_-]{22})$/+const GLOBAL_URL_REF_RE = /^imageurl:([A-Za-z0-9_-]{22})$/+const LEGACY_URL_REF_RE = /^imageurl:([0-9a-f]{32}):([A-Za-z0-9_-]{22})$/export function hashImageBytes(contentKey: string | Buffer, bytes: Buffer): string {return createHmac('sha256', contentKey).update(bytes).digest('base64url').slice(0, 22)@@ -27,16 +29,26 @@ export function imageRef(pseudoTeam: string, hash: string): string {return `${PREFIX}:${pseudoTeam}:${hash}`}-export function urlRef(pseudoTeam: string, hash: string): string {- return `${URL_PREFIX}:${pseudoTeam}:${hash}`+export function urlRef(hash: string): string {+ return `${URL_PREFIX}:${hash}`}export function isImageRef(s: string): boolean {- return REF_RE.test(s)+ return CONTENT_REF_RE.test(s) || GLOBAL_URL_REF_RE.test(s) || LEGACY_URL_REF_RE.test(s)}/** Parses either kind of ref. `source` says which promise the hash carries. */-export function parseImageRef(s: string): { pseudoTeam: string; hash: string; source: 'bytes' | 'url' } | null {- const m = REF_RE.exec(s)- return m ? { pseudoTeam: m[2], hash: m[3], source: m[1] === PREFIX ? 'bytes' : 'url' } : null+export function parseImageRef(+ s: string+): { pseudoTeam: string; hash: string; source: 'bytes' } | { pseudoTeam?: string; hash: string; source: 'url' } | null {+ const content = CONTENT_REF_RE.exec(s)+ if (content) {+ return { pseudoTeam: content[1], hash: content[2], source: 'bytes' }+ }+ const globalUrl = GLOBAL_URL_REF_RE.exec(s)+ if (globalUrl) {+ return { hash: globalUrl[1], source: 'url' }+ }+ const legacyUrl = LEGACY_URL_REF_RE.exec(s)+ return legacyUrl ? { pseudoTeam: legacyUrl[1], hash: legacyUrl[2], source: 'url' } : null}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.test.tsnew file mode 100644index 000000000000..e24de21b4702--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.test.ts@@ -0,0 +1,30 @@+import { KafkaProducerWrapper } from '~/common/kafka/producer'++import { KafkaDeadLetterSink } from './dead-letter-sink'++describe('KafkaDeadLetterSink', () => {+ it('keeps transport headers beside the diagnostic headers', async () => {+ const produced: { headers?: Record<string, string> }[] = []+ const producer = {+ produce: (message: { headers?: Record<string, string> }) => {+ produced.push(message)+ return Promise.resolve()+ },+ } as unknown as KafkaProducerWrapper+ const sink = new KafkaDeadLetterSink(producer, 'image-scrub-dlq')++ await sink.park({+ ref: 'imageurl:team:hash',+ bytes: Buffer.from('compressed'),+ headers: { 'content-type': 'image/png', 'content-encoding': 'gzip' },+ detail: { reason: 'rejected', replayCount: 1 },+ })++ expect(produced[0].headers).toEqual({+ 'content-type': 'image/png',+ 'content-encoding': 'gzip',+ reason: 'rejected',+ replayCount: '1',+ })+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.tsindex 7988b9662711..9a5b30333fce 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink.ts@@ -19,12 +19,20 @@ export class KafkaDeadLetterSink implements DeadLetterSink {private readonly topic: string) {}- public async park(image: { ref: string; bytes: Buffer; detail: Record<string, unknown> }): Promise<void> {+ public async park(image: {+ ref: string+ bytes: Buffer+ headers: Record<string, string>+ detail: Record<string, unknown>+ }): Promise<void> {await this.producer.produce({topic: this.topic,key: Buffer.from(image.ref),value: image.bytes,- headers: Object.fromEntries(Object.entries(image.detail).map(([k, v]) => [k, String(v)])),+ headers: {+ ...image.headers,+ ...Object.fromEntries(Object.entries(image.detail).map(([k, v]) => [k, String(v)])),+ },})}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.tsindex fa56453db54f..f596896b8e9d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts@@ -5,7 +5,12 @@ import { KafkaProducerWrapper } from '~/common/kafka/producer'import { MAX_REPLAYS, replayBatch } from './dlq-replay'import { REPLAY_COUNT_HEADER } from './image-batcher'-function parked(ref: string, bytes: string, replayCount?: number): Message {+function parked(+ ref: string,+ bytes: string,+ replayCount?: number,+ transportHeaders: Record<string, string> = {}+): Message {return {topic: 'session_replay_image_scrub_dlq',partition: 0,@@ -13,6 +18,7 @@ function parked(ref: string, bytes: string, replayCount?: number): Message {key: Buffer.from(ref),value: Buffer.from(bytes),headers: [+ ...Object.entries(transportHeaders).map(([key, value]) => ({ [key]: Buffer.from(value) })),{ reason: Buffer.from('rejected') },...(replayCount === undefined ? [] : [{ [REPLAY_COUNT_HEADER]: Buffer.from(String(replayCount)) }]),],@@ -48,7 +54,7 @@ describe('replayBatch', () => {key: 'ref-1',value: 'original-image',// The park's diagnostic headers describe an old failure and must not travel with a- // fresh attempt; only the count that bounds the round trips survives.+ // fresh attempt. This inline image has no transport headers, so only the count survives.headers: { [REPLAY_COUNT_HEADER]: '1' },},])@@ -74,4 +80,23 @@ describe('replayBatch', () => {expect(produced[0].headers).toEqual({ [REPLAY_COUNT_HEADER]: '2' })})++ it('preserves the content headers needed to decode a replayed URL image', async () => {+ await replayBatch(+ [+ parked('ref-1', 'compressed-image', undefined, {+ 'content-type': 'image/png',+ 'content-encoding': 'gzip',+ }),+ ],+ producer,+ 'session_replay_image_scrub'+ )++ expect(produced[0].headers).toEqual({+ 'content-type': 'image/png',+ 'content-encoding': 'gzip',+ [REPLAY_COUNT_HEADER]: '1',+ })+ })})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.tsindex fc9570ff5ddb..bcaca7827f87 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts@@ -5,6 +5,7 @@ import { KafkaProducerWrapper } from '~/common/kafka/producer'import { logger } from '~/common/utils/logger'import { REPLAY_COUNT_HEADER } from './image-batcher'+import { CONTENT_ENCODING_HEADER, CONTENT_TYPE_HEADER } from './image-transport'import { ImageScrubConsumerMetrics } from './metrics'/**@@ -29,10 +30,9 @@ export interface ReplayOutcome {* exercise is to put it through a fixed sidecar exactly as it arrived the first time. The key is the* ref, so it lands on the partition the rest of that image's copies hash to.*- * Diagnostic headers from the park are deliberately dropped: they describe the failure that put the- * image here, and carrying them onto a topic where every other message has none would leave the- * scrub consumer reading stale reasons on a fresh attempt. Only the replay count survives, because- * it is what stops an image circling between the two topics.+ * Diagnostic headers from the park are deliberately dropped because they describe an old failure.+ * The content headers survive because the consumer needs them to decode and validate fetched images.+ * The replay count also survives because it stops an image circling between the two topics.*/export async function replayBatch(messages: Message[],@@ -59,7 +59,13 @@ export async function replayBatch(topic: sourceTopic,key: Buffer.from(ref),value: message.value,- headers: { [REPLAY_COUNT_HEADER]: String(replayCount + 1) },+ headers: {+ ...(headers[CONTENT_TYPE_HEADER] ? { [CONTENT_TYPE_HEADER]: headers[CONTENT_TYPE_HEADER] } : {}),+ ...(headers[CONTENT_ENCODING_HEADER]+ ? { [CONTENT_ENCODING_HEADER]: headers[CONTENT_ENCODING_HEADER] }+ : {}),+ [REPLAY_COUNT_HEADER]: String(replayCount + 1),+ },})outcome.replayed += 1ImageScrubConsumerMetrics.incReplayed()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 f85e6567fccf..ee331ddcbf73 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@@ -1,14 +1,23 @@-import { Message, TopicPartitionOffset } from 'node-rdkafka'+import { Message, MessageHeader, TopicPartitionOffset } from 'node-rdkafka'+import { gzipSync } from 'node:zlib'-import { hashImageBytes, imageRef } from './content-ref'+import { hashImageBytes, imageRef, urlRef } from './content-ref'import { ImageBatcher, OffsetStore } from './image-batcher'-import { ImageShardStore, ScrubbedImage } from './image-shard-store'+import { ImageShardStore, ScrubbedImage, ScrubbedUrlImage } from './image-shard-store'+import { ImageScrubConsumerMetrics } from './metrics'import { ScrubClient, ScrubPoisoned } from './scrub-client'const pt = (n: number): string => String(n).padStart(32, '0')const CONTENT_KEY = 'fedcba9876543210fedcba9876543210'-function msg(partition: number, offset: number, pseudoTeam: string, bytes: Buffer, keyOverride?: string): Message {+function msg(+ partition: number,+ offset: number,+ pseudoTeam: string,+ bytes: Buffer,+ keyOverride?: string,+ headers?: MessageHeader[]+): Message {const ref = keyOverride ?? imageRef(pseudoTeam, hashImageBytes(CONTENT_KEY, bytes))return {topic: 'session_replay_image_scrub',@@ -16,12 +25,15 @@ function msg(partition: number, offset: number, pseudoTeam: string, bytes: Buffeoffset,key: Buffer.from(ref),value: bytes,+ headers,} as unknown as Message}class FakeStore {public writes: ScrubbedImage[][] = []+ public urlWrites: ScrubbedUrlImage[] = []public failNext = false+ public failNextUrl = false// eslint-disable-next-line @typescript-eslint/require-awaitasync writeShard(images: ScrubbedImage[]): Promise<{ shard: string; bytes: number }> {if (this.failNext) {@@ -30,6 +42,14 @@ class FakeStore {this.writes.push(images)return { shard: 'shard', bytes: images.reduce((n, i) => n + i.bytes.length, 0) }}++ // eslint-disable-next-line @typescript-eslint/require-await+ async writeUrlImage(image: ScrubbedUrlImage): Promise<void> {+ if (this.failNextUrl) {+ throw new Error('url s3 down')+ }+ this.urlWrites.push(image)+ }}class FakeOffsets implements OffsetStore {@@ -54,6 +74,8 @@ const options = {}describe('ImageBatcher', () => {+ afterEach(() => jest.restoreAllMocks())+it('scrubs a multi-team batch into one shard for the flush, storing offsets after', async () => {const store = new FakeStore()const offsets = new FakeOffsets()@@ -85,6 +107,192 @@ describe('ImageBatcher', () => {expect(store.writes[0][0].hash).toBe(ref.split(':')[2])})+ it('decodes and validates a URL image from its Kafka transport headers before scrubbing it', async () => {+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ const received: Buffer[] = []+ const capturingClient = {+ scrub: (bytes: Buffer) => {+ received.push(bytes)+ return Promise.resolve(bytes)+ },+ } as unknown as ScrubClient+ const store = new FakeStore()+ const batcher = new ImageBatcher(+ store as unknown as ImageShardStore,+ new FakeOffsets(),+ capturingClient,+ options,+ 0+ )+ const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))++ await batcher.handleBatch(+ [+ msg(0, 0, pt(1), gzipSync(png), ref, [+ { 'content-type': Buffer.from('image/png') },+ { 'content-encoding': Buffer.from('gzip') },+ ]),+ ],+ 1+ )++ expect(received).toEqual([png])+ expect(store.urlWrites).toEqual([+ {+ hash: ref.slice('imageurl:'.length),+ bytes: png,+ sourcePartition: 0,+ sourceOffset: 0,+ },+ ])+ expect(store.writes).toHaveLength(0)+ })++ it('submits every valid URL image for the conditional store to select the first completed write', async () => {+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ const newer = Buffer.concat([png, Buffer.from('newer')])+ const older = Buffer.concat([png, Buffer.from('older')])+ const store = new FakeStore()+ const batcher = new ImageBatcher(+ store as unknown as ImageShardStore,+ new FakeOffsets(),+ { scrub: (bytes: Buffer) => Promise.resolve(bytes) } as unknown as ScrubClient,+ options,+ 0+ )+ const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))++ await batcher.handleBatch(+ [+ msg(0, 12, pt(1), newer, ref, [{ 'content-type': Buffer.from('image/png') }]),+ msg(0, 10, pt(1), older, ref, [{ 'content-type': Buffer.from('image/png') }]),+ ],+ 1+ )++ expect(store.urlWrites).toEqual([+ {+ hash: ref.slice('imageurl:'.length),+ bytes: newer,+ sourcePartition: 0,+ sourceOffset: 12,+ },+ {+ hash: ref.slice('imageurl:'.length),+ bytes: older,+ sourcePartition: 0,+ sourceOffset: 10,+ },+ ])+ })++ it('uses a later valid URL image when an earlier candidate for the ref is invalid', async () => {+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ const store = new FakeStore()+ const batcher = new ImageBatcher(+ store as unknown as ImageShardStore,+ new FakeOffsets(),+ { scrub: (bytes: Buffer) => Promise.resolve(bytes) } as unknown as ScrubClient,+ options,+ 0+ )+ const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))++ await batcher.handleBatch(+ [+ msg(0, 10, pt(1), Buffer.from('not a png'), ref, [{ 'content-type': Buffer.from('image/png') }]),+ msg(0, 11, pt(1), png, ref, [{ 'content-type': Buffer.from('image/png') }]),+ ],+ 1+ )++ expect(store.urlWrites).toEqual([+ {+ hash: ref.slice('imageurl:'.length),+ bytes: png,+ sourcePartition: 0,+ sourceOffset: 11,+ },+ ])+ })++ it('scrubs a newer URL version after an earlier version was persisted by the same pod', async () => {+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ const first = Buffer.concat([png, Buffer.from('first')])+ const second = Buffer.concat([png, Buffer.from('second')])+ const store = new FakeStore()+ const batcher = new ImageBatcher(+ store as unknown as ImageShardStore,+ new FakeOffsets(),+ { scrub: (bytes: Buffer) => Promise.resolve(bytes) } as unknown as ScrubClient,+ options,+ 0+ )+ const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))++ await batcher.handleBatch([msg(0, 10, pt(1), first, ref, [{ 'content-type': Buffer.from('image/png') }])], 1)+ await batcher.handleBatch([msg(0, 11, pt(1), second, ref, [{ 'content-type': Buffer.from('image/png') }])], 2)++ expect(store.urlWrites.map((image) => [image.sourceOffset, image.bytes])).toEqual([+ [10, first],+ [11, second],+ ])+ })++ it('bounds concurrent URL-image writes by the scrub worker limit', async () => {+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ let activeWrites = 0+ let maximumActiveWrites = 0+ const store = {+ writeUrlImage: async () => {+ activeWrites += 1+ maximumActiveWrites = Math.max(maximumActiveWrites, activeWrites)+ await Promise.resolve()+ activeWrites -= 1+ },+ writeShard: () => Promise.resolve({ shard: 'unused', bytes: 0 }),+ } as unknown as ImageShardStore+ const batcher = new ImageBatcher(+ store,+ new FakeOffsets(),+ { scrub: () => Promise.resolve(png) } as unknown as ScrubClient,+ { ...options, scrubConcurrency: 2 },+ 0+ )+ const messages = Array.from({ length: 6 }, (_, index) => {+ const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from(`https://example.com/${index}.png`)))+ return msg(0, index, pt(1), png, ref, [{ 'content-type': Buffer.from('image/png') }])+ })++ await batcher.handleBatch(messages, 1)++ expect(maximumActiveWrites).toBe(2)+ })++ it('drops a URL image whose bytes do not match its Kafka content-type', async () => {+ let scrubCalls = 0+ const batcher = new ImageBatcher(+ new FakeStore() as unknown as ImageShardStore,+ new FakeOffsets(),+ {+ scrub: () => {+ scrubCalls += 1+ return Promise.resolve(Buffer.from('scrubbed'))+ },+ } as unknown as ScrubClient,+ options,+ 0+ )+ const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))++ await batcher.handleBatch(+ [msg(0, 0, pt(1), Buffer.from([0xff, 0xd8, 0xff]), ref, [{ 'content-type': Buffer.from('image/png') }])],+ 1+ )++ expect(scrubCalls).toBe(0)+ })+it('does not store offsets when the shard write fails (at-least-once replay)', async () => {const store = new FakeStore()store.failNext = true@@ -95,6 +303,28 @@ describe('ImageBatcher', () => {expect(offsets.stored).toBe(0)})+ it('does not create a random inline shard before deterministic URL writes succeed', async () => {+ const store = new FakeStore()+ store.failNextUrl = true+ const offsets = new FakeOffsets()+ const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options, 0)+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))++ await expect(+ batcher.handleBatch(+ [+ msg(0, 0, pt(1), Buffer.from('inline')),+ msg(0, 1, pt(1), png, ref, [{ 'content-type': Buffer.from('image/png') }]),+ ],+ 1+ )+ ).rejects.toThrow('url s3 down')++ expect(store.writes).toHaveLength(0)+ expect(offsets.stored).toBe(0)+ })+it('stores offsets with each mid-batch flush, so a later failure replays only from the flush', async () => {// A flush persists a randomly named shard; if the batch then fails (e.g. the scrub deadline)// without having stored the flushed messages' offsets, Kafka replays them and every replay@@ -543,6 +773,51 @@ describe('ImageBatcher', () => {expect(parked[0].replayCount).toBe(1)})+ it('preserves URL transport headers when it parks the original compressed bytes', async () => {+ const parked: { headers: Record<string, string>; bytes: Buffer }[] = []+ const poisonClient = {+ scrub: () =>+ Promise.reject(+ new ScrubPoisoned('cannot process', {+ reason: 'rejected',+ lastError: 'sidecar responded 500',+ attempts: 12,+ waitedMs: 60_000,+ })+ ),+ } as unknown as ScrubClient+ const batcher = new ImageBatcher(+ new FakeStore() as unknown as ImageShardStore,+ new FakeOffsets(),+ poisonClient,+ options,+ 0,+ {+ park: (image) => Promise.resolve(void parked.push({ headers: image.headers, bytes: image.bytes })),+ }+ )+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ const compressed = gzipSync(png)+ const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/poison.png')))++ await batcher.handleBatch(+ [+ msg(0, 0, pt(1), compressed, ref, [+ { 'content-type': Buffer.from('image/png') },+ { 'content-encoding': Buffer.from('gzip') },+ ]),+ ],+ 1+ )++ expect(parked).toEqual([+ {+ bytes: compressed,+ headers: { 'content-type': 'image/png', 'content-encoding': 'gzip' },+ },+ ])+ })+it('refuses to start when concurrency is too low for dead-lettering to be reachable', () => {// The poison gate can only ever count successes from slots running alongside the image it is// judging: the batch holding that image cannot finish, and the pod cannot poll for more work@@ -612,11 +887,16 @@ describe('ImageBatcher', () => {),} as unknown as ScrubClientconst batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, hangingClient, options, 0)+ const startBatch = jest.spyOn(ImageScrubConsumerMetrics, 'startBatch')+ const finishBatch = jest.spyOn(ImageScrubConsumerMetrics, 'finishBatch')const running = batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)+ expect(startBatch).toHaveBeenCalledTimes(1)+ expect(finishBatch).not.toHaveBeenCalled()batcher.stop()await expect(running).resolves.toBeUndefined()+ expect(finishBatch).toHaveBeenCalledTimes(1)// Nothing finished, so nothing may be committed over: the image replays under the next owner.expect(offsets.received.flat()).toEqual([])expect(store.writes).toHaveLength(0)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.tsindex 34893e3454e9..cef11ad3b650 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts@@ -6,7 +6,13 @@ import { logger } from '~/common/utils/logger'import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'import { parseImageRef } from './content-ref'-import { ImageShardStore, ScrubbedImage } from './image-shard-store'+import { ImageShardStore, ScrubbedImage, ScrubbedUrlImage } from './image-shard-store'+import {+ CONTENT_ENCODING_HEADER,+ CONTENT_TYPE_HEADER,+ InvalidImageTransportError,+ prepareFetchedImage,+} from './image-transport'import { ImageScrubConsumerMetrics } from './metrics'import { POISON_MIN_OTHER_SUCCESSES, ScrubAborted, ScrubClient, ScrubPoisoned } from './scrub-client'@@ -22,7 +28,12 @@ export interface OffsetStore {* the sidecar bug behind it unreproducible. Parking it keeps both properties.*/export interface DeadLetterSink {- park(image: { ref: string; bytes: Buffer; detail: Record<string, unknown> }): Promise<void>+ park(image: {+ ref: string+ bytes: Buffer+ headers: Record<string, string>+ detail: Record<string, unknown>+ }): Promise<void>}/**@@ -54,9 +65,11 @@ const REVOKED_PARTITION_CODES = new Set([interface PlannedScrub {index: numberref: string- pseudoTeam: string+ pseudoTeam?: stringhash: string+ source: 'bytes' | 'url'value: Buffer+ transportHeaders: Record<string, string>/** Where this image came from, carried only so a parked one can be traced back to its source. */sourceTopic: stringsourcePartition: number@@ -73,7 +86,8 @@ interface PlannedScrub {interface ScrubbedRef {ref: string- image: ScrubbedImage+ source: 'bytes' | 'url'+ image: ScrubbedImage | ScrubbedUrlImage}/** Carries the window slot so a completion can be matched back to its position, which is what@@ -93,21 +107,21 @@ export interface ImageBatcherOptions {}export class ImageBatcher {- private buffer: ScrubbedImage[] = []+ private buffer: ScrubbedRef[] = []private bufferBytes = 0private pendingOffsets = new Map<string, TopicPartitionOffset>()private lastFlushMs: numberprivate readonly maxInFlight: numberprivate readonly scrubConcurrency: ConcurrencyController/**- * Refs this pod has resolved, either by buffering the scrubbed bytes or by having the sidecar- * permanently reject them. A best-effort stand-in for asking S3 "are these bytes already in the- * bucket", which shards cannot answer: they pack many images per object, so no per-hash key- * exists. The topic is keyed by ref, so every copy of an image reaches this same pod and within- * capacity the answer is exact; past it we simply rescrub. Marking a scrubbed ref only after its- * buffer push is what stops a rebalance without a restart from skipping a ref it never persisted,- * since a batch that throws keeps its buffer. Sizing is a throughput question, not a correctness- * one.+ * Content-addressed refs this pod has resolved, either by buffering the scrubbed bytes or by+ * having the sidecar permanently reject them. URL refs are absent because their bytes can change+ * between recrawls. A best-effort stand-in for asking S3 "are these bytes already in the bucket",+ * which shards cannot answer: they pack many images per object, so no per-hash key exists. The+ * topic is keyed by ref, so every copy of an inline image reaches this same pod and within capacity+ * the answer is exact; past it we simply rescrub. Marking a scrubbed ref only after its buffer push+ * is what stops a rebalance without a restart from skipping a ref it never persisted, since a batch+ * that throws keeps its buffer. Sizing is a throughput question, not a correctness one.*/private readonly seenRefs: RefDedupCache/**@@ -194,12 +208,16 @@ export class ImageBatcher {this.activeBatch = controllerthis.partitionsRevoked = falseconst startedAt = performance.now()+ if (planned.length > 0) {+ ImageScrubConsumerMetrics.startBatch()+ }try {await this.scrubAndStage(messages, planned, controller, nowMs)} finally {// Empty polls arrive on a timer under callEachBatchWhenEmpty and would otherwise bury// the real distribution of both histograms in a zero bucket.if (planned.length > 0) {+ ImageScrubConsumerMetrics.finishBatch()ImageScrubConsumerMetrics.observeBatchProgress(this.retiredInBatch,planned.length,@@ -279,12 +297,13 @@ export class ImageBatcher {while (retired < planned.length && settled[retired]) {const ready = staged[retired]if (ready) {- this.buffer.push(ready.image)- this.bufferBytes += ready.image.bytes.length+ this.bufferScrubbedRef(ready)// Marked here rather than on completion: a staged image is a local that a thrown// batch discards, so a ref marked before retirement could be skipped on replay// without ever having been persisted.- this.seenRefs.add(ready.ref)+ if (ready.source === 'bytes') {+ this.seenRefs.add(ready.ref)+ }staged[retired] = nullstagedCount -= 1stagedBytes -= ready.image.bytes.length@@ -330,44 +349,73 @@ export class ImageBatcher {/** Retains nothing between batches, so unlike [[seenRefs]] this dedup cannot be sized wrong or disabled. */private planBatch(messages: Message[]): PlannedScrub[] {const planned: PlannedScrub[] = []- const batchRefs = new Set<string>()+ const inlineRefs = new Set<string>()+ const urlLocationByRef = new Map<string, Pick<PlannedScrub, 'sourceTopic' | 'sourcePartition'>>()for (const [index, m] of messages.entries()) {const ref = m.key?.toString('utf8')// The ref's hash is a producer-side per-team HMAC; this consumer doesn't hold the key and// trusts the producer (the topic's only writer) that the key names these bytes.const parsed = ref ? parseImageRef(ref) : null- // A URL ref names a URL, not these bytes. The shard store indexes by (pseudoTeam, hash)- // with the prefix dropped, so accepting one here would file URL-sourced bytes in the- // same slot as content-addressed ones. That is the silent mis-join the prefix exists- // to prevent, so it counts as an invalid key rather than being stored.- if (!ref || !parsed || parsed.source !== 'bytes' || !m.value) {+ if (!ref || !parsed || !m.value) {ImageScrubConsumerMetrics.incInvalidKey()continue}- if (batchRefs.has(ref)) {- ImageScrubConsumerMetrics.incDeduped('batch')- continue- }- batchRefs.add(ref)- if (this.seenRefs.has(ref)) {- ImageScrubConsumerMetrics.incDeduped('pod')- continue- }- planned.push({+ const headers = parseKafkaHeaders(m.headers)+ const transportHeaders =+ parsed.source === 'url'+ ? Object.fromEntries(+ [CONTENT_TYPE_HEADER, CONTENT_ENCODING_HEADER]+ .filter((header) => headers[header] !== undefined)+ .map((header) => [header, headers[header]])+ )+ : {}+ const candidate: PlannedScrub = {index,ref,pseudoTeam: parsed.pseudoTeam,hash: parsed.hash,+ source: parsed.source,value: m.value,+ transportHeaders,sourceTopic: m.topic,sourcePartition: m.partition,sourceOffset: m.offset,- replayCount: Number(parseKafkaHeaders(m.headers)[REPLAY_COUNT_HEADER] ?? 0) || 0,- })+ replayCount: Number(headers[REPLAY_COUNT_HEADER] ?? 0) || 0,+ }+ if (parsed.source === 'url') {+ const existing = urlLocationByRef.get(ref)+ if (existing) {+ if (+ existing.sourceTopic !== candidate.sourceTopic ||+ existing.sourcePartition !== candidate.sourcePartition+ ) {+ throw new Error(`URL image ref ${ref} arrived on more than one Kafka partition`)+ }+ } else {+ urlLocationByRef.set(ref, candidate)+ }+ planned.push(candidate)+ continue+ }+ if (inlineRefs.has(ref)) {+ ImageScrubConsumerMetrics.incDeduped('batch')+ continue+ }+ inlineRefs.add(ref)+ if (this.seenRefs.has(ref)) {+ ImageScrubConsumerMetrics.incDeduped('pod')+ continue+ }+ planned.push(candidate)}return planned}+ private bufferScrubbedRef(ready: ScrubbedRef): void {+ this.buffer.push(ready)+ this.bufferBytes += ready.image.bytes.length+ }+private recordOffsets(messages: Message[]): void {for (const offset of findOffsetsToCommit(messages)) {this.pendingOffsets.set(`${offset.topic}:${offset.partition}`, offset)@@ -385,7 +433,10 @@ export class ImageBatcher {abortController: controller,}).then(- (image): SettledScrub => ({ slot, scrubbed: image ? { ref: p.ref, image } : null }),+ (image): SettledScrub => ({+ slot,+ scrubbed: image ? { ref: p.ref, source: p.source, image } : null,+ }),(error): SettledScrub => ({ slot, scrubbed: null, error: error ?? new Error('scrub failed') }))}@@ -399,10 +450,31 @@ export class ImageBatcher {}}- private async scrubOne(planned: PlannedScrub, signal: AbortSignal): Promise<ScrubbedImage | null> {+ private async scrubOne(+ planned: PlannedScrub,+ signal: AbortSignal+ ): Promise<ScrubbedImage | ScrubbedUrlImage | null> {+ let input = planned.value+ if (planned.source === 'url') {+ try {+ input = await prepareFetchedImage(+ input,+ planned.transportHeaders[CONTENT_TYPE_HEADER],+ planned.transportHeaders[CONTENT_ENCODING_HEADER]+ )+ } catch (error) {+ if (!(error instanceof InvalidImageTransportError)) {+ throw error+ }+ this.rememberContentAddressedRef(planned)+ ImageScrubConsumerMetrics.incSkipped()+ return null+ }+ }+let bytes: Buffer | nulltry {- bytes = await this.scrubClient.scrub(planned.value, signal, planned.ref)+ bytes = await this.scrubClient.scrub(input, signal, planned.ref)} catch (error) {if (!(error instanceof ScrubPoisoned) || !this.deadLetters) {throw error@@ -412,20 +484,33 @@ export class ImageBatcher {// waiting. Marking first would advance the offset over an image held nowhere.await this.parkUntilAccepted(planned, error, signal)logger.warn('☠️', 'image_scrub_dead_lettered', { ref: planned.ref, ...error.detail })- this.seenRefs.add(planned.ref)+ this.rememberContentAddressedRef(planned)ImageScrubConsumerMetrics.incDeadLettered(error.detail.reason)return null}if (bytes === null) {- // Null is only ever a 422/413, a verdict on the content itself, so no retry can succeed.- // Marking it stops every later copy from re-earning the same rejection, and there is- // nothing pending to persist, so this needs none of the care the success path does.- this.seenRefs.add(planned.ref)+ // Null is a verdict on these bytes. Inline refs are content-addressed, so their later+ // copies cannot succeed. URL refs stay eligible because a recrawl can carry new bytes.+ this.rememberContentAddressedRef(planned)ImageScrubConsumerMetrics.incSkipped()return null}ImageScrubConsumerMetrics.incScrubbed()- return { pseudoTeam: planned.pseudoTeam, hash: planned.hash, bytes }+ if (planned.source === 'url') {+ return {+ hash: planned.hash,+ bytes,+ sourcePartition: planned.sourcePartition,+ sourceOffset: planned.sourceOffset,+ }+ }+ return { pseudoTeam: planned.pseudoTeam!, hash: planned.hash, bytes }+ }++ private rememberContentAddressedRef(planned: PlannedScrub): void {+ if (planned.source === 'bytes') {+ this.seenRefs.add(planned.ref)+ }}/**@@ -451,6 +536,7 @@ export class ImageBatcher {await this.deadLetters!.park({ref: planned.ref,bytes: planned.value,+ headers: planned.transportHeaders,detail: {...poisoned.detail,pseudoTeam: planned.pseudoTeam,@@ -496,8 +582,24 @@ export class ImageBatcher {public async flush(nowMs: number): Promise<void> {this.lastFlushMs = nowMsif (this.buffer.length > 0) {- const { bytes } = await this.store.writeShard(this.buffer)- ImageScrubConsumerMetrics.observeShard(this.buffer.length, bytes)+ const inlineImages = this.buffer+ .filter((item): item is ScrubbedRef & { image: ScrubbedImage } => item.source === 'bytes')+ .map((item) => item.image)+ const urlImages = this.buffer+ .filter((item): item is ScrubbedRef & { image: ScrubbedUrlImage } => item.source === 'url')+ .map((item) => item.image)+ await Promise.all(+ urlImages.map((image) =>+ this.scrubConcurrency.run({+ debugTag: image.hash,+ fn: () => this.store.writeUrlImage(image),+ })+ )+ )+ if (inlineImages.length > 0) {+ const { bytes } = await this.store.writeShard(inlineImages)+ ImageScrubConsumerMetrics.observeShard(inlineImages.length, bytes)+ }this.buffer = []this.bufferBytes = 0}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.tsindex 3a74a10041e9..b3679a0b2b8b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts@@ -2,9 +2,15 @@ import { DeleteObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/clientimport { ImageShardStore } from './image-shard-store'-const image = { pseudoTeam: '0'.repeat(32), hash: 'a'.repeat(22), bytes: Buffer.from('img') }-describe('ImageShardStore', () => {+ const inlineImage = { pseudoTeam: '0'.repeat(32), hash: 'a'.repeat(22), bytes: Buffer.from('img') }+ const urlImage = {+ hash: 'AAAAAAAAAAAAAAAAAAAAAA',+ bytes: Buffer.from('scrubbed'),+ sourcePartition: 3,+ sourceOffset: 9,+ }+it('aborts a shard write that exceeds the timeout so the flush throws and replays', async () => {const s3 = {send: (_cmd: unknown, opts: { abortSignal: AbortSignal }) =>@@ -14,26 +20,68 @@ describe('ImageShardStore', () => {} as unknown as S3Clientconst store = new ImageShardStore(s3, 'bucket', 'prefix', 5)- await expect(store.writeShard([image])).rejects.toThrow()+ await expect(store.writeShard([inlineImage])).rejects.toThrow()})it('deletes the orphaned shard when the index write fails', async () => {const deleted: string[] = []const s3 = {- send: (cmd: PutObjectCommand | DeleteObjectCommand) => {- if (cmd instanceof DeleteObjectCommand) {- deleted.push(cmd.input.Key ?? '')+ send: (command: PutObjectCommand | DeleteObjectCommand) => {+ if (command instanceof DeleteObjectCommand) {+ deleted.push(command.input.Key ?? '')return Promise.resolve()}- return cmd.input.Key?.endsWith('.parquet')+ return command.input.Key?.endsWith('.parquet')? Promise.reject(new Error('index write failed'))- : Promise.resolve() // shard PUT succeeds+ : Promise.resolve()},} as unknown as S3Client- const store = new ImageShardStore(s3, 'bucket', 'prefix', 5000)+ const store = new ImageShardStore(s3, 'bucket', 'prefix', 5_000)- await expect(store.writeShard([image])).rejects.toThrow('index write failed')+ await expect(store.writeShard([inlineImage])).rejects.toThrow('index write failed')expect(deleted).toHaveLength(1)expect(deleted[0]).toContain('/shards/')})++ it('creates a URL object once with its source position', async () => {+ const send = jest.fn().mockResolvedValueOnce({})+ const store = new ImageShardStore({ send } as unknown as S3Client, 'bucket', 'images', 1_000, 'node')++ await store.writeUrlImage(urlImage)++ const put = send.mock.calls[0][0] as PutObjectCommand+ expect(put.input).toMatchObject({+ Key: `images/url/${urlImage.hash}`,+ IfNoneMatch: '*',+ Metadata: { 'source-partition': '3', 'source-offset': '9' },+ })+ })++ it('keeps the first URL object when the key already exists', async () => {+ const exists = Object.assign(new Error('exists'), {+ name: 'PreconditionFailed',+ $metadata: { httpStatusCode: 412 },+ })+ const send = jest.fn().mockRejectedValueOnce(exists)+ const store = new ImageShardStore({ send } as unknown as S3Client, 'bucket', 'images', 1_000, 'node')++ await store.writeUrlImage(urlImage)++ expect(send).toHaveBeenCalledTimes(1)+ expect((send.mock.calls[0][0] as PutObjectCommand).input.IfNoneMatch).toBe('*')+ })++ it('retries a concurrent conditional create until one writer succeeds', async () => {+ const conflict = Object.assign(new Error('concurrent write'), {+ name: 'ConditionalRequestConflict',+ $metadata: { httpStatusCode: 409 },+ })+ const send = jest.fn().mockRejectedValueOnce(conflict).mockResolvedValueOnce({})+ const store = new ImageShardStore({ send } as unknown as S3Client, 'bucket', 'images', 1_000, 'node')++ await store.writeUrlImage(urlImage)++ expect(send).toHaveBeenCalledTimes(2)+ expect(send.mock.calls.map(([command]) => (command as PutObjectCommand).input.IfNoneMatch)).toEqual(['*', '*'])+ })})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.tsindex 5e1b7b986b66..bfce2ddeb528 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts@@ -10,6 +10,13 @@ export interface ScrubbedImage {bytes: Buffer}+export interface ScrubbedUrlImage {+ hash: string+ bytes: Buffer+ sourcePartition: number+ sourceOffset: number+}+interface IndexRow {pseudoTeam: stringhash: string@@ -19,6 +26,9 @@ interface IndexRow {}const INDEX_FORMAT_VERSION = 1+const URL_SOURCE_PARTITION_METADATA = 'source-partition'+const URL_SOURCE_OFFSET_METADATA = 'source-offset'+const URL_WRITE_MAX_ATTEMPTS = 8const INDEX_SCHEMA = new ParquetSchema({format_version: { type: 'INT64', compression: 'SNAPPY' },@@ -109,4 +119,65 @@ export class ImageShardStore {}return { shard: shardKey, bytes: offset }}++ public async writeUrlImage(image: ScrubbedUrlImage): Promise<void> {+ if (+ !Number.isSafeInteger(image.sourcePartition) ||+ image.sourcePartition < 0 ||+ !Number.isSafeInteger(image.sourceOffset) ||+ image.sourceOffset < 0+ ) {+ throw new Error('URL image source position must contain non-negative safe integers')+ }+ const key = `${this.prefix}/url/${image.hash}`+ for (let attempt = 0; attempt < URL_WRITE_MAX_ATTEMPTS; attempt++) {+ try {+ await this.send(+ new PutObjectCommand({+ Bucket: this.bucket,+ Key: key,+ Body: image.bytes,+ ContentType: 'application/octet-stream',+ Metadata: {+ [URL_SOURCE_PARTITION_METADATA]: String(image.sourcePartition),+ [URL_SOURCE_OFFSET_METADATA]: String(image.sourceOffset),+ },+ IfNoneMatch: '*',+ })+ )+ return+ } catch (error) {+ if (isPreconditionFailed(error)) {+ return+ }+ if (isConditionalRequestConflict(error)) {+ continue+ }+ throw error+ }+ }+ throw new Error(`URL image ${image.hash} conditional create did not converge`)+ }+}++function s3HttpStatus(error: unknown): number | undefined {+ if (typeof error !== 'object' || error === null) {+ return undefined+ }+ const metadata = (error as { $metadata?: { httpStatusCode?: unknown } }).$metadata+ return typeof metadata?.httpStatusCode === 'number' ? metadata.httpStatusCode : undefined+}++function s3ErrorName(error: unknown): string {+ return typeof error === 'object' && error !== null && typeof (error as { name?: unknown }).name === 'string'+ ? String((error as { name: string }).name)+ : ''+}++function isPreconditionFailed(error: unknown): boolean {+ return s3HttpStatus(error) === 412 || s3ErrorName(error) === 'PreconditionFailed'+}++function isConditionalRequestConflict(error: unknown): boolean {+ return s3HttpStatus(error) === 409 || s3ErrorName(error) === 'ConditionalRequestConflict'}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.tsnew file mode 100644index 000000000000..ac390b6cb74e--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts@@ -0,0 +1,86 @@+import { brotliCompressSync, deflateSync, gzipSync, zstdCompressSync } from 'node:zlib'++import {+ InvalidImageTransportError,+ MAX_UNCOMPRESSED_IMAGE_BYTES,+ SUPPORTED_IMAGE_MEDIA_TYPES,+ imageBytesMatchMediaType,+ prepareFetchedImage,+} from './image-transport'++const imageHeaders = {+ 'image/png': Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ 'image/jpeg': Buffer.from([0xff, 0xd8, 0xff, 0xe0]),+ 'image/gif': Buffer.from('GIF89a', 'ascii'),+ 'image/webp': Buffer.from('RIFF\x04\x00\x00\x00WEBP', 'binary'),+ 'image/avif': Buffer.concat([+ Buffer.from([0x00, 0x00, 0x00, 0x18]),+ Buffer.from('ftypavif', 'ascii'),+ Buffer.alloc(4),+ Buffer.from('avifmif1', 'ascii'),+ ]),+} satisfies Record<(typeof SUPPORTED_IMAGE_MEDIA_TYPES)[number], Buffer>++describe('image transport', () => {+ test.each(SUPPORTED_IMAGE_MEDIA_TYPES)('accepts %s bytes that match the Kafka content-type', (contentType) => {+ expect(imageBytesMatchMediaType(imageHeaders[contentType], contentType)).toBe(true)+ })++ test.each([+ ['gzip', gzipSync],+ ['deflate', deflateSync],+ ['br', brotliCompressSync],+ ['zstd', zstdCompressSync],+ ] as const)('decodes %s response bytes before validating the image', async (contentEncoding, compress) => {+ const png = imageHeaders['image/png']++ await expect(prepareFetchedImage(compress(png), 'image/png', contentEncoding)).resolves.toEqual(png)+ })++ it('decodes stacked content codings in reverse application order', async () => {+ const png = imageHeaders['image/png']+ const encoded = brotliCompressSync(gzipSync(png))++ await expect(prepareFetchedImage(encoded, 'image/png', 'gzip, br')).resolves.toEqual(png)+ })++ it('rejects more than four content coding layers', async () => {+ await expect(+ prepareFetchedImage(+ imageHeaders['image/png'],+ 'image/png',+ 'identity, identity, identity, identity, identity'+ )+ ).rejects.toThrow('content-encoding exceeds 4 codings')+ })++ it('stops decompression when the decoded bytes cross the 20 MiB cap', async () => {+ const compressed = gzipSync(Buffer.alloc(MAX_UNCOMPRESSED_IMAGE_BYTES + 1))++ await expect(prepareFetchedImage(compressed, 'image/png', 'gzip')).rejects.toThrow(+ `decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`+ )+ })++ it.each([+ ['an unsupported content coding', imageHeaders['image/png'], 'compress'],+ ['a malformed content coding list', imageHeaders['image/png'], 'gzip,'],+ ['compressed bytes that are malformed', Buffer.from('not gzip'), 'gzip'],+ ])('rejects %s', async (_case, bytes, contentEncoding) => {+ await expect(prepareFetchedImage(bytes, 'image/png', contentEncoding)).rejects.toBeInstanceOf(+ InvalidImageTransportError+ )+ })++ it('rejects bytes that do not match the declared media type', async () => {+ await expect(prepareFetchedImage(imageHeaders['image/jpeg'], 'image/png', undefined)).rejects.toThrow(+ 'image bytes do not match content-type image/png'+ )+ })++ it('rejects BMP images', async () => {+ await expect(prepareFetchedImage(Buffer.from('BM', 'ascii'), 'image/bmp', undefined)).rejects.toThrow(+ 'unsupported content-type: image/bmp'+ )+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.tsnew file mode 100644index 000000000000..e2eadf580ce9--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts@@ -0,0 +1,130 @@+import { Readable, Transform } from 'node:stream'+import { createBrotliDecompress, createGunzip, createInflate, createZstdDecompress } from 'node:zlib'++export const MAX_UNCOMPRESSED_IMAGE_BYTES = 20 * 1024 * 1024+export const CONTENT_TYPE_HEADER = 'content-type'+export const CONTENT_ENCODING_HEADER = 'content-encoding'++const MAX_CONTENT_ENCODING_LAYERS = 4++export const SUPPORTED_IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif'] as const++export type SupportedImageMediaType = (typeof SUPPORTED_IMAGE_MEDIA_TYPES)[number]++export class InvalidImageTransportError extends Error {}++const decoderFactories: Record<string, () => Transform> = {+ gzip: createGunzip,+ deflate: createInflate,+ br: createBrotliDecompress,+ zstd: createZstdDecompress,+}++function parseContentEncodings(contentEncoding: string | undefined): string[] {+ if (contentEncoding === undefined) {+ return []+ }+ const encodings = contentEncoding.split(',').map((encoding) => encoding.trim().toLowerCase())+ if (encodings.length > MAX_CONTENT_ENCODING_LAYERS) {+ throw new InvalidImageTransportError(`content-encoding exceeds ${MAX_CONTENT_ENCODING_LAYERS} codings`)+ }+ if (encodings.some((encoding) => encoding.length === 0)) {+ throw new InvalidImageTransportError('content-encoding contains an empty coding')+ }+ return encodings.filter((encoding) => encoding !== 'identity')+}++async function decodeWithLimit(bytes: Buffer, encoding: string): Promise<Buffer> {+ const decoderFactory = decoderFactories[encoding]+ if (!decoderFactory) {+ throw new InvalidImageTransportError(`unsupported content-encoding: ${encoding}`)+ }++ const input = Readable.from([bytes])+ const decoder = decoderFactory()+ const chunks: Buffer[] = []+ let outputBytes = 0+ input.pipe(decoder)++ try {+ for await (const chunk of decoder) {+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)+ if (outputBytes + buffer.length > MAX_UNCOMPRESSED_IMAGE_BYTES) {+ throw new InvalidImageTransportError(`decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`)+ }+ chunks.push(buffer)+ outputBytes += buffer.length+ }+ } catch (error) {+ if (error instanceof InvalidImageTransportError) {+ throw error+ }+ throw new InvalidImageTransportError(`invalid ${encoding} content: ${String(error)}`)+ } finally {+ input.destroy()+ decoder.destroy()+ }++ return Buffer.concat(chunks, outputBytes)+}++function isAvif(bytes: Buffer): boolean {+ if (bytes.length < 16 || bytes.toString('ascii', 4, 8) !== 'ftyp') {+ return false+ }+ const boxSize = bytes.readUInt32BE(0)+ if (boxSize < 16 || boxSize > bytes.length) {+ return false+ }+ for (let offset = 8; offset + 4 <= boxSize; offset += 4) {+ const brand = bytes.toString('ascii', offset, offset + 4)+ if (brand === 'avif' || brand === 'avis') {+ return true+ }+ }+ return false+}++export function isSupportedImageMediaType(contentType: string): contentType is SupportedImageMediaType {+ return SUPPORTED_IMAGE_MEDIA_TYPES.includes(contentType as SupportedImageMediaType)+}++export function imageBytesMatchMediaType(bytes: Buffer, contentType: SupportedImageMediaType): boolean {+ switch (contentType) {+ case 'image/png':+ return bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))+ case 'image/jpeg':+ return bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff+ case 'image/gif': {+ const signature = bytes.toString('ascii', 0, 6)+ return signature === 'GIF87a' || signature === 'GIF89a'+ }+ case 'image/webp':+ return bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP'+ case 'image/avif':+ return isAvif(bytes)+ }+}++export async function prepareFetchedImage(+ bytes: Buffer,+ contentType: string | undefined,+ contentEncoding: string | undefined+): Promise<Buffer> {+ if (!contentType || !isSupportedImageMediaType(contentType)) {+ throw new InvalidImageTransportError(`unsupported content-type: ${contentType ?? 'missing'}`)+ }+ if (bytes.length > MAX_UNCOMPRESSED_IMAGE_BYTES) {+ throw new InvalidImageTransportError(`decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`)+ }++ let decoded = bytes+ const encodings = parseContentEncodings(contentEncoding)+ for (const encoding of encodings.reverse()) {+ decoded = await decodeWithLimit(decoded, encoding)+ }+ if (!imageBytesMatchMediaType(decoded, contentType)) {+ throw new InvalidImageTransportError(`image bytes do not match content-type ${contentType}`)+ }+ return decoded+}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 c01adc83dd2d..4bbfef90ba26 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@@ -1,4 +1,4 @@-import { Counter, Histogram } from 'prom-client'+import { Counter, Gauge, Histogram } from 'prom-client'import { ScrubWaitReason } from './scrub-client'@@ -91,6 +91,15 @@ export class ImageScrubConsumerMetrics {help: 'Wall time per poll batch. Read against Kafka max.poll.interval.ms (300s): batches approaching it get the pod evicted mid-batch, and the partition is redone by whoever picks it up',buckets: [1, 5, 15, 30, 60, 120, 240, 300, 600],})+ private static activeBatchStartedAtMs: number | undefined+ private static readonly activeBatchElapsed = new Gauge({+ name: 'ml_mirror_image_scrub_consumer_active_batch_elapsed_seconds',+ help: 'Elapsed wall time of the active non-empty poll batch, or zero between batches. This exposes a stuck batch before Kafka max.poll.interval.ms revokes it',+ collect() {+ const startedAtMs = ImageScrubConsumerMetrics.activeBatchStartedAtMs+ this.set(startedAtMs === undefined ? 0 : Math.max(0, performance.now() - startedAtMs) / 1000)+ },+ })/*** Images parked on the dead-letter topic because the sidecar could not process them.*@@ -162,7 +171,13 @@ export class ImageScrubConsumerMetrics {}this.batchDuration.observe(durationSeconds)}- public static incDeadLettered(reason: string): void {+ public static startBatch(nowMs = performance.now()): void {+ this.activeBatchStartedAtMs = nowMs+ }+ public static finishBatch(): void {+ this.activeBatchStartedAtMs = undefined+ }+ public static incDeadLettered(reason: ScrubWaitReason): void {this.deadLettered.labels(reason).inc()}public static incDeadLetterFailed(): void {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex a73b2511bf51..64f562aefd83 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -49,7 +49,7 @@ export type MlMirrorConfig = {** Enabling changes the mirrored JSONL shape a second time: a remote image keeps its grey* placeholder and a `data-anon-image-ref-<attribute>` sibling carries its- * `imageurl:<pseudoTeam>:<hash>` ref. The prefix differs from the image lane's `image:` on+ * `imageurl:<hash>` ref. The prefix differs from the image lane's `image:` on* purpose, because this hash names the URL rather than the bytes behind it. Nothing fetches* those URLs yet, so every such ref is dangling. What this buys is the measurement of how many* URLs and how many distinct hosts real traffic carries.@@ -62,7 +62,8 @@ export type MlMirrorConfig = {* This flag is separate from the collection flag, because the two steps have different risks.* Collection changes only the mirrored data. A produce puts original, unscrubbed URLs onto a* Kafka topic, so the fetch topic is as sensitive as the raw replay topic. Turn this flag on- * only after the topic exists with the retention that section 2.5 of the plan gives it.+ * only after the topic exists with the required retention and every fetch consumer accepts the+ * current ref format. The disabled default lets consumer support deploy before producers change.** The flag does nothing unless SESSION_RECORDING_ML_URL_COLLECTION_ENABLED is also on, because* the anonymizer collects no URLs until then.@@ -72,61 +73,42 @@ export type MlMirrorConfig = {// US-only, PEM, multiple keys allowed (comma-separated)WEB_BOT_AUTH_PRIVATE_KEYS: string- /**- * While true the fetch lane sends no outbound request. It reads the topic, dedupes, writes the- * ledger and reports the metrics, which is the phase 0 measurement: how many requests the- * fetcher would offer, and how many of those dedup away before one is needed.- *- * Turning it off makes this deployment send requests to customer sites, so it stays on until- * those numbers have been read and the per-site budget has been sized against them.- */+ /** While true, the fetch lane parses input but sends no request and writes no crawl history. */SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN: booleanSESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: stringSESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: number- /** A URL older than this is dropped, so a lane with a backlog sheds work rather than fetching stale work. */- SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS: number- /** Capacity of the per-pod seen-ref cache that sits in front of the crawl history. */- SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS: numberAI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: string/** Bounds one DynamoDB request so an unavailable store cannot hold the poll loop. */AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS: number/** TTL on each DynamoDB crawl-history entry, which sets the recrawl interval. */AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS: number+ /** Requests one registrable domain receives from one pod each second. */+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND: number+ /** Tokens one idle registrable domain can retain. */+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST: number+ /** Also the worker count for one registrable domain. */+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN: number/**- * What one registrable domain receives from one pod.- *- * Every value below is a politeness control, so all of them are environment variables. An- * incident must change the load this lane puts on a customer site in minutes, and a deploy- * takes longer than that.- *- * One request each second is far below the rate a browser puts on the same site. This lane- * works at that rate because one fetch serves every session that refers to the image, and- * because nothing waits on the result.- */- SESSION_RECORDING_ML_IMAGE_FETCH_REQUESTS_PER_SECOND: number- /** Tokens a domain holds while idle, so a site seen once an hour gets a short run rather than one request. */- SESSION_RECORDING_ML_IMAGE_FETCH_BURST: number- /** Also the worker count of one back queue, so the connection limit and the worker count cannot disagree. */- SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN: number- /**- * Requests this pod holds open across every domain at once.+ * Requests this pod holds open across every registrable domain at once.*- * Nothing caps the number of domains, because the topic keys by registrable domain, so a domain- * lands on one partition and one pod, and its rate limit lives there. A pod that owns many- * domains must serve them all, because each has its own allowance and none waits on the others.+ * The topic key sends one registrable domain to one partition and one pod. Its rate limit lives+ * on that pod. The state limits prevent unbounded in-memory maps.** This bounds the pod instead. A body reads into a buffer, so the resident peak is roughly this* times SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES, and the sockets and the DNS lookups* scale with it too. Raise the pod's memory before you raise this.*/SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS: number+ /** Image bodies waiting for Kafka delivery. This must fit inside the producer byte queue. */+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_PENDING_PUBLISHES: number/*** Wall time the fetch pass of one poll batch may take.*- * A batch can hold more URLs for one domain than a polite rate carries in this time. What the- * pass does not reach goes to a delay topic and spends a hop. The value sits well inside Kafka's- * max.poll.interval.ms of 300s, which the crawl history round trips share.+ * A batch can hold more URLs for one registrable domain than a polite rate carries in this+ * time. What the pass does not reach goes to a delay topic without spending a hop. The value+ * sits well inside Kafka's max.poll.interval.ms of 300s, which the crawl history round trips+ * share.*/SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS: number/** Refused before the body when the response declares more, and abandoned mid-body when it declares nothing. */@@ -134,15 +116,15 @@ export type MlMirrorConfig = {/** Covers one URL including its redirects, separate from the connect timeout of the shared request layer. */SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS: numberSESSION_RECORDING_ML_IMAGE_FETCH_MAX_REDIRECTS: number- /** Consecutive failures of one domain before this pod stops sending to it. */- SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_FAILURES: number- SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_COOLDOWN_MS: number- /** The longest a domain stays blocked, whether the breaker or a site's own `Retry-After` blocked it. */- SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_MAX_COOLDOWN_MS: number- /** Held after a 429 or a 503 that named no period. */- SESSION_RECORDING_ML_IMAGE_FETCH_DEFAULT_RETRY_AFTER_MS: number- /** Domains one pod holds rate-limit state for. Past this the least recently used entry goes, and the pod forgets that the domain was blocked. */- SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_DOMAINS: number+ /** Consecutive failures before this pod stops sending to one registrable domain. */+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_FAILURES: number+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_COOLDOWN_MS: number+ /** The longest calculated breaker back-off. A longer valid `Retry-After` remains authoritative. */+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_MAX_COOLDOWN_MS: number+ /** Registrable domains one pod holds request-control state for. */+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_REGISTRABLE_DOMAINS: number+ /** Origins one pod holds configuration and crawl-delay state for. */+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_ORIGINS: number/*** The delay topic one retry pod drains, and the period every record in it waits.@@ -153,13 +135,7 @@ export type MlMirrorConfig = {*/SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_TOPIC: stringSESSION_RECORDING_ML_IMAGE_FETCH_RETRY_DELAY_MS: number- /**- * One record per batch, so the poll interval the server computes is exact.- *- * A batch of many records can hold records written hours apart, and that batch waits once for- * each of them. Sizing the poll interval for that case means multiplying the tier's period by- * the batch size, which soon passes what Kafka accepts at the 1 hour tier.- */+ /** Records released together after one wait based on the latest broker append timestamp. */SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE: number/**@@ -241,27 +217,26 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN: true,SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: 'session-replay-ml-image-fetch',SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: 500,- SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS: 6 * 60 * 60 * 1000,- SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS: 500_000,AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: '',AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS: 5_000,AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS: 30 * 24 * 60 * 60,- SESSION_RECORDING_ML_IMAGE_FETCH_REQUESTS_PER_SECOND: 1,- SESSION_RECORDING_ML_IMAGE_FETCH_BURST: 5,- SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN: 6,+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND: 1,+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST: 5,+ SESSION_RECORDING_ML_IMAGE_FETCH_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_MAX_IMAGE_BYTES: 2 * 1024 * 1024,+ 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,- SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_FAILURES: 5,- SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_COOLDOWN_MS: 60_000,- SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_MAX_COOLDOWN_MS: 2 * 60 * 60 * 1000,- SESSION_RECORDING_ML_IMAGE_FETCH_DEFAULT_RETRY_AFTER_MS: 60_000,- SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_DOMAINS: 20_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_FAILURES: 5,+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_COOLDOWN_MS: 60_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_MAX_COOLDOWN_MS: 60 * 60 * 1000,+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_REGISTRABLE_DOMAINS: 20_000,+ SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_ORIGINS: 20_000,SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_TOPIC: '',SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_DELAY_MS: 60_000,- SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE: 1,+ SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE: 500,SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX: 500_000,SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID: 'session-replay-ml-image-scrub',SESSION_RECORDING_ML_IMAGE_SCRUB_PREFIX: 'scrubbed-images',diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.tsindex dc4022027c7e..4a361729fdb2 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts@@ -43,11 +43,11 @@ export interface MlMirrorImageScrubProducer {export interface MlMirrorUrlFetchProducer {outputs: IngestionOutputs<MlImageFetchOutput | MlImageScrubOutput>producedRefCacheMax: number+ producedRefCacheWindowMs: number}/**- * Which collection lanes the anonymizer runs, and the key they derive their per-team ref prefix- * from.+ * Which collection lanes the anonymizer runs, and the key they derive their ref HMAC keys from.** Separate from the two producer settings, because collecting and producing are separate* decisions. Collection alone measures. A produce puts original, unscrubbed URLs onto Kafka.@@ -56,7 +56,7 @@ export interface MlMirrorUrlFetchProducer {* make that measurement impossible to take on its own.*/export interface MlMirrorCollection {- /** The ML pseudonym HMAC key (also used by the block-metadata sink), for the per-team ref prefix. */+ /** The ML pseudonym HMAC key, also used by the block-metadata sink. */pseudonymSecret: string | BuffercollectImages: booleancollectUrls: boolean@@ -192,7 +192,8 @@ export function createMlMirrorReplayPipeline(? withImagesProduced.pipe(createProduceCollectedUrlsStep(urlFetch.outputs,- urlFetch.producedRefCacheMax+ urlFetch.producedRefCacheMax,+ urlFetch.producedRefCacheWindowMs)): withImagesProduceddiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.tsindex 86f7b021fa92..0fffcac10985 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts@@ -4,7 +4,7 @@ import { PipelineResultType } from '~/ingestion/framework/results'import { CollectedUrl } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'import { MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'-import { createProduceCollectedUrlsStep } from './produce-collected-urls-step'+import { CollectedUrlsMessage, createProduceCollectedUrlsStep } from './produce-collected-urls-step'describe('produceCollectedUrlsStep', () => {const PSEUDO_TEAM = 'a'.repeat(32)@@ -23,11 +23,27 @@ describe('produceCollectedUrlsStep', () => {})function collected(hash: string, host: string, url: string, domain = host): CollectedUrl {- return { ref: `imageurl:${PSEUDO_TEAM}:${hash.padEnd(22, 'x')}`, url, host, domain }+ return { ref: `imageurl:${hash.padEnd(22, 'x')}`, pseudoTeam: PSEUDO_TEAM, url, host, domain }}function decode(batch: { key: string; value: Buffer }[]) {- return batch.map((message) => ({ key: message.key, value: parseJSON(message.value.toString()) }))+ return batch.map((message) => ({+ key: message.key,+ value: parseJSON(message.value.toString()) as CollectedUrlsMessage,+ }))+ }++ function expectedJob(originalRef: string, currentUrl: string) {+ return {+ originalRef,+ currentUrl,+ remainingHops: 10,+ notBeforeMs: 0,+ firstSeenAtMs: CAPTURED_AT,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,+ }}async function run<T extends { collectedUrls?: CollectedUrl[]; message: { timestamp?: number } }>(@@ -63,36 +79,18 @@ describe('produceCollectedUrlsStep', () => {{key: 'cdn.example.com',value: {- v: 1,- pseudoTeam: PSEUDO_TEAM,- capturedAtMs: CAPTURED_AT,- urls: [- {- ref: `imageurl:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`,- url: 'https://cdn.example.com/a.jpg?sig=1',- host: 'cdn.example.com',- },- {- ref: `imageurl:${PSEUDO_TEAM}:h3xxxxxxxxxxxxxxxxxxxx`,- url: 'https://cdn.example.com/c.jpg',- host: 'cdn.example.com',- },+ v: 2,+ jobs: [+ expectedJob(`imageurl:h1xxxxxxxxxxxxxxxxxxxx`, 'https://cdn.example.com/a.jpg?sig=1'),+ expectedJob(`imageurl:h3xxxxxxxxxxxxxxxxxxxx`, 'https://cdn.example.com/c.jpg'),],},},{key: 'img.other.com',value: {- v: 1,- pseudoTeam: PSEUDO_TEAM,- capturedAtMs: CAPTURED_AT,- urls: [- {- ref: `imageurl:${PSEUDO_TEAM}:h2xxxxxxxxxxxxxxxxxxxx`,- url: 'https://img.other.com/b.png',- host: 'img.other.com',- },- ],+ v: 2,+ jobs: [expectedJob(`imageurl:h2xxxxxxxxxxxxxxxxxxxx`, 'https://img.other.com/b.png')],},},])@@ -108,15 +106,32 @@ describe('produceCollectedUrlsStep', () => {expect(queueMessages).not.toHaveBeenCalled()})- it('dedups refs it already produced across messages', async () => {+ it('dedups an identical transport URL but produces a new URL for the same ref', async () => {const step = createProduceCollectedUrlsStep(outputs)- const first = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg')- const second = collected('h2', 'cdn.example.com', 'https://cdn.example.com/b.jpg')+ const first = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg?cb=old')+ const replacement = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg?cb=new')await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [first] })- await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [first, second] })+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [first, replacement] })expect(- queued.map((batch) => decode(batch).map((m) => m.value.urls.map((u: { ref: string }) => u.ref)))- ).toEqual([[[first.ref]], [[second.ref]]])+ queued.map((batch) => decode(batch).map((message) => message.value.jobs.map((job) => job.currentUrl)))+ ).toEqual([[[first.url]], [[replacement.url]]])+ })++ it('produces an identical transport URL again after the dedup window', async () => {+ jest.useFakeTimers().setSystemTime(10_000)+ try {+ const step = createProduceCollectedUrlsStep(outputs, 100, 1_000)+ const entry = collected('h1', 'cdn.example.com', 'https://cdn.example.com/a.jpg')++ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })+ jest.setSystemTime(11_000)+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: [entry] })++ expect(queueMessages).toHaveBeenCalledTimes(2)+ } finally {+ jest.useRealTimers()+ }})it('swallows a failed produce and un-marks its refs so a later sighting produces again', async () => {@@ -134,18 +149,18 @@ describe('produceCollectedUrlsStep', () => {expect(queueMessages).toHaveBeenCalledTimes(2)})- it('refuses to produce a ref whose hash names bytes rather than a URL', async () => {- // A bytes ref comes from an image the page inlined, and its hash cannot be reproduced from- // any URL. Producing one would put a record on the fetch topic that the fetcher indexes- // under a hash nothing will ever match. Both prefixes parse, so only the source check- // separates them.+ test.each([+ ['inline image', `image:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`],+ ['legacy team-scoped URL', `imageurl:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`],+ ])('refuses to produce a %s ref', async (_name, ref) => {const step = createProduceCollectedUrlsStep(outputs, 100)await run(step, {message: { timestamp: CAPTURED_AT },collectedUrls: [{- ref: `image:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`,+ ref,+ pseudoTeam: PSEUDO_TEAM,url: 'https://img.example.com/a.png',host: 'img.example.com',domain: 'example.com',@@ -166,6 +181,7 @@ describe('produceCollectedUrlsStep', () => {collected('h1', 'img.example.com', 'https://img.example.com/a.png'),{ref: `image:${PSEUDO_TEAM}:h2xxxxxxxxxxxxxxxxxxxx`,+ pseudoTeam: PSEUDO_TEAM,url: 'https://img.example.com/inlined.png',host: 'img.example.com',domain: 'example.com',@@ -176,9 +192,9 @@ describe('produceCollectedUrlsStep', () => {const sent = decode(queued[0])expect(sent).toHaveLength(1)- expect(sent[0].value.urls.map((u: { ref: string }) => u.ref)).toEqual([- `imageurl:${PSEUDO_TEAM}:h1xxxxxxxxxxxxxxxxxxxx`,- `imageurl:${PSEUDO_TEAM}:h3xxxxxxxxxxxxxxxxxxxx`,+ expect(sent[0].value.jobs.map((job) => job.originalRef)).toEqual([+ `imageurl:h1xxxxxxxxxxxxxxxxxxxx`,+ `imageurl:h3xxxxxxxxxxxxxxxxxxxx`,])})@@ -199,7 +215,7 @@ describe('produceCollectedUrlsStep', () => {// The fetcher refuses a record above its own count cap, whole. Byte packing alone would let// the collector's per-message cap in another crate decide how many entries a record holds.const step = createProduceCollectedUrlsStep(outputs, 100_000)- const many = Array.from({ length: 600 }, (_v, i) =>+ const many = Array.from({ length: 1200 }, (_v, i) =>collected(`h${i}`.padEnd(22, 'x'), 'img.example.com', `https://img.example.com/${i}.png`))@@ -208,7 +224,7 @@ describe('produceCollectedUrlsStep', () => {const sent = decode(queued[0])expect(sent.length).toBeGreaterThan(1)for (const record of sent) {- expect(record.value.urls.length).toBeLessThanOrEqual(512)+ expect(record.value.jobs.length).toBeLessThanOrEqual(1000)}})@@ -238,7 +254,8 @@ describe('produceCollectedUrlsStep', () => {collectedUrls: [collected('h1', 'img.example.com', 'https://img.example.com/a.png'),{- ref: `imageurl:${otherTeam}:h2xxxxxxxxxxxxxxxxxxxx`,+ ref: `imageurl:h2xxxxxxxxxxxxxxxxxxxx`,+ pseudoTeam: otherTeam,url: 'https://img.example.com/b.png',host: 'img.example.com',domain: 'img.example.com',@@ -247,8 +264,8 @@ describe('produceCollectedUrlsStep', () => {})const sent = decode(queued[0])- expect(sent[0].value.pseudoTeam).toBe(PSEUDO_TEAM)- expect(sent[0].value.urls).toHaveLength(1)+ expect(sent[0].value.jobs).toHaveLength(1)+ expect(sent[0].value.jobs[0].currentUrl).toBe('https://img.example.com/a.png')})it('puts a sharded CDN on one key, and keeps each host on its record', async () => {@@ -269,9 +286,9 @@ describe('produceCollectedUrlsStep', () => {const sent = decode(queued[0])expect(sent.map((m) => m.key).sort()).toEqual(['example.com', 'other.org'])const shared = sent.find((m) => m.key === 'example.com')!- expect(shared.value.urls.map((u: { host: string }) => u.host)).toEqual([- 'img1.cdn.example.com',- 'img8.cdn.example.com',+ expect(shared.value.jobs.map((job) => job.currentUrl)).toEqual([+ 'https://img1.cdn.example.com/a.png',+ 'https://img8.cdn.example.com/b.png',])})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.tsindex faaf8d7a8fbd..ecacdda2a194 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts@@ -1,3 +1,5 @@+import { createHash } from 'node:crypto'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { logger } from '~/common/utils/logger'import { ok } from '~/ingestion/framework/results'@@ -10,30 +12,32 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-de/*** The same trade as the image lane's cache, at a much lower cost per entry: a record here holds a- * ref of approximately 60 bytes and no image bytes. A ref that this cache drops before its next- * arrival produces a second time, which costs topic volume and one more ledger read in the- * fetcher, but never correctness. The fetcher dedupes on the same ref again.+ * digest of the ref and transport URL, with no image bytes or original URL. An entry that this+ * cache drops before its next arrival produces a second time, which costs topic volume and one+ * more ledger read in the fetcher, but never correctness. Time-bucketed keys also make an entry+ * eligible again before crawl history expires, so a mutable URL is recrawled.*/const PRODUCED_REF_CACHE_MAX = 500_000+const DEFAULT_PRODUCED_REF_CACHE_WINDOW_MS = 15 * 24 * 60 * 60 * 1000-/**- * The URL payload one record may carry. The `message.max.bytes` default is 1,000,000 bytes and this- * producer does not override it, so the remainder holds the envelope. The budget counts bytes- * rather than URLs, because a URL can be as long as `MAX_URL_LEN`.- */-const MAX_RECORD_URL_BYTES = 512 * 1024+const MAX_RECORD_BYTES = 512 * 1024/*** The URL count one record may carry. Without it the collector's cap in another crate decides the* count, and an increase there makes records the fetcher refuses whole. Keep it below* `MAX_URLS_PER_RECORD` in `ml-mirror-image-fetch/collected-urls-record.ts`.*/-const MAX_RECORD_URLS = 512+const MAX_RECORD_URLS = 1_000-export interface RecordUrl {- ref: string- url: string- host: string+export interface FrontierJob {+ originalRef: string+ currentUrl: string+ remainingHops: number+ notBeforeMs: number+ firstSeenAtMs: number+ fetchCount: number+ republishCount: number+ lastRepublishReason: null}/** One record on the fetch topic. The Kafka key is the registrable domain, so every URL here@@ -44,17 +48,18 @@ export interface CollectedUrlsMessage {* The wire format version. The fetcher reads this topic from another deployment, so the two* sides roll separately and a reader needs to know what it is holding.*/- v: 1- /** The HMAC pseudonym of the team. The raw team id must not go onto this topic. */- pseudoTeam: string- /**- * When capture recorded the replay message these URLs came from, not when the mirror produced- * them. The fetcher drops a record that is too old, and produce time cannot answer that: a- * mirror replaying a backlog would stamp hours-old URLs as fresh, which is the one case the- * age check exists for.- */- capturedAtMs: number- urls: RecordUrl[]+ v: 2+ jobs: FrontierJob[]+}++function producedUrlCacheKey(entry: CollectedUrl, timeBucket: number): string {+ return createHash('sha256')+ .update(entry.ref)+ .update('\0')+ .update(entry.url)+ .update('\0')+ .update(String(timeBucket))+ .digest('base64url')}/**@@ -74,7 +79,8 @@ export interface CollectedUrlsMessage {* that batch. A buffer that spans messages would break that guarantee, because the pipeline could* commit the offset of a message while the URLs of that message were still in the buffer. A crash* would then lose them. The group-by-host step already removes most of the record count, `linger.ms`- * makes the batches on the wire, and the ref cache stops a repeated image before it produces at all.+ * makes the batches on the wire, and the cache stops an identical transport URL before it produces+ * at all. A new transport URL for the same canonical ref still produces.** Delivery is not awaited and never fails the message. The mirrored lines already carry the refs* in namespaced sibling attributes, while media sources keep their placeholders.@@ -86,9 +92,13 @@ export function createProduceCollectedUrlsStep<T extends { collectedUrls?: CollectedUrl[]; message: { timestamp?: number } },>(outputs: IngestionOutputs<MlImageFetchOutput>,- producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX+ producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX,+ producedRefCacheWindowMs: number = DEFAULT_PRODUCED_REF_CACHE_WINDOW_MS): ProcessingStep<T, T> {- const producedRefs = new RefDedupCache('image_fetch_producer', producedRefCacheMax)+ if (!Number.isSafeInteger(producedRefCacheWindowMs) || producedRefCacheWindowMs <= 0) {+ throw new Error(`produced URL cache window must be a positive safe integer, got ${producedRefCacheWindowMs}`)+ }+ const producedTransportUrls = new RefDedupCache('image_fetch_producer', producedRefCacheMax)return function produceCollectedUrlsStep(input) {const collected = input.collectedUrls@@ -96,7 +106,10 @@ export function createProduceCollectedUrlsStep<return Promise.resolve(ok(input))}- const fresh = collected.filter((entry) => !producedRefs.has(entry.ref))+ const timeBucket = Math.floor(Date.now() / producedRefCacheWindowMs)+ const fresh = collected+ .map((entry) => ({ entry, cacheKey: producedUrlCacheKey(entry, timeBucket) }))+ .filter(({ cacheKey }) => !producedTransportUrls.has(cacheKey))SessionRecordingIngesterMetrics.incrementMlUrlsCollected('deduped', collected.length - fresh.length)if (fresh.length === 0) {return Promise.resolve(ok({ ...input, collectedUrls: undefined }))@@ -107,19 +120,24 @@ export function createProduceCollectedUrlsStep<// reaches the fetcher under a hash nothing will ever match. Both kinds parse, so only// `source` separates them, and checking one entry would let every later one through.//- // The pseudonym comes back out of the ref, because the ref is the only place the collector- // puts it. Every entry must agree on it: one replay message belongs to one team, and a- // record stamped with another team's pseudonym is a tenant-attribution error that nothing- // downstream can detect.- const usable: CollectedUrl[] = []+ // Every entry must use the global URL-ref shape and carry the same transport pseudonym. One+ // replay message belongs to one team, and a record stamped with another team's pseudonym is+ // a tenant-attribution error that nothing downstream can detect.+ const usable: typeof fresh = []let pseudoTeam: string | undefined- for (const entry of fresh) {+ for (const candidate of fresh) {+ const { entry } = candidateconst parsed = parseImageRef(entry.ref)- if (!parsed || parsed.source !== 'url' || (pseudoTeam && parsed.pseudoTeam !== pseudoTeam)) {+ if (+ !parsed ||+ parsed.source !== 'url' ||+ parsed.pseudoTeam !== undefined ||+ (pseudoTeam && entry.pseudoTeam !== pseudoTeam)+ ) {continue}- pseudoTeam ??= parsed.pseudoTeam- usable.push(entry)+ pseudoTeam ??= entry.pseudoTeam+ usable.push(candidate)}const unusable = fresh.length - usable.lengthif (unusable > 0) {@@ -132,11 +150,22 @@ export function createProduceCollectedUrlsStep<return Promise.resolve(ok({ ...input, collectedUrls: undefined }))}- const byDomain = new Map<string, RecordUrl[]>()- for (const entry of usable) {- producedRefs.add(entry.ref)+ const messageTimestamp = input.message.timestamp+ const firstSeenAtMs = messageTimestamp !== undefined && messageTimestamp > 0 ? messageTimestamp : Date.now()+ const byDomain = new Map<string, FrontierJob[]>()+ for (const { entry, cacheKey } of usable) {+ producedTransportUrls.add(cacheKey)const group = byDomain.get(entry.domain)- const record: RecordUrl = { ref: entry.ref, url: entry.url, host: entry.host }+ const record: FrontierJob = {+ originalRef: entry.ref,+ currentUrl: entry.url,+ remainingHops: 10,+ notBeforeMs: 0,+ firstSeenAtMs,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,+ }SessionRecordingIngesterMetrics.observeMlUrlBytes(Buffer.byteLength(entry.url))if (group) {group.push(record)@@ -146,19 +175,12 @@ export function createProduceCollectedUrlsStep<}SessionRecordingIngesterMetrics.incrementMlUrlsCollected('queued', usable.length)- // The capture timestamp of the source Kafka record, so the fetcher's age check measures the- // age of the replay data rather than the age of this produce. librdkafka reports an absent- // timestamp as -1, which is not nullish, so a plain ?? would ship a negative age.- const messageTimestamp = input.message.timestamp- const capturedAtMs = messageTimestamp !== undefined && messageTimestamp > 0 ? messageTimestamp : Date.now()- const messages = [...byDomain].flatMap(([domain, urls]) =>- packByBytes(urls, MAX_RECORD_URL_BYTES).map((slice) => {+ const messages = [...byDomain].flatMap(([domain, jobs]) =>+ packByBytes(jobs, MAX_RECORD_BYTES).map((slice) => {const value = Buffer.from(JSON.stringify({- v: 1,- pseudoTeam,- capturedAtMs,- urls: slice,+ v: 2,+ jobs: slice,} satisfies CollectedUrlsMessage))SessionRecordingIngesterMetrics.observeMlUrlRecord(slice.length, value.length)@@ -166,29 +188,29 @@ export function createProduceCollectedUrlsStep<}))- // The failure handler captures only the refs, so that a produce which is not yet delivered- // does not hold the URL strings alive longer than the messages themselves.- const refs = usable.map((entry) => entry.ref)+ // The failure handler captures only the cache keys, so that a produce which is not yet+ // delivered does not hold the URL strings alive longer than the messages themselves.+ const producedCacheKeys = usable.map(({ cacheKey }) => cacheKey)const produce = outputs.queueMessages(ML_IMAGE_FETCH_OUTPUT, messages).then(() => {// queueMessages resolves on the delivery acks, so `produced` counts what landed.- SessionRecordingIngesterMetrics.incrementMlUrlsCollected('produced', refs.length)+ SessionRecordingIngesterMetrics.incrementMlUrlsCollected('produced', producedCacheKeys.length)}).catch((error) => {// A dangling ref renders as a placeholder, so a failed produce is logged and never- // thrown back into the pipeline. Un-mark the refs: the same image in a later+ // thrown back into the pipeline. Un-mark the cache entries: the same image in a later// snapshot then produces again, one attempt for each recurrence and no retry loop.// A duplicate costs the fetcher one ledger read, because the ledger is keyed by ref.- for (const ref of refs) {- producedRefs.delete(ref)+ for (const cacheKey of producedCacheKeys) {+ producedTransportUrls.delete(cacheKey)}logger.warn('🌐', 'ml_image_fetch_produce_failed', {- count: refs.length,+ count: producedCacheKeys.length,domains: byDomain.size,error: String(error),})- SessionRecordingIngesterMetrics.incrementMlUrlsCollected('produce_failed', refs.length)+ SessionRecordingIngesterMetrics.incrementMlUrlsCollected('produce_failed', producedCacheKeys.length)})return Promise.resolve(ok({ ...input, collectedUrls: undefined }, [produce]))}@@ -199,16 +221,16 @@ export function createProduceCollectedUrlsStep<* an image that every earlier check accepted. `MAX_URL_LEN` keeps that record under the broker* limit.*/-function packByBytes(entries: RecordUrl[], maxBytes: number): RecordUrl[][] {- const out: RecordUrl[][] = []- let current: RecordUrl[] = []- let bytes = 0+function packByBytes(entries: FrontierJob[], maxBytes: number): FrontierJob[][] {+ const out: FrontierJob[][] = []+ let current: FrontierJob[] = []+ let bytes = Buffer.byteLength('{"v":2,"jobs":[]}')for (const entry of entries) {- const size = entryBytes(entry)+ const size = Buffer.byteLength(JSON.stringify(entry)) + (current.length > 0 ? 1 : 0)if (current.length > 0 && (bytes + size > maxBytes || current.length >= MAX_RECORD_URLS)) {out.push(current)current = []- bytes = 0+ bytes = Buffer.byteLength('{"v":2,"jobs":[]}')}current.push(entry)bytes += size@@ -218,19 +240,3 @@ function packByBytes(entries: RecordUrl[], maxBytes: number): RecordUrl[][] {}return out}--/**- * `JSON.stringify` widens a quote or a backslash, so this count is a lower bound. Canonicalization- * percent-encodes both upstream, and the budget is half the broker limit, so the estimate has room.- * The `ml_url_record_bytes` metric shows that margin if it shrinks.- */-const ENTRY_OVERHEAD_BYTES = '{"ref":"","url":"","host":""},'.length--function entryBytes(entry: RecordUrl): number {- return (- Buffer.byteLength(entry.ref) +- Buffer.byteLength(entry.url) +- Buffer.byteLength(entry.host) +- ENTRY_OVERHEAD_BYTES- )-}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.tsindex 24f6f8a26204..e5deb69a0cdc 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts@@ -15,12 +15,8 @@ export function pseudonymize(secret: string | Buffer, namespace: string, value:export const PSEUDONYM_TEAM = 'team'/** Namespace for the per-team image content-HMAC key (see ml-mirror-image-scrub/content-ref.ts). */export const PSEUDONYM_IMAGE_CONTENT_KEY = 'image-content-key'-/**- * Namespace for the per-team URL-HMAC key, which hashes a remote image's URL rather than its bytes.- *- * Separate from the content key on purpose. Both produce a ref of the same shape, and each hashes- * a different thing. A separate key keeps the two kinds of ref independent for one team.- */+/** Namespace for the global URL-HMAC key, which hashes a remote image's URL rather than its bytes. */export const PSEUDONYM_IMAGE_URL_KEY = 'image-url-key'+export const PSEUDONYM_IMAGE_URL_GLOBAL_VALUE = 'global-v1'export const PSEUDONYM_SESSION = 'session'export const PSEUDONYM_DISTINCT_ID = 'distinct_id'diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.tsindex cbebf953965d..41afd57d1039 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts@@ -9,7 +9,13 @@ import {imageRef,isImageRef,parseImageRef,+ urlRef,} from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'+import {+ PSEUDONYM_IMAGE_URL_GLOBAL_VALUE,+ PSEUDONYM_IMAGE_URL_KEY,+ pseudonymize,+} from '~/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize'// Shared fixtures pin the addon's behavior through the FFI; the pure-Rust side of the same// fixtures is covered by rust/replay-anonymizer/tests/parity.rs.@@ -218,7 +224,7 @@ describeAddon('native rust addon matches the shared fixtures', () => {})})-describe('image content hash matches the shared fixtures', () => {+describe('image refs match the shared fixtures', () => {// Pins the keyed hashImageBytes to the Rust collector's HMAC (tests/parity.rs runs the same// fixture): the consumer trusts the producer, so this is the only cross-implementation check.interface HashCase {@@ -230,6 +236,24 @@ describe('image content hash matches the shared fixtures', () => {test.each(load<HashCase>('image-hash.json').map((c) => [c.name, c] as const))('hash: %s', (_name, c) => {expect(hashImageBytes(c.keyAscii, Buffer.from(c.bytesBase64, 'base64'))).toBe(c.hash)})++ interface UrlRefCase {+ name: string+ pseudonymSecret: string+ globalUrlKey: string+ hash: string+ ref: string+ }+ test.each(load<UrlRefCase>('image-url-ref.json').map((c) => [c.name, c] as const))(+ 'global URL ref: %s',+ (_name, c) => {+ expect(pseudonymize(c.pseudonymSecret, PSEUDONYM_IMAGE_URL_KEY, PSEUDONYM_IMAGE_URL_GLOBAL_VALUE)).toBe(+ c.globalUrlKey+ )+ expect(urlRef(c.hash)).toBe(c.ref)+ expect(parseImageRef(c.ref)).toEqual({ hash: c.hash, source: 'url' })+ }+ )})describeAddon('native image collection', () => {@@ -306,16 +330,14 @@ describeAddon('native image collection', () => {expect(result.lines!.toString()).not.toContain('image:')})- it('rejects a per-team key with no pseudonym to attribute it to', async () => {- // Each lane's ref embeds the pseudonym, so a key without one would mint refs that nothing- // can attribute to a team. That fails loudly rather than collecting under a blank prefix.+ it('requires a pseudonym only for the inline image key', async () => {rustAddon!.initAnonymizer({ text: [], url: [] })await expect(rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, undefined, CONTENT_KEY)- ).rejects.toThrow('require pseudoTeam')+ ).rejects.toThrow('contentKey requires pseudoTeam')await expect(rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, undefined, undefined, CONTENT_KEY)- ).rejects.toThrow('require pseudoTeam')+ ).resolves.toMatchObject({ failed: false })})it('runs either collection lane without the other', async () => {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.tsindex c1ef8e9a0ccc..ca6f96bde3a1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts@@ -7,6 +7,7 @@ import { PipelineResultType } from '~/ingestion/framework/results'import { imageRef } from './ml-mirror-image-scrub/content-ref'import {PSEUDONYM_IMAGE_CONTENT_KEY,+ PSEUDONYM_IMAGE_URL_GLOBAL_VALUE,PSEUDONYM_IMAGE_URL_KEY,PSEUDONYM_TEAM,pseudonymize,@@ -295,7 +296,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {describe('createParseAndAnonymizeMessageStep with url collection', () => {const secret = 'test-pseudonym-secret'const pseudoTeam = pseudonymize(secret, PSEUDONYM_TEAM, '1')- const urlKey = pseudonymize(secret, PSEUDONYM_IMAGE_URL_KEY, '1')+ const urlKey = pseudonymize(secret, PSEUDONYM_IMAGE_URL_KEY, PSEUDONYM_IMAGE_URL_GLOBAL_VALUE)const now = Date.now()const team = { teamId: 1, consoleLogIngestionEnabled: true, aiTrainingOptedIn: true }const headers: SessionReplayHeaders = {@@ -331,7 +332,7 @@ describe('createParseAndAnonymizeMessageStep with url collection', () => {beforeEach(() => mockAnonymizeKafkaPayload.mockReset())- it('runs without the image lane, and forwards only the url key', async () => {+ it('uses one global URL key and ref for every team', async () => {// The URL lane measures before any topic exists. Requiring the image lane to be on first// would make that measurement impossible to take on its own.mockAnonymizeKafkaPayload.mockResolvedValue({@@ -347,15 +348,26 @@ describe('createParseAndAnonymizeMessageStep with url collection', () => {})const result: any = await step({ message: kafkaMessage(), headers, team } as any)+ const otherTeam = { ...team, teamId: 2 }+ const otherResult: any = await step({ message: kafkaMessage(), headers, team: otherTeam } as any)expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(expect.anything(), null, pseudoTeam, undefined, urlKey)expect(result.value.collectedUrls).toEqual([{- ref: `imageurl:${pseudoTeam}:${'h'.repeat(22)}`,+ ref: `imageurl:${'h'.repeat(22)}`,+ pseudoTeam,url: 'https://cdn.example.com/a.png',host: 'cdn.example.com',},])+ expect(mockAnonymizeKafkaPayload).toHaveBeenLastCalledWith(+ expect.anything(),+ null,+ pseudonymize(secret, PSEUDONYM_TEAM, '2'),+ undefined,+ urlKey+ )+ expect(otherResult.value.collectedUrls[0].ref).toBe(result.value.collectedUrls[0].ref)expect(result.value.collectedImages).toBeUndefined()})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.tsindex 08f1ac6b52fc..2d6af0bdc81b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts@@ -15,6 +15,7 @@ import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'import { hashImageBytes, imageRef, isImageRef, urlRef } from './ml-mirror-image-scrub/content-ref'import {PSEUDONYM_IMAGE_CONTENT_KEY,+ PSEUDONYM_IMAGE_URL_GLOBAL_VALUE,PSEUDONYM_IMAGE_URL_KEY,PSEUDONYM_TEAM,pseudonymize,@@ -57,8 +58,10 @@ export interface CollectedImage {* label, or any destination outside the fetch topic.*/export interface CollectedUrl {- /** `imageurl:<pseudoTeam>:<hash>` stored in the mirrored line's namespaced ref attribute. */+ /** `imageurl:<hash>` stored in the mirrored line's namespaced ref attribute. */ref: string+ /** The team pseudonym remains transport metadata until the fetch topic moves to its global schema. */+ pseudoTeam: stringurl: string/** The host the request goes to. robots.txt and the connection limit are scoped to this. */host: string@@ -99,13 +102,16 @@ export interface ImageCollectionConfig {export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInput & { team: TeamForReplay }>(imageCollection?: ImageCollectionConfig): ProcessingStep<T, T & ParseAndAnonymizeStepOutput> {- // Both are per-team HMACs of the same secret (domain-separated) — cache them rather than- // re-deriving on every message. The content key keys the image hash so the unencrypted bucket- // carries no unkeyed content digest; it never crosses the FFI as the raw secret.+ const globalUrlKey =+ imageCollection?.collectUrls === true+ ? pseudonymize(imageCollection.pseudonymSecret, PSEUDONYM_IMAGE_URL_KEY, PSEUDONYM_IMAGE_URL_GLOBAL_VALUE)+ : undefined++ // Cache the team values rather than re-deriving them for every message. The content key keys+ // the inline image hash. The URL key is global and does not use this cache.interface TeamImageKeys {pseudoTeam: stringcontentKey?: string- urlKey?: string}const teamKeysCache = new Map<number, TeamImageKeys>()const teamKeysFor = (teamId: number): TeamImageKeys | undefined => {@@ -131,9 +137,6 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInpkeys = {pseudoTeam,contentKey: imageCollection.collectImages ? contentKey : undefined,- urlKey: imageCollection.collectUrls- ? pseudonymize(imageCollection.pseudonymSecret, PSEUDONYM_IMAGE_URL_KEY, String(teamId))- : undefined,}teamKeysCache.set(teamId, keys)}@@ -164,7 +167,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInpcontentEncoding,teamKeys?.pseudoTeam,teamKeys?.contentKey,- teamKeys?.urlKey+ globalUrlKey)} catch (error) {// A rejected promise (native panic, addon load failure) must fail closed.@@ -273,7 +276,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInpconst collectedImages = teamKeys?.contentKey? unpackCollectedImages(teamKeys.pseudoTeam, meta, result.images): undefined- const collectedUrls = teamKeys?.urlKey ? unpackCollectedUrls(teamKeys.pseudoTeam, meta) : undefined+ const collectedUrls = globalUrlKey && teamKeys ? unpackCollectedUrls(teamKeys.pseudoTeam, meta) : undefinedreturn ok({ ...input, parsedMessage, collectedImages, collectedUrls })}}@@ -318,7 +321,8 @@ function unpackCollectedUrls(pseudoTeam: string, meta: AnonymizeMeta): Collectedconst domains = new Set<string>()for (const entry of meta.urls ?? []) {urls.push({- ref: urlRef(pseudoTeam, entry.hash),+ ref: urlRef(entry.hash),+ pseudoTeam,url: entry.url,host: entry.host,domain: entry.domain,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.tsindex ab033dc31d44..32f2e64237d1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts@@ -104,12 +104,11 @@ export function getDefaultKafkaMlImageScrubProducerEnvConfig(): KafkaMlImageScru// Image bytes are already-compressed formats; recompressing burns CPU for nothing.KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_COMPRESSION_CODEC: 'none',KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_LINGER_MS: '',- // Small queue by design: bounds the lane's RSS ceiling (~128 MB of ~900 KB records — four- // worst-case 32 MB source messages) and makes a scrub-topic backlog fail fast in this- // producer instead of accumulating.+ // The byte limit bounds the queue near 128 MiB, so a scrub-topic backlog fails fast instead+ // of accumulating in the mirror process.KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: '10000',KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: '131072',- KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_MAX_BYTES: '',+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER_MESSAGE_MAX_BYTES: `${20 * 1024 * 1024 + 64 * 1024}`,// Short local delivery timeout (librdkafka defaults to 300s): the lane is best-effort and// its ack promises join the mirror's pre-commit side-effect drain, so a scrub-topic// slowdown must fail deliveries fast (dangling ref = placeholder) rather than stall the@@ -121,12 +120,9 @@ export function getDefaultKafkaMlImageScrubProducerEnvConfig(): KafkaMlImageScru/*** ML_IMAGE_FETCH producer — the fetch lane's own client instance on the replay cluster.*- * It does not share the ML_IMAGE_SCRUB producer, whose settings are tuned for the opposite payload.- * That producer sets `compression.codec: none`, which is right for image bytes that are already- * compressed and wrong for a record of JSON URLs, which compress well. Its queue is also sized in- * messages for a lane whose records are ~900 KB each, so this lane's much smaller records would- * share a byte budget shaped for something else, and a scrub-topic backlog would fail URL produces- * that have nothing to do with it.+ * It carries frontier JSON and fetched response bodies. A separate queue prevents a scrub-topic+ * backlog from blocking the mirror's other outputs. Deployments that publish response bodies set+ * compression to none because the accepted image formats and HTTP content codings are compressed.** Broker and security config are shared with the SESSIONREPLAY producer, as on the scrub lane.*/@@ -142,6 +138,7 @@ export const INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_CONFIG_MAP = {'queue.buffering.max.messages':'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES','queue.buffering.max.kbytes': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES',+ 'message.max.bytes': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_MAX_BYTES','message.timeout.ms': 'KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_TIMEOUT_MS',} as const satisfies Partial<Record<AllowedConfigKey, string>>@@ -150,18 +147,19 @@ export type KafkaMlImageFetchProducerEnvConfig = {KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_LINGER_MS: stringKAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: stringKAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: string+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_MAX_BYTES: stringKAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_TIMEOUT_MS: string}export function getDefaultKafkaMlImageFetchProducerEnvConfig(): KafkaMlImageFetchProducerEnvConfig {return {- // JSON URLs compress well, unlike the image bytes on the scrub lane.+ // Mirror and retry deployments carry JSON. The fetch deployment overrides this to none.KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_COMPRESSION_CODEC: 'snappy',KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_LINGER_MS: '',- // A record is packed to a byte budget, so bytes rather than count are what bind here:- // this holds roughly 60 full records in flight against 50,000 small ones.+ // This holds one maximum image response or roughly 60 maximum frontier records.KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: '50000',KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: '32768',+ KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_MAX_BYTES: `${20 * 1024 * 1024 + 64 * 1024}`,// The same short local timeout as the scrub lane, and for the same reason: these ack// promises join the mirror's pre-commit side-effect drain, so a slow topic must fail fast// rather than hold the mirror's offset commits toward max.poll.interval.ms.diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.tsindex 98d27e995c66..3b37841910f8 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts@@ -1,3 +1,5 @@+import { LibrdKafkaError } from 'node-rdkafka'+import { initializePrometheusLabels } from '~/common/api/router'import {KAFKA_SESSION_REPLAY_IMAGE_FETCH,@@ -5,7 +7,7 @@ import {KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M,KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,} from '~/common/config/kafka-topics'-import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'+import { KafkaConsumer, KafkaConsumerConfig, findOffsetsToCommit } from '~/common/kafka/consumer/consumer-v1'import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { logger } from '~/common/utils/logger'import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'@@ -27,17 +29,8 @@ import {*/const POLL_INTERVAL_MARGIN_MS = 60_000const MAX_POLL_INTERVAL_MS = 86_400_000+const REVOKED_PARTITION_CODES = new Set([-172, -190, -142, -144])-/**- * One delay tier of the image fetch lane.- *- * The same server runs every tier. The topic and the period come from the environment, so three- * deployments of one image cover 1 minute, 10 minutes, and one hour. See the lane's README.- *- * One setting belongs to the deployment rather than to this file: one pod, and no more. A lag- * trigger assumes more consumers drain a topic faster, which is false here, because these records- * are waiting on purpose.- *//** The topics the publisher writes to. A pod drains one of these and nothing else. */const DELAY_TOPICS = [KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M,@@ -72,6 +65,9 @@ export class IngestionSessionReplayMlImageFetchRetryServer implements NodeServerconst topic = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_TOPICconst delayMs = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_DELAY_MSconst batchSize = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE+ const producerDeliveryTimeoutMs = Number(+ this.config.KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_MESSAGE_TIMEOUT_MS+ )// A typo here reads as an empty topic name, and librdkafka would subscribe to it and sit// idle while the tier filled. Naming the three the publisher writes to also stops a pod// draining the frontier itself, which has no period and would publish every record straight@@ -81,14 +77,11 @@ export class IngestionSessionReplayMlImageFetchRetryServer implements NodeServer`SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_TOPIC must name one of ${DELAY_TOPICS.join(', ')}, got "${topic}"`)}- // The whole batch is held one record at a time, so the poll interval below has to cover- // every record in it. A tier can hold records written hours apart, and each of those waits- // its own period. The deployment sets this to 1 and there is no reason to raise it: the work- // is one publish, and a record whose wait is spent waits for nothing.- if (batchSize !== 1) {- throw new Error(- `SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE must be 1, because one batch is held record by record, got ${batchSize}`- )+ if (!Number.isInteger(batchSize) || batchSize < 1) {+ throw new Error(`SESSION_RECORDING_ML_IMAGE_FETCH_RETRY_BATCH_SIZE must be positive, got ${batchSize}`)+ }+ if (!Number.isFinite(producerDeliveryTimeoutMs) || producerDeliveryTimeoutMs <= 0) {+ throw new Error(`the image fetch retry producer needs a positive delivery timeout`)}this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)@@ -98,8 +91,7 @@ export class IngestionSessionReplayMlImageFetchRetryServer implements NodeServertopic,groupId: `${this.config.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID}-retry-${delayMs}`,autoCommit: true,- // Stored per record by the consumer rather than for the whole batch, so a record it- // abandoned mid-wait is read again instead of being committed and lost. Requirement 21.+ // Stored after every publish in the batch is acknowledged.autoOffsetStore: false,fetchBatchSize: batchSize,}@@ -107,28 +99,30 @@ export class IngestionSessionReplayMlImageFetchRetryServer implements NodeServer// topic inside one batch, and the shared default of 300s would evict the 10m and 1h tiers// mid-sleep, then replay the partition into a consumer that sleeps just as long.//- // One record per batch keeps this bound exact. A sparse topic can hold records written hours- // apart, and such a batch waits once per record. Throughput does not matter here, because- // the work is one publish and a ready record waits for nothing.- const pollIntervalMs = delayMs + POLL_INTERVAL_MARGIN_MS+ // The batch waits once for its latest broker append timestamp.+ const pollIntervalMs = delayMs + batchSize * producerDeliveryTimeoutMs + POLL_INTERVAL_MARGIN_MS+ if (pollIntervalMs > MAX_POLL_INTERVAL_MS) {+ throw new Error(+ `a delay of ${delayMs}ms and batch of ${batchSize} need a poll interval of ${pollIntervalMs}ms, which is past what Kafka allows`+ )+ }const consumer = new KafkaConsumer(consumerConfig, { 'max.poll.interval.ms': pollIntervalMs })// The shutdown handler sets this before it disconnects the consumer, so a stopping pod// abandons the wait it holds rather than making the rolling deploy wait out a tier period.let stopping = falseconst delayConsumer = new RetryDelayConsumer(producer, {isStopping: () => stopping,- storeOffset: (message) => {+ storeOffsets: (messages) => {try {- // The next offset to read, which is what librdkafka stores.- consumer.offsetsStore([- { topic: message.topic, partition: message.partition, offset: message.offset + 1 },- ])+ consumer.offsetsStore(findOffsetsToCommit(messages))} catch (error) {- // Thrown when the partition was revoked while this batch ran. Another pod owns- // the record now, so it is not lost. Letting the throw out would stop this pod.+ const code = (error as LibrdKafkaError | undefined)?.code+ if (!stopping && !REVOKED_PARTITION_CODES.has(code ?? 0)) {+ throw error+ }logger.warn('🌐', 'ml_image_fetch_retry_offset_store_failed', {- topic: message.topic,- partition: message.partition,+ partitions: messages.map((message) => message.partition),+ code,error: error instanceof Error ? error.name : 'unknown',})}@@ -137,11 +131,6 @@ export class IngestionSessionReplayMlImageFetchRetryServer implements NodeServerdelayMs,heartbeat: () => consumer.reportDeliberateWait(),})- if (pollIntervalMs > MAX_POLL_INTERVAL_MS) {- throw new Error(- `a delay of ${delayMs}ms needs a poll interval of ${pollIntervalMs}ms, which is past what Kafka allows`- )- }logger.info('🌐', 'ml_image_fetch_retry_started', { topic, delayMs, pollIntervalMs })await consumer.connect((messages) => delayConsumer.handleBatch(messages))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.tsindex edc184a172fa..c7508141d5b4 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@@ -7,17 +7,23 @@ import {KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M,KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,+ KAFKA_SESSION_REPLAY_IMAGE_SCRUB,} from '~/common/config/kafka-topics'-import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'+import { KafkaConsumerV2, KafkaConsumerV2Config } from '~/common/kafka/consumer/consumer-v2'import { KafkaProducerWrapper } from '~/common/kafka/producer'import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { logger } from '~/common/utils/logger'import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'+import {+ ConfigurationPolicyService,+ HttpConfigurationFetcher,+} from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy'import { DynamoDBCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history'import { FetchRunner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner'import { FrontierPublisher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher'import { HostBudget } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget'import { HttpImageFetcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'+import { OriginRequestScheduler } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/origin-request-scheduler'import { assertUrlPolicyLoaded } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/politeness-key'import { UrlFetchConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer'import { createWebBotAuthRequestSigner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/web-bot-auth'@@ -30,10 +36,6 @@ import {buildMlMirrorServerConfig,} from './ingestion-session-replay-ml-mirror-server'-// The poll loop only heartbeats between batches, so a slow batch is refreshed from inside it. Must-// stay under CONSUMER_MAX_HEARTBEAT_INTERVAL_MS (30s), which binds long before max.poll.interval.ms.-const BATCH_HEARTBEAT_INTERVAL_MS = 10_000-/*** How long the store may spend on one batch, well inside Kafka's max.poll.interval.ms of 300s.*@@ -58,14 +60,19 @@ function getAnonymizer(): typeof import('@posthog/replay-anonymizer') {return anonymizer}-export function buildFrontierPublisher(producer: KafkaProducerWrapper): FrontierPublisher {+export function buildFrontierPublisher(+ producer: KafkaProducerWrapper,+ maxConcurrentImagePublishes: number+): FrontierPublisher {return new FrontierPublisher(producer, {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 },],+ maxConcurrentImagePublishes,})}@@ -75,14 +82,23 @@ export function buildFetchRunner(): FetchRunner {const webBotAuthSigner = createWebBotAuthRequestSigner(config.WEB_BOT_AUTH_PRIVATE_KEYS)const budget = new HostBudget({- requestsPerSecond: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUESTS_PER_SECOND,- burst: config.SESSION_RECORDING_ML_IMAGE_FETCH_BURST,- maxConcurrent: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN,- breakerFailures: config.SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_FAILURES,- breakerCooldownMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_COOLDOWN_MS,- breakerMaxCooldownMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_BREAKER_MAX_COOLDOWN_MS,- maxTrackedDomains: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_DOMAINS,+ requestsPerSecond: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_REQUESTS_PER_SECOND,+ burst: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BURST,+ maxConcurrent: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN,+ breakerFailures: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_FAILURES,+ breakerCooldownMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_COOLDOWN_MS,+ breakerMaxCooldownMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REGISTRABLE_DOMAIN_BREAKER_MAX_COOLDOWN_MS,+ maxTrackedRegistrableDomains: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_REGISTRABLE_DOMAINS,+ maxTrackedOrigins: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_TRACKED_ORIGINS,})+ const scheduler = new OriginRequestScheduler(budget, config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS)+ const configurationPolicy = new ConfigurationPolicyService(+ new HttpConfigurationFetcher(+ webBotAuthSigner,+ scheduler,+ config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS+ )+ )return new FetchRunner(new HttpImageFetcher({@@ -94,20 +110,25 @@ export function buildFetchRunner(webBotAuthSigner),budget,+ scheduler,+ configurationPolicy,{- maxConcurrentPerDomain: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_DOMAIN,+ maxConcurrentPerRegistrableDomain:+ config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_CONCURRENT_PER_REGISTRABLE_DOMAIN,maxInFlightRequests: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IN_FLIGHT_REQUESTS,batchBudgetMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_BUDGET_MS,maxBytes: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES,requestTimeoutMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS,maxRedirects: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_REDIRECTS,- defaultRetryAfterMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_DEFAULT_RETRY_AFTER_MS,+ seenTtlSeconds: config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS,},publisher)}-export function buildImageFetchConsumerConfig(config: IngestionSessionReplayMlMirrorServerConfig): KafkaConsumerConfig {+export function buildImageFetchConsumerConfig(+ config: IngestionSessionReplayMlMirrorServerConfig+): KafkaConsumerV2Config {return {topic: KAFKA_SESSION_REPLAY_IMAGE_FETCH,groupId: config.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID,@@ -153,11 +174,6 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {assertUrlPolicyLoaded()const dryRun = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN- if (!dryRun) {- throw new Error(- 'SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN cannot be cleared yet: this lane obeys no robots.txt and produces no images'- )- }const tableName = this.config.AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLEif (!tableName) {@@ -187,27 +203,27 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {// one that clears the flag.this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)const publisher = buildFrontierPublisher(- this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER)+ this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER),+ this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_PENDING_PUBLISHES)const fetchConsumer = new UrlFetchConsumer(crawlHistory,publisher,{- maxAgeMs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_AGE_MS,- dedupMaxRefs: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DEDUP_MAX_REFS,seenTtlSeconds: this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS,dryRun,},- dryRun ? undefined : buildFetchRunner(this.config, publisher)+ buildFetchRunner(this.config, publisher))logger.info('🌐', 'ml_image_fetch_started', { dryRun })- const consumer = new KafkaConsumer(buildImageFetchConsumerConfig(this.config))- await consumer.connect((messages) => {- const heartbeat = setInterval(() => consumer.heartbeat(), BATCH_HEARTBEAT_INTERVAL_MS)- return fetchConsumer.handleBatch(messages, Date.now()).finally(() => clearInterval(heartbeat))+ const maximumRecordBytes = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024+ const consumer = new KafkaConsumerV2(buildImageFetchConsumerConfig(this.config), {+ 'fetch.message.max.bytes': maximumRecordBytes,+ 'max.partition.fetch.bytes': maximumRecordBytes,})+ await consumer.connect((messages) => fetchConsumer.handleBatch(messages, Date.now()))this.lifecycle.services.push({id: 'session-replay-ml-image-fetch',diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.tsindex f293b2a1470b..11e2e41de56d 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-dlq-replay-server.ts@@ -59,15 +59,22 @@ export class IngestionSessionReplayMlImageScrubDlqReplayServer implements NodeSe// A separate group from the scrub consumer's, and its own topic, so a replay run cannot// disturb the offsets of the lane it is feeding.- const consumer = new KafkaConsumer({- topic: dlqTopic,- groupId: `${this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID}-dlq-replay`,- autoCommit: true,- autoOffsetStore: true,- // Committing as it goes means an interrupted run resumes rather than starting over and- // replaying images the fixed sidecar has already taken.- callEachBatchWhenEmpty: true,- })+ const maximumRecordBytes = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024+ const consumer = new KafkaConsumer(+ {+ topic: dlqTopic,+ groupId: `${this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_GROUP_ID}-dlq-replay`,+ autoCommit: true,+ autoOffsetStore: true,+ // Committing as it goes means an interrupted run resumes rather than starting over and+ // replaying images the fixed sidecar has already taken.+ callEachBatchWhenEmpty: true,+ },+ {+ 'fetch.message.max.bytes': maximumRecordBytes,+ 'max.partition.fetch.bytes': maximumRecordBytes,+ }+ )let idlePolls = 0let replayed = 0diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.tsindex a8903ed528bc..3239dfef2db8 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts@@ -103,7 +103,11 @@ export class IngestionSessionReplayMlImageScrubServer implements NodeServer {deadLetters !== null)- const consumer = new KafkaConsumer(buildImageScrubConsumerConfig(this.config))+ const maximumRecordBytes = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES + 64 * 1024+ const consumer = new KafkaConsumer(buildImageScrubConsumerConfig(this.config), {+ 'fetch.message.max.bytes': maximumRecordBytes,+ 'max.partition.fetch.bytes': maximumRecordBytes,+ })const batcher = new ImageBatcher(store,consumer,diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex b4daa90af8c0..a6b8acd0ef6e 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -188,6 +188,8 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {? {outputs,producedRefCacheMax: this.config.SESSION_RECORDING_ML_URL_PRODUCED_REF_CACHE_MAX,+ producedRefCacheWindowMs:+ (this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS * 1000) / 2,}: undefined),diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6078c42160c3..621942f85cf7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1633,6 +1633,9 @@ importers:'@temporalio/workflow':specifier: 1.15.0version: 1.15.0+ '@trybyte/robotstxt-parser':+ specifier: ^1.2.0+ version: 1.2.0'@types/node':specifier: 'catalog:'version: 22.18.8@@ -1744,6 +1747,9 @@ importers:snappy:specifier: ^7.2.2version: 7.2.2+ structured-headers:+ specifier: ^2.0.3+ version: 2.0.3tail:specifier: ^2.2.6version: 2.2.6@@ -12444,6 +12450,10 @@ packages:svelte:optional: true+ '@trybyte/[email protected]':+ resolution: {integrity: sha512-AywmLqMu0ljMLEPVb4oPxwnyFmm3xxOS6LmwRia5jgqvzrBAoXXR0JWXEXaq/IG3tlFSXuAp+XzAabrijYzyUQ==}+ engines: {node: '>=20.0.0'}+'@tsconfig/[email protected]':resolution: {integrity: sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==}@@ -21585,6 +21595,10 @@ packages:resolution: {integrity: sha512-l63NF9y/cLROq/yqKXSLtcMeeyOfnSQlfMSlzFt/K73oIaD8DGaQWd7Z34X9GPiKqP5rbSh84Hl4bOlLcjiSrQ==}+ resolution: {integrity: sha512-4g5yxhlDMClRwCcfKfLeS7Z8yAVdOWGDADwm80Poh1iReU2KVKLGBlqwpHWJ2qovq0+ZIf1atAEO1eua2o9Rgg==}+ engines: {node: '>=18', npm: '>=6'}+resolution: {integrity: sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==}@@ -32335,6 +32349,8 @@ snapshots:transitivePeerDependencies:- supports-color+ '@trybyte/[email protected]': {}+'@tsconfig/[email protected]': {}'@tsconfig/[email protected]': {}@@ -44317,6 +44333,8 @@ snapshots:+ [email protected]: {}+diff --git a/posthog/test/test_web_bot_auth.py b/posthog/test/test_web_bot_auth.pyindex f1c5931fd2d5..76caa70213f3 100644--- a/posthog/test/test_web_bot_auth.py+++ b/posthog/test/test_web_bot_auth.py@@ -130,7 +130,7 @@ def test_the_route_serves_a_signed_directory():assert response.status_code == 200assert response["Content-Type"] == CONTENT_TYPE- assert response["Cache-Control"] == "public, max-age=240"+ assert response["Cache-Control"] == "public, max-age=60"assert response["Content-Digest"].startswith("sha-256=:")assert response["Signature-Input"].startswith('sig1=("@authority";req "content-digest")')assert response["Signature"].startswith("sig1=:")diff --git a/posthog/web_bot_auth.py b/posthog/web_bot_auth.pyindex 774d8f206650..99c456d2953c 100644--- a/posthog/web_bot_auth.py+++ b/posthog/web_bot_auth.py@@ -17,7 +17,7 @@ from posthog.web_bot_auth_keys import load_web_bot_auth_private_key_configuratioCONTENT_TYPE = "application/http-message-signatures-directory+json"_TAG = "http-message-signatures-directory"_SIGNATURE_LIFETIME_SECONDS = 300-_CACHE_MAX_AGE_SECONDS = 240+_CACHE_MAX_AGE_SECONDS = 60# Covering @authority prevents cross-authority signature replay. Keep its value constant so this# endpoint cannot act as a confused deputy and sign a directory for a requester-controlled domain.diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 571e7bd341ad..6ab456872525 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8976,7 +8976,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.4.5"+version = "0.4.6"dependencies = ["ahash 0.8.12","anyhow",@@ -8988,6 +8988,7 @@ dependencies = ["libdeflater","lz4","memchr",+ "percent-encoding","public-suffix","serde","serde_json",diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 6a11f6f11ca8..5d7a19e53fa2 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -183,8 +183,9 @@ once_cell = "1.21.4"opentelemetry = { version = "0.22.0", features = ["trace"] }opentelemetry-otlp = "0.15.0"opentelemetry_sdk = { version = "0.22.1", features = ["trace", "rt-tokio"] }-public-suffix = "0.1.2"+percent-encoding = "2.3.1"prost = "0.13"+public-suffix = "0.1.2"rand = "0.8.5"rdkafka = { version = "0.37.0", features = ["tracing", "ssl-vendored"] }reqwest = { version = "0.12.3", features = ["json", "stream"] }diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex f0092e6d833a..6a4af3528b70 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -137,12 +137,11 @@ export function initAnonymizer(allow: AllowListsInput): void {* blur, and the original bytes come back in `images`/`meta.images` for the caller to produce to* the scrub topic.*- * `urlKey` enables the URL-collection lane alongside it: a remote image's `src` keeps the media- * placeholder, a namespaced sibling attribute carries its ref, and its original URL comes back in- * `meta.urls` for the caller to hand to the fetch lane.+ * `urlKey` enables the URL-collection lane independently. It is the global URL HMAC key. A remote+ * image's `src` keeps the media placeholder, a namespaced sibling attribute carries its ref, and+ * its original URL comes back in `meta.urls` for the caller to hand to the fetch lane.*- * The two lanes are independent: either, both, or neither. Both need `pseudoTeam`, because the ref- * embeds it, so a `contentKey` or a `urlKey` without one throws.+ * The two lanes are independent: either, both, or neither. Only `contentKey` needs `pseudoTeam`.*/export async function anonymizeKafkaPayload(payload: Buffer,@@ -197,3 +196,14 @@ export function politenessKey(host: string): string {export function isPublicHost(host: string): boolean {return native.isPublicHost(host)}++export interface CanonicalUrl {+ fetch: string+ dedup: string+ host: string+ domain: string+}++export function canonicalizeUrl(url: string): CanonicalUrl | null {+ return native.canonicalizeUrl(url)+}diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rsindex aab284314b57..8e44fcecc336 100644--- a/rust/replay-anonymizer-node/src/lib.rs+++ b/rust/replay-anonymizer-node/src/lib.rs@@ -12,8 +12,8 @@ use std::sync::RwLock;use neon::prelude::*;use neon::types::buffer::TypedArray;use posthog_replay_anonymizer::{- is_public_host, politeness_key, snapshot, AllowLists, FailKind, ImageCollection, ImagePolicy,- PhaseTimings, UrlCollection,+ canonicalize, is_public_host, politeness_key, snapshot, AllowLists, FailKind, ImageCollection,+ ImagePolicy, PhaseTimings, UrlCollection,};use serde::Deserialize;@@ -100,13 +100,9 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {};let pseudo_team = opt_string_arg(&mut cx, 2)?;let content_key = opt_string_arg(&mut cx, 3)?;- // The URL lane is enabled independently of the image lane, but it needs the same pseudonym, so- // a urlKey without a pseudoTeam is a mis-keyed ref rather than a partial opt-in.let url_key = opt_string_arg(&mut cx, 4)?;- // Each lane needs the pseudonym, because its ref embeds it, and its own per-team key. A key- // without the pseudonym would mint refs nothing can attribute, so it fails loudly instead.- if pseudo_team.is_none() && (content_key.is_some() || url_key.is_some()) {- return cx.throw_error("contentKey and urlKey each require pseudoTeam");+ if pseudo_team.is_none() && content_key.is_some() {+ return cx.throw_error("contentKey requires pseudoTeam");}let image_collection = match (pseudo_team.clone(), content_key) {(Some(pseudo_team), Some(content_key)) => Some(ImageCollection {@@ -115,13 +111,7 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {}),_ => None,};- let url_collection = match (pseudo_team, url_key) {- (Some(pseudo_team), Some(url_key)) => Some(UrlCollection {- pseudo_team,- url_key,- }),- _ => None,- };+ let url_collection = url_key.map(|url_key| UrlCollection { url_key });// Created on the JS thread so every offset shares one monotonic origin: the task-start mark// becomes the threadpool queue wait, and no wall clock is involved.let timings = PhaseTimings::new();@@ -252,11 +242,29 @@ fn is_public_host_ffi(mut cx: FunctionContext) -> JsResult<JsBoolean> {Ok(cx.boolean(is_public_host(&host)))}+fn canonicalize_url_ffi(mut cx: FunctionContext) -> JsResult<JsValue> {+ let raw = cx.argument::<JsString>(0)?.value(&mut cx);+ let Some(canonical) = canonicalize(&raw) else {+ return Ok(cx.null().upcast());+ };+ let result = cx.empty_object();+ let fetch = cx.string(canonical.fetch);+ result.set(&mut cx, "fetch", fetch)?;+ let dedup = cx.string(canonical.dedup);+ result.set(&mut cx, "dedup", dedup)?;+ let host = cx.string(canonical.host);+ result.set(&mut cx, "host", host)?;+ let domain = cx.string(canonical.domain);+ result.set(&mut cx, "domain", domain)?;+ Ok(result.upcast())+}+#[neon::main]fn main(mut cx: ModuleContext) -> NeonResult<()> {cx.export_function("initAnonymizer", init_anonymizer)?;cx.export_function("anonymizeKafkaPayload", anonymize_kafka_payload_ffi)?;cx.export_function("politenessKey", politeness_key_ffi)?;cx.export_function("isPublicHost", is_public_host_ffi)?;+ cx.export_function("canonicalizeUrl", canonicalize_url_ffi)?;Ok(())}diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex c7d2d1ba9c05..1e3f78820e07 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-replay-anonymizer"-version = "0.4.5"+version = "0.4.6"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"license = "MIT"@@ -24,12 +24,13 @@ hmac = { workspace = true }libdeflater = { workspace = true }lz4 = { workspace = true }memchr = "2"-image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp"] }+image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp"] }jpeg-decoder = { version = "0.3", default-features = false }serde = { workspace = true }serde_json = { workspace = true }sha2 = { workspace = true }simd-json = { version = "0.15", features = ["serde_impl"] }+percent-encoding = { workspace = true }public-suffix = { workspace = true }url = { workspace = true }zstd = { workspace = true }diff --git a/rust/replay-anonymizer/src/assets.rs b/rust/replay-anonymizer/src/assets.rsindex bcb5337be3eb..75dfb7087c9e 100644--- a/rust/replay-anonymizer/src/assets.rs+++ b/rust/replay-anonymizer/src/assets.rs@@ -54,7 +54,7 @@ pub(crate) fn tag_src_is_image(tag: &str) -> bool {////// A subset of [`MEDIA_SRC_ATTRS`], because the rest do not name one fetchable image.///-/// `src` and `rr_src` need the tag as well as the name.+/// `src` needs the tag as well as the name.////// Without the tag check, the lane collects the `src` of a `<video>`, an `<audio>` or a `<track>`./// The mutation path is worse: rrweb sends attributes with no tag, so any `src` passes, including@@ -64,18 +64,9 @@ pub(crate) fn tag_src_is_image(tag: &str) -> bool {/// a different workload and a different data-classification question. `tag_src_is_image` is false/// on the tagless mutation path, so that path declines rather than guesses.///-/// `poster` needs no tag check. It exists only on a video element and it always names a still-/// image.-///-/// `srcset` holds several candidates with descriptors, so it needs a parse and a choice of which-/// candidate to fetch. `href` and `xlink:href` on a media tag are as often a link or an SVG-/// fragment reference as an image. Both can be added later without changing anything else here.+/// The other media attributes remain out of scope until the fetcher specification includes them.pub(crate) fn is_fetchable_src_attr(name: &str, tag_src_is_image: bool) -> bool {- match name {- "poster" => true,- "src" | "rr_src" => tag_src_is_image,- _ => false,- }+ name == "src" && tag_src_is_image}/// True if an attribute map contains any media-source attribute.diff --git a/rust/replay-anonymizer/src/collect.rs b/rust/replay-anonymizer/src/collect.rsindex 6f12bf6b804b..613fb98327b2 100644--- a/rust/replay-anonymizer/src/collect.rs+++ b/rust/replay-anonymizer/src/collect.rs@@ -43,8 +43,8 @@ pub fn image_ref(pseudo_team: &str, hash: &str) -> String {/// mis-join rather than an error.pub const URL_REF_PREFIX: &str = "imageurl";-pub fn url_ref(pseudo_team: &str, hash: &str) -> String {- format!("{URL_REF_PREFIX}:{pseudo_team}:{hash}")+pub fn url_ref(hash: &str) -> String {+ format!("{URL_REF_PREFIX}:{hash}")}/// True for strings shaped like a content ref. The `image:` prefix cannot collide with a data URI,@@ -57,27 +57,36 @@ pub fn is_image_ref(s: &str) -> bool {s.starts_with("image:")}-/// True only for a fully well-formed ref: `image:` + 32 lowercase hex (the team pseudonym) + `:`-/// + 22 base64url chars (the truncated HMAC).+/// True only for a fully well-formed content ref or URL ref.////// The loose prefix check would let a captured page set a media attribute to `image:<anything>` and/// have it copied verbatim into anonymized output. This bounds what can survive to a fixed-width/// opaque token with no room for readable content.pub fn is_image_ref_strict(s: &str) -> bool {- let Some(rest) = s- .strip_prefix("image:")- .or_else(|| s.strip_prefix("imageurl:"))- else {- return false;- };- let Some((team, hash)) = rest.split_once(':') else {- return false;- };+ if let Some(rest) = s.strip_prefix("image:") {+ let Some((team, hash)) = rest.split_once(':') else {+ return false;+ };+ return is_pseudo_team(team) && is_ref_hash(hash);+ }+ if let Some(rest) = s.strip_prefix("imageurl:") {+ return is_ref_hash(rest)+ || rest+ .split_once(':')+ .is_some_and(|(team, hash)| is_pseudo_team(team) && is_ref_hash(hash));+ }+ false+}++fn is_pseudo_team(team: &str) -> bool {team.len() == 32&& team.bytes().all(|b| b.is_ascii_digit() || b.is_ascii_lowercase() && b <= b'f')- && hash.len() == 22+}++fn is_ref_hash(hash: &str) -> bool {+ hash.len() == 22&& hash.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')@@ -179,7 +188,6 @@ const COLLECTED_MIME_ALLOWLIST: &[&str] = &["image/jpeg","image/gif","image/webp",- "image/bmp","image/avif",];@@ -203,7 +211,10 @@ pub fn collectable_data_uri_bytes(uri: &str) -> Option<Vec<u8>> {if !meta.starts_with("image/") || !meta.contains("base64") {return None;}- if meta.starts_with("image/svg") {+ let mime_type = meta+ .split_once(';')+ .map_or(meta.as_str(), |(mime_type, _)| mime_type);+ if mime_type.starts_with("image/svg") || mime_type.contains("bmp") {return None;}// An encoded payload that can't decode under the per-image cap would be decoded here only to@@ -212,9 +223,13 @@ pub fn collectable_data_uri_bytes(uri: &str) -> Option<Vec<u8>> {if payload.len() > MAX_IMAGE_BYTES.div_ceil(3) * 4 {return None;}- base64::engine::general_purpose::STANDARD+ let bytes = base64::engine::general_purpose::STANDARD.decode(payload.as_bytes())- .ok()+ .ok()?;+ if bytes.starts_with(b"BM") {+ return None;+ }+ Some(bytes)}#[cfg(test)]@@ -293,6 +308,10 @@ mod tests {#[test]fn collectable_rejects_svg_non_base64_and_non_image() {assert!(collectable_data_uri_bytes("data:image/svg+xml;base64,PHN2Zz4=").is_none());+ assert!(collectable_data_uri_bytes("data:image/bmp;base64,Qk0=").is_none());+ assert!(collectable_data_uri_bytes("data:image/x-bmp;base64,Qk0=").is_none());+ assert!(collectable_data_uri_bytes("data:image/x-ms-bmp;base64,Qk0=").is_none());+ assert!(collectable_data_uri_bytes("data:image/png;base64,Qk0=").is_none());assert!(collectable_data_uri_bytes("data:image/svg+xml;utf8,<svg/>").is_none());assert!(collectable_data_uri_bytes("data:text/plain;base64,aGk=").is_none());assert!(collectable_data_uri_bytes("data:image/png;utf8,notbase64").is_none());diff --git a/rust/replay-anonymizer/src/url_collect.rs b/rust/replay-anonymizer/src/url_collect.rsindex 2ce0352f0089..37d2a12d815d 100644--- a/rust/replay-anonymizer/src/url_collect.rs+++ b/rust/replay-anonymizer/src/url_collect.rs@@ -6,25 +6,21 @@//! sibling attribute carries the content ref. The message also carries the original URL back to//! the caller.//!-//! **Two URLs come out of this module. Do not confuse them.**+//! **Two forms of one URL come out of this module. Do not confuse them.**//!//! The *dedup* URL is canonical, and its volatile parameters are removed. It is the only input to//! the hash, so it sets the ref and the dedup key of the fetch lane.//!-//! The *fetch* URL is canonical, and every parameter stays. The fetcher requests this one. A-//! signed URL works only in this form, and it dedups only in the first form.+//! The *fetch* URL keeps the original query bytes, and every permitted parameter stays. The+//! fetcher requests this one. URLs that carry credentials or signatures are refused before either+//! form is created.//!-//! That split is what makes the ref stable. A URL that carries a fresh signature on each page-//! load would otherwise mint a new ref every time. A ref that appears once joins to nothing-//! downstream. Removing the volatile parameters matters more for that than it does for-//! the request count.+//! That split is what makes the ref stable across non-credential cache busters. A ref that appears+//! once joins to nothing downstream. Removing the volatile parameters matters more for that than+//! it does for the request count.//!-//! The hash is a *keyed* HMAC, for the same reason as the image hash. The ML bucket is not-//! encrypted. An unkeyed digest of a URL would let a reader of the bucket learn which sites the-//! users of a team visited.-//!-//! The caller derives the per-team key from the same KMS-held secret as the team pseudonym.-//! Neither the secret nor the key leaves the ingester.+//! The hash is a *keyed* HMAC. The caller derives one global URL key from the KMS-held secret. The+//! secret does not leave the ingester.use std::collections::{HashMap, HashSet};@@ -55,11 +51,7 @@ pub const MAX_URLS_PER_MESSAGE: usize = 512;/// Enables URL collection for one anonymize call.#[derive(Debug, Clone)]pub struct UrlCollection {- /// The non-reversible HMAC team pseudonym (32 hex chars), computed by the caller. Embedded- /// verbatim in every emitted ref, exactly as on the image lane.- pub pseudo_team: String,- /// Per-team key for the URL HMAC. The caller derives it under its own domain separator, so a- /// URL ref and an image ref stay distinct for one team.+ /// Global key for the URL HMAC. The caller derives it under a URL-specific domain separator.pub url_key: String,}@@ -68,7 +60,7 @@ pub struct UrlCollection {pub struct CollectedUrl {/// First 22 base64url chars of `HMAC-SHA256(url_key, dedup_url)`.pub hash: String,- /// The canonical URL with every parameter intact. This is what the fetcher requests.+ /// The URL with its original query bytes intact. This is what the fetcher requests.pub url: String,/// The host the request goes to. robots.txt and the connection limit are scoped to this.pub host: String,@@ -91,7 +83,6 @@ pub fn hash_url(url_key: &[u8], dedup_url: &str) -> String {/// Accumulates the remote image URLs of one message, deduplicated on the hash.pub struct UrlCollector {- pseudo_team: String,url_key: String,urls: Vec<CollectedUrl>,seen: HashSet<String>,@@ -106,7 +97,6 @@ pub struct UrlCollector {impl UrlCollector {pub fn new(collection: UrlCollection) -> Self {Self {- pseudo_team: collection.pseudo_team,url_key: collection.url_key,urls: Vec::new(),seen: HashSet::new(),@@ -156,7 +146,7 @@ impl UrlCollector {};let hash = hash_url(self.url_key.as_bytes(), &canonical.dedup);if self.seen.contains(&hash) {- return Some(crate::collect::url_ref(&self.pseudo_team, &hash));+ return Some(crate::collect::url_ref(&hash));}self.seen.insert(hash.clone());self.urls.push(CollectedUrl {@@ -165,7 +155,7 @@ impl UrlCollector {host: canonical.host,domain: canonical.domain,});- Some(crate::collect::url_ref(&self.pseudo_team, &hash))+ Some(crate::collect::url_ref(&hash))}/// Counts by reason for the URLs this collector refused.@@ -194,7 +184,6 @@ mod tests {fn collector() -> UrlCollector {UrlCollector::new(UrlCollection {- pseudo_team: "a".repeat(32),url_key: String::from_utf8(TEST_KEY.to_vec()).unwrap(),})}@@ -219,19 +208,13 @@ mod tests {}#[test]- fn two_signatures_of_one_image_share_a_ref() {+ fn a_signed_url_produces_no_global_ref() {let mut c = collector();- let first = c+ assert!(c.collect("https://cdn.example.com/a.png?X-Amz-Signature=aaa")- .unwrap();- let second = c- .collect("https://cdn.example.com/a.png?X-Amz-Signature=bbb")- .unwrap();- assert_eq!(first, second);- // One entry, and it keeps the URL of the first sighting, which is a URL that still works.- let urls = c.into_urls();- assert_eq!(urls.len(), 1);- assert!(urls[0].url.contains("X-Amz-Signature=aaa"));+ .is_none());+ assert_eq!(c.into_declines(), vec![("credential".to_string(), 1)]);+ assert_eq!(c.into_urls(), Vec::new());}#[test]@@ -244,6 +227,21 @@ mod tests {assert_eq!(c.into_urls().len(), 2);}+ #[test]+ fn cache_busters_share_one_global_ref_and_fetch_candidate() {+ let mut c = collector();+ let first_url = "https://cdn.example.com/a.png?w=100&cb=first";+ let first = c.collect(first_url).unwrap();+ let second = c+ .collect("https://cdn.example.com/a.png?w=100&cb=second")+ .unwrap();++ assert_eq!(first, second);+ let urls = c.into_urls();+ assert_eq!(urls.len(), 1);+ assert_eq!(urls[0].url, first_url);+ }+#[test]fn collect_stops_at_the_cap_but_still_refs_a_url_it_already_holds() {let mut c = collector();diff --git a/rust/replay-anonymizer/src/url_policy.rs b/rust/replay-anonymizer/src/url_policy.rsindex 1f30d646b44c..180577e6736b 100644--- a/rust/replay-anonymizer/src/url_policy.rs+++ b/rust/replay-anonymizer/src/url_policy.rs@@ -12,79 +12,58 @@//! URL as data, so that lane reads the result and never repeats the rule.use std::collections::HashSet;-use std::net::{IpAddr, Ipv4Addr};+use std::net::IpAddr;+use percent_encoding::percent_decode_str;use public_suffix::{EffectiveTLDProvider, DEFAULT_PROVIDER};use url::Url;-/// Query parameters that change on each page load without changing the image behind the URL.-///-/// **This is an allow list of names. It must stay one.**-///-/// Never add a rule about the *shape* of a value. "Looks random" and "is long" both describe real-/// image parameters.-///-/// **Never add a name that also selects an image.** `w`, `h`, `q`, `fm`, `dpr`, `fit`, `auto`,-/// `format`, `resize`, `crop` and `quality` all do. Collapsing those onto one ref would point one-/// ref at several genuinely different images, and nothing downstream can detect it.-///-/// Only unambiguous names live here. A short name that one vendor uses for a signature and another-/// uses for a size belongs in [`SCOPED_VOLATILE_PARAMS`], where a marker keeps it honest.-///-/// `s` is the name that forced the split. imgix signs with it. Gravatar sizes with it. Removing it-/// everywhere made a 48-pixel avatar and a 200-pixel avatar the same image.-const VOLATILE_PARAMS: &[&str] = &[- // AWS SigV4 presigned (S3, CloudFront). Long and vendor-prefixed, so unambiguous.- "x-amz-algorithm",+const VOLATILE_PARAMS: &[&str] = &["cb", "nocache", "rnd"];++const CREDENTIAL_PARAMS: &[&str] = &[+ "__cld_token__",+ "__token__",+ "access_token",+ "api_key",+ "apikey",+ "auth_token",+ "authorization",+ "awsaccesskeyid",+ "credential",+ "googleaccessid",+ "hdnea",+ "hdntl",+ "hdnts",+ "id_token",+ "ik-s",+ "jsessionid",+ "ossaccesskeyid",+ "phpsessid",+ "q-ak",+ "q-signature",+ "security-token",+ "session_token",+ "sessionid",+ "sig",+ "signature",+ "signedheaders",+ "token","x-amz-credential",- "x-amz-date",- "x-amz-expires",- "x-amz-signedheaders",- "x-amz-signature","x-amz-security-token",- // CloudFront canned policies. key-pair-id is vendor-specific enough to stand alone.- "key-pair-id",- // Google Cloud Storage V4.- "x-goog-algorithm",+ "x-amz-signature",+ "x-amz-signedheaders",+ "x-cos-security-token","x-goog-credential",- "x-goog-date",- "x-goog-expires",- "x-goog-signedheaders","x-goog-signature",- // Akamai token auth.- "hdnts",- "hdnea",- "hdntl",- "__token__",- // Cache busters whose names say so.- "cb",- "rnd",- "nocache",-];--/// Volatile names that are only volatile in a known context.-///-/// Each entry is `(marker, names)`. The names are removed only when the query also carries the-/// marker, which is a parameter the vendor always sends alongside them. Without the marker the-/// names are left alone, because on another host they select an image.-const SCOPED_VOLATILE_PARAMS: &[(&str, &[&str])] = &[- // Azure Blob shared access signatures always carry sig, and sv alongside the rest.- (- "sig",- &["sv", "st", "se", "sp", "sr", "sig", "spr", "skoid"],- ),- // Meta's CDN always carries _nc_ohc with the rest of its rotating set. stp encodes a crop, so- // it is only safe to drop when the whole set is present and the URL is therefore one of theirs.- ("_nc_ohc", &["_nc_ohc", "_nc_ht", "oh", "oe", "ccb", "stp"]),- // CloudFront canned policies pair Signature with Expires and Policy. Both are ordinary words- // elsewhere: `expires` is a real cache hint, and `policy=thumb` is a plausible image selector.- ("signature", &["signature", "expires", "policy"]),- ("key-pair-id", &["policy", "expires"]),+ "x-goog-signedheaders",+ "x-oss-credential",+ "x-oss-security-token",+ "x-oss-signature",];-/// Hosts whose short signature parameter is safe to remove, because the vendor owns the host.-const HOST_SCOPED_VOLATILE_PARAMS: &[(&str, &[&str])] = &[(".imgix.net", &["s", "expires"])];+const SCOPED_VOLATILE_PARAMS: &[(&str, &[&str])] =+ &[("_nc_ohc", &["_nc_ohc", "_nc_ht", "ccb", "oe", "oh", "stp"])];/// Longer than this and we neither collect nor fetch it. Well past what a real image URL needs,/// and it bounds what one message can pin in memory alongside the count cap.@@ -131,26 +110,19 @@ pub struct CanonicalUrl {pub domain: String,}-/// Whether one parameter of this URL is volatile.-///-/// The name set is built once per URL. A scan of the parameter list made this quadratic in the-/// parameter count, and a page controls both that count and the number of URLs.-fn is_volatile(name: &str, host: &str, names_on_this_url: &HashSet<String>) -> bool {- if VOLATILE_PARAMS.iter().any(|p| p.eq_ignore_ascii_case(name)) {+fn is_volatile(name: &str, names_on_this_url: &HashSet<String>) -> bool {+ if VOLATILE_PARAMS+ .iter()+ .any(|volatile| volatile.eq_ignore_ascii_case(name))+ {return true;}- for (marker, names) in SCOPED_VOLATILE_PARAMS {- if names.iter().any(|p| p.eq_ignore_ascii_case(name)) && names_on_this_url.contains(*marker)- {- return true;- }- }- for (suffix, names) in HOST_SCOPED_VOLATILE_PARAMS {- if host.ends_with(suffix) && names.iter().any(|p| p.eq_ignore_ascii_case(name)) {- return true;- }- }- false+ SCOPED_VOLATILE_PARAMS.iter().any(|(marker, names)| {+ names_on_this_url.contains(*marker)+ && names+ .iter()+ .any(|volatile| volatile.eq_ignore_ascii_case(name))+ })}/// Whether a host is one we would ever fetch from.@@ -165,8 +137,8 @@ fn is_volatile(name: &str, host: &str, names_on_this_url: &HashSet<String>) -> b/// request and on every redirect hop.pub fn is_public_host(host: &str) -> bool {let host = without_brackets_or_trailing_dot(host);- if let Ok(ip) = host.parse::<IpAddr>() {- return is_public_ip(ip);+ if host.parse::<IpAddr>().is_ok() {+ return false;}is_public_domain_name(&host.to_ascii_lowercase())}@@ -204,74 +176,6 @@ fn is_public_domain_name(lowercase_host: &str) -> bool {)}-/// IPv6 offers several ways to write an IPv4 address, and each one used to bypass most of the IPv4-/// rules. Every embedding is now judged by [`is_public_v4`].-fn is_public_ip(ip: IpAddr) -> bool {- let v6 = match ip {- IpAddr::V4(v4) => return is_public_v4(v4),- IpAddr::V6(v6) => v6,- };- if v6.is_loopback() || v6.is_unspecified() || v6.is_multicast() {- return false;- }- let segments = v6.segments();- let is_unique_local = (segments[0] & 0xfe00) == 0xfc00;- let is_link_local = (segments[0] & 0xffc0) == 0xfe80;- if is_unique_local || is_link_local {- return false;- }- match v6- .to_ipv4_mapped()- .or_else(|| v6.to_ipv4())- .or_else(|| ipv4_inside_6to4(segments))- .or_else(|| ipv4_inside_nat64(segments))- {- Some(v4) => is_public_v4(v4),- None => true,- }-}--/// 6to4 carries the address in the two segments after the `2002::/16` prefix.-fn ipv4_inside_6to4(segments: [u16; 8]) -> Option<Ipv4Addr> {- (segments[0] == 0x2002).then(|| ipv4_from_segments(segments[1], segments[2]))-}--/// The NAT64 well-known prefix `64:ff9b::/96` carries it in the last two segments.-fn ipv4_inside_nat64(segments: [u16; 8]) -> Option<Ipv4Addr> {- let has_well_known_prefix = segments[0] == 0x0064- && segments[1] == 0xff9b- && segments[2] == 0- && segments[3] == 0- && segments[4] == 0;- has_well_known_prefix.then(|| ipv4_from_segments(segments[6], segments[7]))-}--fn ipv4_from_segments(high: u16, low: u16) -> Ipv4Addr {- Ipv4Addr::new((high >> 8) as u8, high as u8, (low >> 8) as u8, low as u8)-}--fn is_public_v4(v4: Ipv4Addr) -> bool {- let [a, b, c, _] = v4.octets();- let this_network = a == 0;- let carrier_grade_nat = a == 100 && (64..128).contains(&b);- let ietf_protocol_assignments = a == 192 && b == 0 && c == 0;- let benchmarking = a == 198 && (b == 18 || b == 19);- let reserved = a >= 240;-- !(v4.is_loopback()- || v4.is_private()- || v4.is_link_local()- || v4.is_broadcast()- || v4.is_documentation()- || v4.is_unspecified()- || v4.is_multicast()- || this_network- || carrier_grade_nat- || ietf_protocol_assignments- || benchmarking- || reserved)-}-/// Why a URL was not collected. Each variant is a label on the decline counter. A lane/// that collects less than it should then reads off a dashboard, rather than being guessed at.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]@@ -289,6 +193,10 @@ pub enum Decline {NoHost,/// Loopback, private, link-local or an internal-only name. See [`is_public_host`].NonPublicHost,+ /// A known URL credential, signature, token, signed-header list, or non-empty userinfo.+ Credential,+ /// A query parameter name could not be percent-decoded as UTF-8.+ InvalidQuery,}impl Decline {@@ -301,6 +209,8 @@ impl Decline {Decline::BadPort => "bad_port",Decline::NoHost => "no_host",Decline::NonPublicHost => "non_public_host",+ Decline::Credential => "credential",+ Decline::InvalidQuery => "invalid_query",}}}@@ -331,6 +241,9 @@ pub fn try_canonicalize(raw: &str) -> Result<CanonicalUrl, Decline> {if url.port().is_some() {return Err(Decline::BadPort);}+ if !url.username().is_empty() || url.password().is_some() {+ return Err(Decline::Credential);+ }// `example.com.` and `example.com` name the same host, and the consumer compares the two as// strings in more than one place. The dot comes off the URL as well as off the host, so// everything downstream sees one spelling.@@ -342,16 +255,22 @@ pub fn try_canonicalize(raw: &str) -> Result<CanonicalUrl, Decline> {if host != host_str {url.set_host(Some(&host)).map_err(|_| Decline::NoHost)?;}+ if has_credential_query(&url)? || has_credential_path(&url, &host)? {+ return Err(Decline::Credential);+ }- remove_credentials_and_fragment(&mut url);- let fetch = url.to_string();+ let original_query = original_query(raw);+ url.set_fragment(None);+ url.set_query(None);+ let serialized_without_query = url.to_string();+ let fetch = serialize_with_query(&serialized_without_query, original_query);// Percent-encoding and IDNA can grow a URL, so the cap is re-checked on what we emit.if fetch.len() > MAX_URL_LEN {return Err(Decline::TooLong);}- remove_volatile_params(&mut url, &host);- let dedup = url.to_string();+ let dedup_query = remove_volatile_params(original_query)?;+ let dedup = serialize_with_query(&serialized_without_query, dedup_query.as_deref());Ok(CanonicalUrl {fetch,@@ -361,52 +280,141 @@ pub fn try_canonicalize(raw: &str) -> Result<CanonicalUrl, Decline> {})}-fn remove_credentials_and_fragment(url: &mut Url) {- // The setters fail only on a cannot-be-a-base URL, which the http(s) check already excluded.- let _ = url.set_username("");- let _ = url.set_password(None);- url.set_fragment(None);+fn original_query(raw: &str) -> Option<&str> {+ let before_fragment = raw.split_once('#').map_or(raw, |(before, _)| before);+ before_fragment.split_once('?').map(|(_, query)| query)}-/// Rewrites the query of every URL that has one, whether or not it removed anything.-///-/// Rewriting only when something was removed made the result depend on an unrelated fact. Two-/// encodings of one query then hashed the same when a signature was present and differently when-/// it was absent, so one image could hold two refs.-fn remove_volatile_params(url: &mut Url, host: &str) {- if url.query().is_none() {- return;- }- let pairs: Vec<(String, String)> = url- .query_pairs()- .map(|(k, v)| (k.into_owned(), v.into_owned()))+fn serialize_with_query(serialized_without_query: &str, query: Option<&str>) -> String {+ let mut serialized = serialized_without_query.to_string();+ if let Some(query) = query {+ serialized.push('?');+ serialized.push_str(query);+ }+ serialized+}++fn has_credential_query(url: &Url) -> Result<bool, Decline> {+ let Some(raw_query) = url.query() else {+ return Ok(false);+ };+ for raw_pair in raw_query.split('&') {+ let raw_name = raw_pair.split_once('=').map_or(raw_pair, |(name, _)| name);+ if !has_valid_percent_encoding(raw_name) {+ return Err(Decline::InvalidQuery);+ }+ let form_name = raw_name.replace('+', " ");+ percent_decode_str(&form_name)+ .decode_utf8()+ .map_err(|_| Decline::InvalidQuery)?;+ }+ Ok(url.query_pairs().any(|(name, value)| {+ CREDENTIAL_PARAMS+ .iter()+ .any(|credential| credential.eq_ignore_ascii_case(&name))+ || (name.eq_ignore_ascii_case("s") && value.chars().count() == 32)+ }))+}++fn has_valid_percent_encoding(value: &str) -> bool {+ let bytes = value.as_bytes();+ let mut index = 0;+ while index < bytes.len() {+ if bytes[index] == b'%' {+ if index + 2 >= bytes.len()+ || !bytes[index + 1].is_ascii_hexdigit()+ || !bytes[index + 2].is_ascii_hexdigit()+ {+ return false;+ }+ index += 3;+ } else {+ index += 1;+ }+ }+ true+}++fn has_credential_path(url: &Url, host: &str) -> Result<bool, Decline> {+ if !has_valid_percent_encoding(url.path()) {+ return Err(Decline::Credential);+ }+ let path = percent_decode_str(url.path())+ .decode_utf8()+ .map_err(|_| Decline::Credential)?+ .to_ascii_lowercase();+ let segments: Vec<&str> = path.split('/').collect();+ let first_segment_has_bunny_token = segments+ .get(1)+ .and_then(|segment| segment.strip_prefix("bcdn_token="))+ .and_then(|value| value.split('&').next())+ .is_some_and(|token| !token.is_empty());+ let has_oracle_token = host.starts_with("objectstorage.")+ && host.ends_with(".oraclecloud.com")+ && host.split('.').count() == 4+ && segments.get(1) == Some(&"p")+ && segments.get(2).is_some_and(|token| !token.is_empty())+ && segments.get(3) == Some(&"n");+ let has_cloudinary_signature = segments.iter().any(|segment| {+ segment+ .strip_prefix("s--")+ .and_then(|value| value.strip_suffix("--"))+ .is_some_and(|token| !token.is_empty())+ });+ let has_supabase_signature = path.contains("/storage/v1/object/sign/")+ || path.contains("/storage/v1/render/image/sign/");+ let has_session_token = segments.iter().any(|segment| {+ segment+ .split_once(";jsessionid=")+ .and_then(|(_, value)| value.split(';').next())+ .is_some_and(|token| !token.is_empty())+ });++ Ok(first_segment_has_bunny_token+ || has_oracle_token+ || has_cloudinary_signature+ || has_supabase_signature+ || has_session_token)+}++fn remove_volatile_params(raw_query: Option<&str>) -> Result<Option<String>, Decline> {+ let Some(raw_query) = raw_query else {+ return Ok(None);+ };+ let pairs: Vec<(&str, String)> = raw_query+ .split('&')+ .map(|raw_pair| {+ let raw_name = raw_pair.split_once('=').map_or(raw_pair, |(name, _)| name);+ if !has_valid_percent_encoding(raw_name) {+ return Err(Decline::InvalidQuery);+ }+ let decoded_name = percent_decode_str(raw_name)+ .decode_utf8()+ .map_err(|_| Decline::InvalidQuery)?+ .into_owned();+ Ok((raw_pair, decoded_name))+ })+ .collect::<Result<_, _>>()?;+ let names_on_this_url: HashSet<String> = pairs+ .iter()+ .map(|(_, name)| name.to_ascii_lowercase()).collect();- let names_on_this_url: HashSet<String> =- pairs.iter().map(|(k, _)| k.to_ascii_lowercase()).collect();- let kept: Vec<&(String, String)> = pairs+ let kept: Vec<&str> = pairs.iter()- .filter(|(k, _)| !is_volatile(k, host, &names_on_this_url))+ .filter(|(_, name)| !is_volatile(name, &names_on_this_url))+ .map(|(raw_pair, _)| *raw_pair).collect();if kept.is_empty() {- url.set_query(None);- return;- }- let mut query = url.query_pairs_mut();- query.clear();- for (name, value) in kept {- query.append_pair(name, value);+ return Ok(None);}+ Ok(Some(kept.join("&")))}#[cfg(test)]mod tests {use super::*;- fn volatile(name: &str, host: &str, others: &[&str]) -> bool {- let present: HashSet<String> = others.iter().map(|o| o.to_ascii_lowercase()).collect();- is_volatile(name, host, &present)- }#[test]fn canonicalize_rejects_what_we_will_not_fetch() {for raw in [@@ -423,73 +431,150 @@ mod tests {}#[test]- fn canonicalize_normalizes_and_strips_credentials() {- let c = canonicalize("HTTPS://User:[email protected]:443/A.png#frag").unwrap();+ fn canonicalize_normalizes_and_removes_the_fragment() {+ let c = canonicalize("HTTPS://Example.COM:443/A.png#frag").unwrap();assert_eq!(c.fetch, "https://example.com/A.png");assert_eq!(c.host, "example.com");- assert!(!c.fetch.contains("User"));- assert!(!c.fetch.contains("Pass"));}#[test]- fn the_signature_stays_on_the_fetch_url_and_leaves_the_dedup_url() {- let signed = "https://cdn.example.com/a.png?w=200&X-Amz-Signature=deadbeef&X-Amz-Date=20260810T000000Z";- let c = canonicalize(signed).unwrap();- // The fetcher needs the signature, or the request 403s.- assert!(c.fetch.contains("X-Amz-Signature=deadbeef"));- // The ref must not move when the signature does.- assert_eq!(c.dedup, "https://cdn.example.com/a.png?w=200");+ fn known_query_credentials_are_refused_case_insensitively() {+ for name in CREDENTIAL_PARAMS {+ let raw = format!(+ "https://cdn.example.com/a.png?{}=",+ name.to_ascii_uppercase()+ );+ assert_eq!(try_canonicalize(&raw), Err(Decline::Credential), "{name}");+ }+ assert_eq!(+ try_canonicalize("https://cdn.example.com/a.png?X-Amz-%53ignature=value"),+ Err(Decline::Credential)+ );+ assert_eq!(+ try_canonicalize("https://cdn.example.com/a.png?safe=1&safe=2&TOKEN="),+ Err(Decline::Credential)+ );+ assert_eq!(+ try_canonicalize("https://cdn.example.com/a.png?s=0123456789abcdef0123456789abcdef"),+ Err(Decline::Credential)+ );+ assert!(canonicalize("https://cdn.example.com/a.png?s=200").is_some());}#[test]- fn a_query_that_is_only_volatile_leaves_no_empty_question_mark() {- let c = canonicalize("https://cdn.example.com/a.png?nocache=12345").unwrap();- assert_eq!(c.dedup, "https://cdn.example.com/a.png");+ fn credential_path_patterns_are_refused_case_insensitively() {+ for raw in [+ "https://cdn.example.com/BCDN_TOKEN=value/image.png",+ "https://objectstorage.region.oraclecloud.com/P/value/N/image.png",+ "https://cdn.example.com/S--value--/image.png",+ "https://cdn.example.com/STORAGE/V1/OBJECT/SIGN/value",+ "https://cdn.example.com/storage/v1/render/image/sign/value",+ "https://cdn.example.com/images;JSESSIONID=value/a.png",+ ] {+ assert_eq!(try_canonicalize(raw), Err(Decline::Credential), "{raw}");+ }}#[test]- fn a_generic_word_is_only_volatile_beside_its_vendor_marker() {- // `policy=thumb` and `policy=full` are plausible image selectors on an ordinary host.- let thumb = canonicalize("https://cdn.example.com/a.png?policy=thumb").unwrap();- let full = canonicalize("https://cdn.example.com/a.png?policy=full").unwrap();- assert_ne!(thumb.dedup, full.dedup);- // Beside CloudFront's signature it is part of the signing set.- assert!(volatile("policy", "cdn.example.com", &["signature"]));+ fn percent_encoded_credential_path_patterns_are_refused() {+ for raw in [+ "https://cdn.example.com/BCDN%5fTOKEN=value/image.png",+ "https://objectstorage.region.oraclecloud.com/%70/value/%6e/image.png",+ "https://cdn.example.com/S%2d%2dvalue%2d%2d/image.png",+ "https://cdn.example.com/storage/v1/object/s%69gn/value",+ "https://cdn.example.com/storage/v1/render/image/s%69gn/value",+ "https://cdn.example.com/images%3bJSESSIONID=value/a.png",+ ] {+ assert_eq!(try_canonicalize(raw), Err(Decline::Credential), "{raw}");+ }}#[test]- fn an_ambiguous_cache_buster_is_kept() {- // `v` and `t` are cache busters on some hosts and content-version or variant markers on- // others. Keeping them costs a missed dedup. Removing them merges two different images.- let a = canonicalize("https://cdn.example.com/a.png?v=thumb").unwrap();- let b = canonicalize("https://cdn.example.com/a.png?v=full").unwrap();- assert_ne!(a.dedup, b.dedup);+ fn userinfo_and_invalid_query_names_are_refused() {+ assert_eq!(+ try_canonicalize("https://user:[email protected]/a.png"),+ Err(Decline::Credential)+ );+ assert_eq!(+ try_canonicalize("https://cdn.example.com/a.png?bad%FF=value"),+ Err(Decline::InvalidQuery)+ );+ assert_eq!(+ try_canonicalize("https://cdn.example.com/a.png?bad%ZZ=value"),+ Err(Decline::InvalidQuery)+ );}#[test]- fn volatile_names_never_include_a_name_that_selects_an_image() {- for name in [- "w", "h", "q", "fm", "dpr", "fit", "auto", "format", "resize", "crop", "quality",- ] {- assert!(- !volatile(name, "cdn.example.com", &[]),- "{name} changes the image and must be kept"- );- }+ fn signing_metadata_without_a_credential_is_preserved() {+ let raw = "https://cdn.example.com/a.png?X-Amz-Algorithm=v4&X-Amz-Date=20260810T000000Z&X-Amz-Expires=60";+ let canonical = canonicalize(raw).unwrap();+ assert!(canonical.fetch.contains("X-Amz-Algorithm=v4"));+ assert!(canonical.dedup.contains("X-Amz-Algorithm=v4"));+ }++ #[test]+ fn volatile_query_fields_stay_on_the_fetch_url_and_leave_the_global_ref() {+ let canonical = canonicalize(+ "https://cdn.example.com/a.png?w=200&%63b=first&CB=second&no%63ache=third&RND=fourth",+ )+ .unwrap();++ assert_eq!(+ canonical.fetch,+ "https://cdn.example.com/a.png?w=200&%63b=first&CB=second&no%63ache=third&RND=fourth"+ );+ assert_eq!(canonical.dedup, "https://cdn.example.com/a.png?w=200");+ }++ #[test]+ fn fetch_and_retained_dedup_query_bytes_are_never_rebuilt() {+ let raw = "https://cdn.example.com/a.png?flag&empty=&plus=a+b&space=a%20b&bytes=%FF&slash=%2f&cb=drop#fragment";+ let canonical = canonicalize(raw).unwrap();++ assert_eq!(+ canonical.fetch,+ "https://cdn.example.com/a.png?flag&empty=&plus=a+b&space=a%20b&bytes=%FF&slash=%2f&cb=drop"+ );+ assert_eq!(+ canonical.dedup,+ "https://cdn.example.com/a.png?flag&empty=&plus=a+b&space=a%20b&bytes=%FF&slash=%2f"+ );+ }++ #[test]+ fn distinct_raw_nonvolatile_queries_keep_distinct_global_refs() {+ let bare = canonicalize("https://cdn.example.com/a.png?flag").unwrap();+ let empty = canonicalize("https://cdn.example.com/a.png?flag=").unwrap();+ let plus = canonicalize("https://cdn.example.com/a.png?q=a+b").unwrap();+ let encoded_space = canonicalize("https://cdn.example.com/a.png?q=a%20b").unwrap();++ assert_ne!(bare.dedup, empty.dedup);+ assert_ne!(plus.dedup, encoded_space.dedup);}#[test]- fn a_short_name_is_only_volatile_where_the_vendor_owns_it() {- // `s` sizes a Gravatar avatar and signs an imgix URL. Stripping it everywhere made a- // 48-pixel avatar and a 200-pixel avatar the same image.- assert!(!volatile("s", "www.gravatar.com", &[]));- assert!(volatile("s", "images.imgix.net", &[]));- // The Azure SAS names are volatile only when the signature of that set is also present.- assert!(!volatile("sp", "cdn.example.com", &["w"]));- assert!(volatile("sp", "acct.blob.core.windows.net", &["sig", "sv"]));- // `expires` is a real cache hint until CloudFront's `signature` appears beside it.- assert!(!volatile("expires", "cdn.example.com", &[]));- assert!(volatile("expires", "cdn.example.com", &["signature"]));+ fn meta_query_fields_are_volatile_only_with_their_marker() {+ let without_marker =+ canonicalize("https://cdn.example.com/a.png?stp=first&ccb=second").unwrap();+ assert_eq!(+ without_marker.dedup,+ "https://cdn.example.com/a.png?stp=first&ccb=second"+ );++ let with_marker = canonicalize(+ "https://cdn.example.com/a.png?keep=1&_nc_%6Fhc=a&_NC_HT=b&ccb=c&oe=d&oh=e&stp=f",+ )+ .unwrap();+ assert_eq!(with_marker.dedup, "https://cdn.example.com/a.png?keep=1");+ }++ #[test]+ fn credentials_are_refused_before_volatile_query_fields_are_removed() {+ assert_eq!(+ try_canonicalize("https://cdn.example.com/a.png?cb=first&TOKEN=secret&cb=second"),+ Err(Decline::Credential)+ );}#[test]@@ -600,10 +685,8 @@ mod tests {assert!(canonicalize("https://cdn.example.com/i.png").is_some());// A public name with a trailing dot is still public, so the fix must not over-reject.assert!(canonicalize("https://cdn.example.com./i.png").is_some());- // The address rule accepts a public address. Both use https, because the scheme rule- // refuses plain http on its own.- assert!(canonicalize("https://[2606:4700::1111]/i.png").is_some());- assert!(canonicalize("https://8.8.8.8/i.png").is_some());+ assert!(canonicalize("https://[2606:4700::1111]/i.png").is_none());+ assert!(canonicalize("https://8.8.8.8/i.png").is_none());}#[test]@@ -616,12 +699,10 @@ mod tests {}#[test]- fn the_dedup_url_does_not_depend_on_whether_a_signature_rode_along() {- // The query used to be re-encoded only when something was stripped, so one image could- // hold two refs depending on an unrelated condition.- let plain = canonicalize("https://cdn.example.com/a.png?a=1&b=2").unwrap();- let signed =- canonicalize("https://cdn.example.com/a.png?a=1&b=2&X-Amz-Signature=zz").unwrap();- assert_eq!(plain.dedup, signed.dedup);+ fn a_cache_buster_does_not_identify_a_distinct_resource() {+ let plain = canonicalize("https://cdn.example.com/a.png?a=hello%20world&b=2").unwrap();+ let cache_busted =+ canonicalize("https://cdn.example.com/a.png?a=hello%20world&b=2&cb=zz").unwrap();+ assert_eq!(plain.dedup, cache_busted.dedup);}}diff --git a/rust/replay-anonymizer/tests/fixtures/image-url-ref.json b/rust/replay-anonymizer/tests/fixtures/image-url-ref.jsonnew file mode 100644index 000000000000..7cac22143948--- /dev/null+++ b/rust/replay-anonymizer/tests/fixtures/image-url-ref.json@@ -0,0 +1,18 @@+[+ {+ "name": "hero",+ "pseudonymSecret": "test-pseudonym-secret",+ "canonicalUrl": "https://cdn.example.com/hero.png?w=200",+ "globalUrlKey": "46debdbcad6c0b245d92ed38ac325eac",+ "hash": "7WmDiXph-36Tg6OgJyWa8U",+ "ref": "imageurl:7WmDiXph-36Tg6OgJyWa8U"+ },+ {+ "name": "root",+ "pseudonymSecret": "0123456789abcdef0123456789abcdef",+ "canonicalUrl": "https://example.com/",+ "globalUrlKey": "588b95940ea105e7ecc5f1e9b8ae4f50",+ "hash": "XSZWrG3WXXBn46zmq_k7RS",+ "ref": "imageurl:XSZWrG3WXXBn46zmq_k7RS"+ }+]diff --git a/rust/replay-anonymizer/tests/parity.rs b/rust/replay-anonymizer/tests/parity.rsindex e58cbda5a88e..45441b8d3529 100644--- a/rust/replay-anonymizer/tests/parity.rs+++ b/rust/replay-anonymizer/tests/parity.rs@@ -7,8 +7,13 @@ use std::time::Instant;use base64::Engine;use posthog_replay_anonymizer::allow_lists::AllowLists;use posthog_replay_anonymizer::{- anonymize_event_str, anonymize_message, collect::hash_image_bytes, context::Ctx,- text::scrub_text, url::scrub_url, url::URL_SCHEME_ALLOWLIST,+ anonymize_event_str, anonymize_message,+ collect::{hash_image_bytes, url_ref},+ context::Ctx,+ text::scrub_text,+ url::scrub_url,+ url::URL_SCHEME_ALLOWLIST,+ url_collect::hash_url,};use serde_json::Value;@@ -54,6 +59,27 @@ fn image_hash_fixtures() {}}+#[test]+fn image_url_ref_fixtures() {+ for case in fixtures("image-url-ref.json") {+ let global_url_key = case["globalUrlKey"].as_str().unwrap();+ let canonical_url = case["canonicalUrl"].as_str().unwrap();+ let hash = hash_url(global_url_key.as_bytes(), canonical_url);+ assert_eq!(+ hash,+ case["hash"].as_str().unwrap(),+ "case: {}",+ case["name"]+ );+ assert_eq!(+ url_ref(&hash),+ case["ref"].as_str().unwrap(),+ "case: {}",+ case["name"]+ );+ }+}+#[test]fn text_fixtures() {for case in fixtures("text.json") {diff --git a/rust/replay-anonymizer/tests/ref_idempotence.rs b/rust/replay-anonymizer/tests/ref_idempotence.rsindex 0c2e57696fff..547de8cbe49c 100644--- a/rust/replay-anonymizer/tests/ref_idempotence.rs+++ b/rust/replay-anonymizer/tests/ref_idempotence.rs@@ -3,7 +3,7 @@//!//! The mirror replaces each inlined image with an `image:<pseudo_team>:<hash>` ref and ships the//! bytes out of band, so that ref is the only join key back to them. Remote images keep a media-//! placeholder and carry an `imageurl:<pseudo_team>:<hash>` ref in a namespaced sibling attribute.+//! placeholder and carry an `imageurl:<hash>` ref in a namespaced sibling attribute.//! Scrubbing mirrored output a second time must not destroy either join key.//!//! The ref format is not a secret, though, so preserving anything `image:`-shaped found in a@@ -19,7 +19,8 @@ use serde_json::{json, Value};const TS0: f64 = 1_700_000_000_000.0;const REF: &str = "image:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";-const URL_REF: &str = "imageurl:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";+const URL_REF: &str = "imageurl:AAAAAAAAAAAAAAAAAAAAAA";+const LEGACY_URL_REF: &str = "imageurl:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";fn img_line(value: &str, attr: &str) -> Value {json!(["w", { "type": 3, "timestamp": TS0, "data": {@@ -104,14 +105,16 @@ fn a_ref_survives_a_trusted_rescrub() {#[test]fn a_namespaced_url_ref_survives_only_a_trusted_rescrub() {- let line = img_line(URL_REF, "data-anon-image-ref-src");- assert!(scrub_trusted(&line).contains(URL_REF));- assert!(!scrub_default(&line).contains("data-anon-image-ref-src"));- for byte_walk in [true, false] {- assert!(- !scrub_ingestion(&line, byte_walk).contains("data-anon-image-ref-src"),- "a captured internal ref attribute survived ingestion (byte_walk={byte_walk})"- );+ for url_ref in [URL_REF, LEGACY_URL_REF] {+ let line = img_line(url_ref, "data-anon-image-ref-src");+ assert!(scrub_trusted(&line).contains(url_ref));+ assert!(!scrub_default(&line).contains("data-anon-image-ref-src"));+ for byte_walk in [true, false] {+ assert!(+ !scrub_ingestion(&line, byte_walk).contains("data-anon-image-ref-src"),+ "a captured internal ref attribute survived ingestion (byte_walk={byte_walk})"+ );+ }}}diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rsindex 87b18eead1a9..ea48daee25c4 100644--- a/rust/replay-anonymizer/tests/url_collection.rs+++ b/rust/replay-anonymizer/tests/url_collection.rs@@ -11,7 +11,6 @@ use posthog_replay_anonymizer::{use serde_json::{json, Value};const TS0: f64 = 1_700_000_000_000.0;-const PSEUDO_TEAM: &str = "0123456789abcdef0123456789abcdef";const URL_KEY: &str = "0123456789abcdef0123456789abcdef";fn payload_tagged(tag: &str, attrs: Value) -> Vec<u8> {@@ -54,7 +53,6 @@ fn collect_urls_of(tag: &str, attrs: Value) -> Vec<String> {None,None,Some(UrlCollection {- pseudo_team: PSEUDO_TEAM.to_string(),url_key: URL_KEY.to_string(),}),)@@ -85,15 +83,19 @@ fn only_an_image_bearing_tag_has_its_src_collected() {}#[test]-fn a_video_poster_is_still_collected() {- // poster only exists on a video and always names a still image.- assert_eq!(- collect_urls_of(+fn attributes_other_than_src_are_not_collected() {+ for (tag, attrs) in [+ ("img", json!({ "rr_src": "https://cdn.example.com/a.png" })),+ ("video",- json!({ "poster": "https://cdn.example.com/poster.jpg" })+ json!({ "poster": "https://cdn.example.com/poster.jpg" }),),- vec!["byte_walk=true:1", "byte_walk=false:1"]- );+ ] {+ assert_eq!(+ collect_urls_of(tag, attrs),+ vec!["byte_walk=true:0", "byte_walk=false:0"]+ );+ }}fn payload(attrs: Value) -> Vec<u8> {@@ -129,7 +131,6 @@ fn run(attrs: Value, collect: bool) -> Vec<(String, Value)> {for byte_walk in [true, false] {let mut bytes = payload(attrs.clone());let collection = collect.then(|| UrlCollection {- pseudo_team: PSEUDO_TEAM.to_string(),url_key: URL_KEY.to_string(),});let msg = anonymize_kafka_payload_collecting(@@ -176,18 +177,19 @@ fn a_remote_src_keeps_its_placeholder_and_stashes_the_ref() {let url_ref = attrs_of(line)["data-anon-image-ref-src"].as_str().expect("the URL ref is stashed");- assert!(- url_ref.starts_with(&format!("imageurl:{PSEUDO_TEAM}:")),- "{engine}: expected a URL ref, got {url_ref}"- );+ assert!(url_ref.starts_with("imageurl:"), "{engine}: got {url_ref}");let urls = meta["urls"].as_array().expect("meta.urls present");assert_eq!(urls.len(), 1, "{engine}");assert_eq!(urls[0]["url"], "https://cdn.example.com/hero.png?w=200");assert_eq!(urls[0]["host"], "cdn.example.com");assert!(- url_ref.ends_with(urls[0]["hash"].as_str().expect("hash is a string")),- "{engine}: the ref must carry the hash meta reports"+ url_ref+ == format!(+ "imageurl:{}",+ urls[0]["hash"].as_str().expect("hash is a string")+ ),+ "{engine}: the ref must equal the hash meta reports");assert!(@@ -271,63 +273,31 @@ fn srcset_stays_out_of_scope_and_keeps_the_placeholder() {}#[test]-fn one_url_under_two_signatures_collects_once() {- // The whole reason canonicalization splits the dedup URL from the fetch URL.- let allow = AllowLists::default();- let mut bytes = json!({- "distinct_id": "d",- "data": json!({- "event": "$snapshot_items",- "properties": {- "$session_id": "s",- "$window_id": "w",- "$snapshot_items": [- {"type": 3, "timestamp": TS0, "data": {"source": 0, "adds": [- {"parentId": 1, "nextId": null, "node": {"type": 2, "tagName": "img", "id": 1,- "attributes": {"src": "https://cdn.example.com/a.png?X-Amz-Signature=aaa"}, "childNodes": []}},- {"parentId": 1, "nextId": null, "node": {"type": 2, "tagName": "img", "id": 2,- "attributes": {"src": "https://cdn.example.com/a.png?X-Amz-Signature=bbb"}, "childNodes": []}}- ]}}- ]- }- }).to_string()- })- .to_string()- .into_bytes();-- let msg = anonymize_kafka_payload_collecting(- &allow,- &mut bytes,- AnonymizeOpts::default(),- None,- None,- Some(UrlCollection {- pseudo_team: PSEUDO_TEAM.to_string(),- url_key: URL_KEY.to_string(),- }),- )- .expect("anonymize should succeed");-- assert_eq!(- msg.meta.urls.len(),- 1,- "two signatures of one image are one URL to fetch"- );+fn signed_urls_produce_no_ref_or_fetch_candidate() {+ for (engine, result) in run(+ json!({ "src": "https://cdn.example.com/a.png?X-Amz-Signature=aaa" }),+ true,+ ) {+ let (line, meta) = (&result[0], &result[1]);+ assert!(+ attrs_of(line).get("data-anon-image-ref-src").is_none(),+ "{engine}: signed URLs must not produce a global ref"+ );+ assert!(meta.get("urls").is_none(), "{engine}");+ assert_eq!(meta["urlDeclines"][0]["reason"], "credential", "{engine}");+ assert_eq!(meta["urlDeclines"][0]["count"], 1, "{engine}");+ }}#[test]-fn every_refusal_is_counted_with_a_reason() {+fn a_refusal_is_counted_with_a_reason() {// A silent decline makes the lane look like the traffic carries fewer images than it does,// which is exactly the number the measurement phase exists to produce.let allow = AllowLists::default();let mut bytes = payload_tagged("img",json!({- // https, so this refusal counts as an address refusal. The scheme check runs first, so- // over http it would count as a scheme refusal instead.- "src": "https://169.254.169.254/meta.png",- "rr_src": "ftp://files.example.com/a.png",- "poster": "/relative/a.png"+ "src": "https://169.254.169.254/meta.png"}),);let msg = anonymize_kafka_payload_collecting(@@ -337,7 +307,6 @@ fn every_refusal_is_counted_with_a_reason() {None,None,Some(UrlCollection {- pseudo_team: PSEUDO_TEAM.to_string(),url_key: URL_KEY.to_string(),}),)@@ -351,6 +320,4 @@ fn every_refusal_is_counted_with_a_reason() {.map(|d| d.reason.as_str()).collect();assert!(reasons.contains(&"non_public_host"), "{reasons:?}");- assert!(reasons.contains(&"bad_scheme"), "{reasons:?}");- assert!(reasons.contains(&"not_absolute"), "{reasons:?}");}