: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(ai-research): add a continuous candidate pool to image fetch (#106537)
Robbie8717263862e2
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 48fa1dea7b43..4e95af1b33b8 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md@@ -42,6 +42,8 @@ The frontier consumer uses cooperative rebalancing. Its revoke path drains activEach image-fetch worker creates two Kafka group members by default. A local joiner combines their batches before it starts a fetch pass. When `SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES` is false, each member batch starts its own pass immediately, so a slow partition does not hold back the other members. Group assignments do not overlap, and each member can own multiple partitions. The joiner processes available batches when its join window ends. Each member waits for its group to start before it reads another batch, so a group has at most one contribution per member. The member then tracks completion through the shared Kafka consumer background-task mechanism. Each member can hold two unfinished batches. The consumer waits for the oldest batch at that limit and stores offsets in batch order. Shared request limits still bound total network concurrency. The background-task timeout is 240 seconds, leaving 60 seconds below the default Kafka poll allowance for joining and scheduling. Shutdown stops all consumer loops and waits for the actual joined processing promises before disconnecting consumers and destroying shared dependencies. This wait includes work that outlives the Kafka consumer drain or background-task timeout. The worker divides a 100 MiB Kafka prefetch budget across its group members, with a minimum of 25 MiB per member. This preserves the queue sizes for one to four members and allows a default maximum-sized record in each queue. Sixteen members have a combined prefetch budget of 400 MiB. During a mixed-version rollout, pods with more group members can receive more partitions until the rollout finishes. `SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH` accepts targets from one to sixteen for worker-count experiments.+`SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL` replaces the joiner with one candidate pool for the worker (`fetch-candidate-pool.ts`). A batch no longer waits for the slowest job of another member's batch. The pool counts registrable-domain and origin slots across the worker, so two batches from one partition cannot each claim a domain's full limit. The fetch pass counts those slots per pass, and the request scheduler then refuses the excess as `connection_limit`. The fetch workers start with the first batch and take jobs among eligible origins in the order the jobs entered the pool. The pool holds an origin with a crawl delay until the delay passes, so a job does not hold a pod request slot while it waits. Each member returns from its batch handler only when its pool window has room (`pool-window-batch-handler.ts`), and it can hold four unfinished batches, which is the hard bound on its resident jobs. A fetch worker that finds no eligible job gives room to every member under the queued-job limit, because jobs that count as runnable can still wait on a crawl delay or on another member's hold on a domain. The room wait stops after 30 seconds, below the consumer's 60-second stalled-loop check, so the queued-job limit can be passed by about one batch. Crawl-history reads and writes and republish flushes stay per batch. Shutdown waits for every member batch that has started, including one still reading crawl history before it reaches the pool, before it stops the fetch workers. A batch can outlive the Kafka consumer drain, and the pool refuses candidates once it is closed.+Retry jobs use 1-minute, 10-minute, and 1-hour Kafka topics. The topics use broker append timestamps.Each delay consumer waits once for the latest record in its batch. It then republishes the complete batch to the frontier.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 f24daaab3b5c..65939165642b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md@@ -301,6 +301,8 @@ Removing an eligible entry cannot permit an earlier request.**5.20** Each worker creates one Kafka group member for each configured target partition. Group assignments do not overlap, so ready group members supply batches from different partitions. The worker joins their batches into one fetch pass. The target must be from one to four and defaults to two. The worker starts the fetch pass when all target batches arrive or the join window ends. If fewer batches arrive, the worker processes the available batches. A later group can run concurrently instead of waiting behind a full pass. Shared request limits still bound total network concurrency. The worker divides the existing Kafka prefetch memory budget across its group members.+**5.21** When `SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL` is true, the worker does not join batches. Each group member batch adds its jobs to one candidate pool for the worker and finishes when its own jobs finish. The pool applies the registrable-domain and origin limits across the worker, not per batch. It selects the eligible registrable domain whose first waiting job entered the pool earliest. The order uses the time the worker received the job, not the age of the record, because the pass deadline and the batch timeout count from that time. An origin in its crawl delay is not eligible until the delay passes. At the pass deadline, the batch's waiting jobs leave the pool as pass-deadline deferrals. A group member reads its next batch only when fewer than `SESSION_RECORDING_ML_IMAGE_FETCH_POOL_REFILL_RUNNABLE_URLS` of its waiting jobs can run, and fewer than `SESSION_RECORDING_ML_IMAGE_FETCH_POOL_MAX_QUEUED_URLS_PER_MEMBER` of its jobs wait. A registrable domain counts as runnable only up to its concurrency limit. A member also reads its next batch when a fetch worker finds no eligible job and the member is under the queued-job limit. The member waits at most 30 seconds for room. After that it reads its next batch anyway, so its queued jobs can pass the limit by about one batch until pass deadlines remove them.+### 6. Smokescreen**6.1** Smokescreen is the authoritative network boundary for outbound requests in production. It must refuse a connection to an IP address that is not globally routable.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.test.tsnew file mode 100644index 000000000000..06c51b76e57f--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.test.ts@@ -0,0 +1,224 @@+import { FetchCandidate, MAX_HOPS } from './collected-urls-record'+import { FetchCandidatePool, FetchCandidatePoolLease, OriginPacing } from './fetch-candidate-pool'++const NOW_MS = 1_700_000_000_000++function candidate(url: string, registrableDomain: string): FetchCandidate {+ const parsed = new URL(url)+ return {+ originalRef: `imageurl:${url}`,+ currentUrl: url,+ host: parsed.host,+ origin: parsed.origin,+ registrableDomain,+ remainingHops: MAX_HOPS,+ notBeforeMs: 0,+ firstSeenAtMs: NOW_MS,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,+ }+}++function buildPool(+ crawlDelayMsByOrigin: Record<string, number> = {},+ limits: { maxConcurrentPerRegistrableDomain?: number; refillRunnableUrls?: number } = {}+): FetchCandidatePool<string> {+ const pacing: OriginPacing = {+ originCrawlDelayMs: (origin) => crawlDelayMsByOrigin[origin] ?? 0,+ originNextImageStartAtMs: () => 0,+ }+ return new FetchCandidatePool<string>(+ {+ maxConcurrentPerRegistrableDomain: limits.maxConcurrentPerRegistrableDomain ?? 2,+ refillRunnableUrls: limits.refillRunnableUrls ?? 3,+ maxQueuedUrlsPerOwner: 100,+ },+ pacing+ )+}++async function takeReady(pool: FetchCandidatePool<string>): Promise<FetchCandidatePoolLease<string> | undefined> {+ let lease: FetchCandidatePoolLease<string> | undefined+ let settled = false+ void pool.take().then((taken) => {+ lease = taken+ settled = true+ })+ await jest.advanceTimersByTimeAsync(0)+ if (!settled) {+ pool.close()+ await jest.advanceTimersByTimeAsync(0)+ }+ return lease+}++describe('FetchCandidatePool', () => {+ beforeEach(() => jest.useFakeTimers().setSystemTime(NOW_MS))+ afterEach(() => jest.useRealTimers())++ it('takes the oldest candidate of a domain under its limit, across batches from different partitions', async () => {+ const pool = buildPool()+ pool.add(+ [+ candidate('https://cdn.hot.com/1.png', 'hot.com'),+ candidate('https://cdn.hot.com/2.png', 'hot.com'),+ candidate('https://cdn.hot.com/3.png', 'hot.com'),+ ],+ 'partition-1',+ NOW_MS + 40_000+ )+ jest.advanceTimersByTime(10)+ pool.add([candidate('https://cdn.quiet.com/1.png', 'quiet.com')], 'partition-2', NOW_MS + 40_000)++ const leases = [await takeReady(pool), await takeReady(pool), await takeReady(pool)]++ expect(leases.map((lease) => lease?.candidate.currentUrl)).toEqual([+ 'https://cdn.hot.com/1.png',+ 'https://cdn.hot.com/2.png',+ 'https://cdn.quiet.com/1.png',+ ])+ expect(leases[2]?.context).toBe('partition-2')+ expect(await takeReady(pool)).toBeUndefined()+ })++ it('frees the domain slot on release, not before', async () => {+ const pool = buildPool({}, { maxConcurrentPerRegistrableDomain: 1 })+ pool.add(+ [candidate('https://cdn.hot.com/1.png', 'hot.com'), candidate('https://img.hot.com/2.png', 'hot.com')],+ 'partition-1',+ NOW_MS + 40_000+ )++ const first = await takeReady(pool)+ const waiting = pool.take()+ await jest.advanceTimersByTimeAsync(0)+ first?.release()++ expect((await waiting)?.candidate.currentUrl).toBe('https://img.hot.com/2.png')+ })++ it('holds an origin until its crawl delay passes while other origins keep running', async () => {+ const pool = buildPool({ 'https://slow.example.com': 5_000 })+ pool.add(+ [+ candidate('https://slow.example.com/1.png', 'example.com'),+ candidate('https://slow.example.com/2.png', 'example.com'),+ candidate('https://fast.other.net/1.png', 'other.net'),+ ],+ 'partition-1',+ NOW_MS + 40_000+ )++ const first = await takeReady(pool)+ const second = await takeReady(pool)+ const delayed = pool.take()+ await jest.advanceTimersByTimeAsync(4_999)+ let delayedTaken = false+ void delayed.then(() => {+ delayedTaken = true+ })+ await jest.advanceTimersByTimeAsync(0)+ expect(delayedTaken).toBe(false)+ await jest.advanceTimersByTimeAsync(1)++ expect([first, second, await delayed].map((lease) => lease?.candidate.currentUrl)).toEqual([+ 'https://slow.example.com/1.png',+ 'https://fast.other.net/1.png',+ 'https://slow.example.com/2.png',+ ])+ })++ it('hands out a batch past its deadline without a domain slot', async () => {+ const pool = buildPool({}, { maxConcurrentPerRegistrableDomain: 1 })+ pool.add(+ [candidate('https://cdn.hot.com/1.png', 'hot.com'), candidate('https://cdn.hot.com/2.png', 'hot.com')],+ 'partition-1',+ NOW_MS + 1_000+ )+ const held = await takeReady(pool)+ await jest.advanceTimersByTimeAsync(1_001)++ expect(held?.candidate.currentUrl).toBe('https://cdn.hot.com/1.png')+ expect((await takeReady(pool))?.candidate.currentUrl).toBe('https://cdn.hot.com/2.png')+ expect(pool.candidateCount).toBe(0)+ })++ it('withdraws the queued candidates of a failed batch only', async () => {+ const pool = buildPool()+ const failed = pool.add(+ [+ candidate('https://a.example.com/1.png', 'example.com'),+ candidate('https://b.example.com/2.png', 'example.com'),+ ],+ 'failed',+ NOW_MS + 40_000+ )+ pool.add([candidate('https://c.other.net/1.png', 'other.net')], 'healthy', NOW_MS + 40_000)++ await takeReady(pool)++ expect(pool.withdraw(failed)).toBe(1)+ expect((await takeReady(pool))?.context).toBe('healthy')+ expect(await takeReady(pool)).toBeUndefined()+ })++ it.each([+ ['counts a hot domain only up to its limit, so the owner still has room', 10, 'hot.com', true],+ ['has no room once enough distinct domains can run', 1, 'domain', false],+ ])('%s', (_name, urlsPerDomain, domainPrefix, expectedRoom) => {+ const pool = buildPool({}, { maxConcurrentPerRegistrableDomain: 2, refillRunnableUrls: 3 })+ const owner = pool.createOwner()+ const candidates = Array.from({ length: 10 }, (_unused, index) => {+ const domain = urlsPerDomain === 10 ? domainPrefix : `${domainPrefix}${index}.com`+ return candidate(`https://cdn.${domain}/${index}.png`, domain)+ })++ pool.add(candidates, 'partition-1', NOW_MS + 40_000, owner)++ expect(owner.queuedUrls).toBe(10)+ expect(owner.hasRoom()).toBe(expectedRoom)+ })++ it('keeps an owner without room while a batch waits for admission', async () => {+ const pool = buildPool()+ const owner = pool.createOwner()+ const admission = owner.beginAdmission()+ let hadRoom: boolean | undefined+ void owner.waitForRoom(30_000).then((room) => {+ hadRoom = room+ })+ await jest.advanceTimersByTimeAsync(0)+ expect(hadRoom).toBeUndefined()++ admission.admitted()+ await jest.advanceTimersByTimeAsync(0)++ expect(hadRoom).toBe(true)+ })++ it('gives an owner room when a fetch worker finds nothing eligible, even with runnable URLs queued', async () => {+ const pool = new FetchCandidatePool<string>(+ { maxConcurrentPerRegistrableDomain: 2, refillRunnableUrls: 3, maxQueuedUrlsPerOwner: 100 },+ { originCrawlDelayMs: () => 5_000, originNextImageStartAtMs: () => NOW_MS + 5_000 }+ )+ const owner = pool.createOwner()+ const delayedCandidates = Array.from({ length: 5 }, (_unused, index) =>+ candidate(`https://cdn.site${index}.com/a.png`, `site${index}.com`)+ )+ pool.add(delayedCandidates, 'partition-1', NOW_MS + 40_000, owner)+ let hadRoom: boolean | undefined+ void owner.waitForRoom(30_000).then((room) => {+ hadRoom = room+ })+ await jest.advanceTimersByTimeAsync(0)+ expect(owner.hasRoom()).toBe(false)+ expect(hadRoom).toBeUndefined()++ void pool.take()+ await jest.advanceTimersByTimeAsync(0)++ expect(hadRoom).toBe(true)+ pool.close()+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.tsnew file mode 100644index 000000000000..1f3627b165ee--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool.ts@@ -0,0 +1,605 @@+import { FetchCandidate } from './collected-urls-record'+import { IndexedPriorityQueue } from './fetch-candidate-queue'++export interface FetchCandidatePoolLimits {+ refillRunnableUrls: number+ maxQueuedUrlsPerOwner: number+}++export interface FetchCandidatePoolOptions extends FetchCandidatePoolLimits {+ maxConcurrentPerRegistrableDomain: number+}++export interface OriginPacing {+ originCrawlDelayMs(origin: string): number+ originNextImageStartAtMs(origin: string): number+}++export interface FetchCandidatePoolLease<T> {+ candidate: FetchCandidate+ context: T+ waitedMs: number+ release(): void+}++export interface FetchCandidatePoolAdmission {+ owner: FetchCandidatePoolOwner+ admitted(): void+}++type EntryState = 'queued' | 'expired' | 'taken' | 'withdrawn'++interface EntryPayload<T> {+ candidate: FetchCandidate+ context: T+ batch: PoolBatch<T>+}++interface PoolEntry<T> {+ /** Cleared once the entry leaves the pool, because a spent entry can stay in its origin array until compaction. */+ payload: EntryPayload<T> | undefined+ sequence: number+ enqueuedAtMs: number+ state: EntryState+ origin: OriginQueue<T>+}++interface OriginQueue<T> {+ origin: string+ domain: DomainQueue<T>+ entries: PoolEntry<T>[]+ head: number+ queued: number+ active: number+ pacedUntilMs: number+ delayed: DelayedOrigin<T> | undefined+ heapIndex: number+}++interface DomainQueue<T> {+ registrableDomain: string+ origins: Map<string, OriginQueue<T>>+ eligibleOrigins: IndexedPriorityQueue<OriginQueue<T>>+ active: number+ heapIndex: number+}++interface DelayedOrigin<T> {+ origin: OriginQueue<T>+ readyAtMs: number+ heapIndex: number+}++export interface PoolBatch<T> {+ readonly owner: FetchCandidatePoolOwner | undefined+ readonly entries: PoolEntry<T>[]+ queued: number+ expiryTimer: NodeJS.Timeout | undefined+}++const COMPACT_AFTER_ENTRIES = 64++/**+ * One queue of fetch candidates for the whole pod.+ *+ * Every consumer's batch adds its candidates here, and the fetch workers take them in the order they+ * entered the pool, among the origins that are under their limits and past their crawl delay. The+ * order uses pool entry and not record age, because the pass deadline and the batch timeout count+ * from when the pod received the batch. The limits count across the pod, so two batches from one+ * partition cannot both claim a domain's slots.+ */+export class FetchCandidatePool<T> {+ private readonly domains = new Map<string, DomainQueue<T>>()+ private readonly eligibleDomains = new IndexedPriorityQueue<DomainQueue<T>>(domainHasOlderHead)+ private readonly delayedOrigins = new IndexedPriorityQueue<DelayedOrigin<T>>(+ (left, right) => left.readyAtMs < right.readyAtMs+ )+ private delayTimer: NodeJS.Timeout | undefined+ private delayTimerAtMs = Number.POSITIVE_INFINITY+ private expired: PoolEntry<T>[] = []+ private expiredHead = 0+ private waiters: (() => void)[] = []+ private readonly owners: FetchCandidatePoolOwner[] = []+ private sequence = 0+ private queuedCount = 0+ private closed = false++ constructor(+ private readonly options: FetchCandidatePoolOptions,+ private readonly pacing: OriginPacing+ ) {+ for (const [name, value] of Object.entries(options)) {+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new Error(`the image fetch candidate pool ${name} must be a positive integer, got ${value}`)+ }+ }+ }++ public get candidateCount(): number {+ return this.queuedCount + (this.expired.length - this.expiredHead)+ }++ public createOwner(): FetchCandidatePoolOwner {+ const owner = new FetchCandidatePoolOwner(this.options)+ this.owners.push(owner)+ return owner+ }++ public add(+ candidates: FetchCandidate[],+ context: T,+ deadlineMs: number,+ owner?: FetchCandidatePoolOwner+ ): PoolBatch<T> {+ if (this.closed) {+ throw new Error('the image fetch candidate pool is closed, so no worker would take these candidates')+ }+ const nowMs = Date.now()+ const batch: PoolBatch<T> = { owner, entries: [], queued: 0, expiryTimer: undefined }+ const touched = new Set<OriginQueue<T>>()+ for (const candidate of candidates) {+ const origin = this.originQueueFor(candidate)+ const entry: PoolEntry<T> = {+ payload: { candidate, context, batch },+ sequence: this.sequence++,+ enqueuedAtMs: nowMs,+ state: 'queued',+ origin,+ }+ origin.entries.push(entry)+ origin.queued += 1+ batch.entries.push(entry)+ batch.queued += 1+ this.queuedCount += 1+ owner?.recordQueued(candidate.registrableDomain)+ touched.add(origin)+ }+ for (const origin of touched) {+ this.refreshOrigin(origin, nowMs)+ }+ if (batch.queued > 0) {+ // The fetch path treats a candidate as late only once the clock is past the deadline.+ batch.expiryTimer = setTimeout(() => this.expire(batch), Math.max(0, deadlineMs - nowMs) + 1)+ batch.expiryTimer.unref()+ this.wake(1)+ }+ return batch+ }++ public async take(): Promise<FetchCandidatePoolLease<T> | undefined> {+ for (;;) {+ if (this.closed) {+ return undefined+ }+ const lease = this.tryTake()+ if (lease) {+ if (this.hasSelectableWork()) {+ this.wake(1)+ }+ return lease+ }+ for (const owner of this.owners) {+ owner.recordIdleWorker()+ }+ await new Promise<void>((resolve) => this.waiters.push(resolve))+ }+ }++ /** Removes the batch's candidates that no worker has taken, and returns how many it removed. */+ public withdraw(batch: PoolBatch<T>): number {+ const touched = new Set<OriginQueue<T>>()+ let withdrawn = 0+ for (const entry of batch.entries) {+ if (entry.state === 'queued') {+ this.leaveOriginQueue(entry)+ touched.add(entry.origin)+ } else if (entry.state !== 'expired') {+ continue+ }+ entry.state = 'withdrawn'+ entry.payload = undefined+ withdrawn += 1+ }+ this.clearExpiry(batch)+ const nowMs = Date.now()+ for (const origin of touched) {+ this.refreshOrigin(origin, nowMs)+ }+ return withdrawn+ }++ public close(): void {+ this.closed = true+ if (this.delayTimer) {+ clearTimeout(this.delayTimer)+ this.delayTimer = undefined+ }+ this.wake(this.waiters.length)+ }++ private tryTake(): FetchCandidatePoolLease<T> | undefined {+ const expiredEntry = this.nextExpired()+ if (expiredEntry) {+ expiredEntry.state = 'taken'+ return this.lease(expiredEntry, Date.now(), () => undefined)+ }+ const domain = this.eligibleDomains.peek()+ if (!domain) {+ return undefined+ }+ const origin = domain.eligibleOrigins.peek()!+ const entry = origin.entries[origin.head]+ const nowMs = Date.now()+ this.leaveOriginQueue(entry)+ entry.state = 'taken'+ origin.active += 1+ domain.active += 1+ const crawlDelayMs = this.pacing.originCrawlDelayMs(origin.origin)+ if (crawlDelayMs > 0) {+ origin.pacedUntilMs = Math.max(nowMs, origin.pacedUntilMs) + crawlDelayMs+ }+ this.refreshOrigin(origin, nowMs)+ let released = false+ return this.lease(entry, nowMs, () => {+ if (released) {+ return+ }+ released = true+ origin.active -= 1+ domain.active -= 1+ this.refreshOrigin(origin, Date.now())+ this.wake(1)+ })+ }++ private lease(entry: PoolEntry<T>, nowMs: number, release: () => void): FetchCandidatePoolLease<T> {+ const { candidate, context } = entry.payload!+ entry.payload = undefined+ return {+ candidate,+ context,+ waitedMs: Math.max(0, nowMs - entry.enqueuedAtMs),+ release,+ }+ }++ private leaveOriginQueue(entry: PoolEntry<T>): void {+ const { batch, candidate } = entry.payload!+ entry.origin.queued -= 1+ batch.queued -= 1+ this.queuedCount -= 1+ batch.owner?.recordLeft(candidate.registrableDomain)+ if (batch.queued === 0) {+ this.clearExpiry(batch)+ }+ }++ private expire(batch: PoolBatch<T>): void {+ batch.expiryTimer = undefined+ const touched = new Set<OriginQueue<T>>()+ for (const entry of batch.entries) {+ if (entry.state !== 'queued') {+ continue+ }+ this.leaveOriginQueue(entry)+ entry.state = 'expired'+ this.expired.push(entry)+ touched.add(entry.origin)+ }+ const nowMs = Date.now()+ for (const origin of touched) {+ this.refreshOrigin(origin, nowMs)+ }+ this.wake(1)+ }++ private clearExpiry(batch: PoolBatch<T>): void {+ if (batch.expiryTimer) {+ clearTimeout(batch.expiryTimer)+ batch.expiryTimer = undefined+ }+ }++ private nextExpired(): PoolEntry<T> | undefined {+ while (this.expiredHead < this.expired.length) {+ const entry = this.expired[this.expiredHead++]+ if (entry.state === 'expired') {+ this.compactExpired()+ return entry+ }+ }+ this.compactExpired()+ return undefined+ }++ private compactExpired(): void {+ if (this.expiredHead === this.expired.length) {+ this.expired = []+ this.expiredHead = 0+ } else if (this.expiredHead > COMPACT_AFTER_ENTRIES && this.expiredHead * 2 > this.expired.length) {+ this.expired = this.expired.slice(this.expiredHead)+ this.expiredHead = 0+ }+ }++ private hasSelectableWork(): boolean {+ for (let index = this.expiredHead; index < this.expired.length; index++) {+ if (this.expired[index].state === 'expired') {+ return true+ }+ }+ return this.eligibleDomains.size > 0+ }++ private wake(count: number): void {+ for (let woken = 0; woken < count && this.waiters.length > 0; woken++) {+ this.waiters.shift()!()+ }+ }++ private originQueueFor(candidate: FetchCandidate): OriginQueue<T> {+ let domain = this.domains.get(candidate.registrableDomain)+ if (!domain) {+ domain = {+ registrableDomain: candidate.registrableDomain,+ origins: new Map(),+ eligibleOrigins: new IndexedPriorityQueue<OriginQueue<T>>(originHasOlderHead),+ active: 0,+ heapIndex: -1,+ }+ this.domains.set(candidate.registrableDomain, domain)+ }+ let origin = domain.origins.get(candidate.origin)+ if (!origin) {+ origin = {+ origin: candidate.origin,+ domain,+ entries: [],+ head: 0,+ queued: 0,+ active: 0,+ pacedUntilMs: 0,+ delayed: undefined,+ heapIndex: -1,+ }+ domain.origins.set(candidate.origin, origin)+ }+ return origin+ }++ private refreshOrigin(origin: OriginQueue<T>, nowMs: number): void {+ this.advanceHead(origin)+ const domain = origin.domain+ if (origin.queued === 0 || origin.active >= this.options.maxConcurrentPerRegistrableDomain) {+ domain.eligibleOrigins.remove(origin)+ this.undelay(origin)+ if (origin.queued === 0 && origin.active === 0) {+ domain.origins.delete(origin.origin)+ }+ } else {+ const readyAtMs = Math.max(origin.pacedUntilMs, this.pacing.originNextImageStartAtMs(origin.origin))+ if (readyAtMs > nowMs) {+ domain.eligibleOrigins.remove(origin)+ this.delay(origin, readyAtMs)+ } else {+ this.undelay(origin)+ domain.eligibleOrigins.addOrUpdate(origin)+ }+ }+ this.refreshDomain(domain)+ }++ private refreshDomain(domain: DomainQueue<T>): void {+ if (domain.origins.size === 0 && domain.active === 0) {+ this.eligibleDomains.remove(domain)+ if (this.domains.get(domain.registrableDomain) === domain) {+ this.domains.delete(domain.registrableDomain)+ }+ return+ }+ if (domain.active < this.options.maxConcurrentPerRegistrableDomain && domain.eligibleOrigins.size > 0) {+ this.eligibleDomains.addOrUpdate(domain)+ } else {+ this.eligibleDomains.remove(domain)+ }+ }++ private advanceHead(origin: OriginQueue<T>): void {+ while (origin.head < origin.entries.length && origin.entries[origin.head].state !== 'queued') {+ origin.head += 1+ }+ if (origin.head === origin.entries.length) {+ origin.entries = []+ origin.head = 0+ } else if (origin.head > COMPACT_AFTER_ENTRIES && origin.head * 2 > origin.entries.length) {+ origin.entries = origin.entries.slice(origin.head)+ origin.head = 0+ }+ }++ private delay(origin: OriginQueue<T>, readyAtMs: number): void {+ if (origin.delayed) {+ origin.delayed.readyAtMs = readyAtMs+ this.delayedOrigins.addOrUpdate(origin.delayed)+ } else {+ origin.delayed = { origin, readyAtMs, heapIndex: -1 }+ this.delayedOrigins.addOrUpdate(origin.delayed)+ }+ this.armDelayTimer()+ }++ private undelay(origin: OriginQueue<T>): void {+ if (!origin.delayed) {+ return+ }+ this.delayedOrigins.remove(origin.delayed)+ origin.delayed = undefined+ this.armDelayTimer()+ }++ private armDelayTimer(): void {+ const next = this.delayedOrigins.peek()+ const nextAtMs = next?.readyAtMs ?? Number.POSITIVE_INFINITY+ if (nextAtMs === this.delayTimerAtMs || this.closed) {+ return+ }+ if (this.delayTimer) {+ clearTimeout(this.delayTimer)+ this.delayTimer = undefined+ }+ this.delayTimerAtMs = nextAtMs+ if (next) {+ this.delayTimer = setTimeout(() => this.releaseDelayedOrigins(), Math.max(0, nextAtMs - Date.now()))+ this.delayTimer.unref()+ }+ }++ private releaseDelayedOrigins(): void {+ this.delayTimer = undefined+ this.delayTimerAtMs = Number.POSITIVE_INFINITY+ const nowMs = Date.now()+ for (+ let next = this.delayedOrigins.peek();+ next && next.readyAtMs <= nowMs;+ next = this.delayedOrigins.peek()+ ) {+ this.delayedOrigins.remove(next)+ next.origin.delayed = undefined+ this.refreshOrigin(next.origin, nowMs)+ }+ this.armDelayTimer()+ if (this.eligibleDomains.size > 0) {+ this.wake(1)+ }+ }+}++/**+ * The window of one consumer: how much of its work waits in the pool.+ *+ * A registrable domain counts as runnable only up to its concurrency limit, because the pool never+ * runs more than that at once. A window full of one hot domain therefore still lets the consumer+ * read more, so its other domains do not wait in Kafka while candidate slots are free.+ */+export class FetchCandidatePoolOwner {+ private queued = 0+ private runnable = 0+ private pendingAdmissions = 0+ private readonly queuedByDomain = new Map<string, number>()+ private readonly roomWaiters = new Set<() => void>()++ constructor(private readonly options: FetchCandidatePoolOptions) {}++ public get queuedUrls(): number {+ return this.queued+ }++ public get runnableUrls(): number {+ return this.runnable+ }++ public beginAdmission(): FetchCandidatePoolAdmission {+ this.pendingAdmissions += 1+ let done = false+ return {+ owner: this,+ admitted: () => {+ if (done) {+ return+ }+ done = true+ this.pendingAdmissions -= 1+ this.notifyIfRoom()+ },+ }+ }++ public hasRoom(): boolean {+ return (+ this.pendingAdmissions === 0 &&+ this.runnable < this.options.refillRunnableUrls &&+ this.queued < this.options.maxQueuedUrlsPerOwner+ )+ }++ /** Resolves true when the owner has room for another batch, or false when the wait runs out. */+ public waitForRoom(maxWaitMs: number): Promise<boolean> {+ if (this.hasRoom()) {+ return Promise.resolve(true)+ }+ return new Promise((resolve) => {+ const waiter = (): void => {+ clearTimeout(timer)+ resolve(true)+ }+ const timer = setTimeout(() => {+ this.roomWaiters.delete(waiter)+ resolve(false)+ }, maxWaitMs)+ this.roomWaiters.add(waiter)+ })+ }++ public recordQueued(registrableDomain: string): void {+ this.queued += 1+ this.changeDomainCount(registrableDomain, 1)+ }++ public recordLeft(registrableDomain: string): void {+ this.queued -= 1+ this.changeDomainCount(registrableDomain, -1)+ this.notifyIfRoom()+ }++ /**+ * A fetch worker found no eligible candidate. Queued URLs that count as runnable can still be+ * unable to run, for example behind a crawl delay or behind another member's hold on a domain,+ * so the member reads more while it is under the queue limit.+ */+ public recordIdleWorker(): void {+ if (this.pendingAdmissions === 0 && this.queued < this.options.maxQueuedUrlsPerOwner) {+ this.releaseRoomWaiters()+ }+ }++ private changeDomainCount(registrableDomain: string, delta: number): void {+ const limit = this.options.maxConcurrentPerRegistrableDomain+ const before = this.queuedByDomain.get(registrableDomain) ?? 0+ const after = before + delta+ if (after === 0) {+ this.queuedByDomain.delete(registrableDomain)+ } else {+ this.queuedByDomain.set(registrableDomain, after)+ }+ this.runnable += Math.min(after, limit) - Math.min(before, limit)+ }++ private notifyIfRoom(): void {+ if (this.hasRoom()) {+ this.releaseRoomWaiters()+ }+ }++ private releaseRoomWaiters(): void {+ if (this.roomWaiters.size === 0) {+ return+ }+ const waiters = [...this.roomWaiters]+ this.roomWaiters.clear()+ for (const waiter of waiters) {+ waiter()+ }+ }+}++function originHeadSequence<T>(origin: OriginQueue<T>): number {+ return origin.entries[origin.head].sequence+}++function originHasOlderHead<T>(left: OriginQueue<T>, right: OriginQueue<T>): boolean {+ return originHeadSequence(left) < originHeadSequence(right)+}++function domainHasOlderHead<T>(left: DomainQueue<T>, right: DomainQueue<T>): boolean {+ return originHeadSequence(left.eligibleOrigins.peek()!) < originHeadSequence(right.eligibleOrigins.peek()!)+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.tsindex f4696ce715ff..293df89aabed 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-queue.ts@@ -29,11 +29,11 @@ interface RegistrableDomainQueue {heapIndex: number}-interface IndexedPriorityQueueItem {+export interface IndexedPriorityQueueItem {heapIndex: number}-class IndexedPriorityQueue<T extends IndexedPriorityQueueItem> {+export class IndexedPriorityQueue<T extends IndexedPriorityQueueItem> {private readonly heap: T[] = []constructor(private readonly hasPriority: (left: T, right: T) => boolean) {}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 ff9e9c6715e9..6975e6c0423a 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@@ -21,6 +21,11 @@ const OPTIONS: FetchRunnerOptions = {maxRedirects: 3,seenTtlSeconds: 30 * 24 * 60 * 60,}+const POOL_OPTIONS: FetchRunnerOptions = {+ ...OPTIONS,+ continuousPool: { refillRunnableUrls: 100, maxQueuedUrlsPerOwner: 1_000 },+}+const builtRunners: FetchRunner[] = []function candidate(overrides: Partial<FetchCandidate> = {}): FetchCandidate {return {@@ -101,12 +106,14 @@ function build({ createRepublishBatch, publishImage } as unknown as FrontierPublisher,new ImageFetchTopHogMetrics(recordingTopHog.registry))+ builtRunners.push(runner)return { runner, budget, fetch, check, createPass, republish, publishImage, topHogRecords: recordingTopHog.records }}describe('FetchRunner', () => {beforeEach(() => jest.useFakeTimers().setSystemTime(NOW_MS))- afterEach(() => {+ afterEach(async () => {+ await Promise.all(builtRunners.splice(0).map((runner) => runner.close()))jest.useRealTimers()jest.restoreAllMocks()})@@ -143,9 +150,12 @@ describe('FetchRunner', () => {})})- it('publishes an accepted image and records a terminal URL result', async () => {+ it.each([+ ['a fetch pass', OPTIONS],+ ['the pod candidate pool', POOL_OPTIONS],+ ])('publishes an accepted image and records a terminal URL result through %s', async (_mode, options) => {const bytes = Buffer.from('image')- const harness = build({ bytes, contentType: 'image/png' })+ const harness = build({ bytes, contentType: 'image/png' }, {}, 'queued', options)const [attempt] = await harness.runner.run([candidate()], new Map())@@ -419,6 +429,70 @@ describe('FetchRunner', () => {await Promise.all([firstRun, secondRun])})+ it('finishes a pooled batch with queued candidates before close stops the pool', async () => {+ const harness = build({}, {}, 'queued', { ...POOL_OPTIONS, maxInFlightRequests: 1 })+ let releaseFirst: () => void = () => undefined+ harness.fetch.mockImplementationOnce(+ (url: string) =>+ new Promise<ImageFetchResult>((resolve) => {+ releaseFirst = () => resolve({ outcome: 'ok', redirects: 0, currentUrl: url })+ })+ )+ const queued = candidate({+ originalRef: `imageurl:${'b'.repeat(22)}`,+ currentUrl: 'https://cdn.other.net/b.png',+ host: 'cdn.other.net',+ origin: 'https://cdn.other.net',+ registrableDomain: 'other.net',+ })++ const run = harness.runner.run([candidate(), queued], new Map())+ await jest.advanceTimersByTimeAsync(0)+ let closed = false+ const close = harness.runner.close().then(() => {+ closed = true+ })+ await jest.advanceTimersByTimeAsync(0)+ expect(closed).toBe(false)+ releaseFirst()+ await jest.advanceTimersByTimeAsync(0)++ expect((await run).map((attempt) => attempt.candidate.currentUrl)).toEqual([+ candidate().currentUrl,+ queued.currentUrl,+ ])+ await close+ })++ it('shares one registrable domain limit between batches in the pod candidate pool', async () => {+ const harness = build({}, {}, 'queued', POOL_OPTIONS)+ const releases: Array<() => void> = []+ harness.fetch.mockImplementation(+ (url: string) =>+ new Promise<ImageFetchResult>((resolve) => {+ releases.push(() => resolve({ outcome: 'ok', redirects: 0, currentUrl: url }))+ })+ )+ const onOrigin = (label: string): FetchCandidate =>+ candidate({+ originalRef: `imageurl:${label.repeat(22)}`,+ currentUrl: `https://${label}.example.com/a.png`,+ host: `${label}.example.com`,+ origin: `https://${label}.example.com`,+ })++ const firstBatch = harness.runner.run([onOrigin('a'), onOrigin('b')], new Map())+ const secondBatch = harness.runner.run([onOrigin('c'), onOrigin('d')], new Map())+ await jest.advanceTimersByTimeAsync(0)++ expect(harness.fetch).toHaveBeenCalledTimes(2)+ releases.splice(0).forEach((release) => release())+ await jest.advanceTimersByTimeAsync(0)+ expect(harness.fetch).toHaveBeenCalledTimes(4)+ releases.splice(0).forEach((release) => release())+ await Promise.all([firstBatch, secondBatch])+ })+it('does not start a queued request after another worker aborts its pass', async () => {const harness = build({}, {}, 'queued', { ...OPTIONS, maxInFlightRequests: 2 })let releaseBlocker: () => void = () => undefined@@ -462,8 +536,11 @@ describe('FetchRunner', () => {await blockingRun})- it('stops taking queue work after a fatal candidate error', async () => {- const harness = build({}, {}, 'queued', { ...OPTIONS, maxInFlightRequests: 1 })+ it.each([+ ['a fetch pass', OPTIONS],+ ['the pod candidate pool', POOL_OPTIONS],+ ])('stops taking queue work after a fatal candidate error in %s', async (_mode, options) => {+ const harness = build({}, {}, 'queued', { ...options, maxInFlightRequests: 1 })harness.fetch.mockRejectedValueOnce(new Error('dependency unavailable'))const second = candidate({ originalRef: `imageurl:${'b'.repeat(22)}` })@@ -483,8 +560,11 @@ describe('FetchRunner', () => {expect(attempts[0].candidate).toMatchObject({ republishCount: 1, lastRepublishReason: 'retry' })})- it('marks an image publish failure as lost after all candidate work settles', async () => {- const harness = build({ bytes: Buffer.from('image'), contentType: 'image/png' })+ it.each([+ ['a fetch pass', OPTIONS],+ ['the pod candidate pool', POOL_OPTIONS],+ ])('marks an image publish failure as lost after all candidate work settles in %s', async (_mode, options) => {+ const harness = build({ bytes: Buffer.from('image'), contentType: 'image/png' }, {}, 'queued', options)harness.publishImage.mockRejectedValue(new Error('queue full'))const [attempt] = await harness.runner.run([candidate()], new Map())@@ -634,8 +714,11 @@ describe('FetchRunner', () => {expect(harness.republish).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), 'not_ready', 600_000)})- it('returns pass-deadline work directly to the frontier', async () => {- const harness = build({}, {}, 'queued', { ...OPTIONS, batchBudgetMs: -1 })+ it.each([+ ['a fetch pass', OPTIONS],+ ['the pod candidate pool', POOL_OPTIONS],+ ])('returns pass-deadline work directly to the frontier from %s', async (_mode, options) => {+ const harness = build({}, {}, 'queued', { ...options, batchBudgetMs: -1 })await harness.runner.run([candidate()], new Map())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 57226e32f12e..6364727b628e 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@@ -6,7 +6,13 @@ import { fetchCandidateHistoryKey } from './collected-urls-record'import { FetchCandidate, MAX_HOPS, RepublishReason } from './collected-urls-record'import { ConfigurationPolicyPass, ConfigurationPolicyService } from './configuration-policy'import { ConfigurationCacheItem, CrawlHistoryItem, HttpCacheMetadata, UrlCrawlHistoryItem } from './crawl-history'-import { FetchCandidateLease, FetchCandidateQueue } from './fetch-candidate-queue'+import {+ FetchCandidatePool,+ FetchCandidatePoolAdmission,+ FetchCandidatePoolLimits,+ PoolBatch,+} from './fetch-candidate-pool'+import { FetchCandidateLease, FetchCandidateQueue, deduplicateFetchCandidates } from './fetch-candidate-queue'import { FrontierPublisher, RepublishBatch, RepublishResult } from './frontier-publisher'import { HostBudget } from './host-budget'import {@@ -16,7 +22,7 @@ import {RequestScheduleBlockReason,TransientFetchOutcome,} from './image-fetcher'-import { ImageFetchRequestMetrics } from './metrics'+import { ImageFetchPoolMetrics, ImageFetchRequestMetrics } from './metrics'import { OriginRequestScheduler } from './origin-request-scheduler'import { canonicalizeUrl } from './politeness-key'import { ImageFetchProcessingMetrics } from './processing-metrics'@@ -58,6 +64,8 @@ export interface FetchRunnerOptions {requestTimeoutMs: numbermaxRedirects: numberseenTtlSeconds: number+ /** Set to run every batch through one pod-wide candidate pool instead of a fetch pass of its own. */+ continuousPool?: FetchCandidatePoolLimits}const TRANSIENT_OUTCOMES = new Set<TransientFetchOutcome>(['timeout', 'error', 'rate_limited', 'server_error'])@@ -90,7 +98,8 @@ export interface FetchPass {run(candidates: FetchCandidate[],stored: Map<string, CrawlHistoryItem>,- republishBatch?: RepublishBatch+ republishBatch?: RepublishBatch,+ admission?: FetchCandidatePoolAdmission): Promise<FetchAttempt[]>}@@ -98,8 +107,24 @@ interface FetchPassState {failure?: { error: unknown }}+interface PooledBatch {+ stored: Map<string, CrawlHistoryItem>+ configurationItems: Map<string, ConfigurationCacheItem>+ configurationPolicy: ConfigurationPolicyPass+ deadlineMs: number+ republishBatch: RepublishBatch+ state: FetchPassState+ attempts: FetchAttempt[]+ unsettled: number+ poolBatch?: PoolBatch<PooledBatch>+ settle: () => void+}+export class FetchRunner implements FetchPass {private readonly candidateWork: ConcurrencyController+ private readonly pool?: FetchCandidatePool<PooledBatch>+ private poolWorkers?: Promise<void>[]+ private readonly activePooledBatches = new Set<Promise<FetchAttempt[]>>()constructor(private readonly fetcher: ImageFetcher,@@ -126,9 +151,52 @@ export class FetchRunner implements FetchPass {}this.candidateWork = new ConcurrencyController(options.maxInFlightRequests)ImageFetchRequestMetrics.trackBudget(budget, scheduler)+ if (options.continuousPool) {+ this.pool = new FetchCandidatePool<PooledBatch>(+ {+ ...options.continuousPool,+ maxConcurrentPerRegistrableDomain: options.maxConcurrentPerRegistrableDomain,+ },+ budget+ )+ ImageFetchProcessingMetrics.trackQueue(this.pool)+ }+ }++ public get candidatePool(): FetchCandidatePool<PooledBatch> | undefined {+ return this.pool}public async run(+ candidates: FetchCandidate[],+ stored: Map<string, CrawlHistoryItem>,+ republishBatch?: RepublishBatch,+ admission?: FetchCandidatePoolAdmission+ ): Promise<FetchAttempt[]> {+ if (this.pool) {+ const pooledBatch = this.runPooled(this.pool, candidates, stored, republishBatch, admission)+ this.activePooledBatches.add(pooledBatch)+ try {+ return await pooledBatch+ } finally {+ this.activePooledBatches.delete(pooledBatch)+ }+ }+ admission?.admitted()+ return await this.runPass(candidates, stored, republishBatch)+ }++ /**+ * Waits for every pooled batch before it stops the workers. The Kafka consumer drain on shutdown+ * has a timeout, and a batch that outlives it still needs the workers to take its queued candidates.+ */+ public async close(): Promise<void> {+ await Promise.allSettled(this.activePooledBatches)+ this.pool?.close()+ await Promise.all(this.poolWorkers ?? [])+ }++ private async runPass(candidates: FetchCandidate[],stored: Map<string, CrawlHistoryItem>,republishBatch?: RepublishBatch@@ -137,12 +205,7 @@ export class FetchRunner implements FetchPass {const deadlineMs = Date.now() + this.options.batchBudgetMsconst configurationPolicy = this.configurationPolicy.createPass()const passState: FetchPassState = {}- const configurationItems = new Map<string, ConfigurationCacheItem>()- for (const [key, item] of stored) {- if (item.kind === 'robots' || item.kind === 'tdmrep') {- configurationItems.set(key, item)- }- }+ const configurationItems = configurationItemsFrom(stored)const queue = new FetchCandidateQueue(candidates, this.options)this.topHogMetrics?.recordConcurrencyLimitedUrls(candidates, (registrableDomain) =>this.budget.availableConnections(registrableDomain, this.options.maxConcurrentPerRegistrableDomain)@@ -183,8 +246,116 @@ export class FetchRunner implements FetchPass {if (failedWorker) {throw failedWorker.reason}- if (!republishBatch) {- const result = await activeRepublishBatch.flush()+ return await this.finishPass(attempts, activeRepublishBatch, !republishBatch)+ }++ private async runPooled(+ pool: FetchCandidatePool<PooledBatch>,+ candidates: FetchCandidate[],+ stored: Map<string, CrawlHistoryItem>,+ republishBatch: RepublishBatch | undefined,+ admission: FetchCandidatePoolAdmission | undefined+ ): Promise<FetchAttempt[]> {+ const activeRepublishBatch = republishBatch ?? this.publisher.createRepublishBatch()+ const { candidates: unique } = deduplicateFetchCandidates(candidates)+ this.topHogMetrics?.recordConcurrencyLimitedUrls(unique, (registrableDomain) =>+ this.budget.availableConnections(registrableDomain, this.options.maxConcurrentPerRegistrableDomain)+ )+ let settle: () => void = () => undefined+ const settled = new Promise<void>((resolve) => {+ settle = resolve+ })+ const batch: PooledBatch = {+ stored,+ configurationItems: configurationItemsFrom(stored),+ configurationPolicy: this.configurationPolicy.createPass(),+ deadlineMs: Date.now() + this.options.batchBudgetMs,+ republishBatch: activeRepublishBatch,+ state: {},+ attempts: [],+ unsettled: unique.length,+ settle,+ }+ this.startPoolWorkers(pool)+ try {+ batch.poolBatch = pool.add(unique, batch, batch.deadlineMs, admission?.owner)+ } finally {+ admission?.admitted()+ }+ if (batch.unsettled === 0) {+ settle()+ }+ await settled+ if (batch.state.failure) {+ throw batch.state.failure.error+ }+ return await this.finishPass(batch.attempts, activeRepublishBatch, !republishBatch)+ }++ private startPoolWorkers(pool: FetchCandidatePool<PooledBatch>): void {+ this.poolWorkers ??= Array.from({ length: this.options.maxInFlightRequests }, () => this.runPoolWorker(pool))+ }++ private async runPoolWorker(pool: FetchCandidatePool<PooledBatch>): Promise<void> {+ for (;;) {+ const lease = await pool.take()+ if (!lease) {+ return+ }+ ImageFetchPoolMetrics.observeWait(lease.waitedMs / 1000)+ let signalSlotReleased: () => void = () => undefined+ const slotReleased = new Promise<void>((resolve) => {+ signalSlotReleased = resolve+ })+ const releaseRegistrableDomainSlot = (): void => {+ lease.release()+ signalSlotReleased()+ }+ const work = this.processPooledLease(pool, lease, releaseRegistrableDomainSlot)+ await Promise.race([slotReleased, work])+ }+ }++ private async processPooledLease(+ pool: FetchCandidatePool<PooledBatch>,+ lease: FetchCandidateLease & { context: PooledBatch },+ releaseRegistrableDomainSlot: () => void+ ): Promise<void> {+ const batch = lease.context+ try {+ batch.attempts.push(+ await this.processLease(+ lease,+ batch.stored,+ batch.configurationItems,+ batch.configurationPolicy,+ batch.deadlineMs,+ batch.republishBatch,+ batch.state,+ releaseRegistrableDomainSlot+ )+ )+ } catch (error) {+ batch.state.failure ??= { error }+ if (batch.poolBatch) {+ batch.unsettled -= pool.withdraw(batch.poolBatch)+ }+ } finally {+ releaseRegistrableDomainSlot()+ batch.unsettled -= 1+ if (batch.unsettled <= 0) {+ batch.settle()+ }+ }+ }++ private async finishPass(+ attempts: FetchAttempt[],+ republishBatch: RepublishBatch,+ flushRepublishBatch: boolean+ ): Promise<FetchAttempt[]> {+ if (flushRepublishBatch) {+ const result = await republishBatch.flush()if (result.failedUrls > 0) {throw new Error(`the image fetch lane could not account for ${result.failedUrls} URLs`)}@@ -687,3 +858,13 @@ function mergeCache(function withoutValidators(cache: HttpCacheMetadata | undefined): HttpCacheMetadata | undefined {return cache ? { ...cache, etag: undefined, lastModified: undefined } : undefined}++function configurationItemsFrom(stored: Map<string, CrawlHistoryItem>): Map<string, ConfigurationCacheItem> {+ const configurationItems = new Map<string, ConfigurationCacheItem>()+ for (const [key, item] of stored) {+ if (item.kind === 'robots' || item.kind === 'tdmrep') {+ configurationItems.set(key, item)+ }+ }+ return configurationItems+}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 03ceb6ca91ae..d57f4584dfa1 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@@ -262,6 +262,18 @@ export class HostBudget {return true}+ public originCrawlDelayMs(origin: string): number {+ return this.origins.get(origin)?.crawlDelayMs ?? 0+ }++ public originNextImageStartAtMs(origin: string): number {+ const state = this.origins.get(origin)+ if (!state || state.lastRequestStartedAtMs === null) {+ return 0+ }+ return state.lastRequestStartedAtMs + state.crawlDelayMs+ }+public recordTransientFailure(registrableDomain: string, nowMs: number, retryAfterMs?: number): number {const state = this.registrableDomainStateFor(registrableDomain, nowMs)if (!state) {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 c6ed9aa2cdd8..9feb46ef522d 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@@ -653,3 +653,24 @@ export class RetryDelayMetrics {this.waitSeconds.observe(waitSeconds)}}++export class ImageFetchPoolMetrics {+ private static readonly waitSeconds = new Histogram({+ name: 'ml_image_fetch_pool_wait_seconds',+ help: 'Time a candidate waited in the pod candidate pool before a fetch worker took it',+ buckets: [0, 0.1, 0.5, 1, 2, 5, 10, 20, 40],+ })+ private static readonly refillWaitSeconds = new Histogram({+ name: 'ml_image_fetch_pool_refill_wait_seconds',+ help: 'Time a consumer waited for room in its pool window before it read its next batch. outcome=timeout means the wait reached its cap',+ labelNames: ['outcome'],+ buckets: [0, 0.1, 0.5, 1, 2, 5, 10, 30],+ })++ public static observeWait(waitSeconds: number): void {+ this.waitSeconds.observe(waitSeconds)+ }+ public static observeRefillWait(outcome: 'room' | 'timeout', waitSeconds: number): void {+ this.refillWaitSeconds.labels(outcome).observe(waitSeconds)+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/pool-window-batch-handler.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/pool-window-batch-handler.test.tsnew file mode 100644index 000000000000..500ddf7fef84--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/pool-window-batch-handler.test.ts@@ -0,0 +1,77 @@+import { Message } from 'node-rdkafka'++import { MAX_HOPS } from './collected-urls-record'+import { FetchCandidatePool, FetchCandidatePoolAdmission } from './fetch-candidate-pool'+import { createPoolWindowBatchHandler } from './pool-window-batch-handler'++const NOW_MS = 1_700_000_000_000+const MESSAGE: Message = {+ topic: 'session_replay_image_fetch',+ partition: 3,+ offset: 1,+ value: Buffer.from('x'),+ size: 1,+}++function distinctDomainCandidates(count: number): Parameters<FetchCandidatePool<string>['add']>[0] {+ return Array.from({ length: count }, (_unused, index) => ({+ originalRef: `imageurl:${index}`,+ currentUrl: `https://cdn${index}.example${index}.com/a.png`,+ host: `cdn${index}.example${index}.com`,+ origin: `https://cdn${index}.example${index}.com`,+ registrableDomain: `example${index}.com`,+ remainingHops: MAX_HOPS,+ notBeforeMs: 0,+ firstSeenAtMs: NOW_MS,+ fetchCount: 0,+ republishCount: 0,+ lastRepublishReason: null,+ }))+}++describe('createPoolWindowBatchHandler', () => {+ beforeEach(() => jest.useFakeTimers().setSystemTime(NOW_MS))+ afterEach(() => jest.useRealTimers())++ it.each([+ ['returns once the batch enters the pool and the window has room', 0, 500],+ ['returns at the wait cap while the window stays full', 20, 30_000],+ ])('%s', async (_name, queuedAfterAdmission, expectedReturnMs) => {+ const pool = new FetchCandidatePool<string>(+ { maxConcurrentPerRegistrableDomain: 6, refillRunnableUrls: 10, maxQueuedUrlsPerOwner: 1_000 },+ { originCrawlDelayMs: () => 0, originNextImageStartAtMs: () => 0 }+ )+ const owner = pool.createOwner()+ let finishBatch: () => void = () => undefined+ const processBatch = jest.fn(+ (_messages: Message[], admission: FetchCandidatePoolAdmission) =>+ new Promise<void>((resolve) => {+ setTimeout(() => {+ pool.add(+ distinctDomainCandidates(queuedAfterAdmission),+ 'batch',+ NOW_MS + 40_000,+ admission.owner+ )+ admission.admitted()+ }, 500)+ finishBatch = resolve+ })+ )+ const handler = createPoolWindowBatchHandler(owner, processBatch)++ let returnedAtMs: number | undefined+ const returned = handler([MESSAGE]).then((result) => {+ returnedAtMs = Date.now()+ return result+ })+ await jest.advanceTimersByTimeAsync(30_000)+ const result = await returned+ finishBatch()++ expect(processBatch).toHaveBeenCalledTimes(1)+ expect(returnedAtMs! - NOW_MS).toBe(expectedReturnMs)+ await expect(result?.backgroundTask).resolves.toBeUndefined()+ pool.close()+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/pool-window-batch-handler.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/pool-window-batch-handler.tsnew file mode 100644index 000000000000..c0e7b7994316--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/pool-window-batch-handler.ts@@ -0,0 +1,38 @@+import { Message } from 'node-rdkafka'++import { FetchCandidatePoolAdmission, FetchCandidatePoolOwner } from './fetch-candidate-pool'+import { ImageFetchPoolMetrics } from './metrics'++/** consumer-v2 reports a stalled loop after 60 s without a tick, and this wait holds the loop. */+export const POOL_ROOM_WAIT_CAP_MS = 30_000++type BatchProcessor = (messages: Message[], admission: FetchCandidatePoolAdmission) => Promise<void>++/**+ * The batch handler of one consumer in continuous-pool mode.+ *+ * It starts the batch at once and returns only when the consumer's pool window has room, so the+ * consumer reads its next batch while the pool still holds work for it.+ */+export function createPoolWindowBatchHandler(+ owner: FetchCandidatePoolOwner,+ processBatch: BatchProcessor,+ roomWaitCapMs = POOL_ROOM_WAIT_CAP_MS+): (messages: Message[]) => Promise<{ backgroundTask: Promise<void> } | void> {+ return async (messages) => {+ if (messages.length === 0) {+ return+ }+ const admission = owner.beginAdmission()+ const backgroundTask = processBatch(messages, admission).finally(() => admission.admitted())+ // consumer-v2 attaches its own handler after this returns, so a failure during the wait must not count as unhandled.+ void backgroundTask.catch(() => undefined)+ const waitStartedAtMs = performance.now()+ const hadRoom = await owner.waitForRoom(roomWaitCapMs)+ ImageFetchPoolMetrics.observeRefillWait(+ hadRoom ? 'room' : 'timeout',+ (performance.now() - waitStartedAtMs) / 1000+ )+ return { backgroundTask }+ }+}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 5f38dc7e7654..4cad6e669110 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@@ -18,6 +18,7 @@ import {parseCollectedUrlsRecord,} from './collected-urls-record'import { CrawlHistoryItem, CrawlHistoryStore, UrlCrawlHistoryItem, configurationCacheKey } from './crawl-history'+import { FetchCandidatePoolAdmission } from './fetch-candidate-pool'import { mergeDuplicateFetchCandidates } from './fetch-candidate-queue'import {AttemptOutcome,@@ -68,7 +69,11 @@ export class UrlFetchConsumer {ImageFetchConsumerMetrics.setDryRun(options.dryRun)}- public async handleBatch(messages: Message[], nowMs: number): Promise<void> {+ public async handleBatch(+ messages: Message[],+ nowMs: number,+ admission?: FetchCandidatePoolAdmission+ ): Promise<void> {const decoded: MlDecodedMessage[] = this.keyManager? await this.keyManager.read(messages): messages.map((message) => {@@ -234,7 +239,7 @@ export class UrlFetchConsumer {const republishBatch = this.publisher.createRepublishBatch(republishDeadlineAtMonotonicMs)stage.move('batch_fetch')- const attempts = await this.runner!.run(fetchable, stored, republishBatch)+ const attempts = await this.runner!.run(fetchable, stored, republishBatch, admission)stage.move('batch_prepare_republish')attempts.push(...(await Promise.all(diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex c355ede18524..47731c0fbc04 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -102,6 +102,15 @@ export type MlMirrorConfig = {SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: number/** While true, the batches of all group members in one worker join into one fetch pass. While false, each batch starts its own pass. */SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES: boolean+ /**+ * While true, every batch adds its URLs to one pod-wide candidate pool and finishes on its own,+ * and SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES has no effect.+ */+ SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL: boolean+ /** A group member reads its next batch once fewer of its queued URLs than this can run. */+ SESSION_RECORDING_ML_IMAGE_FETCH_POOL_REFILL_RUNNABLE_URLS: number+ /** A group member also waits while this many of its URLs are queued. The wait stops after 30 s to keep the consumer loop healthy, so a member can pass this by about one batch until pass deadlines remove its queued URLs. */+ SESSION_RECORDING_ML_IMAGE_FETCH_POOL_MAX_QUEUED_URLS_PER_MEMBER: 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@@ -260,6 +269,9 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: 500,SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 2,SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES: true,+ SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL: false,+ SESSION_RECORDING_ML_IMAGE_FETCH_POOL_REFILL_RUNNABLE_URLS: 100,+ SESSION_RECORDING_ML_IMAGE_FETCH_POOL_MAX_QUEUED_URLS_PER_MEMBER: 2_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,diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.tsindex d21a5327d056..c6ae03f170fc 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts@@ -1,7 +1,12 @@import { Message } from 'node-rdkafka'+import {+ FetchCandidatePool,+ FetchCandidatePoolAdmission,+} from '../ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool'import { ImageFetchBatchJoiner } from '../ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner'import {+ buildImageFetchBatchHandlers,buildImageFetchConsumerConfigs,buildImageFetchConsumerOverrides,imageFetchBatchesPerPass,@@ -11,9 +16,9 @@ import { buildMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-describe('image fetch consumer wiring', () => {it.each([- ['the default', {}, 2, 2, 102_400],- ['four consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 4 }, 4, 4, 164_096],- ['eight consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 8 }, 8, 8, 328_192],+ ['the default', {}, 2, 2, 2, 102_400],+ ['four consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 4 }, 4, 4, 2, 164_096],+ ['eight consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 8 }, 8, 8, 2, 328_192],['eight unjoined consumers',{@@ -22,19 +27,40 @@ describe('image fetch consumer wiring', () => {},8,1,+ 2,+ 328_192,+ ],+ [+ 'eight continuous-pool consumers',+ {+ SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 8,+ SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL: true,+ },+ 8,+ 8,+ 4,328_192,],- ['sixteen consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 16 }, 16, 16, 656_384],+ ['sixteen consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 16 }, 16, 16, 2, 656_384],])('creates %s number of Kafka group members',- (_name, overrides, expectedConsumers, expectedBatchesPerPass, expectedQueueBudget) => {+ (+ _name,+ overrides,+ expectedConsumers,+ expectedBatchesPerPass,+ expectedBatchesInFlightPerMember,+ expectedQueueBudget+ ) => {const serverConfig = buildMlMirrorServerConfig(overrides)const consumerConfigs = buildImageFetchConsumerConfigs(serverConfig)const consumerOverrides = buildImageFetchConsumerOverrides(serverConfig, consumerConfigs.length)expect(consumerConfigs).toHaveLength(expectedConsumers)expect(imageFetchBatchesPerPass(serverConfig, consumerConfigs.length)).toBe(expectedBatchesPerPass)- expect(consumerConfigs.every((config) => config.maxBackgroundTasks === 2)).toBe(true)+ expect(consumerConfigs.map((config) => config.maxBackgroundTasks)).toEqual(+ Array(expectedConsumers).fill(expectedBatchesInFlightPerMember)+ )expect(consumerConfigs.every((config) => config.backgroundTaskTimeoutMs === 240_000)).toBe(true)expect(consumerConfigs.map((config) => config.groupId)).toEqual(Array(expectedConsumers).fill(serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID)@@ -51,6 +77,69 @@ describe('image fetch consumer wiring', () => {})+ it.each([+ ['the joiner without a pool', false],+ ['its own pool window with a pool', true],+ ])('routes each member batch through %s', async (_name, withPool) => {+ const pool = withPool+ ? new FetchCandidatePool<unknown>(+ { maxConcurrentPerRegistrableDomain: 6, refillRunnableUrls: 100, maxQueuedUrlsPerOwner: 1_000 },+ { originCrawlDelayMs: () => 0, originNextImageStartAtMs: () => 0 }+ )+ : undefined+ const fetchConsumer = { handleBatch: jest.fn().mockResolvedValue(undefined) }+ const joiner = {+ handleBatch: jest.fn().mockResolvedValue(undefined),+ waitForProcessing: jest.fn().mockResolvedValue(undefined),+ }+ const message: Message = { topic: 'test-topic', partition: 0, offset: 1, value: Buffer.from('x'), size: 1 }++ const { handlers } = buildImageFetchBatchHandlers(2, fetchConsumer, { candidatePool: pool }, joiner)+ await Promise.all(handlers.map((handler) => handler([message])))++ expect(handlers).toHaveLength(2)+ expect(joiner.handleBatch).toHaveBeenCalledTimes(withPool ? 0 : 2)+ expect(fetchConsumer.handleBatch).toHaveBeenCalledTimes(withPool ? 2 : 0)+ if (withPool) {+ const [firstAdmission, secondAdmission] = fetchConsumer.handleBatch.mock.calls.map((call) => call[2])+ expect(firstAdmission.owner).not.toBe(secondAdmission.owner)+ }+ pool?.close()+ })++ it('waits for a pooled member batch that is still preparing before it closes the fetch runner', async () => {+ const pool = new FetchCandidatePool<unknown>(+ { maxConcurrentPerRegistrableDomain: 6, refillRunnableUrls: 100, maxQueuedUrlsPerOwner: 1_000 },+ { originCrawlDelayMs: () => 0, originNextImageStartAtMs: () => 0 }+ )+ let finishBatch: () => void = () => undefined+ const fetchConsumer = {+ handleBatch: jest.fn(+ (_messages: Message[], _nowMs: number, admission?: FetchCandidatePoolAdmission) =>+ new Promise<void>((resolve) => {+ admission?.admitted()+ finishBatch = resolve+ })+ ),+ }+ const joiner = { handleBatch: jest.fn(), waitForProcessing: jest.fn().mockResolvedValue(undefined) }+ const startedBatches = buildImageFetchBatchHandlers(1, fetchConsumer, { candidatePool: pool }, joiner)+ await startedBatches.handlers[0]([+ { topic: 'test-topic', partition: 0, offset: 1, value: Buffer.from('x'), size: 1 },+ ])+ const consumers = [{ stopConsuming: jest.fn().mockResolvedValue(undefined), disconnect: jest.fn() }]+ const fetchRunner = { close: jest.fn().mockResolvedValue(undefined) }++ const shutdown = shutdownImageFetchConsumers(consumers, startedBatches, fetchRunner)+ await new Promise((resolve) => setImmediate(resolve))+ expect(fetchRunner.close).not.toHaveBeenCalled()+ finishBatch()+ await shutdown++ expect(fetchRunner.close).toHaveBeenCalledTimes(1)+ pool.close()+ })+it.each([false, true])('waits for joined work before disconnecting and cleaning up (failure=%s)', async (fails) => {jest.useFakeTimers()try {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 9a939496b88f..447d051249be 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@@ -8,7 +8,12 @@ import {KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,KAFKA_SESSION_REPLAY_IMAGE_SCRUB,} from '~/common/config/kafka-topics'-import { KafkaConsumerV2, KafkaConsumerV2Config, RdKafkaConsumerOverrides } from '~/common/kafka/consumer/consumer-v2'+import {+ EachBatch,+ KafkaConsumerV2,+ KafkaConsumerV2Config,+ RdKafkaConsumerOverrides,+} 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'@@ -19,6 +24,7 @@ import {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 { FetchCandidatePool } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-candidate-pool'import { FetchRunner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner'import { KafkaFrontierDeadLetterSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink'import { FrontierPublisher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher'@@ -30,6 +36,7 @@ import {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 { createPoolWindowBatchHandler } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/pool-window-batch-handler'import { ImageFetchTopHogMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/tophog-metrics'import { UrlFetchConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer'import { VersionedCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/versioned-crawl-history'@@ -54,6 +61,11 @@ import { MlMirrorConsumerServer } from './ml-mirror-consumer-server'const STORE_BATCH_BUDGET_MS = 50_000const IMAGE_FETCH_KAFKA_QUEUE_BUDGET_KBYTES = 102_400const IMAGE_FETCH_MIN_CONSUMER_QUEUE_KBYTES = 25_600+/**+ * The pool window paces a member in continuous-pool mode. This limit stays above that window at typical+ * batch sizes, and it is the hard bound on a member's resident URLs and crash replay when batches are large.+ */+const POOL_MAX_BATCHES_IN_FLIGHT_PER_MEMBER = 4/** Matches MAX_URL_LEN in the crate, which is what the collector applied to the first candidate. */const MAX_REDIRECT_URL_LENGTH = 2048@@ -145,6 +157,12 @@ export function buildFetchRunner(requestTimeoutMs: config.SESSION_RECORDING_ML_IMAGE_FETCH_REQUEST_TIMEOUT_MS,maxRedirects: config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_REDIRECTS,seenTtlSeconds: config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS,+ continuousPool: config.SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL+ ? {+ refillRunnableUrls: config.SESSION_RECORDING_ML_IMAGE_FETCH_POOL_REFILL_RUNNABLE_URLS,+ maxQueuedUrlsPerOwner: config.SESSION_RECORDING_ML_IMAGE_FETCH_POOL_MAX_QUEUED_URLS_PER_MEMBER,+ }+ : undefined,},publisher,topHogMetrics@@ -162,7 +180,9 @@ export function buildImageFetchConsumerConfigs(autoCommit: true,autoOffsetStore: true,fetchBatchSize: config.SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE,- maxBackgroundTasks: 2,+ maxBackgroundTasks: config.SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL+ ? POOL_MAX_BATCHES_IN_FLIGHT_PER_MEMBER+ : 2,backgroundTaskTimeoutMs: 240_000,}))}@@ -191,13 +211,54 @@ export function buildImageFetchConsumerOverrides(}}+export interface ImageFetchBatchHandlers {+ handlers: EachBatch[]+ /** Resolves once every batch started so far has settled, including pooled batches that the Kafka drain gave up on. */+ waitForProcessing(): Promise<void>+}++export function buildImageFetchBatchHandlers(+ consumerCount: number,+ fetchConsumer: Pick<UrlFetchConsumer, 'handleBatch'>,+ fetchRunner: { candidatePool?: Pick<FetchCandidatePool<unknown>, 'createOwner'> },+ batchJoiner: Pick<ImageFetchBatchJoiner, 'handleBatch' | 'waitForProcessing'>+): ImageFetchBatchHandlers {+ const pool = fetchRunner.candidatePool+ const pooledBatches = new Set<Promise<void>>()+ const trackPooledBatch = (batch: Promise<void>): Promise<void> => {+ pooledBatches.add(batch)+ const forget = (): void => {+ pooledBatches.delete(batch)+ }+ batch.then(forget, forget)+ return batch+ }+ const handlers = Array.from({ length: consumerCount }, (): EachBatch => {+ if (!pool) {+ return (messages) => batchJoiner.handleBatch(messages)+ }+ return createPoolWindowBatchHandler(pool.createOwner(), (messages, admission) =>+ trackPooledBatch(fetchConsumer.handleBatch(messages, Date.now(), admission))+ )+ })+ return {+ handlers,+ waitForProcessing: async () => {+ await batchJoiner.waitForProcessing()+ await Promise.allSettled([...pooledBatches])+ },+ }+}+export async function shutdownImageFetchConsumers(consumers: Pick<KafkaConsumerV2, 'stopConsuming' | 'disconnect'>[],- batchJoiner: ImageFetchBatchJoiner+ startedBatches: Pick<ImageFetchBatchHandlers, 'waitForProcessing'>,+ fetchRunner?: Pick<FetchRunner, 'close'>): Promise<void> {await Promise.allSettled(consumers.map((consumer) => consumer.stopConsuming()))- await batchJoiner.waitForProcessing()+ await startedBatches.waitForProcessing()await Promise.allSettled(consumers.map((consumer) => consumer.disconnect()))+ await fetchRunner?.close()}/**@@ -284,6 +345,7 @@ export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerSe? new KafkaFrontierDeadLetterSink(producer, deadLetterTopic, BLOCKED_IMAGE_FETCH_DEAD_LETTER_TOPICS): null+ const fetchRunner = buildFetchRunner(this.config, publisher, topHogMetrics)const fetchConsumer = new UrlFetchConsumer(crawlHistory,publisher,@@ -291,18 +353,27 @@ export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerSeseenTtlSeconds: this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS,dryRun,},- buildFetchRunner(this.config, publisher, topHogMetrics),+ fetchRunner,deadLetters,topHogMetrics,this.keyManager?.kafka)- logger.info('🌐', 'ml_image_fetch_started', { dryRun })+ logger.info('🌐', 'ml_image_fetch_started', {+ dryRun,+ continuousPool: this.config.SESSION_RECORDING_ML_IMAGE_FETCH_CONTINUOUS_POOL,+ })const consumerConfigs = buildImageFetchConsumerConfigs(this.config)const batchJoiner = new ImageFetchBatchJoiner(imageFetchBatchesPerPass(this.config, consumerConfigs.length),(messages) => fetchConsumer.handleBatch(messages, Date.now()))+ const batchHandlers = buildImageFetchBatchHandlers(+ consumerConfigs.length,+ fetchConsumer,+ fetchRunner,+ batchJoiner+ )const consumerOverrides = buildImageFetchConsumerOverrides(this.config, consumerConfigs.length)const consumers = consumerConfigs.map((consumerConfig) => new KafkaConsumerV2(consumerConfig, consumerOverrides)@@ -310,7 +381,7 @@ export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerSethis.lifecycle.services.push({id: 'session-replay-ml-image-fetch',- onShutdown: () => shutdownImageFetchConsumers(consumers, batchJoiner),+ onShutdown: () => shutdownImageFetchConsumers(consumers, batchHandlers, fetchRunner),healthcheck: () => {for (const consumer of consumers) {const health = consumer.isHealthy()@@ -321,9 +392,7 @@ export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerSereturn new HealthCheckResultOk()},})- await Promise.all(- consumers.map((consumer) => consumer.connect((messages) => batchJoiner.handleBatch(messages)))- )+ await Promise.all(consumers.map((consumer, index) => consumer.connect(batchHandlers.handlers[index])))}protected getCleanupResources(): CleanupResources {