: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: Perserve person and group stores between batches (#60223)
José Sequeirad1868d9d30a6
diff --git a/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.integration.test.ts b/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.integration.test.tsindex e7c344f4eed8..f918522610b0 100644--- a/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.integration.test.ts+++ b/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.integration.test.ts@@ -9,6 +9,8 @@ import { createTestPluginEvent } from '../../../../tests/helpers/plugin-event'import { createTestTeam } from '../../../../tests/helpers/team'import { InternalPerson, PropertyUpdateOperation } from '../../../types'import { parseJSON } from '../../../utils/json-parse'+import { GroupStoreForBatch } from '../../../worker/ingestion/groups/group-store-for-batch'+import { PersonsStoreForBatch } from '../../../worker/ingestion/persons/persons-store-for-batch'import { AI_EVENTS_OUTPUT, EVENTS_OUTPUT, PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '../../analytics/outputs'import { INGESTION_WARNINGS_OUTPUT } from '../../common/outputs'import { IngestionOutputs } from '../../outputs/ingestion-outputs'@@ -35,6 +37,17 @@ const existingPerson: InternalPerson = {last_seen_at: null,}+const mockPersonsStoreForBatch: jest.Mocked<PersonsStoreForBatch> = {+ fetchForChecking: jest.fn().mockResolvedValue(null),+ getPersonlessBatchResult: jest.fn().mockReturnValue(false),+ fetchForUpdate: jest.fn().mockResolvedValue(existingPerson),+ updatePersonWithPropertiesDiffForUpdate: jest.fn().mockResolvedValue([existingPerson, [], false]),+} as unknown as jest.Mocked<PersonsStoreForBatch>++const mockGroupStoreForBatch: jest.Mocked<GroupStoreForBatch> = {+ upsertGroup: jest.fn().mockResolvedValue(undefined),+} as unknown as jest.Mocked<GroupStoreForBatch>+function createAiEvent(overrides: Partial<PluginEvent> = {}): PluginEvent {return createTestPluginEvent({event: '$ai_generation',@@ -85,13 +98,6 @@ function buildPipeline(configOverrides: Partial<AiEventSubpipelineConfig> = {})hogTransformer: {transformEventAndProduceMessages: (event: PluginEvent) => Promise.resolve({ event, invocationResults: [] }),} as any,- personsStore: {- fetchForChecking: jest.fn().mockResolvedValue(null),- getPersonlessBatchResult: jest.fn().mockReturnValue(false),- fetchForUpdate: jest.fn().mockResolvedValue(existingPerson),- updatePersonWithPropertiesDiffForUpdate: jest.fn().mockResolvedValue([existingPerson, [], false]),- } as any,- groupStore: {} as any,splitAiEventsConfig: {enabled: false,enabledTeams: '*',@@ -111,7 +117,14 @@ function buildPipeline(configOverrides: Partial<AiEventSubpipelineConfig> = {})}function createInput(event: PluginEvent): AiEventSubpipelineInput {- return { message, event, team, headers }+ return {+ message,+ event,+ team,+ headers,+ personsStoreForBatch: mockPersonsStoreForBatch,+ groupStoreForBatch: mockGroupStoreForBatch,+ }}type AiOutputs =diff --git a/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.ts b/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.tsindex 8ceee6ac5cf9..346802613b57 100644--- a/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.ts+++ b/nodejs/src/ingestion/ai/pipelines/ai-event-subpipeline.ts@@ -7,8 +7,8 @@ import { HogTransformerService } from '../../../cdp/hog-transformations/hog-tranimport { EventHeaders, Team } from '../../../types'import { TeamManager } from '../../../utils/team-manager'import { GroupTypeManager } from '../../../worker/ingestion/group-type-manager'-import { BatchWritingGroupStore } from '../../../worker/ingestion/groups/batch-writing-group-store'-import { PersonsStore } from '../../../worker/ingestion/persons/persons-store'+import { GroupStoreForBatch } from '../../../worker/ingestion/groups/group-store-for-batch'+import { PersonsStoreForBatch } from '../../../worker/ingestion/persons/persons-store-for-batch'import { AiEventOutput, AsyncOutput, EVENTS_OUTPUT, EventOutput } from '../../analytics/outputs'import { PersonDistinctIdsOutput, PersonsOutput } from '../../analytics/outputs'import { IngestionWarningsOutput } from '../../common/outputs'@@ -33,6 +33,8 @@ export interface AiEventSubpipelineInput {event: PluginEventteam: Teamheaders: EventHeaders+ personsStoreForBatch: PersonsStoreForBatch+ groupStoreForBatch: GroupStoreForBatch}export interface AiEventSubpipelineConfig {@@ -43,8 +45,6 @@ export interface AiEventSubpipelineConfig {teamManager: TeamManagergroupTypeManager: GroupTypeManagerhogTransformer: HogTransformerService- personsStore: PersonsStore- groupStore: BatchWritingGroupStoresplitAiEventsConfig: SplitAiEventsStepConfiggroupId: stringtopHog: TopHogWrapper@@ -54,18 +54,8 @@ export function createAiEventSubpipeline<TInput extends AiEventSubpipelineInput,builder: StartPipelineBuilder<TInput, TContext>,config: AiEventSubpipelineConfig): PipelineBuilder<TInput, void, TContext, AsyncOutput> {- const {- options,- outputs,- teamManager,- groupTypeManager,- hogTransformer,- personsStore,- groupStore,- splitAiEventsConfig,- groupId,- topHog,- } = config+ const { options, outputs, teamManager, groupTypeManager, hogTransformer, splitAiEventsConfig, groupId, topHog } =+ configreturn builder.pipe(createNormalizeProcessPersonFlagStep())@@ -101,9 +91,9 @@ export function createAiEventSubpipeline<TInput extends AiEventSubpipelineInput,).pipe(createNormalizeEventStep()).pipe(createProcessAiEventStep())- .pipe(createProcessPersonlessStep(personsStore))+ .pipe(createProcessPersonlessStep()).pipe(- topHog(createProcessPersonsStep(options, outputs, personsStore), [+ topHog(createProcessPersonsStep(options, outputs), [timer('process_persons_time', (input) => ({team_id: String(input.team.id),distinct_id: input.normalizedEvent.distinct_id,@@ -111,7 +101,7 @@ export function createAiEventSubpipeline<TInput extends AiEventSubpipelineInput,])).pipe(createPrepareEventStep())- .pipe(createProcessGroupsStep(teamManager, groupTypeManager, groupStore, options))+ .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options)).pipe(createCreateEventStep(EVENTS_OUTPUT)).pipe(createSplitAiEventsStep(splitAiEventsConfig)).pipe(diff --git a/nodejs/src/ingestion/analytics/event-subpipeline.ts b/nodejs/src/ingestion/analytics/event-subpipeline.tsindex 96ee01e4d3af..af3429d9eaff 100644--- a/nodejs/src/ingestion/analytics/event-subpipeline.ts+++ b/nodejs/src/ingestion/analytics/event-subpipeline.ts@@ -6,8 +6,8 @@ import { HogTransformerService } from '../../cdp/hog-transformations/hog-transfoimport { EventHeaders, Team } from '../../types'import { TeamManager } from '../../utils/team-manager'import { GroupTypeManager } from '../../worker/ingestion/group-type-manager'-import { BatchWritingGroupStore } from '../../worker/ingestion/groups/batch-writing-group-store'-import { PersonsStore } from '../../worker/ingestion/persons/persons-store'+import { GroupStoreForBatch } from '../../worker/ingestion/groups/group-store-for-batch'+import { PersonsStoreForBatch } from '../../worker/ingestion/persons/persons-store-for-batch'import { IngestionWarningsOutput } from '../common/outputs'import { createCreateEventStep } from '../event-processing/create-event-step'import { createEmitEventStep } from '../event-processing/emit-event-step'@@ -30,6 +30,8 @@ export interface EventSubpipelineInput {event: PluginEventteam: Teamheaders: EventHeaders+ personsStoreForBatch: PersonsStoreForBatch+ groupStoreForBatch: GroupStoreForBatch}export interface EventSubpipelineConfig {@@ -38,8 +40,6 @@ export interface EventSubpipelineConfig {teamManager: TeamManagergroupTypeManager: GroupTypeManagerhogTransformer: HogTransformerService- personsStore: PersonsStore- groupStore: BatchWritingGroupStoregroupId: stringtopHog: TopHogWrapper}@@ -48,17 +48,7 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput, TCobuilder: StartPipelineBuilder<TInput, TContext>,config: EventSubpipelineConfig): PipelineBuilder<TInput, void, TContext, AsyncOutput> {- const {- options,- outputs,- teamManager,- groupTypeManager,- hogTransformer,- personsStore,- groupStore,- groupId,- topHog,- } = config+ const { options, outputs, teamManager, groupTypeManager, hogTransformer, groupId, topHog } = configreturn builder.pipe(createNormalizeProcessPersonFlagStep())@@ -93,9 +83,9 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput, TCo])).pipe(createNormalizeEventStep())- .pipe(createProcessPersonlessStep(personsStore))+ .pipe(createProcessPersonlessStep()).pipe(- topHog(createProcessPersonsStep(options, outputs, personsStore), [+ topHog(createProcessPersonsStep(options, outputs), [timer('process_persons_time', (input) => ({team_id: String(input.team.id),distinct_id: input.normalizedEvent.distinct_id,@@ -103,7 +93,7 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput, TCo])).pipe(createPrepareEventStep())- .pipe(createProcessGroupsStep(teamManager, groupTypeManager, groupStore, options))+ .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options)).pipe(createCreateEventStep(EVENTS_OUTPUT)).pipe(topHog(diff --git a/nodejs/src/ingestion/analytics/heatmap-subpipeline.ts b/nodejs/src/ingestion/analytics/heatmap-subpipeline.tsindex 465b3335b802..209e908ddfa7 100644--- a/nodejs/src/ingestion/analytics/heatmap-subpipeline.ts+++ b/nodejs/src/ingestion/analytics/heatmap-subpipeline.ts@@ -3,7 +3,7 @@ import { PluginEvent } from '~/plugin-scaffold'import { EventHeaders, Team } from '../../types'import { TeamManager } from '../../utils/team-manager'import { GroupTypeManager } from '../../worker/ingestion/group-type-manager'-import { BatchWritingGroupStore } from '../../worker/ingestion/groups/batch-writing-group-store'+import { GroupStoreForBatch } from '../../worker/ingestion/groups/group-store-for-batch'import { createCheckHeatmapOptInStep } from '../event-processing/check-heatmap-opt-in-step'import { createDisablePersonProcessingStep } from '../event-processing/disable-person-processing-step'import { EventPipelineRunnerOptions } from '../event-processing/event-pipeline-options'@@ -20,6 +20,7 @@ export interface HeatmapSubpipelineInput {event: PluginEventteam: Teamheaders: EventHeaders+ groupStoreForBatch: GroupStoreForBatch}export interface HeatmapSubpipelineConfig {@@ -27,21 +28,20 @@ export interface HeatmapSubpipelineConfig {outputs: IngestionOutputs<HeatmapsOutput>teamManager: TeamManagergroupTypeManager: GroupTypeManager- groupStore: BatchWritingGroupStore}export function createHeatmapSubpipeline<TInput extends HeatmapSubpipelineInput, TContext>(builder: StartPipelineBuilder<TInput, TContext>,config: HeatmapSubpipelineConfig): PipelineBuilder<TInput, void, TContext> {- const { options, outputs, teamManager, groupTypeManager, groupStore } = config+ const { options, outputs, teamManager, groupTypeManager } = configreturn builder.pipe(createCheckHeatmapOptInStep()).pipe(createDisablePersonProcessingStep()).pipe(createNormalizeEventStep()).pipe(createPrepareEventStep())- .pipe(createProcessGroupsStep(teamManager, groupTypeManager, groupStore, options))+ .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options)).pipe(createExtractHeatmapDataStep(outputs)).pipe(createSkipEmitEventStep())}diff --git a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.tsindex a5ecc1bd497d..b6a0bf8c5dda 100644--- a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts@@ -17,6 +17,8 @@ import {createEventFiltersBatchAppMetricsBeforeBatchStep,createFlushEventFiltersBatchAppMetricsStep,} from '../common/steps/event-filters-steps'+import { GroupStoreBatchContext, createGroupStoreBeforeBatchStep } from '../common/steps/group-store-batch-step'+import { PersonsStoreBatchContext, createPersonsStoreBeforeBatchStep } from '../common/steps/persons-store-batch-step'import { CookielessManager } from '../cookieless/cookieless-manager'import {createApplyEventRestrictionsStep,@@ -103,6 +105,8 @@ export interface JoinedIngestionPipelineDeps {topHog: TopHogRegistry}+type IngestionBatchContext = EventFiltersBatchContext & PersonsStoreBatchContext & GroupStoreBatchContext+export interface JoinedIngestionPipelineInput {message: Message}@@ -178,7 +182,6 @@ export function createJoinedIngestionPipeline<preservePartitionLocality,overflowRedirectService,overflowLaneTTLRefreshService,- personsStore,personsPrefetchEnabled,hogTransformer,cdpHogWatcherSampleRate,@@ -191,21 +194,16 @@ export function createJoinedIngestionPipeline<teamManager,groupTypeManager,hogTransformer,- personsStore,- groupStore,groupId,topHog: topHogWrapper,}- return newBatchingPipeline<- TInput,- void,- TContext,- EventFiltersBatchContext,- TContext,- OverflowOutput | AsyncOutput- >(- (beforeBatch) => beforeBatch.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)),+ return newBatchingPipeline<TInput, void, TContext, IngestionBatchContext, TContext, OverflowOutput | AsyncOutput>(+ (beforeBatch) =>+ beforeBatch+ .pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs))+ .pipe(createPersonsStoreBeforeBatchStep(personsStore))+ .pipe(createGroupStoreBeforeBatchStep(groupStore)),(batch) =>batch.messageAware((b) =>@@ -264,11 +262,12 @@ export function createJoinedIngestionPipeline<afterBatch.pipe(createFlushBatchStoresStep({ personsStore, groupStore, outputs })).pipe(createFlushEventFiltersBatchAppMetricsStep()),- // Batch stores (personsStore, groupStore) are singletons that don't support- // concurrent batches yet — they accumulate state across events and flush once.- // The Rust consumer's per-worker Semaphore caps in-flight batches at the- // same value (INGESTION_WORKER_CONCURRENT_BATCHES); divergence shows up as- // HTTP 503s in `ingestion_api_batch_capacity_rejections_total`.+ // Batch stores are singleton persistent caches, but each batch receives a+ // batch-bound view so entries can be reference-counted and released after+ // that batch's flush lifecycle completes. The Rust consumer's per-worker+ // Semaphore caps in-flight batches at the same value+ // (INGESTION_WORKER_CONCURRENT_BATCHES); divergence shows up as HTTP 503s+ // in `ingestion_api_batch_capacity_rejections_total`.{ concurrentBatches })}diff --git a/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts b/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.tsindex 6f9a32830c58..20eeceb29d80 100644--- a/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts+++ b/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts@@ -4,8 +4,6 @@ import { HogTransformerService } from '../../cdp/hog-transformations/hog-transfoimport { Team } from '../../types'import { TeamManager } from '../../utils/team-manager'import { GroupTypeManager } from '../../worker/ingestion/group-type-manager'-import { BatchWritingGroupStore } from '../../worker/ingestion/groups/batch-writing-group-store'-import { PersonsStore } from '../../worker/ingestion/persons/persons-store'import { AI_EVENT_TYPES } from '../ai'import { AiEventSubpipelineInput, createAiEventSubpipeline } from '../ai/pipelines/ai-event-subpipeline'import { IngestionWarningsOutput } from '../common/outputs'@@ -36,8 +34,6 @@ export interface PerDistinctIdPipelineConfig {teamManager: TeamManagergroupTypeManager: GroupTypeManagerhogTransformer: HogTransformerService- personsStore: PersonsStore- groupStore: BatchWritingGroupStoregroupId: stringtopHog: TopHogWrapper}@@ -62,18 +58,8 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipelinebuilder: StartPipelineBuilder<TInput, TContext>,config: PerDistinctIdPipelineConfig): PipelineBuilder<TInput, void, TContext, AsyncOutput> {- const {- options,- outputs,- splitAiEventsConfig,- teamManager,- groupTypeManager,- hogTransformer,- personsStore,- groupStore,- groupId,- topHog,- } = config+ const { options, outputs, splitAiEventsConfig, teamManager, groupTypeManager, hogTransformer, groupId, topHog } =+ configreturn builder.retry((e) =>@@ -85,7 +71,6 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipelineoutputs,teamManager,groupTypeManager,- groupStore,})).branch('ai', (b) =>@@ -95,8 +80,6 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipelineteamManager,groupTypeManager,hogTransformer,- personsStore,- groupStore,splitAiEventsConfig,groupId,topHog,@@ -109,8 +92,6 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipelineteamManager,groupTypeManager,hogTransformer,- personsStore,- groupStore,groupId,topHog,})diff --git a/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.tsindex 624e62d91276..c0e800264c5f 100644--- a/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts+++ b/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts@@ -8,7 +8,7 @@ import { EventHeaders, Team } from '../../types'import { EventIngestionRestrictionManager } from '../../utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '../../utils/event-schema-enforcement-manager'import { prefetchPersonsStep } from '../../worker/ingestion/event-pipeline/prefetchPersonsStep'-import { PersonsStore } from '../../worker/ingestion/persons/persons-store'+import { PersonsStoreForBatch } from '../../worker/ingestion/persons/persons-store-for-batch'import { EventFilterManager } from '../common/event-filters'import { EventFiltersBatchAppMetrics } from '../common/event-filters/batch-app-metrics'import { createApplyEventFiltersStep } from '../common/steps/event-filters-steps'@@ -33,6 +33,7 @@ export interface PostTeamPreprocessingSubpipelineInput {event: PluginEventteam: TeameventFiltersBatchAppMetrics: EventFiltersBatchAppMetrics+ personsStoreForBatch: PersonsStoreForBatch}export interface PostTeamPreprocessingSubpipelineConfig {@@ -44,7 +45,6 @@ export interface PostTeamPreprocessingSubpipelineConfig {preservePartitionLocality: booleanoverflowRedirectService?: OverflowRedirectServiceoverflowLaneTTLRefreshService?: OverflowRedirectService- personsStore: PersonsStorepersonsPrefetchEnabled: booleanhogTransformer: HogTransformerServicecdpHogWatcherSampleRate: number@@ -63,7 +63,6 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPrpreservePartitionLocality,overflowRedirectService,overflowLaneTTLRefreshService,- personsStore,personsPrefetchEnabled,hogTransformer,cdpHogWatcherSampleRate,@@ -100,11 +99,11 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr// Prefetch is fire-and-forget (best-effort cache warming), so retry here would be a// no-op — transient persons-Postgres failures are swallowed inside prefetchPersons so// they can't surface as an unhandled rejection and crash the worker.- .pipeBatch(prefetchPersonsStep(personsStore, personsPrefetchEnabled))+ .pipeBatch(prefetchPersonsStep(personsPrefetchEnabled))// Batch insert personless distinct IDs after prefetch (uses prefetch cache).// This step awaits its DB write, so retry transient persons-Postgres failures// (e.g. PgBouncer scale-down) instead of letting them crash the consumer loop.- .pipeBatchWithRetry(processPersonlessDistinctIdsBatchStep(personsStore, personsPrefetchEnabled), {+ .pipeBatchWithRetry(processPersonlessDistinctIdsBatchStep(personsPrefetchEnabled), {tries: 5,sleepMs: 100,name: 'personless_distinct_ids',diff --git a/nodejs/src/ingestion/common/steps/event-filters-steps.test.ts b/nodejs/src/ingestion/common/steps/event-filters-steps.test.tsindex c634189f14d2..753b902ed526 100644--- a/nodejs/src/ingestion/common/steps/event-filters-steps.test.ts+++ b/nodejs/src/ingestion/common/steps/event-filters-steps.test.ts@@ -32,7 +32,7 @@ describe('createEventFiltersBatchAppMetricsBeforeBatchStep', () => {const step = createEventFiltersBatchAppMetricsBeforeBatchStep(mockOutputs)const result = await step({elements: [{ result: ok({ foo: 1 }), context: makePipelineContext() }],- batchId: 0,+ batchContext: { batchId: 0 },})expect(isOkResult(result)).toBe(true)@@ -42,14 +42,14 @@ describe('createEventFiltersBatchAppMetricsBeforeBatchStep', () => {expect(result.value.batchContext.eventFiltersBatchAppMetrics).toBeInstanceOf(EventFiltersBatchAppMetrics)})- it('attaches the same batch metrics instance to each element', async () => {+ it('attaches the same batch metrics instance to the batch context', async () => {const step = createEventFiltersBatchAppMetricsBeforeBatchStep(mockOutputs)const result = await step({elements: [{ result: ok({ a: 1 }), context: makePipelineContext() },{ result: ok({ a: 2 }), context: makePipelineContext() },],- batchId: 0,+ batchContext: { batchId: 0 },})expect(isOkResult(result)).toBe(true)@@ -57,17 +57,15 @@ describe('createEventFiltersBatchAppMetricsBeforeBatchStep', () => {return}- const batchMetrics = result.value.batchContext.eventFiltersBatchAppMetrics- for (const element of result.value.elements) {- expect(element.result.value.eventFiltersBatchAppMetrics).toBe(batchMetrics)- }+ expect(result.value.batchContext.eventFiltersBatchAppMetrics).toBeInstanceOf(EventFiltersBatchAppMetrics)+ expect(result.value.elements).toHaveLength(2)})it('preserves existing element values and context', async () => {const step = createEventFiltersBatchAppMetricsBeforeBatchStep(mockOutputs)const result = await step({elements: [{ result: ok({ data: 'hello' }), context: makePipelineContext({ ctx: true }) }],- batchId: 0,+ batchContext: { batchId: 0 },})expect(isOkResult(result)).toBe(true)@@ -503,7 +501,7 @@ describe('createFlushEventFiltersBatchAppMetricsStep', () => {const step = createFlushEventFiltersBatchAppMetricsStep()const input = {elements: [],- batchContext: { eventFiltersBatchAppMetrics: metrics },+ batchContext: { eventFiltersBatchAppMetrics: metrics, batchId: 0 },}const result = await step(input)@@ -524,7 +522,7 @@ describe('createFlushEventFiltersBatchAppMetricsStep', () => {const step = createFlushEventFiltersBatchAppMetricsStep()const input = {elements: [],- batchContext: { eventFiltersBatchAppMetrics: metrics },+ batchContext: { eventFiltersBatchAppMetrics: metrics, batchId: 0 },}const result = await step(input)@@ -545,7 +543,7 @@ describe('createFlushEventFiltersBatchAppMetricsStep', () => {const step = createFlushEventFiltersBatchAppMetricsStep()const input = {elements: [{ some: 'data' }],- batchContext: { eventFiltersBatchAppMetrics: metrics },+ batchContext: { eventFiltersBatchAppMetrics: metrics, batchId: 0 },}const result = await step(input)diff --git a/nodejs/src/ingestion/common/steps/event-filters-steps.ts b/nodejs/src/ingestion/common/steps/event-filters-steps.tsindex b4b5610932d9..e0b1b17d9e6e 100644--- a/nodejs/src/ingestion/common/steps/event-filters-steps.ts+++ b/nodejs/src/ingestion/common/steps/event-filters-steps.ts@@ -16,22 +16,16 @@ export interface EventFiltersBatchContext {* BeforeBatch step that creates an EventFiltersBatchAppMetrics instance* and attaches it to the batch context and each element.*/-export function createEventFiltersBatchAppMetricsBeforeBatchStep<TInput, CInput>(+export function createEventFiltersBatchAppMetricsBeforeBatchStep<TInput, CInput, CBatch>(outputs: IngestionOutputs<AppMetricsOutput>-): BeforeBatchStep<TInput, CInput, EventFiltersBatchContext> {+): BeforeBatchStep<TInput, CInput, CBatch, CBatch & EventFiltersBatchContext> {return function eventFiltersBatchAppMetricsBeforeBatchStep(input) {const eventFiltersBatchAppMetrics = new EventFiltersBatchAppMetrics(outputs)- const batchContext: EventFiltersBatchContext = { eventFiltersBatchAppMetrics }-- const elements = input.elements.map((element) => ({- result: {- ...element.result,- value: { ...element.result.value, ...batchContext },- },- context: element.context,- }))-- return Promise.resolve(ok({ elements, batchContext }))+ const batchContext = {+ ...input.batchContext,+ eventFiltersBatchAppMetrics,+ }+ return Promise.resolve(ok({ elements: input.elements, batchContext }))}}diff --git a/nodejs/src/ingestion/common/steps/group-store-batch-step.ts b/nodejs/src/ingestion/common/steps/group-store-batch-step.tsnew file mode 100644index 000000000000..e0c8885caca8--- /dev/null+++ b/nodejs/src/ingestion/common/steps/group-store-batch-step.ts@@ -0,0 +1,18 @@+import { BatchWritingGroupStore } from '../../../worker/ingestion/groups/batch-writing-group-store'+import { BatchBoundGroupStore, GroupStoreForBatch } from '../../../worker/ingestion/groups/group-store-for-batch'+import { BeforeBatchStep } from '../../pipelines/batching-pipeline'+import { ok } from '../../pipelines/results'++export interface GroupStoreBatchContext {+ groupStoreForBatch: GroupStoreForBatch+}++export function createGroupStoreBeforeBatchStep<TInput, CInput, CBatch>(+ groupStore: BatchWritingGroupStore+): BeforeBatchStep<TInput, CInput, CBatch, CBatch & GroupStoreBatchContext> {+ return function groupStoreBeforeBatchStep(input) {+ const groupStoreForBatch: GroupStoreForBatch = new BatchBoundGroupStore(groupStore, input.batchContext.batchId)+ const batchContext = { ...input.batchContext, groupStoreForBatch }+ return Promise.resolve(ok({ elements: input.elements, batchContext }))+ }+}diff --git a/nodejs/src/ingestion/common/steps/persons-store-batch-step.ts b/nodejs/src/ingestion/common/steps/persons-store-batch-step.tsnew file mode 100644index 000000000000..5bc083e1864e--- /dev/null+++ b/nodejs/src/ingestion/common/steps/persons-store-batch-step.ts@@ -0,0 +1,28 @@+import { PersonsStore } from '../../../worker/ingestion/persons/persons-store'+import { BatchBoundPersonsStore, PersonsStoreForBatch } from '../../../worker/ingestion/persons/persons-store-for-batch'+import { BeforeBatchStep } from '../../pipelines/batching-pipeline'+import { ok } from '../../pipelines/results'++export interface PersonsStoreBatchContext {+ personsStoreForBatch: PersonsStoreForBatch+}++/**+ * BeforeBatch step that creates a batch-bound PersonsStore and attaches it to+ * the batch context and each element value.+ *+ * Must run after createEventFiltersBatchAppMetricsBeforeBatchStep so that+ * EventFiltersBatchContext is already present on elements and batchContext.+ */+export function createPersonsStoreBeforeBatchStep<TInput, CInput, CBatch>(+ personsStore: PersonsStore+): BeforeBatchStep<TInput, CInput, CBatch, CBatch & PersonsStoreBatchContext> {+ return async function personsStoreBeforeBatchStep(input) {+ const personsStoreForBatch: PersonsStoreForBatch = new BatchBoundPersonsStore(+ personsStore,+ input.batchContext.batchId+ )+ const batchContext = { ...input.batchContext, personsStoreForBatch }+ return Promise.resolve(ok({ elements: input.elements, batchContext }))+ }+}diff --git a/nodejs/src/ingestion/event-processing/flush-batch-stores-step.test.ts b/nodejs/src/ingestion/event-processing/flush-batch-stores-step.test.tsindex bbf30f92814a..34bdcda082f9 100644--- a/nodejs/src/ingestion/event-processing/flush-batch-stores-step.test.ts+++ b/nodejs/src/ingestion/event-processing/flush-batch-stores-step.test.ts@@ -3,6 +3,16 @@ import { MessageSizeTooLarge } from '../../utils/db/error'import { BatchWritingGroupStore } from '../../worker/ingestion/groups/batch-writing-group-store'import { PersonOutputs } from '../../worker/ingestion/persons/person-context'import { FlushResult, PersonsStore } from '../../worker/ingestion/persons/persons-store'+import {+ batchStoreFlushCacheEntriesHistogram,+ batchStoreFlushDirtyEntriesHistogram,+ batchStoreFlushKafkaMessagesHistogram,+ batchStoreFlushLatencyHistogram,+ batchStoreFlushOperationsCounter,+ batchStoreFlushReferencedBatchesHistogram,+ batchStoreFlushResultRecordsHistogram,+ batchStoreFlushTriggerBatchSizeHistogram,+} from '../../worker/ingestion/stores/metrics'import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '../analytics/outputs'import { emitIngestionWarning } from '../common/ingestion-warnings'import { INGESTION_WARNINGS_OUTPUT } from '../common/outputs'@@ -14,6 +24,17 @@ jest.mock('../common/ingestion-warnings', () => ({emitIngestionWarning: jest.fn(),}))+jest.mock('../../worker/ingestion/stores/metrics', () => ({+ batchStoreFlushCacheEntriesHistogram: { observe: jest.fn() },+ batchStoreFlushDirtyEntriesHistogram: { observe: jest.fn() },+ batchStoreFlushKafkaMessagesHistogram: { observe: jest.fn() },+ batchStoreFlushLatencyHistogram: { observe: jest.fn() },+ batchStoreFlushOperationsCounter: { inc: jest.fn() },+ batchStoreFlushReferencedBatchesHistogram: { observe: jest.fn() },+ batchStoreFlushResultRecordsHistogram: { observe: jest.fn() },+ batchStoreFlushTriggerBatchSizeHistogram: { observe: jest.fn() },+}))+describe('flush-batch-stores-step', () => {let mockPersonsStore: jest.Mocked<PersonsStore>let mockGroupStore: jest.Mocked<BatchWritingGroupStore>@@ -22,15 +43,25 @@ describe('flush-batch-stores-step', () => {beforeEach(() => {mockPersonsStore = {+ getFlushStats: jest.fn(() => ({+ dirtyEntryCount: 0,+ referencedBatchCount: 0,+ cacheEntryCount: 0,+ })),flush: jest.fn(),- reportBatch: jest.fn(),- reset: jest.fn(),+ shutdown: jest.fn(),+ releaseBatch: jest.fn(),} as anymockGroupStore = {+ getFlushStats: jest.fn(() => ({+ dirtyEntryCount: 0,+ referencedBatchCount: 0,+ cacheEntryCount: 0,+ })),flush: jest.fn(),- reportBatch: jest.fn(),- reset: jest.fn(),+ shutdown: jest.fn(),+ releaseBatch: jest.fn(),} as anymockOutputs = createMockIngestionOutputs<@@ -74,26 +105,6 @@ describe('flush-batch-stores-step', () => {expect(mockGroupStore.flush).toHaveBeenCalledTimes(1)})- it('should report batch metrics after flushing', async () => {- mockPersonsStore.flush.mockResolvedValue([])- mockGroupStore.flush.mockResolvedValue([])-- await step(makeInput())-- expect(mockPersonsStore.reportBatch).toHaveBeenCalledTimes(1)- expect(mockGroupStore.reportBatch).toHaveBeenCalledTimes(1)- })-- it('should reset both stores after flushing', async () => {- mockPersonsStore.flush.mockResolvedValue([])- mockGroupStore.flush.mockResolvedValue([])-- await step(makeInput())-- expect(mockPersonsStore.reset).toHaveBeenCalledTimes(1)- expect(mockGroupStore.reset).toHaveBeenCalledTimes(1)- })-it('should return ok result with produce promises as side effects', async () => {const personMessages: FlushResult[] = [{@@ -196,6 +207,63 @@ describe('flush-batch-stores-step', () => {}})+ it('reports flush lifecycle metrics', async () => {+ const personMessages: FlushResult[] = [+ {+ messages: [+ { output: PERSONS_OUTPUT, value: Buffer.from('value1') },+ { output: PERSONS_OUTPUT, value: Buffer.from('value2') },+ ],+ teamId: 1,+ distinctId: 'user1',+ uuid: 'uuid1',+ },+ {+ messages: [{ output: PERSON_DISTINCT_IDS_OUTPUT, value: Buffer.from('value3') }],+ teamId: 1,+ distinctId: 'user2',+ uuid: 'uuid2',+ },+ ]++ mockPersonsStore.getFlushStats.mockReturnValue({+ dirtyEntryCount: 2,+ referencedBatchCount: 2,+ cacheEntryCount: 5,+ })+ mockGroupStore.getFlushStats.mockReturnValue({+ dirtyEntryCount: 1,+ referencedBatchCount: 1,+ cacheEntryCount: 3,+ })+ mockPersonsStore.flush.mockResolvedValue(personMessages)+ mockGroupStore.flush.mockResolvedValue([])++ await step(makeInput(7))++ expect(batchStoreFlushTriggerBatchSizeHistogram.observe).toHaveBeenCalledWith(7)+ expect(batchStoreFlushDirtyEntriesHistogram.observe).toHaveBeenCalledWith({ store: 'person' }, 2)+ expect(batchStoreFlushDirtyEntriesHistogram.observe).toHaveBeenCalledWith({ store: 'group' }, 1)+ expect(batchStoreFlushReferencedBatchesHistogram.observe).toHaveBeenCalledWith({ store: 'person' }, 2)+ expect(batchStoreFlushReferencedBatchesHistogram.observe).toHaveBeenCalledWith({ store: 'group' }, 1)+ expect(batchStoreFlushCacheEntriesHistogram.observe).toHaveBeenCalledWith({ store: 'person' }, 5)+ expect(batchStoreFlushCacheEntriesHistogram.observe).toHaveBeenCalledWith({ store: 'group' }, 3)+ expect(batchStoreFlushOperationsCounter.inc).toHaveBeenCalledWith({ store: 'person', outcome: 'success' })+ expect(batchStoreFlushOperationsCounter.inc).toHaveBeenCalledWith({ store: 'group', outcome: 'success' })+ expect(batchStoreFlushLatencyHistogram.observe).toHaveBeenCalledWith(+ { store: 'person', outcome: 'success' },+ expect.any(Number)+ )+ expect(batchStoreFlushLatencyHistogram.observe).toHaveBeenCalledWith(+ { store: 'group', outcome: 'success' },+ expect.any(Number)+ )+ expect(batchStoreFlushResultRecordsHistogram.observe).toHaveBeenCalledWith({ store: 'person' }, 2)+ expect(batchStoreFlushResultRecordsHistogram.observe).toHaveBeenCalledWith({ store: 'group' }, 0)+ expect(batchStoreFlushKafkaMessagesHistogram.observe).toHaveBeenCalledWith({ store: 'person' }, 3)+ expect(batchStoreFlushKafkaMessagesHistogram.observe).toHaveBeenCalledWith({ store: 'group' }, 0)+ })+it('should handle MessageSizeTooLarge errors gracefully', async () => {const personMessages: FlushResult[] = [{@@ -264,16 +332,26 @@ describe('flush-batch-stores-step', () => {await expect(step(makeInput())).rejects.toThrow('Database connection failed')})- it('should not reset or report if flush fails', async () => {+ it('calls releaseBatch on both stores with the correct batchId after a successful flush', async () => {+ mockPersonsStore.flush.mockResolvedValue([])+ mockGroupStore.flush.mockResolvedValue([])++ const input = makeInput()+ await step(input)++ expect(mockPersonsStore.releaseBatch).toHaveBeenCalledWith(input.batchId)+ expect(mockGroupStore.releaseBatch).toHaveBeenCalledWith(input.batchId)+ })++ it('calls releaseBatch on both stores even when flush throws', async () => {mockPersonsStore.flush.mockRejectedValue(new Error('DB error'))mockGroupStore.flush.mockResolvedValue([])- await expect(step(makeInput())).rejects.toThrow('DB error')+ const input = makeInput()+ await expect(step(input)).rejects.toThrow('DB error')- expect(mockPersonsStore.reportBatch).not.toHaveBeenCalled()- expect(mockGroupStore.reportBatch).not.toHaveBeenCalled()- expect(mockPersonsStore.reset).not.toHaveBeenCalled()- expect(mockGroupStore.reset).not.toHaveBeenCalled()+ expect(mockPersonsStore.releaseBatch).toHaveBeenCalledWith(input.batchId)+ expect(mockGroupStore.releaseBatch).toHaveBeenCalledWith(input.batchId)})it('should handle null values in messages', async () => {@@ -297,7 +375,7 @@ describe('flush-batch-stores-step', () => {})})- it('should call lifecycle methods in correct order', async () => {+ it('flushes both stores in parallel', async () => {const callOrder: string[] = []mockPersonsStore.flush.mockImplementation(() => {@@ -308,28 +386,10 @@ describe('flush-batch-stores-step', () => {callOrder.push('group.flush')return Promise.resolve([])})- mockPersonsStore.reportBatch.mockImplementation(() => {- callOrder.push('persons.reportBatch')- })- mockGroupStore.reportBatch.mockImplementation(() => {- callOrder.push('group.reportBatch')- })- mockPersonsStore.reset.mockImplementation(() => {- callOrder.push('persons.reset')- })- mockGroupStore.reset.mockImplementation(() => {- callOrder.push('group.reset')- })await step(makeInput())- expect(callOrder.slice(0, 2).sort()).toEqual(['group.flush', 'persons.flush'])- expect(callOrder.slice(2)).toEqual([- 'persons.reportBatch',- 'group.reportBatch',- 'persons.reset',- 'group.reset',- ])+ expect(callOrder.sort()).toEqual(['group.flush', 'persons.flush'])})it('should produce messages with correct Buffer conversion', async () => {diff --git a/nodejs/src/ingestion/event-processing/flush-batch-stores-step.ts b/nodejs/src/ingestion/event-processing/flush-batch-stores-step.tsindex 8632b9d3e1be..79af1cb21f34 100644--- a/nodejs/src/ingestion/event-processing/flush-batch-stores-step.ts+++ b/nodejs/src/ingestion/event-processing/flush-batch-stores-step.ts@@ -3,6 +3,17 @@ import { logger } from '../../utils/logger'import { BatchWritingGroupStore } from '../../worker/ingestion/groups/batch-writing-group-store'import { PersonOutputs } from '../../worker/ingestion/persons/person-context'import { FlushResult, PersonsStore } from '../../worker/ingestion/persons/persons-store'+import { BatchWritingStore } from '../../worker/ingestion/stores/batch-writing-store'+import {+ batchStoreFlushCacheEntriesHistogram,+ batchStoreFlushDirtyEntriesHistogram,+ batchStoreFlushKafkaMessagesHistogram,+ batchStoreFlushLatencyHistogram,+ batchStoreFlushOperationsCounter,+ batchStoreFlushReferencedBatchesHistogram,+ batchStoreFlushResultRecordsHistogram,+ batchStoreFlushTriggerBatchSizeHistogram,+} from '../../worker/ingestion/stores/metrics'import { emitIngestionWarning } from '../common/ingestion-warnings'import { AfterBatchStep } from '../pipelines/batching-pipeline'import { ok } from '../pipelines/results'@@ -13,6 +24,8 @@ export interface FlushBatchStoresStepConfig {outputs: PersonOutputs}+type BatchStoreName = 'person' | 'group'+/*** AfterBatch hook that flushes person and group stores and returns* Kafka produce promises as side effects.@@ -41,26 +54,31 @@ export function createFlushBatchStoresStep<TOutput, COutput, CBatch, R extends sconst { personsStore, groupStore, outputs } = configreturn async function flushBatchStoresStep(input) {+ batchStoreFlushTriggerBatchSizeHistogram.observe(input.elements.length)+try {- // Flush both stores in parallel (DB operations, still blocking)- const [_groupResults, personsStoreMessages] = await Promise.all([groupStore.flush(), personsStore.flush()])+ // Flush both stores in parallel (DB operations, still blocking).+ // Stores own their own metric-emission lifecycle (periodic timer+ // started in their constructors, drained by shutdown()), so this+ // step no longer touches reset/reportBatch — caches persist across+ // batches by design under concurrentBatches > 1.+ const [groupResults, personsStoreMessages] = await Promise.all([+ flushStore('group', groupStore),+ flushStore('person', personsStore),+ ])++ const personStoreKafkaMessageCount = countFlushResultMessages(personsStoreMessages)logger.info('🔄', 'flushBatchStoresStep: Flushed stores', {batchSize: input.elements.length,personStoreMessageCount: personsStoreMessages.length,+ personStoreKafkaMessageCount,+ groupStoreMessageCount: groupResults.length,})// Create Kafka produce promises for all person/group store updatesconst producePromises = createProducePromises(personsStoreMessages, outputs)- // Report metrics for this batch- personsStore.reportBatch()- groupStore.reportBatch()-- // Reset stores for next batch- personsStore.reset()- groupStore.reset()-return ok(input, producePromises)} catch (error) {// If flush fails, the error will bubble up and fail the entire batch@@ -70,10 +88,41 @@ export function createFlushBatchStoresStep<TOutput, COutput, CBatch, R extends sbatchSize: input.elements.length,})throw error+ } finally {+ // Always release the batch to prevent refcount leaks, even on flush failure.+ personsStore.releaseBatch(input.batchId)+ groupStore.releaseBatch(input.batchId)}}}+async function flushStore(store: BatchStoreName, batchWritingStore: BatchWritingStore): Promise<FlushResult[]> {+ const flushStats = batchWritingStore.getFlushStats()+ batchStoreFlushDirtyEntriesHistogram.observe({ store }, flushStats.dirtyEntryCount)+ batchStoreFlushReferencedBatchesHistogram.observe({ store }, flushStats.referencedBatchCount)+ batchStoreFlushCacheEntriesHistogram.observe({ store }, flushStats.cacheEntryCount)++ const flushStartTime = performance.now()+ try {+ const flushResults = await batchWritingStore.flush()+ const latencySeconds = (performance.now() - flushStartTime) / 1000+ batchStoreFlushLatencyHistogram.observe({ store, outcome: 'success' }, latencySeconds)+ batchStoreFlushOperationsCounter.inc({ store, outcome: 'success' })+ batchStoreFlushResultRecordsHistogram.observe({ store }, flushResults.length)+ batchStoreFlushKafkaMessagesHistogram.observe({ store }, countFlushResultMessages(flushResults))+ return flushResults+ } catch (error) {+ const latencySeconds = (performance.now() - flushStartTime) / 1000+ batchStoreFlushLatencyHistogram.observe({ store, outcome: 'error' }, latencySeconds)+ batchStoreFlushOperationsCounter.inc({ store, outcome: 'error' })+ throw error+ }+}++function countFlushResultMessages(flushResults: FlushResult[]): number {+ return flushResults.reduce((count, record) => count + record.messages.length, 0)+}+/*** Creates Kafka produce promises for all person store flush results.* These promises handle errors appropriately:diff --git a/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.test.ts b/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.test.tsindex 62db10a732a6..73bb76b24a5b 100644--- a/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.test.ts+++ b/nodejs/src/ingestion/event-processing/normalize-process-person-flag-step.test.ts@@ -1,18 +1,16 @@import { v4 } from 'uuid'import { PluginEvent } from '~/plugin-scaffold'+import { EventHeaders } from '~/types'import { createTestEventHeaders } from '../../../tests/helpers/event-headers'-import { createTestMessage } from '../../../tests/helpers/kafka-message'import { createTestPluginEvent } from '../../../tests/helpers/plugin-event'-import { createTestTeam } from '../../../tests/helpers/team'-import { PerDistinctIdPipelineInput } from '../analytics'import { PipelineResultType } from '../pipelines/results'import { createNormalizeProcessPersonFlagStep } from './normalize-process-person-flag-step'-describe('normalizeProcessPersonFlagStep', () => {- const team = createTestTeam()+type StepInput = { event: PluginEvent; headers: EventHeaders }+describe('normalizeProcessPersonFlagStep', () => {const baseEvent: PluginEvent = createTestPluginEvent({distinct_id: 'my_id',site_url: '',@@ -21,10 +19,8 @@ describe('normalizeProcessPersonFlagStep', () => {uuid: v4(),})- const baseInput: PerDistinctIdPipelineInput = {- message: createTestMessage(),+ const baseInput: StepInput = {event: baseEvent,- team,headers: createTestEventHeaders(),}@@ -34,7 +30,7 @@ describe('normalizeProcessPersonFlagStep', () => {it.each(['$identify', '$create_alias', '$merge_dangerously', '$groupidentify'])('drops event %s when $process_person_profile=false',async (eventName) => {- const input: PerDistinctIdPipelineInput = {+ const input: StepInput = {...baseInput,event: {...baseEvent,@@ -60,7 +56,7 @@ describe('normalizeProcessPersonFlagStep', () => {)it('allows regular events when $process_person_profile=false', async () => {- const input: PerDistinctIdPipelineInput = {+ const input: StepInput = {...baseInput,event: {...baseEvent,@@ -79,7 +75,7 @@ describe('normalizeProcessPersonFlagStep', () => {})it('adds warning for invalid $process_person_profile values', async () => {- const input: PerDistinctIdPipelineInput = {+ const input: StepInput = {...baseInput,event: {...baseEvent,@@ -107,7 +103,7 @@ describe('normalizeProcessPersonFlagStep', () => {describe('force_disable_person_processing header', () => {it('sets processPerson to false when header is true', async () => {- const input: PerDistinctIdPipelineInput = {+ const input: StepInput = {...baseInput,headers: createTestEventHeaders({ force_disable_person_processing: true }),}@@ -122,7 +118,7 @@ describe('normalizeProcessPersonFlagStep', () => {})it('defaults to processPerson=true when header is false and no $process_person_profile property', async () => {- const input: PerDistinctIdPipelineInput = {+ const input: StepInput = {...baseInput,headers: createTestEventHeaders(),}@@ -137,7 +133,7 @@ describe('normalizeProcessPersonFlagStep', () => {})it('overrides $process_person_profile property when header is true', async () => {- const input: PerDistinctIdPipelineInput = {+ const input: StepInput = {...baseInput,event: {...baseEvent,@@ -156,7 +152,7 @@ describe('normalizeProcessPersonFlagStep', () => {})it('respects $process_person_profile=false when header is false', async () => {- const input: PerDistinctIdPipelineInput = {+ const input: StepInput = {...baseInput,event: {...baseEvent,@@ -177,7 +173,7 @@ describe('normalizeProcessPersonFlagStep', () => {describe('default behavior', () => {it('defaults to processPerson=true when no header and no $process_person_profile property', async () => {- const input: PerDistinctIdPipelineInput = {+ const input: StepInput = {...baseInput,}@@ -191,7 +187,7 @@ describe('normalizeProcessPersonFlagStep', () => {})it('keeps processPerson=true when $process_person_profile=true explicitly', async () => {- const input: PerDistinctIdPipelineInput = {+ const input: StepInput = {...baseInput,event: {...baseEvent,diff --git a/nodejs/src/ingestion/event-processing/process-groups-step.test.ts b/nodejs/src/ingestion/event-processing/process-groups-step.test.tsindex f22eb2793d7c..835a35343c7c 100644--- a/nodejs/src/ingestion/event-processing/process-groups-step.test.ts+++ b/nodejs/src/ingestion/event-processing/process-groups-step.test.ts@@ -5,7 +5,7 @@ import { PreIngestionEvent, ProjectId, Team, TimestampFormat } from '../../typesimport { TeamManager } from '../../utils/team-manager'import { castTimestampOrNow } from '../../utils/utils'import { GroupTypeManager } from '../../worker/ingestion/group-type-manager'-import { BatchWritingGroupStore } from '../../worker/ingestion/groups/batch-writing-group-store'+import { GroupStoreForBatch } from '../../worker/ingestion/groups/group-store-for-batch'import { PipelineResultType } from '../pipelines/results'import { createProcessGroupsStep } from './process-groups-step'@@ -24,12 +24,13 @@ type TestInput = {preparedEvent: PreIngestionEventteam: TeamprocessPerson: boolean+ groupStoreForBatch: GroupStoreForBatch}describe('createProcessGroupsStep', () => {let mockTeamManager: jest.Mocked<Pick<TeamManager, 'setTeamIngestedEvent'>>let mockGroupTypeManager: jest.Mocked<Pick<GroupTypeManager, 'fetchGroupTypeIndex'>>- let mockGroupStore: jest.Mocked<Pick<BatchWritingGroupStore, 'upsertGroup'>>+ let mockGroupStore: jest.Mocked<Pick<GroupStoreForBatch, 'upsertGroup'>>beforeEach(() => {jest.clearAllMocks()@@ -43,6 +44,7 @@ describe('createProcessGroupsStep', () => {preparedEvent: createTestPreIngestionEvent(),team: createTestTeam(),processPerson: true,+ groupStoreForBatch: mockGroupStore as unknown as GroupStoreForBatch,...overrides,})@@ -50,7 +52,6 @@ describe('createProcessGroupsStep', () => {createProcessGroupsStep<TestInput>(mockTeamManager as unknown as TeamManager,mockGroupTypeManager as unknown as GroupTypeManager,- mockGroupStore as unknown as BatchWritingGroupStore,{ SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP: skipUpdate })diff --git a/nodejs/src/ingestion/event-processing/process-groups-step.ts b/nodejs/src/ingestion/event-processing/process-groups-step.tsindex ad807f080cbb..2eaed71a622a 100644--- a/nodejs/src/ingestion/event-processing/process-groups-step.ts+++ b/nodejs/src/ingestion/event-processing/process-groups-step.ts@@ -8,7 +8,7 @@ import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { TeamManager } from '../../utils/team-manager'import { GroupTypeManager } from '../../worker/ingestion/group-type-manager'-import { BatchWritingGroupStore } from '../../worker/ingestion/groups/batch-writing-group-store'+import { GroupStoreForBatch } from '../../worker/ingestion/groups/group-store-for-batch'import { ok } from '../pipelines/results'import { ProcessingStep } from '../pipelines/steps'import { EventPipelineRunnerOptions } from './event-pipeline-options'@@ -20,6 +20,7 @@ export interface ProcessGroupsStepInput {preparedEvent: PreIngestionEventteam: TeamprocessPerson: boolean+ groupStoreForBatch: GroupStoreForBatch}export type ProcessGroupsStepResult<TInput> = TInput@@ -27,11 +28,10 @@ export type ProcessGroupsStepResult<TInput> = TInputexport function createProcessGroupsStep<TInput extends ProcessGroupsStepInput>(teamManager: TeamManager,groupTypeManager: GroupTypeManager,- groupStore: BatchWritingGroupStore,options: Pick<EventPipelineRunnerOptions, 'SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP'>): ProcessingStep<TInput, ProcessGroupsStepResult<TInput>> {return async function processGroupsStep(input: TInput) {- const { preparedEvent, team, processPerson } = input+ const { preparedEvent, team, processPerson, groupStoreForBatch } = inputif (!options.SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP) {try {@@ -57,7 +57,7 @@ export function createProcessGroupsStep<TInput extends ProcessGroupsStepInput>(if (preparedEvent.event === '$groupidentify') {await upsertGroup(groupTypeManager,- groupStore,+ groupStoreForBatch,team.id,team.project_id,preparedEvent.properties,@@ -94,7 +94,7 @@ async function updateGroupsAndFirstEvent(async function upsertGroup(groupTypeManager: GroupTypeManager,- groupStore: BatchWritingGroupStore,+ groupStore: GroupStoreForBatch,teamId: TeamId,projectId: ProjectId,properties: Properties,diff --git a/nodejs/src/ingestion/event-processing/process-personless-step.test.ts b/nodejs/src/ingestion/event-processing/process-personless-step.test.tsindex add82b6ec4ab..734ea1e523e0 100644--- a/nodejs/src/ingestion/event-processing/process-personless-step.test.ts+++ b/nodejs/src/ingestion/event-processing/process-personless-step.test.ts@@ -5,6 +5,7 @@ import { DateTime } from 'luxon'import { PipelineResultType, isOkResult } from '~/ingestion/pipelines/results'import { PluginEvent, Properties } from '~/plugin-scaffold'import { BatchWritingPersonsStore } from '~/worker/ingestion/persons/batch-writing-person-store'+import { BatchBoundPersonsStore } from '~/worker/ingestion/persons/persons-store-for-batch'import { PostgresPersonRepository } from '~/worker/ingestion/persons/repositories/postgres-person-repository'import { createOrganization, createTeam, getTeam, resetTestDatabase } from '../../../tests/helpers/sql'@@ -80,7 +81,14 @@ describe('createProcessPersonlessStep', () => {team = (await getTeam(hub.postgres, teamId))!const personRepository = new PostgresPersonRepository(hub.postgres)- const ingestionWarningsOutputs = new IngestionOutputs({+ const storeOutputs = new IngestionOutputs({+ [PERSONS_OUTPUT]: new SingleIngestionOutput(PERSONS_OUTPUT, KAFKA_PERSON, mockProducer, 'test'),+ [PERSON_DISTINCT_IDS_OUTPUT]: new SingleIngestionOutput(+ PERSON_DISTINCT_IDS_OUTPUT,+ KAFKA_PERSON_DISTINCT_ID,+ mockProducer,+ 'test'+ ),[INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(INGESTION_WARNINGS_OUTPUT,'ingestion_warnings_test',@@ -88,7 +96,7 @@ describe('createProcessPersonlessStep', () => {'test'),})- personsStore = new BatchWritingPersonsStore(personRepository, ingestionWarningsOutputs)+ personsStore = new BatchWritingPersonsStore(personRepository, storeOutputs)pluginEvent = {distinct_id: 'test-user-123',@@ -114,11 +122,12 @@ describe('createProcessPersonlessStep', () => {timestamp,processPerson: false,forceDisablePersonProcessing: false,+ personsStoreForBatch: new BatchBoundPersonsStore(personsStore, 0),...overrides,})it('passes through when processPerson is true', async () => {- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()const input = createInput({ processPerson: true })const result = await step(input)@@ -131,7 +140,7 @@ describe('createProcessPersonlessStep', () => {describe('basic personless functionality', () => {it('returns fake person when no existing person found', async () => {- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -152,7 +161,7 @@ describe('createProcessPersonlessStep', () => {distinctId: pluginEvent.distinct_id,})- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -167,7 +176,7 @@ describe('createProcessPersonlessStep', () => {it('checks batch result for personless distinct ID when no person exists', async () => {const getPersonlessBatchResultSpy = jest.spyOn(personsStore, 'getPersonlessBatchResult')- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()await step(createInput())expect(getPersonlessBatchResultSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id)@@ -176,7 +185,7 @@ describe('createProcessPersonlessStep', () => {it('returns fake person when batch result indicates no merge', async () => {jest.spyOn(personsStore, 'getPersonlessBatchResult').mockReturnValue(false)- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -196,7 +205,7 @@ describe('createProcessPersonlessStep', () => {distinctId: pluginEvent.distinct_id,})- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -215,7 +224,7 @@ describe('createProcessPersonlessStep', () => {distinctId: pluginEvent.distinct_id,})- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -236,7 +245,7 @@ describe('createProcessPersonlessStep', () => {distinctId: pluginEvent.distinct_id,})- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -270,11 +279,11 @@ describe('createProcessPersonlessStep', () => {jest.spyOn(personsStore, 'getPersonlessBatchResult').mockReturnValue(true)const fetchForUpdateSpy = jest.spyOn(personsStore, 'fetchForUpdate').mockResolvedValue(person)- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)- expect(fetchForUpdateSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id)+ expect(fetchForUpdateSpy).toHaveBeenCalledWith(teamId, pluginEvent.distinct_id, 0)})})@@ -283,7 +292,7 @@ describe('createProcessPersonlessStep', () => {const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')const getPersonlessBatchResultSpy = jest.spyOn(personsStore, 'getPersonlessBatchResult')- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()const result = await step(createInput({ forceDisablePersonProcessing: true }))expect(result.type).toBe(PipelineResultType.OK)@@ -301,7 +310,7 @@ describe('createProcessPersonlessStep', () => {it('performs normal processing when false', async () => {const fetchForCheckingSpy = jest.spyOn(personsStore, 'fetchForChecking')- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()await step(createInput())expect(fetchForCheckingSpy).toHaveBeenCalled()@@ -309,7 +318,7 @@ describe('createProcessPersonlessStep', () => {it('works with different distinct IDs', async () => {const distinctIds = ['user-1', 'user-2', 'user-3']- const step = createProcessPersonlessStep(personsStore)+ const step = createProcessPersonlessStep()for (const distinctId of distinctIds) {const result = await step(diff --git a/nodejs/src/ingestion/event-processing/process-personless-step.ts b/nodejs/src/ingestion/event-processing/process-personless-step.tsindex 8916ca6c2a33..632b53216a1e 100644--- a/nodejs/src/ingestion/event-processing/process-personless-step.ts+++ b/nodejs/src/ingestion/event-processing/process-personless-step.ts@@ -4,7 +4,7 @@ import { PluginEvent } from '~/plugin-scaffold'import { Person, Team } from '../../types'import { uuidFromDistinctId } from '../../worker/ingestion/person-uuid'-import { PersonsStore } from '../../worker/ingestion/persons/persons-store'+import { PersonsStoreForBatch } from '../../worker/ingestion/persons/persons-store-for-batch'import { PipelineResult, ok } from '../pipelines/results'import { ProcessingStep } from '../pipelines/steps'@@ -14,6 +14,7 @@ export type ProcessPersonlessInput = {timestamp: DateTimeprocessPerson: booleanforceDisablePersonProcessing: boolean+ personsStoreForBatch: PersonsStoreForBatch}export type ProcessPersonlessOutput = {@@ -29,9 +30,10 @@ export type ProcessPersonlessOutput = {* 3. Calculates force_upgrade flag* 4. Returns person (real or fake) with potential force_upgrade flag*/-export function createProcessPersonlessStep<TInput extends ProcessPersonlessInput>(- personsStore: PersonsStore-): ProcessingStep<TInput, TInput & ProcessPersonlessOutput> {+export function createProcessPersonlessStep<TInput extends ProcessPersonlessInput>(): ProcessingStep<+ TInput,+ TInput & ProcessPersonlessOutput+> {return async function processPersonlessStep(input: TInput): Promise<PipelineResult<TInput & ProcessPersonlessOutput>> {@@ -39,7 +41,7 @@ export function createProcessPersonlessStep<TInput extends ProcessPersonlessInpureturn ok(input)}- const { normalizedEvent, team, timestamp, forceDisablePersonProcessing } = input+ const { normalizedEvent, team, timestamp, forceDisablePersonProcessing, personsStoreForBatch } = inputconst distinctId = normalizedEvent.distinct_idif (forceDisablePersonProcessing) {@@ -47,19 +49,19 @@ export function createProcessPersonlessStep<TInput extends ProcessPersonlessInpu}// Check if a real person exists for this distinct_id (from prefetch cache)- let existingPerson = await personsStore.fetchForChecking(team.id, distinctId)+ let existingPerson = await personsStoreForBatch.fetchForChecking(team.id, distinctId)if (!existingPerson) {// Check if batch insert found this distinct_id was merged// The batch step (processPersonlessDistinctIdsBatchStep) already did the INSERT// and stored is_merged=true results in the personsStore cache- const personIsMerged = personsStore.getPersonlessBatchResult(team.id, distinctId)+ const personIsMerged = personsStoreForBatch.getPersonlessBatchResult(team.id, distinctId)if (personIsMerged) {// If is_merged came back true, it means the posthog_personlessdistinctid// was updated by a merge. We need to fetch the person again (using the leader)// so that we properly associate this event with the Person we got merged into.- existingPerson = await personsStore.fetchForUpdate(team.id, distinctId)+ existingPerson = await personsStoreForBatch.fetchForUpdate(team.id, distinctId)}}diff --git a/nodejs/src/ingestion/event-processing/process-persons-step.integration.test.ts b/nodejs/src/ingestion/event-processing/process-persons-step.integration.test.tsindex f08837016046..fa0973e2d337 100644--- a/nodejs/src/ingestion/event-processing/process-persons-step.integration.test.ts+++ b/nodejs/src/ingestion/event-processing/process-persons-step.integration.test.ts@@ -6,6 +6,7 @@ import { ASYNC_OUTPUT } from '~/ingestion/analytics/outputs'import { PipelineResultType, isDlqResult, isOkResult, isRedirectResult } from '~/ingestion/pipelines/results'import { PluginEvent } from '~/plugin-scaffold'import { BatchWritingPersonsStore } from '~/worker/ingestion/persons/batch-writing-person-store'+import { BatchBoundPersonsStore } from '~/worker/ingestion/persons/persons-store-for-batch'import { PostgresPersonRepository } from '~/worker/ingestion/persons/repositories/postgres-person-repository'import {@@ -71,15 +72,7 @@ describe('createProcessPersonsStep', () => {'test'),})- const ingestionWarningsOutputs = new IngestionOutputs({- [INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(- INGESTION_WARNINGS_OUTPUT,- KAFKA_INGESTION_WARNINGS,- mockProducer,- 'test'- ),- })- personsStore = new BatchWritingPersonsStore(personRepository, ingestionWarningsOutputs)+ personsStore = new BatchWritingPersonsStore(personRepository, personOutputs)pluginEvent = {distinct_id: 'my_id',@@ -107,6 +100,7 @@ describe('createProcessPersonsStep', () => {normalizedEvent: pluginEvent,team,timestamp,+ personsStoreForBatch: new BatchBoundPersonsStore(personsStore, 0),...overrides,})@@ -132,7 +126,7 @@ describe('createProcessPersonsStep', () => {}it('creates person with $set properties', async () => {- const step = createProcessPersonsStep(options, personOutputs, personsStore)+ const step = createProcessPersonsStep(options, personOutputs)const result = await step(createInput())expect(result.type).toBe(PipelineResultType.OK)@@ -169,7 +163,7 @@ describe('createProcessPersonsStep', () => {const normalizedEvent = normalizeProcessPerson(normalizeEvent(event), processPerson)const normalizedTimestamp = parseEventTimestamp(normalizedEvent)- const step = createProcessPersonsStep(options, personOutputs, personsStore)+ const step = createProcessPersonsStep(options, personOutputs)const result = await step(createInput({ normalizedEvent, timestamp: normalizedTimestamp }))expect(result.type).toBe(PipelineResultType.OK)@@ -216,7 +210,7 @@ describe('createProcessPersonsStep', () => {created_at: DateTime.fromISO('1970-01-01T00:00:05.000Z'),}- const step = createProcessPersonsStep(options, personOutputs, personsStore)+ const step = createProcessPersonsStep(options, personOutputs)const result = await step(createInput({ personlessPerson }))expect(result.type).toBe(PipelineResultType.OK)@@ -238,7 +232,7 @@ describe('createProcessPersonsStep', () => {force_upgrade: true,}- const step = createProcessPersonsStep(options, personOutputs, personsStore)+ const step = createProcessPersonsStep(options, personOutputs)const result = await step(createInput({ personlessPerson }))expect(result.type).toBe(PipelineResultType.OK)@@ -253,7 +247,7 @@ describe('createProcessPersonsStep', () => {})it('preserves additional input fields in the output', async () => {- const step = createProcessPersonsStep(options, personOutputs, personsStore)+ const step = createProcessPersonsStep(options, personOutputs)const input = { ...createInput(), extraField: 'preserved' }const result = await step(input)@@ -284,7 +278,7 @@ describe('createProcessPersonsStep', () => {PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: 2,}- const step = createProcessPersonsStep(limitOptions, personOutputs, personsStore)+ const step = createProcessPersonsStep(limitOptions, personOutputs)const result = await step(createInput({normalizedEvent: identifyEvent,@@ -312,7 +306,7 @@ describe('createProcessPersonsStep', () => {uuid: new UUIDT().toString(),}- const step = createProcessPersonsStep(options, personOutputs, personsStore)+ const step = createProcessPersonsStep(options, personOutputs)const result = await step(createInput({normalizedEvent: laterEvent,@@ -355,7 +349,7 @@ describe('createProcessPersonsStep', () => {uuid: new UUIDT().toString(),}- const step = createProcessPersonsStep(options, personOutputs, personsStore)+ const step = createProcessPersonsStep(options, personOutputs)const result = await step(createInput({normalizedEvent: laterEvent,@@ -390,7 +384,7 @@ describe('createProcessPersonsStep', () => {PERSON_MERGE_ASYNC_ENABLED: true,}- const step = createProcessPersonsStep(asyncOptions, personOutputs, personsStore)+ const step = createProcessPersonsStep(asyncOptions, personOutputs)const result = await step(createInput({normalizedEvent: identifyEvent,diff --git a/nodejs/src/ingestion/event-processing/process-persons-step.ts b/nodejs/src/ingestion/event-processing/process-persons-step.tsindex 51816e8111f4..1cd6262e5bd0 100644--- a/nodejs/src/ingestion/event-processing/process-persons-step.ts+++ b/nodejs/src/ingestion/event-processing/process-persons-step.ts@@ -8,7 +8,7 @@ import { PersonEventProcessor } from '../../worker/ingestion/persons/person-evenimport { PersonMergeService } from '../../worker/ingestion/persons/person-merge-service'import { determineMergeMode } from '../../worker/ingestion/persons/person-merge-types'import { PersonPropertyService } from '../../worker/ingestion/persons/person-property-service'-import { PersonsStore } from '../../worker/ingestion/persons/persons-store'+import { PersonsStoreForBatch } from '../../worker/ingestion/persons/persons-store-for-batch'import { AsyncOutput } from '../analytics/outputs'import { PipelineResult, isOkResult, ok } from '../pipelines/results'import { ProcessingStep } from '../pipelines/steps'@@ -19,6 +19,7 @@ export type ProcessPersonsInput = {team: Teamtimestamp: DateTimepersonlessPerson?: Person+ personsStoreForBatch: PersonsStoreForBatch}export type ProcessPersonsOutput = {@@ -27,8 +28,7 @@ export type ProcessPersonsOutput = {export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(options: EventPipelineRunnerOptions,- personOutputs: PersonOutputs,- personsStore: PersonsStore+ personOutputs: PersonOutputs): ProcessingStep<TInput, TInput & ProcessPersonsOutput, AsyncOutput> {const mergeMode = determineMergeMode(options.PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT,@@ -39,7 +39,7 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(return async function processPersonsStep(input: TInput): Promise<PipelineResult<TInput & ProcessPersonsOutput, AsyncOutput>> {- const { normalizedEvent, team, timestamp, personlessPerson } = input+ const { normalizedEvent, team, timestamp, personlessPerson, personsStoreForBatch } = inputif (personlessPerson && !personlessPerson.force_upgrade) {return ok({ ...input, person: personlessPerson })@@ -54,7 +54,7 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(timestamp,true,personOutputs,- personsStore,+ personsStoreForBatch,options.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,mergeMode,options.PERSON_PROPERTIES_UPDATE_ALL,diff --git a/nodejs/src/ingestion/ingestion-consumer.test.ts b/nodejs/src/ingestion/ingestion-consumer.test.tsindex 1583176e948d..c6be1280ad2d 100644--- a/nodejs/src/ingestion/ingestion-consumer.test.ts+++ b/nodejs/src/ingestion/ingestion-consumer.test.ts@@ -10,7 +10,7 @@ import { template as geoipTemplate } from '~/cdp/templates/_transformations/geoiimport { compileHog } from '~/cdp/templates/compiler'import { COOKIELESS_MODE_FLAG_PROPERTY, COOKIELESS_SENTINEL_VALUE } from '~/ingestion/cookieless/cookieless-manager'import { forSnapshot } from '~/tests/helpers/snapshots'-import { createTeam, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'+import { createTeam, fetchPostgresPersons, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'import { CookielessServerHashMode, Hub, PipelineEvent, Team } from '../../src/types'import { closeHub, createHub } from '../../src/utils/db/hub'@@ -22,6 +22,7 @@ import { parseJSON } from '../utils/json-parse'import { logger } from '../utils/logger'import { UUIDT } from '../utils/utils'import { ClickhouseGroupRepository } from '../worker/ingestion/groups/repositories/clickhouse-group-repository'+import { BatchWritingPersonsStore } from '../worker/ingestion/persons/batch-writing-person-store'import { createPrepareEventStep } from './event-processing/prepare-event-step'import { IngestionConsumer } from './ingestion-consumer'@@ -1489,8 +1490,6 @@ describe('IngestionConsumer', () => {it('should flush stores exactly once per batch regardless of number of events', async () => {const flushSpy = jest.spyOn(ingester['personsStore'], 'flush')const groupFlushSpy = jest.spyOn(ingester['groupStore'], 'flush')- const reportBatchSpy = jest.spyOn(ingester['personsStore'], 'reportBatch')- const resetSpy = jest.spyOn(ingester['personsStore'], 'reset')const events: PipelineEvent[] = [{@@ -1532,32 +1531,23 @@ describe('IngestionConsumer', () => {await ingester.handleKafkaBatch(messages)- // Verify stores were flushed exactly onceexpect(flushSpy).toHaveBeenCalledTimes(1)expect(groupFlushSpy).toHaveBeenCalledTimes(1)- // Verify lifecycle methods called exactly once- expect(reportBatchSpy).toHaveBeenCalledTimes(1)- expect(resetSpy).toHaveBeenCalledTimes(1)-flushSpy.mockRestore()groupFlushSpy.mockRestore()- reportBatchSpy.mockRestore()- resetSpy.mockRestore()})- it('should call flush before reportBatch and reset', async () => {+ it('should flush persons and group stores for each batch', async () => {const callOrder: string[] = []const flushSpy = jest.spyOn(ingester['personsStore'], 'flush').mockImplementation(() => {- callOrder.push('flush')+ callOrder.push('personsFlush')return Promise.resolve([])})- const reportBatchSpy = jest.spyOn(ingester['personsStore'], 'reportBatch').mockImplementation(() => {- callOrder.push('reportBatch')- })- const resetSpy = jest.spyOn(ingester['personsStore'], 'reset').mockImplementation(() => {- callOrder.push('reset')+ const groupFlushSpy = jest.spyOn(ingester['groupStore'], 'flush').mockImplementation(() => {+ callOrder.push('groupFlush')+ return Promise.resolve([])})const events: PipelineEvent[] = [@@ -1576,11 +1566,68 @@ describe('IngestionConsumer', () => {await ingester.handleKafkaBatch(createKafkaMessages(events))- expect(callOrder).toEqual(['flush', 'reportBatch', 'reset'])+ expect(callOrder).toContain('personsFlush')+ expect(callOrder).toContain('groupFlush')flushSpy.mockRestore()- reportBatchSpy.mockRestore()- resetSpy.mockRestore()+ groupFlushSpy.mockRestore()+ })+ })++ describe('multi-batch cache eviction and ordering', () => {+ it('person properties from batch 1 are visible in batch 2', async () => {+ await ingester.handleKafkaBatch(+ createKafkaMessages([createEvent({ properties: { $set: { name: 'Alice' } } })])+ )++ const personsAfterBatch1 = await fetchPostgresPersons(hub.postgres, team.id)+ expect(personsAfterBatch1).toHaveLength(1)+ expect(personsAfterBatch1[0].properties).toMatchObject({ name: 'Alice' })++ await ingester.handleKafkaBatch(+ createKafkaMessages([createEvent({ properties: { $set: { email: '[email protected]' } } })])+ )++ const personsAfterBatch2 = await fetchPostgresPersons(hub.postgres, team.id)+ expect(personsAfterBatch2).toHaveLength(1)+ expect(personsAfterBatch2[0].properties).toMatchObject({+ name: 'Alice',+ email: '[email protected]',+ })+ })++ it('cache entries are evicted after each batch completes', async () => {+ const personsStore = ingester['personsStore'] as BatchWritingPersonsStore++ await ingester.handleKafkaBatch(createKafkaMessages([createEvent()]))++ const batchDistinctKeys = (personsStore as any)['batchDistinctKeys'] as Map<number, Set<string>>+ expect(batchDistinctKeys.size).toBe(0)+ expect(personsStore.getCheckCache().size).toBe(0)+ })++ it('cache does not grow unboundedly across many sequential batches', async () => {+ const personsStore = ingester['personsStore'] as BatchWritingPersonsStore++ for (let i = 0; i < 5; i++) {+ await ingester.handleKafkaBatch(createKafkaMessages([createEvent({ distinct_id: `user-${i}` })]))+ }++ const batchDistinctKeys = (personsStore as any)['batchDistinctKeys'] as Map<number, Set<string>>+ expect(batchDistinctKeys.size).toBe(0)+ expect(personsStore.getCheckCache().size).toBe(0)+ })+ })++ describe('stop()', () => {+ it('calls shutdown() on persons and group stores', async () => {+ const personShutdownSpy = jest.spyOn(ingester['personsStore'], 'shutdown')+ const groupShutdownSpy = jest.spyOn(ingester['groupStore'], 'shutdown')++ await ingester.stop()++ expect(personShutdownSpy).toHaveBeenCalledTimes(1)+ expect(groupShutdownSpy).toHaveBeenCalledTimes(1)})})})diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex 216bfc8346ed..670285395b66 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -316,6 +316,9 @@ export class IngestionConsumer {}public async stop(): Promise<void> {+ if (this.isStopping) {+ return+ }logger.info('🔁', `${this.name} - stopping`)this.isStopping = true@@ -328,6 +331,21 @@ export class IngestionConsumer {await this.hogTransformer.stop()await this.stopEventFilterManager?.()await this.stopEventIngestionRestrictionManager?.()+ // Stores must be clean by now — flushBatchStoresStep runs after every+ // batch as part of the pipeline. After disconnect, we cannot commit+ // offsets, so writing dirty data here would produce duplicates on+ // partition rebalance. shutdown() will throw if anything is dirty,+ // which surfaces the drain-ordering bug without masking it.+ try {+ await this.personsStore.shutdown()+ } catch (error) {+ logger.error('🚨', `${this.name} - personsStore.shutdown() failed`, { error })+ }+ try {+ await this.groupStore.shutdown()+ } catch (error) {+ logger.error('🚨', `${this.name} - groupStore.shutdown() failed`, { error })+ }logger.info('👍', `${this.name} - stopped!`)}diff --git a/nodejs/src/ingestion/pipelines/batching-pipeline.test.ts b/nodejs/src/ingestion/pipelines/batching-pipeline.test.tsindex 35d758a49da5..39237659546d 100644--- a/nodejs/src/ingestion/pipelines/batching-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/batching-pipeline.test.ts@@ -36,7 +36,7 @@ describe('BatchingPipeline', () => {let afterBatchStep: jest.MockbeforeEach(() => {- beforeBatchStep = jest.fn(({ elements }) => Promise.resolve(ok({ elements, batchContext: {} })))+ beforeBatchStep = jest.fn(({ elements, batchContext }) => Promise.resolve(ok({ elements, batchContext })))afterBatchStep = jest.fn((input) =>Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext })))@@ -88,9 +88,9 @@ describe('BatchingPipeline', () => {await collector.feed(makeBatch([3]))expect(beforeBatchStep).toHaveBeenCalledTimes(2)- expect(beforeBatchStep.mock.calls[0][0].batchId).toBe(0)+ expect(beforeBatchStep.mock.calls[0][0].batchContext.batchId).toBe(0)expect(beforeBatchStep.mock.calls[0][0].elements).toHaveLength(2)- expect(beforeBatchStep.mock.calls[1][0].batchId).toBe(1)+ expect(beforeBatchStep.mock.calls[1][0].batchContext.batchId).toBe(1)expect(beforeBatchStep.mock.calls[1][0].elements).toHaveLength(1)})@@ -238,19 +238,20 @@ describe('BatchingPipeline', () => {})it('beforeBatch can add extra context to elements', async () => {- const collector = newBatchingPipeline<any, any, MsgCtx, string>(+ type BatchStore = { batchStore: string }+ const collector = newBatchingPipeline<any, any, MsgCtx, BatchStore>((builder) =>- builder.pipe(({ elements, batchId }) =>+ builder.pipe(({ elements, batchContext }) =>Promise.resolve(ok({elements: elements.map((el: any) => ({...el,context: {...el.context,- batchStore: `store-for-batch-${batchId}`,+ batchStore: `store-for-batch-${batchContext.batchId}`,},})),- batchContext: `store-for-batch-${batchId}`,+ batchContext: { ...batchContext, batchStore: `store-for-batch-${batchContext.batchId}` },}))),@@ -276,12 +277,13 @@ describe('BatchingPipeline', () => {const capturedAfter: Stores[] = []const collector = newBatchingPipeline<any, any, MsgCtx, Stores>((builder) =>- builder.pipe(({ elements, batchId }) => {- const batchContext: Stores =- batchId === 0+ builder.pipe(({ elements, batchContext: initBatchContext }) => {+ const stores: Stores =+ initBatchContext.batchId === 0? { personsStore: 'persons-0', groupStore: 'groups-0' }: { personsStore: 'persons-1', groupStore: 'groups-1' }- capturedBefore.push(batchContext)+ const batchContext = { ...initBatchContext, ...stores }+ capturedBefore.push(stores)return Promise.resolve(ok({ elements: elements as any, batchContext }))}),(builder) => builder,@@ -302,15 +304,17 @@ describe('BatchingPipeline', () => {{ personsStore: 'persons-1', groupStore: 'groups-1' },])expect(capturedAfter).toEqual([- { personsStore: 'persons-0', groupStore: 'groups-0' },- { personsStore: 'persons-1', groupStore: 'groups-1' },+ expect.objectContaining({ personsStore: 'persons-0', groupStore: 'groups-0' }),+ expect.objectContaining({ personsStore: 'persons-1', groupStore: 'groups-1' }),])})describe('side effects', () => {it('collects before pipeline side effects in next() result', async () => {const sideEffect = Promise.resolve('before-effect')- beforeBatchStep.mockImplementation(({ elements }: any) => ok({ elements, batchContext: {} }, [sideEffect]))+ beforeBatchStep.mockImplementation(({ elements, batchContext }: any) =>+ ok({ elements, batchContext }, [sideEffect])+ )const collector = createCollector()await collector.feed(makeBatch([1]))@@ -338,8 +342,8 @@ describe('BatchingPipeline', () => {const beforeEffect = Promise.resolve('before')const afterEffect = Promise.resolve('after')- beforeBatchStep.mockImplementation(({ elements }: any) =>- ok({ elements, batchContext: {} }, [beforeEffect])+ beforeBatchStep.mockImplementation(({ elements, batchContext }: any) =>+ ok({ elements, batchContext }, [beforeEffect]))afterBatchStep.mockImplementation((input: any) =>ok({ elements: input.elements, batchContext: input.batchContext }, [afterEffect])diff --git a/nodejs/src/ingestion/pipelines/batching-pipeline.ts b/nodejs/src/ingestion/pipelines/batching-pipeline.tsindex 51faf0f72419..9ef79324f74c 100644--- a/nodejs/src/ingestion/pipelines/batching-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/batching-pipeline.ts@@ -11,14 +11,14 @@ export interface BatchingContext {messageId: number}-export interface BeforeBatchInput<TInput, CInput> {+export interface BeforeBatchInput<TInput, CInput, CBatch = Record<never, object>> {elements: OkResultWithContext<TInput, CInput>[]- batchId: number+ batchContext: { batchId: number } & CBatch}export interface BeforeBatchOutput<TInput, CInput, CBatch> {- elements: OkResultWithContext<TInput & CBatch, CInput>[]- batchContext: CBatch+ elements: OkResultWithContext<TInput, CInput>[]+ batchContext: CBatch & { batchId: number }}export interface AfterBatchInput<TOutput, COutput, CBatch, R extends string = never> {@@ -38,9 +38,9 @@ export interface AfterBatchInput<TOutput, COutput, CBatch, R extends string = neexport interface AfterBatchOutput<TOutput, COutput, CBatch, R extends string = never>extends AfterBatchInput<TOutput, COutput, CBatch, R> {}-export type BeforeBatchStep<TInput, CInput, CBatch> = (- input: BeforeBatchInput<TInput, CInput>-) => Promise<PipelineResult<BeforeBatchOutput<TInput, CInput, CBatch>>>+export type BeforeBatchStep<TInput, CInput, CBatchInput, CBatchOutput = CBatchInput> = (+ input: BeforeBatchInput<TInput, CInput, CBatchInput>+) => Promise<PipelineResult<BeforeBatchOutput<TInput, CInput, CBatchOutput>>>export type AfterBatchStep<TOutput, COutput, CBatch, R extends string = never> = (input: AfterBatchInput<TOutput, COutput, CBatch, R>@@ -60,7 +60,7 @@ const BATCHING_PIPELINE_DEFAULTS: BatchingPipelineOptions = {}interface TrackedBatch<TOutput, CBatch, COutput, R extends string = never> {- batchContext: CBatch+ batchContext: CBatch & { batchId: number }messageIds: number[]inflight: Set<number>results: Map<number, PipelineResultWithContext<TOutput, COutput, R>>@@ -100,28 +100,34 @@ export class BatchingPipeline<TInput,TOutput,CInput,- CBatch,+ CBatchOutput,COutput extends BatchingContext,R extends string = never,> {private nextBatchId = 0private nextMessageId = 0- private batches = new Map<number, TrackedBatch<TOutput, CBatch, COutput, R>>()+ private batches = new Map<number, TrackedBatch<TOutput, CBatchOutput, COutput, R>>()private messageIdToBatchId = new Map<number, number>()private completedResults: BatchResult<BatchPipelineResultWithContext<TOutput, COutput, R>>[] = []private options: BatchingPipelineOptionsconstructor(- private subPipeline: BatchPipeline<TInput & CBatch, TOutput, CInput & BatchingContext, COutput, R>,+ private subPipeline: BatchPipeline<+ TInput & CBatchOutput & { batchId: number },+ TOutput,+ CInput & BatchingContext,+ COutput,+ R+ >,private beforePipeline: Pipeline<BeforeBatchInput<TInput, CInput>,- BeforeBatchOutput<TInput, CInput, CBatch>,+ BeforeBatchOutput<TInput, CInput, CBatchOutput>,Record<string, never>>,private afterPipeline: Pipeline<- AfterBatchInput<TOutput, COutput, CBatch, R>,- AfterBatchOutput<TOutput, COutput, CBatch, R>,+ AfterBatchInput<TOutput, COutput, CBatchOutput, R>,+ AfterBatchOutput<TOutput, COutput, CBatchOutput, R>,Record<string, never>>,options?: Partial<BatchingPipelineOptions>@@ -140,7 +146,7 @@ export class BatchingPipeline<const batchId = this.nextBatchId++- const beforeInput: BeforeBatchInput<TInput, CInput> = { elements, batchId }+ const beforeInput: BeforeBatchInput<TInput, CInput> = { elements, batchContext: { batchId } }const beforeResult = await this.beforePipeline.process(createOkContext(beforeInput, {}))if (!isOkResult(beforeResult.result)) {@@ -164,7 +170,13 @@ export class BatchingPipeline<this.messageIdToBatchId.set(messageId, batchId)return {- result: element.result,+ result: {+ ...element.result,+ value: {+ ...element.result.value,+ ...batchContext,+ },+ },context: {...element.context,messageId,@@ -224,7 +236,7 @@ export class BatchingPipeline<this.messageIdToBatchId.delete(id)}- const afterInput: AfterBatchInput<TOutput, COutput, CBatch, R> = {+ const afterInput: AfterBatchInput<TOutput, COutput, CBatchOutput, R> = {elements: orderedResults,batchContext: batch.batchContext,batchId,diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 67c2d57b31de..5a5f22a63eba 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -148,6 +148,8 @@ export class IngestionApiServer implements NodeServer {private cookielessRedisPool?: RedisPoolprivate cookielessManager?: CookielessManagerprivate pubsub?: PubSub+ private personsStore?: BatchWritingPersonsStore+ private groupStore?: BatchWritingGroupStoreprivate joinedPipeline!: ReturnType<typeof createJoinedIngestionPipeline<JoinedIngestionPipelineInput, JoinedIngestionPipelineContext>@@ -300,7 +302,7 @@ export class IngestionApiServer implements NodeServer {this.config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID.split(',').filter(Boolean),}).start()- const personsStore: PersonsStore = new BatchWritingPersonsStore(personRepository, ingestionOutputs, {+ this.personsStore = new BatchWritingPersonsStore(personRepository, ingestionOutputs, {dbWriteMode: this.config.PERSON_BATCH_WRITING_DB_WRITE_MODE,useBatchUpdates: this.config.PERSON_BATCH_WRITING_USE_BATCH_UPDATES,maxConcurrentUpdates: this.config.PERSON_BATCH_WRITING_MAX_CONCURRENT_UPDATES,@@ -308,12 +310,14 @@ export class IngestionApiServer implements NodeServer {optimisticUpdateRetryInterval: this.config.PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,})+ const personsStore: PersonsStore = this.personsStore- const groupStore = new BatchWritingGroupStore(ingestionOutputs, groupRepository, clickhouseGroupRepository, {+ this.groupStore = new BatchWritingGroupStore(ingestionOutputs, groupRepository, clickhouseGroupRepository, {maxConcurrentUpdates: this.config.GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES,maxOptimisticUpdateRetries: this.config.GROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,optimisticUpdateRetryInterval: this.config.GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,})+ const groupStore = this.groupStorethis.topHog = new TopHog({outputs: ingestionOutputs,@@ -476,8 +480,18 @@ export class IngestionApiServer implements NodeServer {postgres: this.postgres,pubsub: this.pubsub,additionalCleanup: async () => {- await this.ingestionProducerRegistry?.disconnectAll()+ // No Kafka offsets in this server — drain buffered writes before+ // shutdown so shutdown() can assert a clean cache.+ if (this.personsStore) {+ await this.personsStore.flushAndProduceMessages()+ await this.personsStore.shutdown()+ }+ if (this.groupStore) {+ await this.groupStore.flush()+ await this.groupStore.shutdown()+ }this.cookielessManager?.shutdown()+ await this.ingestionProducerRegistry?.disconnectAll()},}}diff --git a/nodejs/src/worker/ingestion/event-pipeline/prefetchPersonsStep.test.ts b/nodejs/src/worker/ingestion/event-pipeline/prefetchPersonsStep.test.tsnew file mode 100644index 000000000000..ba45f556087a--- /dev/null+++ b/nodejs/src/worker/ingestion/event-pipeline/prefetchPersonsStep.test.ts@@ -0,0 +1,52 @@+import { PipelineEvent, Team } from '~/types'++import { PipelineResultType, isOkResult } from '../../../ingestion/pipelines/results'+import { PersonsStoreForBatch } from '../persons/persons-store-for-batch'+import { prefetchPersonsStep } from './prefetchPersonsStep'++type TestInput = { event: PipelineEvent; team: Team; personsStoreForBatch: PersonsStoreForBatch }++function createStore(batchId: number): PersonsStoreForBatch {+ return {+ batchId,+ prefetchPersons: jest.fn().mockResolvedValue(undefined),+ } as unknown as PersonsStoreForBatch+}++function createInput(distinctId: string, teamId: number, personsStoreForBatch: PersonsStoreForBatch): TestInput {+ return {+ event: { distinct_id: distinctId } as unknown as PipelineEvent,+ team: { id: teamId } as unknown as Team,+ personsStoreForBatch,+ }+}++describe('prefetchPersonsStep', () => {+ it('groups prefetch entries by batch store', async () => {+ const storeA = createStore(1)+ const storeB = createStore(2)+ const step = prefetchPersonsStep<TestInput>(true)++ const results = await step([+ createInput('user-a', 3, storeA),+ createInput('user-b', 4, storeB),+ createInput('user-c', 5, storeA),+ ])++ expect(results.map((result) => result.type)).toEqual([+ PipelineResultType.OK,+ PipelineResultType.OK,+ PipelineResultType.OK,+ ])+ expect(results.filter(isOkResult).map((result) => result.value.event.distinct_id)).toEqual([+ 'user-a',+ 'user-b',+ 'user-c',+ ])+ expect(storeA.prefetchPersons).toHaveBeenCalledWith([+ { teamId: 3, distinctId: 'user-a', batchId: 1 },+ { teamId: 5, distinctId: 'user-c', batchId: 1 },+ ])+ expect(storeB.prefetchPersons).toHaveBeenCalledWith([{ teamId: 4, distinctId: 'user-b', batchId: 2 }])+ })+})diff --git a/nodejs/src/worker/ingestion/event-pipeline/prefetchPersonsStep.ts b/nodejs/src/worker/ingestion/event-pipeline/prefetchPersonsStep.tsindex 05349acd8f9a..aebf431bcf6a 100644--- a/nodejs/src/worker/ingestion/event-pipeline/prefetchPersonsStep.ts+++ b/nodejs/src/worker/ingestion/event-pipeline/prefetchPersonsStep.ts@@ -1,18 +1,38 @@import { PipelineResult, ok } from '~/ingestion/pipelines/results'import { PipelineEvent, Team } from '~/types'-import { PersonsStore } from '../persons/persons-store'+import { PersonsStoreForBatch } from '../persons/persons-store-for-batch'-type PrefetchPersonsStepInput = { event: PipelineEvent; team: Team }+type PrefetchPersonsStepInput = { event: PipelineEvent; team: Team; personsStoreForBatch: PersonsStoreForBatch }-export function prefetchPersonsStep<T extends PrefetchPersonsStepInput>(personsStore: PersonsStore, enabled: boolean) {+export function prefetchPersonsStep<T extends PrefetchPersonsStepInput>(enabled: boolean) {return function prefetchPersonsStep(events: T[]): Promise<PipelineResult<T>[]> {if (enabled && events.length > 0) {- // Fire prefetch without awaiting. fetchForChecking/fetchForUpdate will wait- // on the pending promises if they need data that's still being fetched- void personsStore.prefetchPersons(- events.map((x) => ({ teamId: x.team.id, distinctId: x.event.distinct_id }))- )+ // Events in a chunk may come from different Kafka batches (due to the feed primitive).+ // Group by batch store so each store only receives entries it owns. Fire without+ // awaiting — fetchForChecking/fetchForUpdate will wait on the pending promises if+ // they need data that's still being fetched.+ const entriesByStore = new Map<+ PersonsStoreForBatch,+ { teamId: number; distinctId: string; batchId: number }[]+ >()++ for (const event of events) {+ let entries = entriesByStore.get(event.personsStoreForBatch)+ if (!entries) {+ entries = []+ entriesByStore.set(event.personsStoreForBatch, entries)+ }+ entries.push({+ teamId: event.team.id,+ distinctId: event.event.distinct_id,+ batchId: event.personsStoreForBatch.batchId,+ })+ }++ for (const [store, entries] of entriesByStore) {+ void store.prefetchPersons(entries)+ }}return Promise.resolve(events.map((event) => ok(event)))}diff --git a/nodejs/src/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.ts b/nodejs/src/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.tsindex 58fae55d90c3..ebac80394592 100644--- a/nodejs/src/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.ts+++ b/nodejs/src/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.ts@@ -5,9 +5,13 @@ import { PipelineResult, ok } from '~/ingestion/pipelines/results'import { PipelineEvent, Team } from '~/types'import { ONE_HOUR } from '../../../config/constants'-import { PersonsStore } from '../persons/persons-store'+import { PersonsStoreForBatch } from '../persons/persons-store-for-batch'-type ProcessPersonlessDistinctIdsBatchStepInput = { event: PipelineEvent; team: Team }+type ProcessPersonlessDistinctIdsBatchStepInput = {+ event: PipelineEvent+ team: Team+ personsStoreForBatch: PersonsStoreForBatch+}export const personlessDistinctIdCacheOperationsCounter = new Counter({name: 'personless_distinct_id_cache_operations_total',@@ -32,15 +36,16 @@ const PERSONLESS_DISTINCT_ID_INSERTED_CACHE = new LRUCache<string, boolean>({* and consumed by processPersonlessStep to determine force_upgrade.*/export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonlessDistinctIdsBatchStepInput>(- personsStore: PersonsStore,enabled: boolean) {return async function processPersonlessDistinctIdsBatchStep(events: T[]): Promise<PipelineResult<T>[]> {if (enabled) {- // Deduplicate personless events within the batch first, then check cache- const seenInBatch = new Set<string>()+ // Events in a chunk may come from different Kafka batches (due to the feed primitive).+ // Group by personsStoreForBatch so each batch's is_merged results land in the right+ // cache. Deduplicate per batch to avoid redundant DB calls within the same batch.+ type StoreData = { seenInBatch: Set<string>; entries: { teamId: number; distinctId: string }[] }+ const entriesByStore = new Map<PersonsStoreForBatch, StoreData>()let cacheHits = 0- const personlessEntries: { teamId: number; distinctId: string }[] = []for (const e of events) {if (e.event.properties?.$process_person_profile !== false) {@@ -48,19 +53,21 @@ export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonles}const cacheKey = `${e.team.id}|${e.event.distinct_id}`- // Skip if already seen in this batch- if (seenInBatch.has(cacheKey)) {+ let storeData = entriesByStore.get(e.personsStoreForBatch)+ if (!storeData) {+ storeData = { seenInBatch: new Set(), entries: [] }+ entriesByStore.set(e.personsStoreForBatch, storeData)+ }++ if (storeData.seenInBatch.has(cacheKey)) {continue}- seenInBatch.add(cacheKey)+ storeData.seenInBatch.add(cacheKey)if (PERSONLESS_DISTINCT_ID_INSERTED_CACHE.get(cacheKey)) {cacheHits++} else {- personlessEntries.push({- teamId: e.team.id,- distinctId: e.event.distinct_id,- })+ storeData.entries.push({ teamId: e.team.id, distinctId: e.event.distinct_id })}}@@ -68,15 +75,20 @@ export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonlespersonlessDistinctIdCacheOperationsCounter.inc({ operation: 'hit' }, cacheHits)}- if (personlessEntries.length > 0) {- personlessDistinctIdCacheOperationsCounter.inc({ operation: 'miss' }, personlessEntries.length)+ const storeCalls = Array.from(entriesByStore.entries()).filter(([, { entries }]) => entries.length > 0)- await personsStore.processPersonlessDistinctIdsBatch(personlessEntries)+ if (storeCalls.length > 0) {+ const totalMisses = storeCalls.reduce((sum, [, { entries }]) => sum + entries.length, 0)+ personlessDistinctIdCacheOperationsCounter.inc({ operation: 'miss' }, totalMisses)- // Update LRU cache for all entries we just inserted- for (const entry of personlessEntries) {- PERSONLESS_DISTINCT_ID_INSERTED_CACHE.set(`${entry.teamId}|${entry.distinctId}`, true)- }+ await Promise.all(+ storeCalls.map(async ([store, { entries }]) => {+ await store.processPersonlessDistinctIdsBatch(entries)+ for (const entry of entries) {+ PERSONLESS_DISTINCT_ID_INSERTED_CACHE.set(`${entry.teamId}|${entry.distinctId}`, true)+ }+ })+ )}}return events.map((event) => ok(event))diff --git a/nodejs/src/worker/ingestion/groups/batch-writing-group-store.test.ts b/nodejs/src/worker/ingestion/groups/batch-writing-group-store.test.tsindex af712fcb013e..5af7fdae9995 100644--- a/nodejs/src/worker/ingestion/groups/batch-writing-group-store.test.ts+++ b/nodejs/src/worker/ingestion/groups/batch-writing-group-store.test.ts@@ -111,7 +111,21 @@ describe('BatchWritingGroupStore', () => {groupStore = new BatchWritingGroupStore(mockOutputs, groupRepository, clickhouseGroupRepository)})- afterEach(() => {+ afterEach(async () => {+ // Clear the metric-emission interval started in the constructor;+ // unref() prevents it from blocking process exit, but we still want+ // a clean slate between tests. Tests may leave dirty entries behind,+ // so flush first — shutdown() throws on dirty cache by design.+ try {+ await groupStore?.flush()+ } catch {+ // ignore — some tests intentionally fail flush+ }+ try {+ await groupStore?.shutdown()+ } catch {+ // ignore — some tests intentionally leave the cache dirty+ }jest.clearAllMocks()})@@ -364,4 +378,162 @@ describe('BatchWritingGroupStore', () => {{})})++ describe('persistent cache (concurrentBatches > 1)', () => {+ it('clears needsWrite on dirty entries synchronously during flush', async () => {+ // Linearization point: flush() must clear needsWrite BEFORE awaiting+ // any DB I/O. Any code path that introduces an await between the+ // dirty-filter pass and the clear would re-open the cross-batch+ // race documented in the design doc — this test guards against it.+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: 'test' }, DateTime.now())++ const groupCache = groupStore.getGroupCache()+ const dirtyBefore = Array.from(groupCache.entries()).filter(([_, u]) => u && u.needsWrite)+ expect(dirtyBefore.length).toBeGreaterThan(0)++ // Kick off flush WITHOUT awaiting it, then synchronously inspect+ // needsWrite. If flush yields before clearing the flag, this will+ // catch it — the assertion runs at the first microtask boundary.+ const flushPromise = groupStore.flush()++ const stillDirty = Array.from(groupCache.entries()).filter(([_, u]) => u && u.needsWrite)+ expect(stillDirty).toHaveLength(0)++ await flushPromise+ })++ it('re-dirty during flush window drives the next flush', async () => {+ // After an entry is written and cleaned by a flush, a subsequent+ // upsert with new properties re-dirties it, and the next flush picks+ // up the delta.+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now())+ await groupStore.flush()+ ;(groupRepository.updateGroupOptimistically as jest.Mock).mockClear()++ // Re-dirty via a second update with new properties. The cache is+ // still referenced by batch 0 until releaseBatch() runs, so the+ // second update merges with the first batch's cached properties.+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { b: '2' }, DateTime.now())+ const dirtyAfter = Array.from(groupStore.getGroupCache().entries()).filter(([_, u]) => u && u.needsWrite)+ expect(dirtyAfter.length).toBeGreaterThan(0)++ await groupStore.flush()++ // Second flush wrote the updated properties merged onto the still-referenced cache.+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledWith(+ teamId,+ 1,+ 'test',+ 1,+ { test: 'test', a: '1', b: '2' },+ group.created_at,+ {},+ {}+ )+ })+ })++ describe('releaseBatch()', () => {+ it('is a no-op for an unknown batchId', () => {+ expect(() => groupStore.releaseBatch(999)).not.toThrow()+ })++ it('reports dirty entries and referenced batches in flush stats', async () => {+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now(), 0)+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { b: '2' }, DateTime.now(), 1)++ expect(groupStore.getFlushStats()).toEqual({+ dirtyEntryCount: 1,+ referencedBatchCount: 2,+ cacheEntryCount: 1,+ })+ })++ it('removes clean entries from cache after flush and release', async () => {+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now())++ await groupStore.flush()+ expect(groupStore.getGroupCache().getSize()).toBe(1)+ groupStore.releaseBatch(0)++ expect(groupStore.getGroupCache().getSize()).toBe(0)+ })++ it('keeps entries that were re-dirtied during the DB write', async () => {+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now())++ // Re-dirty the entry during the async DB write after the linearization point.+ jest.spyOn(groupRepository, 'updateGroupOptimistically').mockImplementationOnce(() => {+ const entry = groupStore.getGroupCache().get(teamId, 'test')+ if (entry) {+ entry.needsWrite = true+ }+ return Promise.resolve(2)+ })++ await groupStore.flush()++ expect(groupStore.getGroupCache().getSize()).toBe(1)+ expect(groupStore.getGroupCache().get(teamId, 'test')?.needsWrite).toBe(true)+ })++ it('defers eviction of dirty entries until after flush', async () => {+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now())++ groupStore.releaseBatch(0)+ expect(groupStore.getGroupCache().getSize()).toBe(1)++ await groupStore.flush()++ expect(groupStore.getGroupCache().getSize()).toBe(0)+ })++ it('keeps overlapping batch entries until the last release', async () => {+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now(), 0)+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { b: '2' }, DateTime.now(), 1)++ await groupStore.flush()++ groupStore.releaseBatch(0)+ expect(groupStore.getGroupCache().getSize()).toBe(1)++ groupStore.releaseBatch(1)+ expect(groupStore.getGroupCache().getSize()).toBe(0)+ })+ })++ describe('shutdown()', () => {+ it('succeeds without calling flush when no dirty entries exist', async () => {+ const flushSpy = jest.spyOn(groupStore, 'flush')++ await groupStore.shutdown()++ expect(flushSpy).not.toHaveBeenCalled()+ })++ it('throws when dirty entries exist — caller must flush first', async () => {+ // upsertGroup on an existing group with new properties marks the cache entry dirty+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now())++ expect(() => groupStore.shutdown()).toThrow(/dirty cache entries/)+ })++ it('emits accumulated metrics before throwing on dirty cache', async () => {+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now())++ const emitSpy = jest.spyOn(groupStore as any, 'emitAccumulatedMetrics')++ expect(() => groupStore.shutdown()).toThrow()++ expect(emitSpy).toHaveBeenCalledTimes(1)+ })++ it('explicit flush before shutdown succeeds', async () => {+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now())++ await groupStore.flush()+ await expect(groupStore.shutdown()).resolves.not.toThrow()+ })+ })})diff --git a/nodejs/src/worker/ingestion/groups/batch-writing-group-store.ts b/nodejs/src/worker/ingestion/groups/batch-writing-group-store.tsindex 422852b2d9ff..15df0978709e 100644--- a/nodejs/src/worker/ingestion/groups/batch-writing-group-store.ts+++ b/nodejs/src/worker/ingestion/groups/batch-writing-group-store.ts@@ -12,6 +12,7 @@ import { logger } from '../../../utils/logger'import { promiseRetry } from '../../../utils/retries'import { RaceConditionError } from '../../../utils/utils'import { FlushResult } from '../persons/persons-store'+import { BatchWritingStoreFlushStats } from '../stores/batch-writing-store'import { logMissingRow, logVersionMismatch } from './group-logging'import { CacheMetrics, GroupStore } from './group-store.interface'import { GroupUpdate, calculateUpdate, fromGroup } from './group-update'@@ -30,22 +31,38 @@ class GroupCache {private cache: Map<string, GroupUpdate | null>private fetchPromises: Map<string, Promise<GroupUpdate | null>>private metrics: CacheMetrics+ private batchGroupKeys: Map<number, Set<string>>+ private groupKeyRefCount: Map<string, number>+ private deferredEvictions: Set<string>constructor() {this.cache = new Map()this.fetchPromises = new Map()+ this.batchGroupKeys = new Map()+ this.groupKeyRefCount = new Map()+ this.deferredEvictions = new Set()this.metrics = {cacheHits: 0,cacheMisses: 0,}}- has(teamId: TeamId, groupKey: string): boolean {+ obtainForBatchId(batchId: number): BatchBoundGroupCache {+ return new BatchBoundGroupCache(this, batchId)+ }++ get(teamId: TeamId, groupKey: string): GroupUpdate | null | undefined {+ return this.cache.get(this.getCacheKey(teamId, groupKey))+ }++ hasForBatch(batchId: number, teamId: TeamId, groupKey: string): boolean {+ this.trackBatchEntry(batchId, teamId, groupKey)const key = this.getCacheKey(teamId, groupKey)return this.cache.has(key)}- get(teamId: TeamId, groupKey: string): GroupUpdate | null | undefined {+ getForBatch(batchId: number, teamId: TeamId, groupKey: string): GroupUpdate | null | undefined {+ this.trackBatchEntry(batchId, teamId, groupKey)const key = this.getCacheKey(teamId, groupKey)const result = this.cache.get(key)if (result !== undefined) {@@ -56,7 +73,8 @@ class GroupCache {return result}- set(teamId: TeamId, groupKey: string, group: GroupUpdate | null): void {+ setForBatch(batchId: number, teamId: TeamId, groupKey: string, group: GroupUpdate | null): void {+ this.trackBatchEntry(batchId, teamId, groupKey)const key = this.getCacheKey(teamId, groupKey)this.cache.set(key, group)}@@ -93,18 +111,128 @@ class GroupCache {return this.cache.entries()}- reset(): void {- this.cache.clear()- this.fetchPromises.clear()+ getFlushStats(): BatchWritingStoreFlushStats {+ const dirtyGroupKeys = new Set<string>()+ for (const [groupKey, update] of this.cache.entries()) {+ if (update?.needsWrite) {+ dirtyGroupKeys.add(groupKey)+ }+ }++ const referencedBatchIds = new Set<number>()+ for (const [batchId, groupKeys] of this.batchGroupKeys.entries()) {+ for (const groupKey of groupKeys) {+ if (dirtyGroupKeys.has(groupKey)) {+ referencedBatchIds.add(batchId)+ break+ }+ }+ }++ return {+ dirtyEntryCount: dirtyGroupKeys.size,+ referencedBatchCount: referencedBatchIds.size,+ cacheEntryCount: this.cache.size,+ }+ }++ /**+ * Reset per-batch metric accumulators. The cache and in-flight fetch+ * promises persist across batches under the persistent-cache model.+ */+ resetMetrics(): void {this.metrics = {cacheHits: 0,cacheMisses: 0,}}+ releaseBatchId(batchId: number): void {+ const keys = this.batchGroupKeys.get(batchId)+ if (!keys) {+ return+ }++ for (const groupKey of keys) {+ const refCount = (this.groupKeyRefCount.get(groupKey) ?? 1) - 1+ if (refCount <= 0) {+ this.groupKeyRefCount.delete(groupKey)+ this.evictGroupKey(groupKey)+ } else {+ this.groupKeyRefCount.set(groupKey, refCount)+ }+ }++ this.batchGroupKeys.delete(batchId)+ }++ processDeferredEvictions(): void {+ for (const groupKey of this.deferredEvictions) {+ const update = this.cache.get(groupKey)+ if (!update || !update.needsWrite) {+ this.cache.delete(groupKey)+ this.deferredEvictions.delete(groupKey)+ }+ }+ }+private getCacheKey(teamId: TeamId, groupKey: string): string {return `${teamId}:${groupKey}`}++ private trackBatchEntry(batchId: number, teamId: TeamId, groupKey: string): void {+ const key = this.getCacheKey(teamId, groupKey)+ let keys = this.batchGroupKeys.get(batchId)+ if (!keys) {+ keys = new Set()+ this.batchGroupKeys.set(batchId, keys)+ }+ if (!keys.has(key)) {+ keys.add(key)+ this.groupKeyRefCount.set(key, (this.groupKeyRefCount.get(key) ?? 0) + 1)+ }+ }++ private evictGroupKey(groupKey: string): void {+ const update = this.cache.get(groupKey)+ if (update && update.needsWrite) {+ this.deferredEvictions.add(groupKey)+ return+ }++ this.cache.delete(groupKey)+ }+}++class BatchBoundGroupCache {+ constructor(+ private readonly cache: GroupCache,+ private readonly batchId: number+ ) {}++ has(teamId: TeamId, groupKey: string): boolean {+ return this.cache.hasForBatch(this.batchId, teamId, groupKey)+ }++ get(teamId: TeamId, groupKey: string): GroupUpdate | null | undefined {+ return this.cache.getForBatch(this.batchId, teamId, groupKey)+ }++ set(teamId: TeamId, groupKey: string, group: GroupUpdate | null): void {+ this.cache.setForBatch(this.batchId, teamId, groupKey, group)+ }++ getFetchPromise(teamId: TeamId, groupKey: string): Promise<GroupUpdate | null> | undefined {+ return this.cache.getFetchPromise(teamId, groupKey)+ }++ setFetchPromise(teamId: TeamId, groupKey: string, promise: Promise<GroupUpdate | null>): void {+ this.cache.setFetchPromise(teamId, groupKey, promise)+ }++ deleteFetchPromise(teamId: TeamId, groupKey: string): void {+ this.cache.deleteFetchPromise(teamId, groupKey)+ }}interface PropertiesUpdate {@@ -116,21 +244,29 @@ export interface BatchWritingGroupStoreOptions {maxConcurrentUpdates: numbermaxOptimisticUpdateRetries: numberoptimisticUpdateRetryInterval: number+ /**+ * Interval at which accumulated group operation metrics are emitted and+ * cleared. Set to 0 to disable the timer (used by tests; production+ * always wants a positive interval).+ */+ metricEmissionIntervalMs: number}const DEFAULT_OPTIONS: BatchWritingGroupStoreOptions = {maxConcurrentUpdates: 10,maxOptimisticUpdateRetries: 5,optimisticUpdateRetryInterval: 50,+ metricEmissionIntervalMs: 30_000,}/**- * This class is used to write groups to the database in batches.- * It will use a cache to avoid reading the same group from the database multiple times.- * And will accumulate all changes for the same group in a single batch. At the- * end of the batch processing, it flushes all changes to the database.+ * Writes groups to the database in batches, accumulating all changes for the+ * same group across events and flushing them on `flush()` calls. The cache+ * persists across batches under concurrentBatches > 1.*- * After each batch, call reset() to clear the cache and prepare for the next batch.+ * **Lifecycle:** construction starts a metric-emission timer. Callers MUST+ * invoke `shutdown()` on graceful exit to stop the timer and flush any+ * remaining dirty entries.*/export class BatchWritingGroupStore implements GroupStore {private groupCache: GroupCache@@ -139,6 +275,9 @@ export class BatchWritingGroupStore implements GroupStore {private outputs: IngestionOutputs<GroupsOutput | IngestionWarningsOutput>private groupRepository: GroupRepositoryprivate clickhouseGroupRepository: ClickhouseGroupRepository+ // Periodic metric emitter — emits accumulated group-operation metrics on+ // a fixed cadence rather than at batch boundaries.+ private metricEmissionTimer: NodeJS.Timeout | undefinedconstructor(outputs: IngestionOutputs<GroupsOutput | IngestionWarningsOutput>,@@ -152,6 +291,14 @@ export class BatchWritingGroupStore implements GroupStore {this.outputs = outputsthis.groupRepository = groupRepositorythis.clickhouseGroupRepository = clickhouseGroupRepository++ if (this.options.metricEmissionIntervalMs > 0) {+ this.metricEmissionTimer = setInterval(+ () => this.emitAccumulatedMetrics(),+ this.options.metricEmissionIntervalMs+ )+ this.metricEmissionTimer.unref?.()+ }}getGroupCache(): GroupCache {@@ -159,11 +306,27 @@ export class BatchWritingGroupStore implements GroupStore {}async flush(): Promise<FlushResult[]> {- const pendingUpdates = Array.from(this.groupCache.entries()).filter((entry): entry is [string, GroupUpdate] => {- const [_, update] = entry- return update !== null && update.needsWrite- })+ // SYNCHRONOUS LINEARIZATION POINT for cross-batch correctness.+ // Walk every dirty entry, capture it for writing, and clear+ // `needsWrite` before any await below. Concurrent batches that+ // mutate an entry between this clear and the async DB write will+ // re-set `needsWrite=true` and be picked up by the next flush.+ // DO NOT introduce any `await` inside this block.+ const pendingUpdates: [string, GroupUpdate][] = []+ for (const [key, update] of this.groupCache.entries()) {+ if (!update) {+ continue+ }+ if (!update.needsWrite) {+ continue+ }+ update.needsWrite = false+ pendingUpdates.push([key, update])+ }+ // END synchronous linearization point.+if (pendingUpdates.length === 0) {+ this.groupCache.processDeferredEvictions()return []}@@ -173,6 +336,7 @@ export class BatchWritingGroupStore implements GroupStore {await Promise.all(pendingUpdates.map(([distinctId, update]) => limit(() => this.processGroupUpdate(update, distinctId))))+ this.groupCache.processDeferredEvictions()return []} catch (error) {logger.error('Failed to flush group updates', {@@ -184,6 +348,10 @@ export class BatchWritingGroupStore implements GroupStore {}}+ getFlushStats(): BatchWritingStoreFlushStats {+ return this.groupCache.getFlushStats()+ }+private async processGroupUpdate(update: GroupUpdate, distinctId: string): Promise<void> {try {await promiseRetry(@@ -234,7 +402,8 @@ export class BatchWritingGroupStore implements GroupStore {update.group_properties,update.created_at,true, // forUpdate = true, making us not use the cache- 'conflictRetry'+ 'conflictRetry',+ undefined)} catch (fallbackError) {logger.error('Failed to update group after max retries and direct upsert fallback', {@@ -255,12 +424,23 @@ export class BatchWritingGroupStore implements GroupStore {groupTypeIndex: GroupTypeIndex,groupKey: string,properties: Properties,- timestamp: DateTime+ timestamp: DateTime,+ batchId?: number): Promise<void> {+ const effectiveBatchId = batchId ?? 0try {- await this.addToBatch(teamId, groupTypeIndex, groupKey, properties, timestamp)+ await this.addToBatch(teamId, groupTypeIndex, groupKey, properties, timestamp, effectiveBatchId)} catch (error) {- await this.handleUpsertError(error, teamId, projectId, groupTypeIndex, groupKey, properties, timestamp)+ await this.handleUpsertError(+ error,+ teamId,+ projectId,+ groupTypeIndex,+ groupKey,+ properties,+ timestamp,+ effectiveBatchId+ )}}@@ -269,9 +449,11 @@ export class BatchWritingGroupStore implements GroupStore {groupTypeIndex: GroupTypeIndex,groupKey: string,properties: Properties,- timestamp: DateTime+ timestamp: DateTime,+ batchId: number): Promise<void> {- const group = await this.getGroup(teamId, groupTypeIndex, groupKey, false)+ const groupCache = this.groupCache.obtainForBatchId(batchId)+ const group = await this.getGroup(teamId, groupTypeIndex, groupKey, false, groupCache)if (!group) {await this.executeGroupUpsert(@@ -281,14 +463,15 @@ export class BatchWritingGroupStore implements GroupStore {properties,timestamp,false,- 'batch-create'+ 'batch-create',+ batchId)return}const propertiesUpdate = calculateUpdate(group.group_properties || {}, properties)if (propertiesUpdate.updated) {- this.groupCache.set(teamId, groupKey, {+ groupCache.set(teamId, groupKey, {team_id: teamId,group_type_index: groupTypeIndex,group_key: groupKey,@@ -307,7 +490,8 @@ export class BatchWritingGroupStore implements GroupStore {properties: Properties,timestamp: DateTime,forUpdate: boolean,- source: string+ source: string,+ batchId?: number): Promise<void> {const operation = 'upsertGroup' + (source ? `-${source}` : '')this.incrementDatabaseOperation(operation)@@ -315,7 +499,16 @@ export class BatchWritingGroupStore implements GroupStore {const [propertiesUpdate, createdAt, actualVersion] = await this.groupRepository.inTransaction(operation,async (tx) =>- this.executeUpsertTransaction(teamId, groupTypeIndex, groupKey, properties, timestamp, forUpdate, tx)+ this.executeUpsertTransaction(+ teamId,+ groupTypeIndex,+ groupKey,+ properties,+ timestamp,+ forUpdate,+ tx,+ batchId+ ))if (propertiesUpdate.updated) {@@ -358,9 +551,11 @@ export class BatchWritingGroupStore implements GroupStore {properties: Properties,timestamp: DateTime,forUpdate: boolean,- tx: GroupRepositoryTransaction+ tx: GroupRepositoryTransaction,+ batchId?: number): Promise<[PropertiesUpdate, DateTime, number]> {- const group = await this.getGroup(teamId, groupTypeIndex, groupKey, forUpdate, tx)+ const groupCache = batchId === undefined ? undefined : this.groupCache.obtainForBatchId(batchId)+ const group = await this.getGroup(teamId, groupTypeIndex, groupKey, forUpdate, groupCache, tx)const createdAt = DateTime.min(group?.created_at || DateTime.now(), timestamp)const expectedVersion = (group?.version || 0) + 1const propertiesUpdate = calculateUpdate(group?.group_properties || {}, properties)@@ -393,7 +588,7 @@ export class BatchWritingGroupStore implements GroupStore {expectedVersion,tx)- this.groupCache.set(teamId, groupKey, {+ groupCache?.set(teamId, groupKey, {team_id: teamId,group_type_index: groupTypeIndex,group_key: groupKey,@@ -509,16 +704,17 @@ export class BatchWritingGroupStore implements GroupStore {groupTypeIndex: GroupTypeIndex,groupKey: string,forUpdate: boolean,+ groupCache: BatchBoundGroupCache | undefined,tx?: GroupRepositoryTransaction): Promise<GroupUpdate | null> {- if (this.groupCache.has(teamId, groupKey) && !forUpdate) {- const cachedGroup = this.groupCache.get(teamId, groupKey)+ if (groupCache?.has(teamId, groupKey) && !forUpdate) {+ const cachedGroup = groupCache.get(teamId, groupKey)if (cachedGroup !== undefined) {return cachedGroup}}- let fetchPromise = this.groupCache.getFetchPromise(teamId, groupKey)+ let fetchPromise = groupCache?.getFetchPromise(teamId, groupKey)if (!fetchPromise) {groupFetchPromisesCacheOperationsCounter.inc({ operation: 'miss' })fetchPromise = (async () => {@@ -528,20 +724,20 @@ export class BatchWritingGroupStore implements GroupStore {const existingGroup = await repository.fetchGroup(teamId, groupTypeIndex, groupKey, { forUpdate })if (existingGroup) {const groupUpdate = fromGroup(existingGroup)- this.groupCache.set(teamId, groupKey, {+ groupCache?.set(teamId, groupKey, {...groupUpdate,needsWrite: false,})return groupUpdate} else {- this.groupCache.set(teamId, groupKey, null)+ groupCache?.set(teamId, groupKey, null)return null}} finally {- this.groupCache.deleteFetchPromise(teamId, groupKey)+ groupCache?.deleteFetchPromise(teamId, groupKey)}})()- this.groupCache.setFetchPromise(teamId, groupKey, fetchPromise)+ groupCache?.setFetchPromise(teamId, groupKey, fetchPromise)} else {groupFetchPromisesCacheOperationsCounter.inc({ operation: 'hit' })}@@ -555,7 +751,8 @@ export class BatchWritingGroupStore implements GroupStore {groupTypeIndex: GroupTypeIndex,groupKey: string,properties: Properties,- timestamp: DateTime+ timestamp: DateTime,+ batchId: number): Promise<void> {if (error instanceof MessageSizeTooLarge) {await emitIngestionWarning(this.outputs, teamId, 'group_upsert_message_size_too_large', {@@ -567,11 +764,15 @@ export class BatchWritingGroupStore implements GroupStore {if (error instanceof RaceConditionError) {// Remove from cache to prevent retry, the group was already created by another threadthis.groupCache.delete(teamId, groupKey)- return this.upsertGroup(teamId, projectId, groupTypeIndex, groupKey, properties, timestamp)+ return this.upsertGroup(teamId, projectId, groupTypeIndex, groupKey, properties, timestamp, batchId)}throw error}+ releaseBatch(batchId: number): void {+ this.groupCache.releaseBatchId(batchId)+ }+getCacheMetrics(): CacheMetrics {return this.groupCache.getMetrics()}@@ -580,7 +781,16 @@ export class BatchWritingGroupStore implements GroupStore {this.databaseOperationCounts.set(operation, (this.databaseOperationCounts.get(operation) || 0) + 1)}- reportBatch(): void {+ /**+ * Emit accumulated group operation metrics to Prometheus and reset the+ * in-memory accumulators. Runs on a fixed-interval timer in production.+ *+ * Under concurrentBatches > 1, per-batch attribution is unreliable+ * (first-flush-wins), so emission is decoupled from batch boundaries.+ * The histogram names retain a "...PerBatch..." suffix for dashboard+ * compatibility but the window is now the emission interval.+ */+ private emitAccumulatedMetrics(): void {groupCacheSizeHistogram.observe(this.groupCache.getSize())const metrics = this.groupCache.getMetrics()groupCacheOperationsCounter.inc({ operation: 'hit' }, metrics.cacheHits)@@ -588,11 +798,44 @@ export class BatchWritingGroupStore implements GroupStore {for (const [operation, count] of this.databaseOperationCounts.entries()) {groupDatabaseOperationsPerBatchHistogram.observe({ operation }, count)}- }- reset(): void {- this.groupCache.reset()+ this.groupCache.resetMetrics()this.databaseOperationCounts.clear()groupOptimisticUpdateConflictsPerBatchCounter.reset()}++ /**+ * Stop the metric-emission timer and emit accumulated metrics. Idempotent.+ *+ * Callers MUST call `flush()` before `shutdown()`. Reaching shutdown with a+ * dirty cache indicates a drain-ordering bug — writing here without a+ * subsequent offset commit would create duplicate writes when the partition+ * is reprocessed, and silently dropping the data masks the bug. We throw+ * instead and let the caller decide whether to flush, drop, or fail loudly.+ *+ * Does NOT clear the group cache. Cache eviction is intentionally+ * decoupled from this lifecycle hook.+ */+ shutdown(): Promise<void> {+ if (this.metricEmissionTimer) {+ clearInterval(this.metricEmissionTimer)+ this.metricEmissionTimer = undefined+ }++ let dirtyCount = 0+ for (const [_, entry] of this.groupCache.entries()) {+ if (entry && entry.needsWrite) {+ dirtyCount+++ }+ }+ if (dirtyCount > 0) {+ this.emitAccumulatedMetrics()+ throw new Error(+ `BatchWritingGroupStore.shutdown() called with ${dirtyCount} dirty cache entries — call flush() first`+ )+ }++ this.emitAccumulatedMetrics()+ return Promise.resolve()+ }}diff --git a/nodejs/src/worker/ingestion/groups/group-store-for-batch.interface.ts b/nodejs/src/worker/ingestion/groups/group-store-for-batch.interface.tsdeleted file mode 100644index e057e334d86f..000000000000--- a/nodejs/src/worker/ingestion/groups/group-store-for-batch.interface.ts+++ /dev/null@@ -1,35 +0,0 @@-import { DateTime } from 'luxon'--import { Properties } from '~/plugin-scaffold'--import { GroupTypeIndex, ProjectId, TeamId } from '../../../types'-import { BatchWritingStore } from '../stores/batch-writing-store'--export interface CacheMetrics {- cacheHits: number- cacheMisses: number-}--export interface GroupStoreForBatch extends BatchWritingStore {- /**- * Reports metrics about group operations in batch- */- reportBatch(): void-- /**- * Resets the batch store state, clearing all caches and metrics.- * Should be called after flush() to prepare for the next batch.- */- reset(): void-- upsertGroup(- teamId: TeamId,- projectId: ProjectId,- groupTypeIndex: GroupTypeIndex,- groupKey: string,- properties: Properties,- timestamp: DateTime- ): Promise<void>-- getCacheMetrics(): CacheMetrics-}diff --git a/nodejs/src/worker/ingestion/groups/group-store-for-batch.ts b/nodejs/src/worker/ingestion/groups/group-store-for-batch.tsnew file mode 100644index 000000000000..65db678f89b3--- /dev/null+++ b/nodejs/src/worker/ingestion/groups/group-store-for-batch.ts@@ -0,0 +1,50 @@+import { DateTime } from 'luxon'++import { Properties } from '~/plugin-scaffold'++import { GroupTypeIndex, ProjectId, TeamId } from '../../../types'+import { FlushResult } from '../persons/persons-store'+import { BatchWritingGroupStore } from './batch-writing-group-store'+import { CacheMetrics, GroupStore } from './group-store.interface'++export type GroupStoreForBatch = Omit<GroupStore, 'upsertGroup' | 'releaseBatch' | 'getFlushStats'> & {+ upsertGroup(+ teamId: TeamId,+ projectId: ProjectId,+ groupTypeIndex: GroupTypeIndex,+ groupKey: string,+ properties: Properties,+ timestamp: DateTime+ ): Promise<void>+ readonly batchId: number+}++export class BatchBoundGroupStore implements GroupStoreForBatch {+ constructor(+ private readonly store: BatchWritingGroupStore,+ public readonly batchId: number+ ) {}++ upsertGroup(+ teamId: TeamId,+ projectId: ProjectId,+ groupTypeIndex: GroupTypeIndex,+ groupKey: string,+ properties: Properties,+ timestamp: DateTime+ ): Promise<void> {+ return this.store.upsertGroup(teamId, projectId, groupTypeIndex, groupKey, properties, timestamp, this.batchId)+ }++ getCacheMetrics(): CacheMetrics {+ return this.store.getCacheMetrics()+ }++ flush(): Promise<FlushResult[]> {+ return this.store.flush()+ }++ shutdown(): Promise<void> {+ return this.store.shutdown()+ }+}diff --git a/nodejs/src/worker/ingestion/groups/group-store.interface.ts b/nodejs/src/worker/ingestion/groups/group-store.interface.tsindex 55b2817be726..20ae6eb7da22 100644--- a/nodejs/src/worker/ingestion/groups/group-store.interface.ts+++ b/nodejs/src/worker/ingestion/groups/group-store.interface.ts@@ -12,15 +12,11 @@ export interface CacheMetrics {export interface GroupStore extends BatchWritingStore {/**- * Reports metrics about group operations in batch+ * Stop any background work (e.g., periodic metric emission) and flush+ * remaining accumulated metrics. Called on graceful shutdown. Does NOT+ * clear data caches.*/- reportBatch(): void-- /**- * Resets the batch store state, clearing all caches and metrics.- * Should be called after flush() to prepare for the next batch.- */- reset(): void+ shutdown(): Promise<void>upsertGroup(teamId: TeamId,@@ -28,7 +24,8 @@ export interface GroupStore extends BatchWritingStore {groupTypeIndex: GroupTypeIndex,groupKey: string,properties: Properties,- timestamp: DateTime+ timestamp: DateTime,+ batchId: number): Promise<void>getCacheMetrics(): CacheMetricsdiff --git a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.tsindex 4497c871daba..89ee36437bd6 100644--- a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts+++ b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts@@ -1,7 +1,7 @@import { DateTime } from 'luxon'+import { PERSONS_OUTPUT, PersonDistinctIdsOutput, PersonsOutput } from '~/ingestion/analytics/outputs'import { INGESTION_WARNINGS_OUTPUT } from '~/ingestion/common/outputs'-import { IngestionOutputs } from '~/ingestion/outputs/ingestion-outputs'import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'import { InternalPerson, TeamId } from '~/types'import { DependencyUnavailableError, MessageSizeTooLarge } from '~/utils/db/error'@@ -15,6 +15,7 @@ import {personPropertyKeyUpdateCounter,} from './metrics'import { fromInternalPerson } from './person-update-batch'+import { BatchBoundPersonsStore } from './persons-store-for-batch'// Mock the ingestion warnings modulejest.mock('../../../ingestion/common/ingestion-warnings', () => ({@@ -46,7 +47,13 @@ jest.mock('./metrics', () => ({describe('BatchWritingPersonStore', () => {// let db: DB- let mockIngestionWarningsOutputs: IngestionOutputs<typeof INGESTION_WARNINGS_OUTPUT>+ let mockIngestionWarningsOutputs: jest.Mocked<+ ReturnType<+ typeof createMockIngestionOutputs<+ PersonsOutput | PersonDistinctIdsOutput | typeof INGESTION_WARNINGS_OUTPUT+ >+ >+ >let mockPostgres: PostgresRouterlet personStore: BatchWritingPersonsStorelet mockRepo: any@@ -77,13 +84,29 @@ describe('BatchWritingPersonStore', () => {}),} as unknown as PostgresRouter- mockIngestionWarningsOutputs = createMockIngestionOutputs<typeof INGESTION_WARNINGS_OUTPUT>()+ mockIngestionWarningsOutputs = createMockIngestionOutputs<+ PersonsOutput | PersonDistinctIdsOutput | typeof INGESTION_WARNINGS_OUTPUT+ >()mockRepo = createMockRepository()personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)})- afterEach(() => {+ afterEach(async () => {+ // Clear the metric-emission interval started in the constructor;+ // unref() prevents it from blocking process exit, but we still want+ // a clean slate between tests. Tests may leave dirty entries behind,+ // so flush first — shutdown() throws on dirty cache by design.+ try {+ await personStore?.flush()+ } catch {+ // ignore — some tests intentionally fail flush+ }+ try {+ await personStore?.shutdown()+ } catch {+ // ignore — some tests intentionally leave the cache dirty+ }jest.clearAllMocks()})@@ -389,14 +412,14 @@ describe('BatchWritingPersonStore', () => {const personStore = getPersonsStore()// Fetch for checking should cache in check cache- const personFromCheck = await personStore.fetchForChecking(teamId, 'test-distinct')+ const personFromCheck = await personStore.fetchForChecking(teamId, 'test-distinct', 0)expect(personFromCheck).toEqual(person)const checkCache = (personStore as any)['personCheckCache']expect(checkCache.get('1:test-distinct')).toEqual(person)// Fetch for update should cache in update cache and return PersonUpdate converted to InternalPerson- const personFromUpdate = await personStore.fetchForUpdate(teamId, 'test-distinct2')+ const personFromUpdate = await personStore.fetchForUpdate(teamId, 'test-distinct2', 0)expect(personFromUpdate).toBeDefined()expect(personFromUpdate!.id).toBe(person.id)expect(personFromUpdate!.team_id).toBe(person.team_id)@@ -413,18 +436,18 @@ describe('BatchWritingPersonStore', () => {const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)// First fetch should hit the database- await personStore.fetchForChecking(teamId, 'test-distinct')+ await personStore.fetchForChecking(teamId, 'test-distinct', 0)expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(1)// Second fetch should hit the cache- await personStore.fetchForChecking(teamId, 'test-distinct')+ await personStore.fetchForChecking(teamId, 'test-distinct', 0)expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(1) // No additional call// Similar for update cache- await personStore.fetchForUpdate(teamId, 'test-distinct2')+ await personStore.fetchForUpdate(teamId, 'test-distinct2', 0)expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(2)- await personStore.fetchForUpdate(teamId, 'test-distinct2')+ await personStore.fetchForUpdate(teamId, 'test-distinct2', 0)expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(2) // No additional call})@@ -433,13 +456,13 @@ describe('BatchWritingPersonStore', () => {const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)// First populate update cache- await personStore.fetchForUpdate(teamId, 'test-distinct')+ await personStore.fetchForUpdate(teamId, 'test-distinct', 0)// Reset the mock to track new callsjest.clearAllMocks()// fetchForChecking should use the cached PersonUpdate instead of hitting DB- const result = await personStore.fetchForChecking(teamId, 'test-distinct')+ const result = await personStore.fetchForChecking(teamId, 'test-distinct', 0)expect(result).toBeDefined()expect(mockRepo.fetchPerson).not.toHaveBeenCalled()})@@ -449,10 +472,10 @@ describe('BatchWritingPersonStore', () => {mockRepo.fetchPerson = jest.fn().mockResolvedValue(undefined)const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)- const checkResult = await personStore.fetchForChecking(teamId, 'nonexistent')+ const checkResult = await personStore.fetchForChecking(teamId, 'nonexistent', 0)expect(checkResult).toBeNull()- const updateResult = await personStore.fetchForUpdate(teamId, 'nonexistent')+ const updateResult = await personStore.fetchForUpdate(teamId, 'nonexistent', 0)expect(updateResult).toBeNull()})})@@ -1294,7 +1317,7 @@ describe('BatchWritingPersonStore', () => {// Step 3: moveDistinctIds - this should preserve the merged cacheconst tx = createMockTransaction() as any- await personStore.moveDistinctIds(sourcePerson, targetPerson, 'target-distinct', undefined, tx)+ await personStore.moveDistinctIds(sourcePerson, targetPerson, 'target-distinct', undefined, tx, 0)// Verify the repository method was called// moveDistinctIds is executed via tx, not repo@@ -1350,7 +1373,7 @@ describe('BatchWritingPersonStore', () => {// Move distinct IDsconst tx = createMockTransaction() as any- await personStore.moveDistinctIds(sourcePerson, targetPerson, 'target-distinct', undefined, tx)+ await personStore.moveDistinctIds(sourcePerson, targetPerson, 'target-distinct', undefined, tx, 0)// Verify the repository method was calledexpect(tx.moveDistinctIds).toHaveBeenCalledTimes(1)@@ -1395,7 +1418,7 @@ describe('BatchWritingPersonStore', () => {// Move distinct IDsconst tx = createMockTransaction() as any- await personStore.moveDistinctIds(sourcePerson, targetPerson, 'target-distinct', undefined, tx)+ await personStore.moveDistinctIds(sourcePerson, targetPerson, 'target-distinct', undefined, tx, 0)// Verify the repository method was calledexpect(tx.moveDistinctIds).toHaveBeenCalledTimes(1)@@ -1466,7 +1489,7 @@ describe('BatchWritingPersonStore', () => {// Step 3: moveDistinctIdsconst tx = createMockTransaction() as any- await personStore.moveDistinctIds(sourcePerson, targetPerson, 'target-distinct', undefined, tx)+ await personStore.moveDistinctIds(sourcePerson, targetPerson, 'target-distinct', undefined, tx, 0)// Verify the repository method was calledexpect(tx.moveDistinctIds).toHaveBeenCalledTimes(1)@@ -1520,7 +1543,7 @@ describe('BatchWritingPersonStore', () => {const mockRepo = createMockRepository()const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)- const result = await personStore.addPersonlessDistinctIdForMerge(teamId, 'test-distinct')+ const result = await personStore.addPersonlessDistinctIdForMerge(teamId, 'test-distinct', undefined, 0)expect(mockRepo.addPersonlessDistinctIdForMerge).toHaveBeenCalledWith(teamId, 'test-distinct')expect(result).toBe(true)@@ -1531,7 +1554,7 @@ describe('BatchWritingPersonStore', () => {mockRepo.addPersonlessDistinctIdForMerge = jest.fn().mockResolvedValue(false)const personStore = new BatchWritingPersonsStore(mockRepo, mockIngestionWarningsOutputs)- const result = await personStore.addPersonlessDistinctIdForMerge(teamId, 'test-distinct')+ const result = await personStore.addPersonlessDistinctIdForMerge(teamId, 'test-distinct', undefined, 0)expect(mockRepo.addPersonlessDistinctIdForMerge).toHaveBeenCalledWith(teamId, 'test-distinct')expect(result).toBe(false)@@ -2321,46 +2344,45 @@ describe('BatchWritingPersonStore', () => {})})- describe('reset', () => {- it('should clear all caches and metrics after reset', async () => {+ describe('persistent cache (concurrentBatches > 1)', () => {+ it('cache data persists across batch boundaries (no reset)', async () => {const personStore = getPersonsStore()// Populate caches by fetching and updating a person- await personStore.fetchForUpdate(teamId, 'distinct-1')- await personStore.fetchForChecking(teamId, 'distinct-2')+ await personStore.fetchForUpdate(teamId, 'distinct-1', 0)+ await personStore.fetchForChecking(teamId, 'distinct-2', 0)await personStore.updatePersonWithPropertiesDiffForUpdate(person, { name: 'test' }, [], {}, 'distinct-1')- // Verify caches are populated- expect(personStore.getUpdateCache().size).toBeGreaterThan(0)- expect(personStore.getCheckCache().size).toBeGreaterThan(0)+ const updateCacheSizeBefore = personStore.getUpdateCache().size+ const checkCacheSizeBefore = personStore.getCheckCache().size+ expect(updateCacheSizeBefore).toBeGreaterThan(0)+ expect(checkCacheSizeBefore).toBeGreaterThan(0)- // Reset the store- personStore.reset()+ // No reset() method; caches persist for the worker's lifetime.+ // Flushing writes dirty entries but does not evict.+ await personStore.flush()- // Verify all caches are cleared- expect(personStore.getUpdateCache().size).toBe(0)- expect(personStore.getCheckCache().size).toBe(0)+ expect(personStore.getUpdateCache().size).toBe(updateCacheSizeBefore)+ expect(personStore.getCheckCache().size).toBe(checkCacheSizeBefore)})- it('should allow reuse of the store after reset', async () => {+ it('subsequent flushes pick up only newly-dirtied entries', async () => {const personStore = getPersonsStore()// First batch: populate and flush- await personStore.fetchForUpdate(teamId, 'distinct-1')+ await personStore.fetchForUpdate(teamId, 'distinct-1', 0)await personStore.updatePersonWithPropertiesDiffForUpdate(person, { batch: '1' }, [], {}, 'distinct-1')await personStore.flush()- personStore.reportBatch()- personStore.reset()- // Second batch: should work normally without stale data+ // Second batch: same persistent cache, new write to a different distinct_idconst person2 = { ...person, id: '2', properties: { original: 'value' } }mockRepo.fetchPerson.mockResolvedValueOnce(person2)- await personStore.fetchForUpdate(teamId, 'distinct-2')+ await personStore.fetchForUpdate(teamId, 'distinct-2', 0)await personStore.updatePersonWithPropertiesDiffForUpdate(person2, { batch: '2' }, [], {}, 'distinct-2')await personStore.flush()- // Verify second batch wrote correctly (NO_ASSERT mode uses batch updates)+ // Two flushes, second one wrote the round 2 deltaexpect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(2)expect(mockRepo.updatePersonsBatch).toHaveBeenLastCalledWith([expect.objectContaining({@@ -2369,27 +2391,90 @@ describe('BatchWritingPersonStore', () => {])})- it('should not share cached person data between batches', async () => {+ it('reuses cached person data across batches (persistent-cache model)', async () => {const personStore = getPersonsStore()// First batch: cache person with specific propertiesconst personBatch1 = { ...person, properties: { name: 'Batch1Person' } }mockRepo.fetchPerson.mockResolvedValueOnce(personBatch1)- await personStore.fetchForUpdate(teamId, 'user-1')+ await personStore.fetchForUpdate(teamId, 'user-1', 0)await personStore.flush()- personStore.reportBatch()- personStore.reset()- // Second batch: same distinct_id should fetch fresh from DB- const personBatch2 = { ...person, properties: { name: 'Batch2Person', newProp: 'value' } }- mockRepo.fetchPerson.mockResolvedValueOnce(personBatch2)+ // Second batch: same distinct_id should hit the persisted cache and+ // NOT re-fetch from DB. This is the cross-batch caching benefit+ // unlocked by the persistent-cache model.+ const fetchedPerson = await personStore.fetchForUpdate(teamId, 'user-1', 0)- const fetchedPerson = await personStore.fetchForUpdate(teamId, 'user-1')+ expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(1)+ expect(fetchedPerson?.properties).toEqual({ name: 'Batch1Person' })+ })- // Should have fetched from DB again, not used stale cache- expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(2)- expect(fetchedPerson?.properties).toEqual({ name: 'Batch2Person', newProp: 'value' })+ it('clears needs_write on dirty entries synchronously during flush', async () => {+ // Linearization point: flush() must clear needs_write BEFORE awaiting+ // any DB I/O. Any code path that introduces an await between the+ // dirty-filter pass and the clear would re-open the cross-batch race+ // documented in the design doc — this test guards against that.+ const personStore = getPersonsStore()++ await personStore.fetchForUpdate(teamId, 'distinct-1', 0)+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { name: 'test' }, [], {}, 'distinct-1')++ const updateCache = personStore.getUpdateCache()+ const dirtyEntriesBefore = Array.from(updateCache.values()).filter((u) => u?.needs_write)+ expect(dirtyEntriesBefore.length).toBeGreaterThan(0)++ // Kick off flush WITHOUT awaiting it, then synchronously inspect+ // needs_write. If flush yields before clearing the bit, this will+ // catch it — the assertion runs at the first microtask boundary.+ const flushPromise = personStore.flush()++ const stillDirty = Array.from(updateCache.values()).filter((u) => u?.needs_write)+ expect(stillDirty).toHaveLength(0)++ await flushPromise+ })++ it('persists update cache across flushes; re-dirty drives the next flush', async () => {+ // The persistent-cache model: flushing does NOT remove entries from+ // personUpdateCache. A subsequent write to the same distinct_id+ // re-dirties the existing entry, and the next flush picks up the+ // delta.+ const personStore = getPersonsStore()++ await personStore.fetchForUpdate(teamId, 'distinct-1', 0)+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { round: '1' }, [], {}, 'distinct-1')++ const updateCacheKeyBefore = Array.from(personStore.getUpdateCache().keys())+ expect(updateCacheKeyBefore.length).toBeGreaterThan(0)++ await personStore.flush()++ // Cache entries persist+ expect(Array.from(personStore.getUpdateCache().keys())).toEqual(updateCacheKeyBefore)+ // All entries are clean after flush+ for (const entry of personStore.getUpdateCache().values()) {+ if (entry) {+ expect(entry.needs_write).toBe(false)+ }+ }++ // Re-dirty via a second update+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { round: '2' }, [], {}, 'distinct-1')+ const dirtyAfterSecondWrite = Array.from(personStore.getUpdateCache().values()).filter(+ (u) => u?.needs_write+ )+ expect(dirtyAfterSecondWrite.length).toBeGreaterThan(0)++ mockRepo.updatePersonsBatch.mockClear()+ await personStore.flush()++ // Second flush wrote the round 2 delta+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledWith([+ expect.objectContaining({+ properties_to_set: expect.objectContaining({ round: '2' }),+ }),+ ])})})@@ -2414,7 +2499,9 @@ describe('BatchWritingPersonStore', () => {false,'new-uuid',{ distinctId: 'primary-id' },- [{ distinctId: 'extra-id-1' }, { distinctId: 'extra-id-2' }, { distinctId: 'extra-id-3' }]+ [{ distinctId: 'extra-id-1' }, { distinctId: 'extra-id-2' }, { distinctId: 'extra-id-3' }],+ undefined,+ 0)// All distinct IDs should be cached - verify by checking the cache directly@@ -2444,8 +2531,8 @@ describe('BatchWritingPersonStore', () => {mockRepo.fetchPersonsByDistinctIds.mockResolvedValueOnce([person1, person2])await personStoreForBatch.prefetchPersons([- { teamId, distinctId: 'user-1' },- { teamId, distinctId: 'user-2' },+ { teamId, distinctId: 'user-1', batchId: 0 },+ { teamId, distinctId: 'user-2', batchId: 0 },])// Should have called fetchPersonsByDistinctIds once with both entries (useReadReplica=false)@@ -2476,8 +2563,8 @@ describe('BatchWritingPersonStore', () => {mockRepo.fetchPersonsByDistinctIds.mockResolvedValueOnce([person1])await personStoreForBatch.prefetchPersons([- { teamId, distinctId: 'user-1' },- { teamId, distinctId: 'user-2' },+ { teamId, distinctId: 'user-1', batchId: 0 },+ { teamId, distinctId: 'user-2', batchId: 0 },])// Check cache: person1 should be cached (without distinct_id), person2 should be null@@ -2501,8 +2588,8 @@ describe('BatchWritingPersonStore', () => {mockRepo.fetchPersonsByDistinctIds.mockResolvedValueOnce([person2])await personStoreForBatch.prefetchPersons([- { teamId, distinctId: 'user-1' },- { teamId, distinctId: 'user-2' },+ { teamId, distinctId: 'user-1', batchId: 0 },+ { teamId, distinctId: 'user-2', batchId: 0 },])// Should only fetch user-2 since user-1 was already cached@@ -2514,14 +2601,14 @@ describe('BatchWritingPersonStore', () => {// Pre-populate by fetching for updatemockRepo.fetchPerson.mockResolvedValueOnce(person)- await personStoreForBatch.fetchForUpdate(teamId, 'user-1')+ await personStoreForBatch.fetchForUpdate(teamId, 'user-1', 0)const person2 = { ...person, id: '2', team_id: teamId, distinct_id: 'user-2' }mockRepo.fetchPersonsByDistinctIds.mockResolvedValueOnce([person2])await personStoreForBatch.prefetchPersons([- { teamId, distinctId: 'user-1' },- { teamId, distinctId: 'user-2' },+ { teamId, distinctId: 'user-1', batchId: 0 },+ { teamId, distinctId: 'user-2', batchId: 0 },])// Should only fetch user-2 since user-1 was already in update cache@@ -2544,8 +2631,8 @@ describe('BatchWritingPersonStore', () => {personStoreForBatch.getCheckCache().set(`${teamId}:user-2`, null)await personStoreForBatch.prefetchPersons([- { teamId, distinctId: 'user-1' },- { teamId, distinctId: 'user-2' },+ { teamId, distinctId: 'user-1', batchId: 0 },+ { teamId, distinctId: 'user-2', batchId: 0 },])expect(mockRepo.fetchPersonsByDistinctIds).not.toHaveBeenCalled()@@ -2557,10 +2644,10 @@ describe('BatchWritingPersonStore', () => {const prefetchedPerson = { ...person, id: '1', team_id: teamId, distinct_id: 'user-1' }mockRepo.fetchPersonsByDistinctIds.mockResolvedValueOnce([prefetchedPerson])- await personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])+ await personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1', batchId: 0 }])// Now fetchForChecking should use cached data- const result = await personStoreForBatch.fetchForChecking(teamId, 'user-1')+ const result = await personStoreForBatch.fetchForChecking(teamId, 'user-1', 0)// Result is InternalPerson (no distinct_id), so compare without itconst { distinct_id: _, ...expectedPerson } = prefetchedPerson@@ -2575,10 +2662,10 @@ describe('BatchWritingPersonStore', () => {const prefetchedPerson = { ...person, id: '1', team_id: teamId, distinct_id: 'user-1' }mockRepo.fetchPersonsByDistinctIds.mockResolvedValueOnce([prefetchedPerson])- await personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])+ await personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1', batchId: 0 }])// Now fetchForUpdate should use cached data- const result = await personStoreForBatch.fetchForUpdate(teamId, 'user-1')+ const result = await personStoreForBatch.fetchForUpdate(teamId, 'user-1', 0)// Result is InternalPerson (no distinct_id), so compare without itconst { distinct_id: _, ...expectedPerson } = prefetchedPerson@@ -2600,10 +2687,12 @@ describe('BatchWritingPersonStore', () => {mockRepo.fetchPersonsByDistinctIds.mockReturnValueOnce(prefetchPromise)// Start prefetch but don't await it (simulating non-blocking behavior)- const prefetchCompletion = personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])+ const prefetchCompletion = personStoreForBatch.prefetchPersons([+ { teamId, distinctId: 'user-1', batchId: 0 },+ ])// Now call fetchForChecking while prefetch is still in flight- const fetchCheckingPromise = personStoreForBatch.fetchForChecking(teamId, 'user-1')+ const fetchCheckingPromise = personStoreForBatch.fetchForChecking(teamId, 'user-1', 0)// Resolve the prefetchresolvePrefetch!([prefetchedPerson])@@ -2633,10 +2722,12 @@ describe('BatchWritingPersonStore', () => {mockRepo.fetchPersonsByDistinctIds.mockReturnValueOnce(prefetchPromise)// Start prefetch but don't await it- const prefetchCompletion = personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])+ const prefetchCompletion = personStoreForBatch.prefetchPersons([+ { teamId, distinctId: 'user-1', batchId: 0 },+ ])// Now call fetchForUpdate while prefetch is still in flight- const fetchUpdatePromise = personStoreForBatch.fetchForUpdate(teamId, 'user-1')+ const fetchUpdatePromise = personStoreForBatch.fetchForUpdate(teamId, 'user-1', 0)// Resolve the prefetchresolvePrefetch!([prefetchedPerson])@@ -2653,6 +2744,35 @@ describe('BatchWritingPersonStore', () => {expect(mockRepo.fetchPerson).not.toHaveBeenCalled()})+ it('should discard late prefetch writes after the batch is released', async () => {+ const personStoreForBatch = getPersonsStore()++ const prefetchedPerson = { ...person, id: '1', team_id: teamId, distinct_id: 'user-1' }++ let resolvePrefetch: (value: (typeof prefetchedPerson)[]) => void+ const prefetchPromise = new Promise<(typeof prefetchedPerson)[]>((resolve) => {+ resolvePrefetch = resolve+ })+ mockRepo.fetchPersonsByDistinctIds.mockReturnValueOnce(prefetchPromise)++ const prefetchCompletion = personStoreForBatch.prefetchPersons([+ { teamId, distinctId: 'user-1', batchId: 0 },+ ])++ personStoreForBatch.releaseBatch(0)++ resolvePrefetch!([prefetchedPerson])+ await prefetchCompletion++ expect(personStoreForBatch.getCheckCache().has(`${teamId}:user-1`)).toBe(false)+ expect(personStoreForBatch.getUpdateCache().has(`${teamId}:1`)).toBe(false)++ const batchDistinctKeys = (personStoreForBatch as any)['batchDistinctKeys'] as Map<number, Set<string>>+ expect(batchDistinctKeys.has(0)).toBe(false)+ const distinctKeyRefCount = (personStoreForBatch as any)['distinctKeyRefCount'] as Map<string, number>+ expect(distinctKeyRefCount.has(`${teamId}:user-1`)).toBe(false)+ })+it('should resolve (not reject) on a transient persons-Postgres failure', async () => {const personStoreForBatch = getPersonsStore()@@ -2663,7 +2783,7 @@ describe('BatchWritingPersonStore', () => {// Prefetch is fired without being awaited by its pipeline step, so a rejection here would// surface as an unhandled rejection and crash the worker. It must resolve instead.await expect(- personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])+ personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1', batchId: 0 }])).resolves.toBeUndefined()// Nothing should have been cached for the failed entry@@ -2676,9 +2796,9 @@ describe('BatchWritingPersonStore', () => {// A non-transient error (e.g. a broken query) must surface loudly, not be swallowed.mockRepo.fetchPersonsByDistinctIds.mockRejectedValueOnce(new Error('something unexpected'))- await expect(personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])).rejects.toThrow(- 'something unexpected'- )+ await expect(+ personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1', batchId: 0 }])+ ).rejects.toThrow('something unexpected')})it('should let fetchForUpdate fall back to an on-demand fetch after a failed prefetch', async () => {@@ -2688,10 +2808,10 @@ describe('BatchWritingPersonStore', () => {new DependencyUnavailableError('connect ECONNREFUSED', 'Postgres', new Error('connect ECONNREFUSED')))- await personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])+ await personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1', batchId: 0 }])// The failed prefetch left the caches empty, so fetchForUpdate must do its own fetch.- const result = await personStoreForBatch.fetchForUpdate(teamId, 'user-1')+ const result = await personStoreForBatch.fetchForUpdate(teamId, 'user-1', 0)expect(result).toEqual(person)expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(1)@@ -2707,8 +2827,8 @@ describe('BatchWritingPersonStore', () => {})mockRepo.fetchPersonsByDistinctIds.mockReturnValueOnce(fetchPromise)- const prefetch = personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])- const checking = personStoreForBatch.fetchForChecking(teamId, 'user-1')+ const prefetch = personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1', batchId: 0 }])+ const checking = personStoreForBatch.fetchForChecking(teamId, 'user-1', 0)rejectFetch!(new DependencyUnavailableError('connect ECONNREFUSED', 'Postgres', new Error('boom')))@@ -2728,8 +2848,8 @@ describe('BatchWritingPersonStore', () => {})mockRepo.fetchPersonsByDistinctIds.mockReturnValueOnce(fetchPromise)- const prefetch = personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])- const update = personStoreForBatch.fetchForUpdate(teamId, 'user-1')+ const prefetch = personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1', batchId: 0 }])+ const update = personStoreForBatch.fetchForUpdate(teamId, 'user-1', 0)rejectFetch!(new DependencyUnavailableError('connect ECONNREFUSED', 'Postgres', new Error('boom')))@@ -2737,4 +2857,497 @@ describe('BatchWritingPersonStore', () => {await expect(prefetch).resolves.toBeUndefined()})})++ describe('cross-batch cache scenarios (persistent-cache model)', () => {+ // These tests simulate the pipeline calling flush() at the end of each+ // "batch" while the store's caches persist. They verify that the data+ // we care about — accumulated person updates, distinct_id→person_id+ // mappings, merge results — survive across flush() boundaries and are+ // correctly merged into the next batch's writes.++ it('accumulates property updates for the same person across two batches', async () => {+ const personStore = getPersonsStore()++ // BATCH 1 — set props {a, b} on distinct_id_1's person+ await personStore.fetchForUpdate(teamId, 'distinct_id_1', 0)+ await personStore.updatePersonWithPropertiesDiffForUpdate(+ person,+ { a: '1', b: '2' },+ [],+ {},+ 'distinct_id_1'+ )+ await personStore.flush()++ expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(1)+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(1)+ expect(mockRepo.updatePersonsBatch).toHaveBeenLastCalledWith([+ expect.objectContaining({+ properties_to_set: expect.objectContaining({ a: '1', b: '2' }),+ }),+ ])++ // BATCH 2 — add prop {c}, unset {a}. Cache for distinct_id_1 should+ // already have the merged state from batch 1 (no re-fetch).+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { c: '3' }, ['a'], {}, 'distinct_id_1')+ await personStore.flush()++ // No second fetch — persistent cache had the person+ expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(1)+ // Second flush writes the accumulated state — which includes the+ // batch 1 changes still in the cache (`a`, `b`) merged with batch+ // 2 changes (`c` added, `a` unset).+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(2)+ const secondCallPayload = mockRepo.updatePersonsBatch.mock.calls[1][0][0]+ expect(secondCallPayload.properties_to_set).toEqual(expect.objectContaining({ b: '2', c: '3' }))+ expect(secondCallPayload.properties_to_unset).toContain('a')+ })++ it('two distinct_ids pointing to the same person share a single cache entry across batches', async () => {+ const personStore = getPersonsStore()++ // Both fetches resolve to the SAME underlying person (same uuid / id).+ // Simulates the case where distinct_id_a and distinct_id_b have+ // already been merged to one person in the DB.+ mockRepo.fetchPerson.mockResolvedValue(person)++ // BATCH 1 — write via distinct_id_a+ await personStore.fetchForUpdate(teamId, 'distinct_id_a', 0)+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { via: 'a' }, [], {}, 'distinct_id_a')+ await personStore.flush()++ // BATCH 2 — write via distinct_id_b. The store maintains a per-+ // distinct_id update cache, so this hits a separate cache slot,+ // but both slots map to the same person id internally (via+ // distinctIdToPersonId resolution).+ await personStore.fetchForUpdate(teamId, 'distinct_id_b', 0)+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { via: 'b' }, [], {}, 'distinct_id_b')+ await personStore.flush()++ // Both batches landed updates targeting the same person.uuid.+ const allUpdatePayloads = mockRepo.updatePersonsBatch.mock.calls.flatMap((call: any) => call[0])+ expect(allUpdatePayloads).toHaveLength(2)+ for (const payload of allUpdatePayloads) {+ expect(payload.uuid).toBe(person.uuid)+ }+ })++ it('does not double-write a stale entry when the same person is touched in batch A, untouched in batch B', async () => {+ const personStore = getPersonsStore()++ // BATCH 1 — write+ await personStore.fetchForUpdate(teamId, 'distinct_id_1', 0)+ await personStore.updatePersonWithPropertiesDiffForUpdate(+ person,+ { name: 'first' },+ [],+ {},+ 'distinct_id_1'+ )+ await personStore.flush()+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(1)++ // BATCH 2 — no writes. Just reads from the cache.+ const cachedPerson = await personStore.fetchForUpdate(teamId, 'distinct_id_1', 0)+ expect(cachedPerson).toBeTruthy()+ await personStore.flush()++ // Batch 2 must NOT have triggered another DB write — needs_write+ // was cleared by the first flush and no mutation re-dirtied it.+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(1)+ })++ it('preserves distinctId→personId mapping after addDistinctId across batches', async () => {+ const personStore = getPersonsStore()+ mockRepo.fetchPerson.mockResolvedValue(person)++ // BATCH 1 — primary distinct_id fetched, then a new distinct_id+ // is added to the same person.+ await personStore.fetchForUpdate(teamId, 'distinct_id_primary', 0)+ await personStore.addDistinctId(person, 'distinct_id_secondary', 0, undefined, 0)+ await personStore.flush()++ const distinctIdToPersonId = (personStore as any).distinctIdToPersonId as Map<string, string>+ const secondaryMappingAfterBatch1 = distinctIdToPersonId.get(`${teamId}:distinct_id_secondary`)+ expect(secondaryMappingAfterBatch1).toBe(person.id)++ // BATCH 2 — write via the newly-added distinct_id. It should+ // resolve to the same person via the persistent mapping; no+ // additional fetchPerson roundtrip.+ mockRepo.fetchPerson.mockClear()+ await personStore.updatePersonWithPropertiesDiffForUpdate(+ person,+ { from: 'secondary' },+ [],+ {},+ 'distinct_id_secondary'+ )+ await personStore.flush()++ // The mapping is preserved+ expect(distinctIdToPersonId.get(`${teamId}:distinct_id_secondary`)).toBe(person.id)+ // ...and we didn't re-fetch the person for the secondary distinct_id+ expect(mockRepo.fetchPerson).not.toHaveBeenCalled()+ })++ it('moveDistinctIds in batch A makes batch B writes target the merged person', async () => {+ const personStore = getPersonsStore()++ const sourcePerson: InternalPerson = {+ ...person,+ id: 'source-id',+ uuid: 'source-uuid',+ properties: { source: 'true' },+ }+ const targetPerson: InternalPerson = {+ ...person,+ id: 'target-id',+ uuid: 'target-uuid',+ properties: { target: 'true' },+ }++ // BATCH 1 — fetch both persons into the cache, then merge source+ // → target by moving the source's distinct_ids onto the target.+ mockRepo.fetchPerson.mockResolvedValueOnce(sourcePerson).mockResolvedValueOnce(targetPerson)++ await personStore.fetchForUpdate(teamId, 'distinct_id_source', 0)+ await personStore.fetchForUpdate(teamId, 'distinct_id_target', 0)++ const tx = createMockTransaction() as any+ tx.moveDistinctIds.mockResolvedValueOnce({+ success: true,+ messages: [],+ distinctIdsMoved: ['distinct_id_source'],+ })++ await personStore.moveDistinctIds(sourcePerson, targetPerson, 'distinct_id_target', undefined, tx, 0)+ await personStore.flush()++ // BATCH 2 — write via the previously-source distinct_id.+ // distinctIdToPersonId now maps it to the target.+ const distinctIdToPersonId = (personStore as any).distinctIdToPersonId as Map<string, string>+ expect(distinctIdToPersonId.get(`${teamId}:distinct_id_source`)).toBe(targetPerson.id)++ mockRepo.fetchPerson.mockClear()+ mockRepo.updatePersonsBatch.mockClear()+ await personStore.updatePersonWithPropertiesDiffForUpdate(+ targetPerson,+ { post_merge: 'yes' },+ [],+ {},+ 'distinct_id_source'+ )+ await personStore.flush()++ // We should NOT have re-fetched (mapping cached) and the write+ // should be attributed to the target person, not the source.+ expect(mockRepo.fetchPerson).not.toHaveBeenCalled()+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(1)+ const payload = mockRepo.updatePersonsBatch.mock.calls[0][0][0]+ expect(payload.uuid).toBe(targetPerson.uuid)+ expect(payload.properties_to_set).toEqual(expect.objectContaining({ post_merge: 'yes' }))+ })+ })++ describe('shutdown()', () => {+ it('succeeds without calling flush when no dirty entries exist', async () => {+ const flushSpy = jest.spyOn(personStore, 'flush')++ await personStore.shutdown()++ expect(flushSpy).not.toHaveBeenCalled()+ expect(mockIngestionWarningsOutputs.produce).not.toHaveBeenCalled()+ })++ it('throws when dirty entries exist — caller must flush first', () => {+ const cache = (personStore as any).personUpdateCache as Map<string, any>+ cache.set(`${teamId}:${person.id}`, {+ ...fromInternalPerson(person, 'test'),+ needs_write: true,+ properties_to_set: { x: '1' },+ })++ expect(() => personStore.shutdown()).toThrow(/dirty cache entries/)++ cache.delete(`${teamId}:${person.id}`)+ })++ it('emits accumulated metrics before throwing on dirty cache', () => {+ const cache = (personStore as any).personUpdateCache as Map<string, any>+ cache.set(`${teamId}:${person.id}`, {+ ...fromInternalPerson(person, 'test'),+ needs_write: true,+ properties_to_set: { x: '1' },+ })++ const emitSpy = jest.spyOn(personStore as any, 'emitAccumulatedMetrics')++ expect(() => personStore.shutdown()).toThrow()++ expect(emitSpy).toHaveBeenCalledTimes(1)++ cache.delete(`${teamId}:${person.id}`)+ })++ it('flushAndProduceMessages drains dirty entries and produces Kafka messages', async () => {+ const cache = (personStore as any).personUpdateCache as Map<string, any>+ cache.set(`${teamId}:${person.id}`, {+ id: person.id,+ uuid: person.uuid,+ team_id: teamId,+ distinct_id: 'test',+ needs_write: true,+ properties: person.properties,+ properties_to_set: { new_prop: 'value' },+ properties_to_unset: [],+ version: person.version,+ created_at: person.created_at,+ is_identified: false,+ is_user_id: null,+ })++ const message = { output: PERSONS_OUTPUT, value: Buffer.from('{}') }+ const flushSpy = jest+ .spyOn(personStore, 'flush')+ .mockResolvedValue([{ messages: [message], teamId, distinctId: 'test', uuid: person.uuid }])++ await personStore.flushAndProduceMessages()++ expect(flushSpy).toHaveBeenCalledTimes(1)+ expect(mockIngestionWarningsOutputs.produce).toHaveBeenCalledTimes(1)+ expect(mockIngestionWarningsOutputs.produce).toHaveBeenCalledWith(PERSONS_OUTPUT, {+ key: null,+ value: message.value,+ teamId,+ })++ // Remove injected entry so afterEach shutdown does not re-trigger a flush+ cache.delete(`${teamId}:${person.id}`)+ })+ })++ describe('releaseBatch', () => {+ it('is a no-op for an unknown batchId', () => {+ expect(() => personStore.releaseBatch(999)).not.toThrow()+ })++ it('reports dirty entries and referenced batches in flush stats', () => {+ const personUpdate = { ...fromInternalPerson(person, 'user-a'), needs_write: true }++ personStore.setCachedPersonForUpdate(teamId, 'user-a', personUpdate, 0)+ personStore.setCachedPersonForUpdate(teamId, 'user-a', { ...personUpdate }, 1)++ expect(personStore.getFlushStats()).toEqual({+ dirtyEntryCount: 1,+ referencedBatchCount: 2,+ cacheEntryCount: 1,+ })+ })++ it('evicts check cache and distinctId mapping after single batch is released', () => {+ personStore.setCheckCachedPerson(teamId, 'user-a', person, 0)+ personStore.setCachedPersonForUpdate(teamId, 'user-a', fromInternalPerson(person, 'user-a'), 0)++ expect(personStore.getCheckCache().has(`${teamId}:user-a`)).toBe(true)++ personStore.releaseBatch(0)++ expect(personStore.getCheckCache().has(`${teamId}:user-a`)).toBe(false)+ expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'user-a')).toBeUndefined()+ })++ it('only evicts when the last referencing batch is released', () => {+ personStore.setCheckCachedPerson(teamId, 'user-a', person, 0)+ personStore.setCheckCachedPerson(teamId, 'user-a', person, 1)++ personStore.releaseBatch(0)+ // Still held by batch 1+ expect(personStore.getCheckCache().has(`${teamId}:user-a`)).toBe(true)++ personStore.releaseBatch(1)+ // Now unreferenced+ expect(personStore.getCheckCache().has(`${teamId}:user-a`)).toBe(false)+ })++ it('defers eviction of dirty person update entries until after flush', async () => {+ const personUpdate = { ...fromInternalPerson(person, 'user-a'), needs_write: true }+ personStore.setCachedPersonForUpdate(teamId, 'user-a', personUpdate, 0)++ personStore.releaseBatch(0)++ // Both the cache entry AND the distinctId mapping are kept alive while dirty —+ // evicting the mapping would orphan the cache entry after the next flush.+ expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'user-a')).toBeDefined()+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)).toBeDefined()++ // After flush clears needs_write, processDeferredEvictions() runs and+ // cleans up both the cache entry and the mapping.+ await personStore.flush()++ expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'user-a')).toBeUndefined()+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)).toBeUndefined()+ })++ it('deferred eviction is skipped if entry is re-dirtied during the DB write', async () => {+ // properties_to_set must be non-empty so getPersonUpdateOutcome returns 'changed'+ // and the entry is included in the batch (otherwise the mock is never called).+ const personUpdate = {+ ...fromInternalPerson(person, 'user-a'),+ needs_write: true,+ properties_to_set: { new_prop: 'new_value' },+ }+ personStore.setCachedPersonForUpdate(teamId, 'user-a', personUpdate, 0)+ personStore.releaseBatch(0)++ // Simulate a concurrent batch re-dirtying the entry during the async DB write+ // (i.e., after the linearization point clears needs_write but before processDeferredEvictions).+ // kafkaMessage must be truthy to avoid the fallback individual-update path.+ mockRepo.updatePersonsBatch.mockImplementationOnce((updates: any[]) => {+ const results = new Map()+ for (const update of updates) {+ results.set(update.uuid, { success: true, version: update.version + 1, kafkaMessage: {} })+ }+ // getCachedPersonForUpdateByPersonId returns a deep copy, so we must access the+ // internal map directly to simulate a concurrent batch re-dirtying the entry.+ const cache: Map<string, any> = (personStore as any)['personUpdateCache']+ const actualUpdate = cache.get(`${teamId}:${person.id}`)+ if (actualUpdate) {+ actualUpdate.needs_write = true+ }+ return Promise.resolve(results)+ })++ await personStore.flush()++ // Entry is still alive because it was re-dirtied during the DB write+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)).toBeDefined()++ // A second flush clears it properly+ await personStore.flush()+ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)).toBeUndefined()+ expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'user-a')).toBeUndefined()+ })++ it('evicts clean person update entries from personUpdateCache', () => {+ const personUpdate = { ...fromInternalPerson(person, 'user-a'), needs_write: false }+ personStore.setCachedPersonForUpdate(teamId, 'user-a', personUpdate, 0)++ personStore.releaseBatch(0)++ expect(personStore.getCachedPersonForUpdateByPersonId(teamId, person.id)).toBeUndefined()+ })++ it('clears personlessBatchResults for evicted distinct IDs', () => {+ personStore.setCheckCachedPerson(teamId, 'user-a', null, 0)+ ;(personStore as any)['personlessBatchResults'].set(`${teamId}:user-a`, true)++ personStore.releaseBatch(0)++ expect(personStore.getPersonlessBatchResult(teamId, 'user-a')).toBeUndefined()+ })++ it('evicts personlessBatchResults written via addPersonlessDistinctIdForMerge after batch release', async () => {+ const batchStore = new BatchBoundPersonsStore(personStore, 0)++ await batchStore.addPersonlessDistinctIdForMerge(teamId, 'lonely-merge-distinct')+ expect(personStore.getPersonlessBatchResult(teamId, 'lonely-merge-distinct')).toBe(true)++ personStore.releaseBatch(0)++ expect(personStore.getPersonlessBatchResult(teamId, 'lonely-merge-distinct')).toBeUndefined()+ })++ it('tracks property-update cache writes through the batch-bound store', async () => {+ const batchStore = new BatchBoundPersonsStore(personStore, 0)++ await batchStore.updatePersonWithPropertiesDiffForUpdate(+ person,+ { plan: 'enterprise' },+ [],+ {},+ 'batch-bound-property'+ )++ expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'batch-bound-property')).toBeDefined()++ await personStore.flush()+ personStore.releaseBatch(0)++ expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'batch-bound-property')).toBeUndefined()+ })++ it('tracks merge-update cache writes through the batch-bound store', async () => {+ const batchStore = new BatchBoundPersonsStore(personStore, 0)++ await batchStore.updatePersonForMerge(+ person,+ { properties: { merge_marker: 'tracked' } },+ 'batch-bound-merge'+ )++ expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'batch-bound-merge')).toBeDefined()++ await personStore.flush()+ personStore.releaseBatch(0)++ expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'batch-bound-merge')).toBeUndefined()+ })++ it('only evicts entries for the released batch, leaving other batch entries intact', () => {+ personStore.setCheckCachedPerson(teamId, 'user-a', person, 0)+ personStore.setCheckCachedPerson(teamId, 'user-b', person, 1)++ personStore.releaseBatch(0)++ expect(personStore.getCheckCache().has(`${teamId}:user-a`)).toBe(false)+ expect(personStore.getCheckCache().has(`${teamId}:user-b`)).toBe(true)+ })++ it('cleans up batch tracking data after release', () => {+ personStore.setCheckCachedPerson(teamId, 'user-a', person, 0)++ personStore.releaseBatch(0)++ const batchDistinctKeys = (personStore as any)['batchDistinctKeys'] as Map<number, Set<string>>+ expect(batchDistinctKeys.has(0)).toBe(false)+ const distinctKeyRefCount = (personStore as any)['distinctKeyRefCount'] as Map<string, number>+ expect(distinctKeyRefCount.has(`${teamId}:user-a`)).toBe(false)+ })++ it('overlapping prefetches keep entry alive through first flush, evict on second', async () => {+ // Simulate batch 0 and batch 1 both prefetching the same distinct ID+ // before either has flushed (the concurrent-batches scenario).+ mockRepo.fetchPersonsByDistinctIds.mockResolvedValueOnce([{ ...person, distinct_id: 'user-a' }])+ await personStore.prefetchPersons([{ teamId, distinctId: 'user-a', batchId: 0 }])+ // Batch 1 prefetches same user — already in cache, just bumps refcount+ await personStore.prefetchPersons([{ teamId, distinctId: 'user-a', batchId: 1 }])++ const distinctKeyRefCount = (personStore as any)['distinctKeyRefCount'] as Map<string, number>+ expect(distinctKeyRefCount.get(`${teamId}:user-a`)).toBe(2)++ // Batch 0 per-event work: update user-a+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { prop0: 'batch0' }, [], {}, 'user-a', 0)++ // Batch 0 flushes — writes the dirty entry, clears needs_write+ await personStore.flush()+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(1)++ // Release batch 0 — refcount drops to 1, entry survives for batch 1+ personStore.releaseBatch(0)+ expect(distinctKeyRefCount.get(`${teamId}:user-a`)).toBe(1)+ expect(personStore.getCheckCache().has(`${teamId}:user-a`)).toBe(true)++ // Batch 1 per-event work: update user-a (reuses the cached entry, no DB re-fetch)+ await personStore.updatePersonWithPropertiesDiffForUpdate(person, { prop1: 'batch1' }, [], {}, 'user-a', 1)++ // Batch 1 flushes — writes batch 1's dirty entry+ await personStore.flush()+ expect(mockRepo.updatePersonsBatch).toHaveBeenCalledTimes(2)++ // Release batch 1 — refcount drops to 0, entry evicted+ personStore.releaseBatch(1)+ expect(distinctKeyRefCount.has(`${teamId}:user-a`)).toBe(false)+ expect(personStore.getCheckCache().has(`${teamId}:user-a`)).toBe(false)+ })+ })})diff --git a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.tsindex 8d09b8eff701..18dd074d6d85 100644--- a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts+++ b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts@@ -5,8 +5,6 @@ import { Properties } from '~/plugin-scaffold'import { NoRowsUpdatedError } from '~/utils/utils'import { emitIngestionWarning } from '../../../ingestion/common/ingestion-warnings'-import { IngestionWarningsOutput } from '../../../ingestion/common/outputs'-import { IngestionOutputs } from '../../../ingestion/outputs/ingestion-outputs'import {InternalPerson,PersonBatchWritingDbWriteMode,@@ -17,7 +15,7 @@ import {import { CreatePersonResult, MoveDistinctIdsResult } from '../../../utils/db/db'import { MessageSizeTooLarge } from '../../../utils/db/error'import { logger } from '../../../utils/logger'-import { BatchWritingStore } from '../stores/batch-writing-store'+import { BatchWritingStore, BatchWritingStoreFlushStats } from '../stores/batch-writing-store'import {observeLatencyByVersion,personCacheOperationsCounter,@@ -36,6 +34,7 @@ import {personWriteMethodAttemptCounter,totalPersonUpdateLatencyPerBatchHistogram,} from './metrics'+import { PersonOutputs } from './person-context'import { isFilteredPersonUpdateProperty } from './person-property-utils'import { getMetricKey } from './person-update'import { PersonUpdate, fromInternalPerson, toInternalPerson } from './person-update-batch'@@ -91,6 +90,12 @@ export interface BatchWritingPersonsStoreOptions {optimisticUpdateRetryInterval: number/** When true, all property changes trigger person updates (disables batch-level filtering) */updateAllProperties: boolean+ /**+ * Interval at which accumulated per-distinct_id metrics are emitted and+ * cleared. Set to 0 to disable the timer (used by tests; production+ * always wants a positive interval).+ */+ metricEmissionIntervalMs: number}const DEFAULT_OPTIONS: BatchWritingPersonsStoreOptions = {@@ -100,6 +105,7 @@ const DEFAULT_OPTIONS: BatchWritingPersonsStoreOptions = {maxOptimisticUpdateRetries: 5,optimisticUpdateRetryInterval: 50,updateAllProperties: false,+ metricEmissionIntervalMs: 30_000,}interface CacheMetrics {@@ -109,46 +115,463 @@ interface CacheMetrics {checkCacheMisses: number}+class BatchWritingPersonsCache {+ private personCheckCache = new Map<string, InternalPerson | null>()+ private distinctIdToPersonId = new Map<string, string>()+ private personUpdateCache = new Map<string, PersonUpdate | null>()+ private personlessBatchResults = new Map<string, boolean>()+ private batchDistinctKeys = new Map<number, Set<string>>()+ private distinctKeyRefCount = new Map<string, number>()+ private deferredEvictions = new Set<string>()+ private pendingPrefetchesByBatchId = new Map<number, number>()+ private releasedBatchIdsWithPendingPrefetch = new Set<number>()+ private cacheMetrics: CacheMetrics = {+ updateCacheHits: 0,+ updateCacheMisses: 0,+ checkCacheHits: 0,+ checkCacheMisses: 0,+ }++ obtainForBatchId(batchId: number): BatchBoundPersonsCache {+ return new BatchBoundPersonsCache(this, batchId)+ }++ getCheckCache(): Map<string, InternalPerson | null> {+ return this.personCheckCache+ }++ getUpdateCache(): Map<string, PersonUpdate | null> {+ return this.personUpdateCache+ }++ getDistinctIdToPersonIdCache(): Map<string, string> {+ return this.distinctIdToPersonId+ }++ getPersonlessBatchResultsCache(): Map<string, boolean> {+ return this.personlessBatchResults+ }++ getBatchDistinctKeys(): Map<number, Set<string>> {+ return this.batchDistinctKeys+ }++ getDistinctKeyRefCount(): Map<string, number> {+ return this.distinctKeyRefCount+ }++ getCacheMetrics(): CacheMetrics {+ return this.cacheMetrics+ }++ resetMetrics(): void {+ this.cacheMetrics = {+ updateCacheHits: 0,+ updateCacheMisses: 0,+ checkCacheHits: 0,+ checkCacheMisses: 0,+ }+ }++ getUpdateCacheValues(): IterableIterator<PersonUpdate | null> {+ return this.personUpdateCache.values()+ }++ getUpdateCacheEntries(): IterableIterator<[string, PersonUpdate | null]> {+ return this.personUpdateCache.entries()+ }++ getFlushStats(): BatchWritingStoreFlushStats {+ const dirtyPersonKeys = new Set<string>()+ for (const [personKey, update] of this.personUpdateCache.entries()) {+ if (update?.needs_write) {+ dirtyPersonKeys.add(personKey)+ }+ }++ const referencedBatchIds = new Set<number>()+ for (const [batchId, distinctKeys] of this.batchDistinctKeys.entries()) {+ for (const distinctKey of distinctKeys) {+ const personId = this.distinctIdToPersonId.get(distinctKey)+ if (!personId) {+ continue+ }++ const separatorIndex = distinctKey.indexOf(':')+ const teamId = distinctKey.slice(0, separatorIndex)+ if (dirtyPersonKeys.has(`${teamId}:${personId}`)) {+ referencedBatchIds.add(batchId)+ break+ }+ }+ }++ return {+ dirtyEntryCount: dirtyPersonKeys.size,+ referencedBatchCount: referencedBatchIds.size,+ cacheEntryCount: this.personUpdateCache.size,+ }+ }++ getCheckCachedPerson(teamId: number, distinctId: string): InternalPerson | null | undefined {+ const cacheKey = this.getDistinctCacheKey(teamId, distinctId)+ const result = this.personCheckCache.get(cacheKey)+ if (result !== undefined) {+ this.cacheMetrics.checkCacheHits+++ return result === null+ ? null+ : {+ ...result,+ properties: { ...result.properties },+ created_at: result.created_at,+ }+ }++ this.cacheMetrics.checkCacheMisses+++ return result+ }++ getCachedPersonForUpdateByPersonId(teamId: number, personId: string | undefined): PersonUpdate | null | undefined {+ if (personId === undefined) {+ this.cacheMetrics.updateCacheMisses+++ return undefined+ }++ const result = this.personUpdateCache.get(this.getPersonIdCacheKey(teamId, personId))+ if (result !== undefined) {+ this.cacheMetrics.updateCacheHits+++ if (result === null) {+ return null+ }++ return {+ ...result,+ properties: { ...result.properties },+ properties_to_set: { ...result.properties_to_set },+ properties_to_unset: [...result.properties_to_unset],+ }+ }++ this.cacheMetrics.updateCacheMisses+++ return undefined+ }++ getCachedPersonForUpdateByDistinctId(teamId: number, distinctId: string): PersonUpdate | null | undefined {+ const cacheKey = this.getDistinctCacheKey(teamId, distinctId)+ const personId = this.distinctIdToPersonId.get(cacheKey)++ return this.getCachedPersonForUpdateByPersonId(teamId, personId)+ }++ setCachedPersonForUpdate(teamId: number, distinctId: string, person: PersonUpdate | null): void {+ const cacheKey = this.getDistinctCacheKey(teamId, distinctId)++ if (person === null) {+ const existingPersonId = this.distinctIdToPersonId.get(cacheKey)+ this.distinctIdToPersonId.delete(cacheKey)+ if (existingPersonId) {+ this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, existingPersonId), null)+ }+ return+ }++ this.distinctIdToPersonId.set(cacheKey, person.id)++ const existingPersonUpdate = this.personUpdateCache.get(this.getPersonIdCacheKey(teamId, person.id))++ if (existingPersonUpdate) {+ const mergedPersonUpdate = this.mergeUpdateIntoCachedPersonUpdate(existingPersonUpdate, person)+ this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, person.id), mergedPersonUpdate)+ } else {+ this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, person.id), person)+ }+ }++ setCheckCachedPerson(teamId: number, distinctId: string, person: InternalPerson | null): void {+ this.personCheckCache.set(this.getDistinctCacheKey(teamId, distinctId), person)+ }++ setDistinctIdToPersonId(teamId: number, distinctId: string, personId: string): void {+ this.distinctIdToPersonId.set(this.getDistinctCacheKey(teamId, distinctId), personId)+ }++ clearPersonCacheForPersonId(teamId: number, personId: string): void {+ this.personUpdateCache.delete(this.getPersonIdCacheKey(teamId, personId))+ }++ clearAllCachesForPersonId(teamId: number, personId: string): void {+ this.clearPersonCacheForPersonId(teamId, personId)++ const distinctIdsToRemove: string[] = []+ for (const [distinctCacheKey, mappedPersonId] of this.distinctIdToPersonId.entries()) {+ if (mappedPersonId === personId && distinctCacheKey.startsWith(`${teamId}:`)) {+ distinctIdsToRemove.push(distinctCacheKey)+ }+ }++ for (const distinctCacheKey of distinctIdsToRemove) {+ this.distinctIdToPersonId.delete(distinctCacheKey)+ this.personCheckCache.delete(distinctCacheKey)+ }+ }++ removeDistinctIdFromCache(teamId: number, distinctId: string): void {+ this.distinctIdToPersonId.delete(this.getDistinctCacheKey(teamId, distinctId))+ }++ clearAllCachesForDistinctId(teamId: number, distinctId: string): void {+ const cacheKey = this.getDistinctCacheKey(teamId, distinctId)+ const personId = this.distinctIdToPersonId.get(cacheKey)++ this.distinctIdToPersonId.delete(cacheKey)++ if (personId) {+ this.clearPersonCacheForPersonId(teamId, personId)+ }++ this.personCheckCache.delete(cacheKey)+ }++ setPersonlessBatchResult(teamId: number, distinctId: string, value: boolean): void {+ this.personlessBatchResults.set(this.getDistinctCacheKey(teamId, distinctId), value)+ }++ getPersonlessBatchResult(teamId: number, distinctId: string): boolean | undefined {+ return this.personlessBatchResults.get(this.getDistinctCacheKey(teamId, distinctId))+ }++ releaseBatchId(batchId: number): void {+ const keys = this.batchDistinctKeys.get(batchId)+ if (this.pendingPrefetchesByBatchId.has(batchId)) {+ this.releasedBatchIdsWithPendingPrefetch.add(batchId)+ }+ if (!keys) {+ return+ }++ for (const distinctKey of keys) {+ const refCount = (this.distinctKeyRefCount.get(distinctKey) ?? 1) - 1+ if (refCount <= 0) {+ this.distinctKeyRefCount.delete(distinctKey)+ this.evictDistinctKey(distinctKey)+ } else {+ this.distinctKeyRefCount.set(distinctKey, refCount)+ }+ }++ this.batchDistinctKeys.delete(batchId)+ }++ trackPendingPrefetch(batchIds: Set<number>): void {+ for (const batchId of batchIds) {+ this.pendingPrefetchesByBatchId.set(batchId, (this.pendingPrefetchesByBatchId.get(batchId) ?? 0) + 1)+ }+ }++ finishPendingPrefetch(batchIds: Set<number>): void {+ for (const batchId of batchIds) {+ const pendingCount = (this.pendingPrefetchesByBatchId.get(batchId) ?? 1) - 1+ if (pendingCount <= 0) {+ this.pendingPrefetchesByBatchId.delete(batchId)+ this.releasedBatchIdsWithPendingPrefetch.delete(batchId)+ } else {+ this.pendingPrefetchesByBatchId.set(batchId, pendingCount)+ }+ }+ }++ isBatchReleasedWithPendingPrefetch(batchId: number): boolean {+ return this.releasedBatchIdsWithPendingPrefetch.has(batchId)+ }++ processDeferredEvictions(): void {+ for (const distinctKey of this.deferredEvictions) {+ const colonIdx = distinctKey.indexOf(':')+ const teamId = Number(distinctKey.slice(0, colonIdx))+ const personId = this.distinctIdToPersonId.get(distinctKey)+ if (personId === undefined) {+ this.deferredEvictions.delete(distinctKey)+ continue+ }+ const personIdKey = this.getPersonIdCacheKey(teamId, personId)+ const update = this.personUpdateCache.get(personIdKey)+ if (!update || !update.needs_write) {+ this.personUpdateCache.delete(personIdKey)+ this.distinctIdToPersonId.delete(distinctKey)+ this.deferredEvictions.delete(distinctKey)+ }+ }+ }++ trackBatchEntry(batchId: number, teamId: number, distinctId: string): void {+ const distinctKey = this.getDistinctCacheKey(teamId, distinctId)+ let keys = this.batchDistinctKeys.get(batchId)+ if (!keys) {+ keys = new Set()+ this.batchDistinctKeys.set(batchId, keys)+ }+ if (!keys.has(distinctKey)) {+ keys.add(distinctKey)+ this.distinctKeyRefCount.set(distinctKey, (this.distinctKeyRefCount.get(distinctKey) ?? 0) + 1)+ }+ }++ private evictDistinctKey(distinctKey: string): void {+ const colonIdx = distinctKey.indexOf(':')+ const teamId = Number(distinctKey.slice(0, colonIdx))+ const personId = this.distinctIdToPersonId.get(distinctKey)++ if (personId !== undefined) {+ const personIdKey = this.getPersonIdCacheKey(teamId, personId)+ const update = this.personUpdateCache.get(personIdKey)+ if (!update || !update.needs_write) {+ this.personUpdateCache.delete(personIdKey)+ this.distinctIdToPersonId.delete(distinctKey)+ } else {+ this.deferredEvictions.add(distinctKey)+ }+ }++ this.personCheckCache.delete(distinctKey)+ this.personlessBatchResults.delete(distinctKey)+ }++ private mergeUpdateIntoCachedPersonUpdate(existingPersonUpdate: PersonUpdate, person: PersonUpdate): PersonUpdate {+ const mergedPersonUpdate: PersonUpdate = {+ ...existingPersonUpdate,+ properties: {+ ...existingPersonUpdate.properties,+ ...person.properties,+ },+ is_identified: existingPersonUpdate.is_identified || person.is_identified,+ }++ mergedPersonUpdate.properties_to_set = {+ ...existingPersonUpdate.properties_to_set,+ ...person.properties,+ ...person.properties_to_set,+ }+ for (const key of person.properties_to_unset) {+ delete mergedPersonUpdate.properties_to_set[key]+ }++ mergedPersonUpdate.properties_to_unset = [+ ...new Set([...existingPersonUpdate.properties_to_unset, ...person.properties_to_unset]),+ ]+ const keysToSet = new Set(Object.keys(person.properties_to_set))+ mergedPersonUpdate.properties_to_unset = mergedPersonUpdate.properties_to_unset.filter(+ (key) => !keysToSet.has(key)+ )++ mergedPersonUpdate.created_at = DateTime.min(existingPersonUpdate.created_at, person.created_at)+ mergedPersonUpdate.needs_write = existingPersonUpdate.needs_write || person.needs_write+ mergedPersonUpdate.force_update = existingPersonUpdate.force_update || person.force_update++ if (person.last_seen_at) {+ if (!mergedPersonUpdate.last_seen_at || person.last_seen_at > mergedPersonUpdate.last_seen_at) {+ mergedPersonUpdate.last_seen_at = person.last_seen_at+ }+ }++ return mergedPersonUpdate+ }++ private getDistinctCacheKey(teamId: number, distinctId: string): string {+ return `${teamId}:${distinctId}`+ }++ private getPersonIdCacheKey(teamId: number, personId: string): string {+ return `${teamId}:${personId}`+ }+}++class BatchBoundPersonsCache {+ constructor(+ private readonly cache: BatchWritingPersonsCache,+ private readonly batchId: number+ ) {}++ getCachedPersonForUpdateByDistinctId(teamId: number, distinctId: string): PersonUpdate | null | undefined {+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)+ return this.cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)+ }++ getCheckCachedPerson(teamId: number, distinctId: string): InternalPerson | null | undefined {+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)+ return this.cache.getCheckCachedPerson(teamId, distinctId)+ }++ setCachedPersonForUpdate(teamId: number, distinctId: string, person: PersonUpdate | null): void {+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)+ this.cache.setCachedPersonForUpdate(teamId, distinctId, person)+ }++ setCheckCachedPerson(teamId: number, distinctId: string, person: InternalPerson | null): void {+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)+ this.cache.setCheckCachedPerson(teamId, distinctId, person)+ }++ setDistinctIdToPersonId(teamId: number, distinctId: string, personId: string): void {+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)+ this.cache.setDistinctIdToPersonId(teamId, distinctId, personId)+ }++ setPersonlessBatchResult(teamId: number, distinctId: string, value: boolean): void {+ this.cache.trackBatchEntry(this.batchId, teamId, distinctId)+ this.cache.setPersonlessBatchResult(teamId, distinctId, value)+ }+}+/**- * This class is used to write persons to the database in batches.- * It will use a cache to avoid reading the same person from the database multiple times.- * And will accumulate all changes for the same person in a single batch. At the- * end of the batch processing, it flushes all changes to the database.+ * Writes persons to the database in batches, accumulating all changes for the+ * same person across events and flushing them on `flush()` calls. The cache+ * persists across batches under concurrentBatches > 1.+ *+ * **Lifecycle:** construction starts a metric-emission timer. Callers MUST+ * invoke `shutdown()` on graceful exit to stop the timer and flush any+ * remaining dirty entries.*/export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore {- private personCheckCache: Map<string, InternalPerson | null>- private distinctIdToPersonId: Map<string, string>- private personUpdateCache: Map<string, PersonUpdate | null>+ private personCache: BatchWritingPersonsCacheprivate fetchPromisesForUpdate: Map<string, Promise<InternalPerson | null>>private fetchPromisesForChecking: Map<string, Promise<InternalPerson | null>>private methodCountsPerDistinctId: Map<string, Map<MethodName, number>>private databaseOperationCountsPerDistinctId: Map<string, Map<MethodName, number>>private updateLatencyPerDistinctIdSeconds: Map<string, Map<UpdateType, number>>- private cacheMetrics: CacheMetricsprivate options: BatchWritingPersonsStoreOptions- // Cache for batch personless distinct ID insert results (is_merged values)- private personlessBatchResults: Map<string, boolean>+ // Periodic metric emitter — emits accumulated per-distinct_id metrics on+ // a fixed cadence rather than at batch boundaries (which are unreliable+ // under concurrentBatches > 1).+ private metricEmissionTimer: NodeJS.Timeout | undefinedconstructor(private personRepository: PersonRepository,- private ingestionWarningsOutputs: IngestionOutputs<IngestionWarningsOutput>,+ private ingestionWarningsOutputs: PersonOutputs,options?: Partial<BatchWritingPersonsStoreOptions>) {this.options = { ...DEFAULT_OPTIONS, ...options }- this.distinctIdToPersonId = new Map()- this.personUpdateCache = new Map()- this.personCheckCache = new Map()+ this.personCache = new BatchWritingPersonsCache()+ Object.defineProperties(this, {+ personUpdateCache: { get: () => this.personCache.getUpdateCache() },+ personCheckCache: { get: () => this.personCache.getCheckCache() },+ distinctIdToPersonId: { get: () => this.personCache.getDistinctIdToPersonIdCache() },+ personlessBatchResults: { get: () => this.personCache.getPersonlessBatchResultsCache() },+ batchDistinctKeys: { get: () => this.personCache.getBatchDistinctKeys() },+ distinctKeyRefCount: { get: () => this.personCache.getDistinctKeyRefCount() },+ })this.fetchPromisesForUpdate = new Map()this.fetchPromisesForChecking = new Map()this.methodCountsPerDistinctId = new Map()this.databaseOperationCountsPerDistinctId = new Map()this.updateLatencyPerDistinctIdSeconds = new Map()- this.personlessBatchResults = new Map()- this.cacheMetrics = {- updateCacheHits: 0,- updateCacheMisses: 0,- checkCacheHits: 0,- checkCacheMisses: 0,++ if (this.options.metricEmissionIntervalMs > 0) {+ this.metricEmissionTimer = setInterval(+ () => this.emitAccumulatedMetrics(),+ this.options.metricEmissionIntervalMs+ )+ // Don't keep the process alive solely for this timer.+ this.metricEmissionTimer.unref?.()}}@@ -226,42 +649,51 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreasync flush(): Promise<FlushResult[]> {const flushStartTime = performance.now()- // Track outcomes for all person updates that were actually modified and filter to only those that should write- const updateEntries = Array.from(this.personUpdateCache.entries()).filter(- (entry): entry is [string, PersonUpdate] => {- const [_, update] = entry-- // Skip null entries - these are deleted persons or cleared cache entries- if (!update) {- return false- }+ // SYNCHRONOUS LINEARIZATION POINT for cross-batch correctness.+ // Walk every dirty entry, decide whether it needs a DB write, and+ // clear `needs_write` before any await below. Concurrent batches+ // that mutate an entry between this clear and the async DB write+ // will re-set `needs_write=true` and be picked up by the next flush.+ // DO NOT introduce any `await` inside this block.+ const updateEntries: [string, PersonUpdate][] = []+ for (const [key, update] of this.personCache.getUpdateCacheEntries()) {+ // Skip null entries - these are deleted persons or cleared cache entries+ if (!update) {+ continue+ }- // Skip entries not marked for write - these are read-only cache entries from fetchForUpdate- // that were cached but never modified (no events tried to update their properties)- if (!update.needs_write) {- return false- }+ // Skip entries not marked for write - these are read-only cache entries from fetchForUpdate+ // that were cached but never modified (no events tried to update their properties)+ if (!update.needs_write) {+ continue+ }- // Determine outcome and track metrics for this person update- const outcome = this.getPersonUpdateOutcome(update)- personProfileBatchUpdateOutcomeCounter.labels({ outcome }).inc()+ // Determine outcome and track metrics for this person update+ const outcome = this.getPersonUpdateOutcome(update)+ personProfileBatchUpdateOutcomeCounter.labels({ outcome }).inc()- // Track which property keys caused person updates (only for 'changed' outcomes)- if (outcome === 'changed') {- const metricsKeys = new Set<string>()- Object.keys(update.properties_to_set).forEach((key) => {- metricsKeys.add(getMetricKey(key))- })- update.properties_to_unset.forEach((key) => {- metricsKeys.add(getMetricKey(key))- })- metricsKeys.forEach((key) => personPropertyKeyUpdateCounter.labels({ key: key }).inc())- }+ if (outcome === 'changed') {+ // Track which property keys caused person updates+ const metricsKeys = new Set<string>()+ Object.keys(update.properties_to_set).forEach((propertyKey) => {+ metricsKeys.add(getMetricKey(propertyKey))+ })+ update.properties_to_unset.forEach((propertyKey) => {+ metricsKeys.add(getMetricKey(propertyKey))+ })+ metricsKeys.forEach((propertyKey) => personPropertyKeyUpdateCounter.labels({ key: propertyKey }).inc())- // Only write to database if outcome is 'changed'- return outcome === 'changed'+ updateEntries.push([key, update])}- )++ // Clear needs_write for every dirty entry we considered, including+ // ones we decided not to write (ignored / no_change). This is the+ // linearization point — concurrent batches that mutate the entry+ // after this point will re-set needs_write=true and the next+ // flush will pick those changes up.+ update.needs_write = false+ }+ // END synchronous linearization point.const batchSize = updateEntries.lengthpersonFlushBatchSizeHistogram.observe({ db_write_mode: this.options.dbWriteMode }, batchSize)@@ -269,6 +701,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreif (batchSize === 0) {personFlushLatencyHistogram.observe({ db_write_mode: this.options.dbWriteMode }, 0)personFlushOperationsCounter.inc({ db_write_mode: this.options.dbWriteMode, outcome: 'success' })+ this.personCache.processDeferredEvictions()return []}@@ -298,6 +731,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorepersonFlushLatencyHistogram.observe({ db_write_mode: this.options.dbWriteMode }, flushLatency)personFlushOperationsCounter.inc({ db_write_mode: this.options.dbWriteMode, outcome: 'success' })+ this.personCache.processDeferredEvictions()return allKafkaMessages} catch (error) {// Record failed flush@@ -314,6 +748,10 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore}}+ getFlushStats(): BatchWritingStoreFlushStats {+ return this.personCache.getFlushStats()+ }+/*** Flush all person updates using a single batch query (NO_ASSERT mode).* Falls back to individual updates for any persons that fail in the batch.@@ -642,17 +1080,18 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore})}- async fetchForChecking(teamId: Team['id'], distinctId: string): Promise<InternalPerson | null> {+ async fetchForChecking(teamId: Team['id'], distinctId: string, batchId: number): Promise<InternalPerson | null> {this.incrementCount('fetchForChecking', distinctId)+ const cache = this.personCache.obtainForBatchId(batchId)// First check the main cache- const cachedPerson = this.getCachedPersonForUpdateByDistinctId(teamId, distinctId)+ const cachedPerson = cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)if (cachedPerson !== undefined) {return cachedPerson === null ? null : toInternalPerson(cachedPerson)}// Then check the checking-specific cache- const checkCachedPerson = this.getCheckCachedPerson(teamId, distinctId)+ const checkCachedPerson = cache.getCheckCachedPerson(teamId, distinctId)if (checkCachedPerson !== undefined) {return checkCachedPerson}@@ -670,7 +1109,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorecallerTag: 'ingestion/person-resolution',})observeLatencyByVersion(person, start, 'fetchForChecking')- this.setCheckCachedPerson(teamId, distinctId, person ?? null)+ cache.setCheckCachedPerson(teamId, distinctId, person ?? null)return person ?? null} finally {this.fetchPromisesForChecking.delete(cacheKey)@@ -679,6 +1118,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorethis.fetchPromisesForChecking.set(cacheKey, fetchPromise)} else {personFetchForCheckingCacheOperationsCounter.inc({ operation: 'hit' })+ cache.getCheckCachedPerson(teamId, distinctId)}return fetchPromise}@@ -691,23 +1131,24 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore* consumer propagates the error and the per-distinct-id pipeline retries it. Any other error* (e.g. a broken query) is rethrown so it crashes loudly rather than being silently masked.*/- async prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string }[]): Promise<void> {+ async prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {if (teamDistinctIds.length === 0) {return}// Filter out entries that are already cached or have pending fetches- const uncachedEntries: { teamId: number; distinctId: string; cacheKey: string }[] = []+ const uncachedEntries: { teamId: number; distinctId: string; batchId: number; cacheKey: string }[] = []- for (const { teamId, distinctId } of teamDistinctIds) {+ for (const { teamId, distinctId, batchId } of teamDistinctIds) {+ const cache = this.personCache.obtainForBatchId(batchId)// Check if already in update cache- const cachedPerson = this.getCachedPersonForUpdateByDistinctId(teamId, distinctId)+ const cachedPerson = cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)if (cachedPerson !== undefined) {continue}// Check if already in check cache- const checkCachedPerson = this.getCheckCachedPerson(teamId, distinctId)+ const checkCachedPerson = cache.getCheckCachedPerson(teamId, distinctId)if (checkCachedPerson !== undefined) {continue}@@ -718,13 +1159,16 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorecontinue}- uncachedEntries.push({ teamId, distinctId, cacheKey })+ uncachedEntries.push({ teamId, distinctId, batchId, cacheKey })}if (uncachedEntries.length === 0) {return}+ const prefetchBatchIds = new Set(uncachedEntries.map(({ batchId }) => batchId))+ this.personCache.trackPendingPrefetch(prefetchBatchIds)+// Create a shared promise for the batch fetch that populates caches when complete// Use primary (useReadReplica=false) to ensure fresh data for updatesconst batchFetchPromise = this.personRepository@@ -742,15 +1186,20 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorepersonsByKey.set(cacheKey, internalPerson)}- // Cache all results (found persons and nulls for missing ones)- for (const { teamId, distinctId, cacheKey } of uncachedEntries) {+ // Cache all results (found persons and nulls for missing ones).+ for (const { teamId, distinctId, batchId, cacheKey } of uncachedEntries) {+ if (this.personCache.isBatchReleasedWithPendingPrefetch(batchId)) {+ continue+ }++ const cache = this.personCache.obtainForBatchId(batchId)const person = personsByKey.get(cacheKey)if (person) {- this.setCheckCachedPerson(teamId, distinctId, person)+ cache.setCheckCachedPerson(teamId, distinctId, person)const personUpdate = fromInternalPerson(person, distinctId)- this.setCachedPersonForUpdate(teamId, distinctId, personUpdate)+ cache.setCachedPersonForUpdate(teamId, distinctId, personUpdate)} else {- this.setCheckCachedPerson(teamId, distinctId, null)+ cache.setCheckCachedPerson(teamId, distinctId, null)}}@@ -761,6 +1210,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorefor (const { cacheKey } of uncachedEntries) {this.fetchPromisesForChecking.delete(cacheKey)}+ this.personCache.finishPendingPrefetch(prefetchBatchIds)})// Register per-key promises so fetchForChecking/fetchForUpdate can wait on the in-flight@@ -792,10 +1242,11 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore})}- async fetchForUpdate(teamId: Team['id'], distinctId: string): Promise<InternalPerson | null> {+ async fetchForUpdate(teamId: Team['id'], distinctId: string, batchId: number): Promise<InternalPerson | null> {this.incrementCount('fetchForUpdate', distinctId)+ const cache = this.personCache.obtainForBatchId(batchId)- const cachedPerson = this.getCachedPersonForUpdateByDistinctId(teamId, distinctId)+ const cachedPerson = cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)if (cachedPerson !== undefined) {return cachedPerson === null ? null : toInternalPerson(cachedPerson)}@@ -807,7 +1258,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreconst prefetchPromise = this.fetchPromisesForChecking.get(cacheKey)if (prefetchPromise) {await prefetchPromise- const prefetchedPerson = this.getCachedPersonForUpdateByDistinctId(teamId, distinctId)+ const prefetchedPerson = cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)if (prefetchedPerson !== undefined) {return prefetchedPerson === null ? null : toInternalPerson(prefetchedPerson)}@@ -827,7 +1278,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreobserveLatencyByVersion(person, start, 'fetchForUpdate')if (person !== undefined) {const personUpdate = fromInternalPerson(person, distinctId)- this.setCachedPersonForUpdate(teamId, distinctId, personUpdate)+ cache.setCachedPersonForUpdate(teamId, distinctId, personUpdate)return person} else {// Before caching null, check if another async operation populated@@ -838,9 +1289,9 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore// 4. Without this check, we would overwrite the other operation's cached person//// From this point, all operations are synchronous to avoid further race conditions.- const currentCache = this.getCachedPersonForUpdateByDistinctId(teamId, distinctId)+ const currentCache = cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)if (currentCache === undefined) {- this.setCachedPersonForUpdate(teamId, distinctId, null)+ cache.setCachedPersonForUpdate(teamId, distinctId, null)return null}return currentCache === null ? null : toInternalPerson(currentCache)@@ -852,6 +1303,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorethis.fetchPromisesForUpdate.set(cacheKey, fetchPromise)} else {personFetchForUpdateCacheOperationsCounter.inc({ operation: 'hit' })+ cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)}return fetchPromise}@@ -860,12 +1312,37 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreperson: InternalPerson,update: Partial<InternalPerson>,distinctId: string,+ batchId: number,+ _tx?: PersonRepositoryTransaction+ ): Promise<[InternalPerson, PersonMessage[], boolean]>+ updatePersonForMerge(+ person: InternalPerson,+ update: Partial<InternalPerson>,+ distinctId: string,+ _tx?: PersonRepositoryTransaction+ ): Promise<[InternalPerson, PersonMessage[], boolean]>+ updatePersonForMerge(+ person: InternalPerson,+ update: Partial<InternalPerson>,+ distinctId: string,+ batchIdOrTx?: number | PersonRepositoryTransaction,_tx?: PersonRepositoryTransaction): Promise<[InternalPerson, PersonMessage[], boolean]> {this.incrementCount('updatePersonForMerge', distinctId)- return Promise.resolve(this.addPersonUpdateToBatch(person, update, distinctId))+ const batchId = typeof batchIdOrTx === 'number' ? batchIdOrTx : 0+ return Promise.resolve(this.addPersonUpdateToBatch(person, update, distinctId, batchId))}+ updatePersonWithPropertiesDiffForUpdate(+ person: InternalPerson,+ propertiesToSet: Properties,+ propertiesToUnset: string[],+ otherUpdates: Partial<InternalPerson>,+ distinctId: string,+ batchId: number,+ forceUpdate?: boolean,+ _tx?: PersonRepositoryTransaction+ ): Promise<[InternalPerson, PersonMessage[], boolean]>updatePersonWithPropertiesDiffForUpdate(person: InternalPerson,propertiesToSet: Properties,@@ -874,13 +1351,27 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoredistinctId: string,forceUpdate?: boolean,_tx?: PersonRepositoryTransaction+ ): Promise<[InternalPerson, PersonMessage[], boolean]>+ updatePersonWithPropertiesDiffForUpdate(+ person: InternalPerson,+ propertiesToSet: Properties,+ propertiesToUnset: string[],+ otherUpdates: Partial<InternalPerson>,+ distinctId: string,+ batchIdOrForceUpdate?: number | boolean,+ forceUpdateOrTx?: boolean | PersonRepositoryTransaction,+ _tx?: PersonRepositoryTransaction): Promise<[InternalPerson, PersonMessage[], boolean]> {+ const batchId = typeof batchIdOrForceUpdate === 'number' ? batchIdOrForceUpdate : 0+ const forceUpdate =+ typeof batchIdOrForceUpdate === 'number' ? (forceUpdateOrTx as boolean | undefined) : batchIdOrForceUpdateconst [updatedPerson, kafkaMessages] = this.addPersonPropertiesUpdateToBatch(person,propertiesToSet,propertiesToUnset,otherUpdates,distinctId,+ batchId,forceUpdate)return Promise.resolve([updatedPerson, kafkaMessages, false])@@ -910,14 +1401,15 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreperson: InternalPerson,distinctId: string,version: number,- tx?: PersonRepositoryTransaction+ tx: PersonRepositoryTransaction | undefined,+ batchId: number): Promise<PersonMessage[]> {this.incrementCount('addDistinctId', distinctId)this.incrementDatabaseOperation('addDistinctId', distinctId)const start = performance.now()const response = await (tx || this.personRepository).addDistinctId(person, distinctId, version)observeLatencyByVersion(person, start, 'addDistinctId')- this.setDistinctIdToPersonId(person.team_id, distinctId, person.id)+ this.setDistinctIdToPersonId(person.team_id, distinctId, person.id, batchId)return response}@@ -926,7 +1418,8 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoretarget: InternalPerson,distinctId: string,limit: number | undefined,- tx: PersonRepositoryTransaction+ tx: PersonRepositoryTransaction,+ batchId: number): Promise<MoveDistinctIdsResult> {this.incrementCount('moveDistinctIds', distinctId)this.incrementDatabaseOperation('moveDistinctIds', distinctId)@@ -944,14 +1437,14 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore// We have existing cached data with merged properties - preserve it// Create a new PersonUpdate for this distinctId that preserves the merged dataconst mergedPersonUpdate = { ...existingTargetCache, distinct_id: distinctId }- this.setCachedPersonForUpdate(target.team_id, distinctId, mergedPersonUpdate)+ this.setCachedPersonForUpdate(target.team_id, distinctId, mergedPersonUpdate, batchId)} else {// No existing cache, create fresh cache from target person- this.setCachedPersonForUpdate(target.team_id, distinctId, fromInternalPerson(target, distinctId))+ this.setCachedPersonForUpdate(target.team_id, distinctId, fromInternalPerson(target, distinctId), batchId)}if (response.success) {- for (const distinctId of response.distinctIdsMoved) {- this.setDistinctIdToPersonId(target.team_id, distinctId, target.id)+ for (const movedDistinctId of response.distinctIdsMoved) {+ this.setDistinctIdToPersonId(target.team_id, movedDistinctId, target.id, batchId)}}@@ -992,40 +1485,57 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreasync addPersonlessDistinctIdForMerge(teamId: Team['id'],distinctId: string,- tx?: PersonRepositoryTransaction+ tx: PersonRepositoryTransaction | undefined,+ batchId: number): Promise<boolean> {this.incrementCount('addPersonlessDistinctIdForMerge', distinctId)const isMerged = await (tx || this.personRepository).addPersonlessDistinctIdForMerge(teamId, distinctId)// Update the batch results cache so processPersonlessStep knows this was mergedif (isMerged) {- this.personlessBatchResults.set(`${teamId}|${distinctId}`, true)+ this.personCache.obtainForBatchId(batchId).setPersonlessBatchResult(teamId, distinctId, true)}return isMerged}- async processPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[]): Promise<void> {+ async processPersonlessDistinctIdsBatch(+ entries: { teamId: number; distinctId: string }[],+ batchId: number+ ): Promise<void> {if (entries.length === 0) {return}+ const cache = this.personCache.obtainForBatchId(batchId)+const results = await this.personRepository.addPersonlessDistinctIdsBatch(entries)- // Only store merged distinct IDs - these need force_upgrade handling- for (const [key, isMerged] of results) {- if (isMerged) {- this.personlessBatchResults.set(key, true)+ // Only store merged distinct IDs - these need force_upgrade handling.+ // Iterate entries (not result keys) to use the ':' cache key format consistently.+ for (const { teamId, distinctId } of entries) {+ if (results.get(`${teamId}|${distinctId}`)) {+ cache.setPersonlessBatchResult(teamId, distinctId, true)}}}getPersonlessBatchResult(teamId: number, distinctId: string): boolean | undefined {- return this.personlessBatchResults.get(`${teamId}|${distinctId}`)+ return this.personCache.getPersonlessBatchResult(teamId, distinctId)}async personPropertiesSize(personId: string, teamId: number): Promise<number> {return await this.personRepository.personPropertiesSize(personId, teamId)}- reportBatch(): void {+ /**+ * Emit the accumulated per-distinct_id metric samples to Prometheus and+ * reset the in-memory accumulators. Runs on a fixed-interval timer in+ * production; tests may invoke it directly via `shutdown()`.+ *+ * Under concurrentBatches > 1, per-batch attribution is unreliable+ * (first-flush-wins), so emission is decoupled from batch boundaries.+ * The histogram names retain a "...PerBatch..." suffix for dashboard+ * compatibility but the window is now the emission interval.+ */+ private emitAccumulatedMetrics(): void {for (const [_, methodCounts] of this.methodCountsPerDistinctId.entries()) {for (const [method, count] of methodCounts.entries()) {personMethodCallsPerBatchHistogram.observe({ method }, count)@@ -1044,221 +1554,119 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore}}- personCacheOperationsCounter.inc({ cache: 'update', operation: 'hit' }, this.cacheMetrics.updateCacheHits)- personCacheOperationsCounter.inc({ cache: 'update', operation: 'miss' }, this.cacheMetrics.updateCacheMisses)- personCacheOperationsCounter.inc({ cache: 'check', operation: 'hit' }, this.cacheMetrics.checkCacheHits)- personCacheOperationsCounter.inc({ cache: 'check', operation: 'miss' }, this.cacheMetrics.checkCacheMisses)- }+ const cacheMetrics = this.personCache.getCacheMetrics()+ personCacheOperationsCounter.inc({ cache: 'update', operation: 'hit' }, cacheMetrics.updateCacheHits)+ personCacheOperationsCounter.inc({ cache: 'update', operation: 'miss' }, cacheMetrics.updateCacheMisses)+ personCacheOperationsCounter.inc({ cache: 'check', operation: 'hit' }, cacheMetrics.checkCacheHits)+ personCacheOperationsCounter.inc({ cache: 'check', operation: 'miss' }, cacheMetrics.checkCacheMisses)- reset(): void {- this.personCheckCache.clear()- this.distinctIdToPersonId.clear()- this.personUpdateCache.clear()- this.fetchPromisesForUpdate.clear()- this.fetchPromisesForChecking.clear()this.methodCountsPerDistinctId.clear()this.databaseOperationCountsPerDistinctId.clear()this.updateLatencyPerDistinctIdSeconds.clear()- this.personlessBatchResults.clear()- this.cacheMetrics = {- updateCacheHits: 0,- updateCacheMisses: 0,- checkCacheHits: 0,- checkCacheMisses: 0,+ this.personCache.resetMetrics()+ }++ /**+ * Flush all dirty entries and produce the resulting Kafka messages inline.+ *+ * Convenience wrapper for callers that don't run inside the pipeline's+ * side-effect scheduler (e.g. server shutdown paths) and just need to drain+ * buffered writes synchronously. Throws on the first produce failure.+ */+ async flushAndProduceMessages(): Promise<void> {+ const flushResults = await this.flush()+ await Promise.all(+ flushResults.flatMap((record) =>+ record.messages.map((message) =>+ this.ingestionWarningsOutputs.produce(message.output, {+ key: null,+ value: message.value,+ teamId: record.teamId,+ })+ )+ )+ )+ }++ /**+ * Stop the metric-emission timer and emit accumulated metrics. Idempotent.+ *+ * Callers MUST call `flush()` before `shutdown()`. Reaching shutdown with a+ * dirty cache indicates a drain-ordering bug — writing here without a+ * subsequent offset commit would create duplicate writes when the partition+ * is reprocessed, and silently dropping the data masks the bug. We throw+ * instead and let the caller decide whether to flush, drop, or fail loudly.+ *+ * Does NOT clear the data caches (personUpdateCache et al.). Those+ * persist for the worker's lifetime; eviction is intentionally+ * decoupled from this lifecycle hook.+ */+ shutdown(): Promise<void> {+ if (this.metricEmissionTimer) {+ clearInterval(this.metricEmissionTimer)+ this.metricEmissionTimer = undefined}++ const dirtyCount = Array.from(this.personCache.getUpdateCacheValues()).filter((u) => u?.needs_write).length+ if (dirtyCount > 0) {+ this.emitAccumulatedMetrics()+ throw new Error(+ `BatchWritingPersonsStore.shutdown() called with ${dirtyCount} dirty cache entries — call flush() first`+ )+ }++ this.emitAccumulatedMetrics()+ return Promise.resolve()}// Private implementation methodsgetCheckCache(): Map<string, InternalPerson | null> {- return this.personCheckCache+ return this.personCache.getCheckCache()}getUpdateCache(): Map<string, PersonUpdate | null> {- return this.personUpdateCache+ return this.personCache.getUpdateCache()}private getDistinctCacheKey(teamId: number, distinctId: string): string {return `${teamId}:${distinctId}`}- private getPersonIdCacheKey(teamId: number, personId: string): string {- return `${teamId}:${personId}`- }-clearPersonCacheForPersonId(teamId: number, personId: string): void {- this.personUpdateCache.delete(this.getPersonIdCacheKey(teamId, personId))+ this.personCache.clearPersonCacheForPersonId(teamId, personId)}clearAllCachesForPersonId(teamId: number, personId: string): void {- // Clear the person id cache- this.clearPersonCacheForPersonId(teamId, personId)-- // Find and clear all distinct ID mappings that point to this person id- const distinctIdsToRemove: string[] = []- for (const [distinctCacheKey, mappedPersonId] of this.distinctIdToPersonId.entries()) {- if (mappedPersonId === personId && distinctCacheKey.startsWith(`${teamId}:`)) {- distinctIdsToRemove.push(distinctCacheKey)- }- }-- // Remove all distinct ID mappings and their check cache entries- for (const distinctCacheKey of distinctIdsToRemove) {- this.distinctIdToPersonId.delete(distinctCacheKey)- this.personCheckCache.delete(distinctCacheKey)- }+ this.personCache.clearAllCachesForPersonId(teamId, personId)}removeDistinctIdFromCache(teamId: number, distinctId: string): void {- this.distinctIdToPersonId.delete(this.getDistinctCacheKey(teamId, distinctId))+ this.personCache.removeDistinctIdFromCache(teamId, distinctId)}clearAllCachesForDistinctId(teamId: number, distinctId: string): void {- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)- const personId = this.distinctIdToPersonId.get(cacheKey)-- // Clear the distinct ID mapping- this.distinctIdToPersonId.delete(cacheKey)-- // Clear the person data if we have the id- if (personId) {- this.clearPersonCacheForPersonId(teamId, personId)- }-- // Clear the check cache- this.personCheckCache.delete(cacheKey)- }-- private getCheckCachedPerson(teamId: number, distinctId: string): InternalPerson | null | undefined {- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)- const result = this.personCheckCache.get(cacheKey)- if (result !== undefined) {- this.cacheMetrics.checkCacheHits++- // Return a deep copy to prevent modifications from affecting the cached object- return result === null- ? null- : {- ...result,- properties: { ...result.properties },- created_at: result.created_at,- }- } else {- this.cacheMetrics.checkCacheMisses++- }- return result+ this.personCache.clearAllCachesForDistinctId(teamId, distinctId)}getCachedPersonForUpdateByPersonId(teamId: number, personId: string | undefined): PersonUpdate | null | undefined {- if (personId === undefined) {- this.cacheMetrics.updateCacheMisses++- return undefined- }-- const result = this.personUpdateCache.get(this.getPersonIdCacheKey(teamId, personId))- if (result !== undefined) {- this.cacheMetrics.updateCacheHits++- // Return a deep copy to prevent modifications from affecting the cached object- if (result === null) {- return null- }-- return {- ...result,- properties: { ...result.properties },- properties_to_set: { ...result.properties_to_set },- properties_to_unset: [...result.properties_to_unset],- }- } else {- this.cacheMetrics.updateCacheMisses++- return undefined- }+ return this.personCache.getCachedPersonForUpdateByPersonId(teamId, personId)}getCachedPersonForUpdateByDistinctId(teamId: number, distinctId: string): PersonUpdate | null | undefined {- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)- const personId = this.distinctIdToPersonId.get(cacheKey)-- return this.getCachedPersonForUpdateByPersonId(teamId, personId)+ return this.personCache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)}- setCachedPersonForUpdate(teamId: number, distinctId: string, person: PersonUpdate | null): void {- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)-- if (person === null) {- // Remove mappings when person is null- const existingPersonId = this.distinctIdToPersonId.get(cacheKey)- this.distinctIdToPersonId.delete(cacheKey)- if (existingPersonId) {- this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, existingPersonId), null)- }- return- }-- // Set the distinct ID -> person id mapping- this.distinctIdToPersonId.set(cacheKey, person.id)-- // Check if we already have cached data for this person id- const existingPersonUpdate = this.personUpdateCache.get(this.getPersonIdCacheKey(teamId, person.id))-- if (existingPersonUpdate) {- // Merge the properties and changesets from both updates- const mergedPersonUpdate = this.mergeUpdateIntoPersonUpdate(- existingPersonUpdate,- {- properties: person.properties,- is_identified: person.is_identified,- } as Partial<InternalPerson>,- false- )-- // Handle fields that are specific to PersonUpdate - merge properties_to_set and properties_to_unset- // with proper conflict resolution (last write wins)- mergedPersonUpdate.properties_to_set = {- ...existingPersonUpdate.properties_to_set,- ...person.properties_to_set,- }- // Remove from properties_to_set any keys that are in the incoming properties_to_unset- for (const key of person.properties_to_unset) {- delete mergedPersonUpdate.properties_to_set[key]- }-- mergedPersonUpdate.properties_to_unset = [- ...new Set([...existingPersonUpdate.properties_to_unset, ...person.properties_to_unset]),- ]- // Remove from properties_to_unset any keys that are in the incoming properties_to_set- const keysToSet = new Set(Object.keys(person.properties_to_set))- mergedPersonUpdate.properties_to_unset = mergedPersonUpdate.properties_to_unset.filter(- (key) => !keysToSet.has(key)- )-- mergedPersonUpdate.created_at = DateTime.min(existingPersonUpdate.created_at, person.created_at)- mergedPersonUpdate.needs_write = existingPersonUpdate.needs_write || person.needs_write-- // Handle force_update with || operator - once true, stays true- mergedPersonUpdate.force_update = existingPersonUpdate.force_update || person.force_update-- // Handle last_seen_at - take the newer timestamp (max)- if (person.last_seen_at) {- if (!mergedPersonUpdate.last_seen_at || person.last_seen_at > mergedPersonUpdate.last_seen_at) {- mergedPersonUpdate.last_seen_at = person.last_seen_at- }- }-- this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, person.id), mergedPersonUpdate)- } else {- // First time we're caching this person id- this.personUpdateCache.set(this.getPersonIdCacheKey(teamId, person.id), person)- }+ setCachedPersonForUpdate(teamId: number, distinctId: string, person: PersonUpdate | null, batchId?: number): void {+ this.personCache.obtainForBatchId(batchId ?? 0).setCachedPersonForUpdate(teamId, distinctId, person)}- setCheckCachedPerson(teamId: number, distinctId: string, person: InternalPerson | null): void {- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)- this.personCheckCache.set(cacheKey, person)+ setCheckCachedPerson(teamId: number, distinctId: string, person: InternalPerson | null, batchId?: number): void {+ this.personCache.obtainForBatchId(batchId ?? 0).setCheckCachedPerson(teamId, distinctId, person)}- setDistinctIdToPersonId(teamId: number, distinctId: string, personId: string): void {- const cacheKey = this.getDistinctCacheKey(teamId, distinctId)- this.distinctIdToPersonId.set(cacheKey, personId)+ setDistinctIdToPersonId(teamId: number, distinctId: string, personId: string, batchId?: number): void {+ this.personCache.obtainForBatchId(batchId ?? 0).setDistinctIdToPersonId(teamId, distinctId, personId)}async createPerson(@@ -1271,8 +1679,9 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreisIdentified: boolean,uuid: string,primaryDistinctId: { distinctId: string; version?: number },- extraDistinctIds?: { distinctId: string; version?: number }[],- tx?: PersonRepositoryTransaction+ extraDistinctIds: { distinctId: string; version?: number }[] | undefined,+ tx: PersonRepositoryTransaction | undefined,+ batchId: number): Promise<CreatePersonResult> {this.incrementCount('createPerson', primaryDistinctId.distinctId)this.incrementDatabaseOperation('createPerson', primaryDistinctId.distinctId)@@ -1291,18 +1700,20 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreif (result.success) {const { person } = result- this.setCheckCachedPerson(teamId, primaryDistinctId.distinctId, person)+ this.setCheckCachedPerson(teamId, primaryDistinctId.distinctId, person, batchId)this.setCachedPersonForUpdate(teamId,primaryDistinctId.distinctId,- fromInternalPerson(person, primaryDistinctId.distinctId)+ fromInternalPerson(person, primaryDistinctId.distinctId),+ batchId)for (const extraDistinctId of extraDistinctIds || []) {- this.setDistinctIdToPersonId(teamId, extraDistinctId.distinctId, person.id)+ this.setDistinctIdToPersonId(teamId, extraDistinctId.distinctId, person.id, batchId)this.setCachedPersonForUpdate(teamId,extraDistinctId.distinctId,- fromInternalPerson(person, extraDistinctId.distinctId)+ fromInternalPerson(person, extraDistinctId.distinctId),+ batchId)}}@@ -1313,9 +1724,11 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreprivate addPersonUpdateToBatch(person: InternalPerson,update: Partial<InternalPerson>,- distinctId: string+ distinctId: string,+ batchId: number): [InternalPerson, PersonMessage[], boolean] {- const existingUpdate = this.getCachedPersonForUpdateByDistinctId(person.team_id, distinctId)+ const cache = this.personCache.obtainForBatchId(batchId)+ const existingUpdate = cache.getCachedPersonForUpdateByDistinctId(person.team_id, distinctId)let personUpdate: PersonUpdateif (!existingUpdate) {@@ -1323,12 +1736,12 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorepersonUpdate = fromInternalPerson(person, distinctId)personUpdate = this.mergeUpdateIntoPersonUpdate(personUpdate, update, true)personUpdate.id = person.id- this.setCachedPersonForUpdate(person.team_id, distinctId, personUpdate)+ cache.setCachedPersonForUpdate(person.team_id, distinctId, personUpdate)} else {// Merge updates into existing cached PersonUpdatepersonUpdate = this.mergeUpdateIntoPersonUpdate(existingUpdate, update, true)personUpdate.id = person.id- this.setCachedPersonForUpdate(person.team_id, distinctId, personUpdate)+ cache.setCachedPersonForUpdate(person.team_id, distinctId, personUpdate)}// Return the merged person from the cachereturn [toInternalPerson(personUpdate), [], false]@@ -1394,9 +1807,11 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorepropertiesToUnset: string[],otherUpdates: Partial<InternalPerson>,distinctId: string,+ batchId: number,forceUpdate?: boolean): [InternalPerson, PersonMessage[]] {- const existingUpdate = this.getCachedPersonForUpdateByDistinctId(person.team_id, distinctId)+ const cache = this.personCache.obtainForBatchId(batchId)+ const existingUpdate = cache.getCachedPersonForUpdateByDistinctId(person.team_id, distinctId)let personUpdate: PersonUpdateif (!existingUpdate) {@@ -1446,7 +1861,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorepersonUpdate.force_update = personUpdate.force_update || forceUpdate}- this.setCachedPersonForUpdate(person.team_id, distinctId, personUpdate)+ cache.setCachedPersonForUpdate(person.team_id, distinctId, personUpdate)return [toInternalPerson(personUpdate), []]}@@ -1653,6 +2068,15 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorethrow new Error('Unexpected end of retry loop')}+ /**+ * Releases cache entries associated with the given batch ID, using reference+ * counting so entries shared across concurrent batches are only evicted when+ * all referencing batches have completed.+ */+ releaseBatch(batchId: number): void {+ this.personCache.releaseBatchId(batchId)+ }+/*** Refreshes the person ID for a given distinct ID by fetching from the database.* This handles cases where the person was merged and the ID changed.@@ -1673,7 +2097,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorethis.clearPersonCacheForPersonId(personUpdate.team_id, personUpdate.id)// Update our cache mapping to reflect the new person ID- this.setDistinctIdToPersonId(personUpdate.team_id, personUpdate.distinct_id, currentPerson.id)+ this.personCache.setDistinctIdToPersonId(personUpdate.team_id, personUpdate.distinct_id, currentPerson.id)// Create updated PersonUpdate with the new person ID and versionconst updatedPersonUpdate: PersonUpdate = {diff --git a/nodejs/src/worker/ingestion/persons/person-context.ts b/nodejs/src/worker/ingestion/persons/person-context.tsindex 66db7bb9c33c..4006bb5adfc5 100644--- a/nodejs/src/worker/ingestion/persons/person-context.ts+++ b/nodejs/src/worker/ingestion/persons/person-context.ts@@ -8,7 +8,7 @@ import { IngestionOutputs } from '../../../ingestion/outputs/ingestion-outputs'import { Team } from '../../../types'import { MergeMode } from './person-merge-types'import { PersonMessage } from './person-message'-import { PersonsStore } from './persons-store'+import { PersonsStoreForBatch } from './persons-store-for-batch'export type PersonOutputs = IngestionOutputs<PersonsOutput | PersonDistinctIdsOutput | IngestionWarningsOutput>@@ -27,7 +27,7 @@ export class PersonContext {public readonly timestamp: DateTime,public readonly processPerson: boolean, // $process_person_profile flag from the eventpublic readonly outputs: PersonOutputs,- public readonly personStore: PersonsStore,+ public readonly personStore: PersonsStoreForBatch,public readonly measurePersonJsonbSize: number = 0,public readonly mergeMode: MergeMode,public readonly updateAllProperties: boolean = false, // When true, all property changes trigger person updatesdiff --git a/nodejs/src/worker/ingestion/persons/person-create-service.test.ts b/nodejs/src/worker/ingestion/persons/person-create-service.test.tsindex 82f6a63e2303..9074918a37db 100644--- a/nodejs/src/worker/ingestion/persons/person-create-service.test.ts+++ b/nodejs/src/worker/ingestion/persons/person-create-service.test.ts@@ -51,7 +51,9 @@ describe('PersonCreateService', () => {mockOutputs,mockPersonStore,0,- createDefaultSyncMergeMode()+ createDefaultSyncMergeMode(),+ false,+ false)personCreateService = new PersonCreateService(personContext)diff --git a/nodejs/src/worker/ingestion/persons/person-create-service.ts b/nodejs/src/worker/ingestion/persons/person-create-service.tsindex e11d59c27ddf..e44681e3201d 100644--- a/nodejs/src/worker/ingestion/persons/person-create-service.ts+++ b/nodejs/src/worker/ingestion/persons/person-create-service.ts@@ -6,7 +6,7 @@ import { emitIngestionWarning } from '../../../ingestion/common/ingestion-warninimport { InternalPerson, PropertyUpdateOperation } from '../../../types'import { uuidFromDistinctId } from '../person-uuid'import { PersonContext } from './person-context'-import { PersonsStoreTransaction } from './persons-store-transaction'+import { PersonsStoreTransactionForBatch } from './persons-store-for-batch'import { PersonPropertiesSizeViolationError } from './repositories/person-repository'export class PersonCreateService {@@ -25,7 +25,7 @@ export class PersonCreateService {creatorEventUuid: string,primaryDistinctId: { distinctId: string; version?: number },extraDistinctIds?: { distinctId: string; version?: number }[],- tx?: PersonsStoreTransaction+ tx?: PersonsStoreTransactionForBatch): Promise<[InternalPerson, boolean]> {const uuid = uuidFromDistinctId(teamId, primaryDistinctId.distinctId)diff --git a/nodejs/src/worker/ingestion/persons/person-merge-service.ts b/nodejs/src/worker/ingestion/persons/person-merge-service.tsindex 84fe03fa0c09..4b9808e82b4a 100644--- a/nodejs/src/worker/ingestion/persons/person-merge-service.ts+++ b/nodejs/src/worker/ingestion/persons/person-merge-service.ts@@ -24,7 +24,7 @@ import {} from './person-merge-types'import { PersonMessage } from './person-message'import { applyEventPropertyUpdates, computeEventPropertyUpdates } from './person-update'-import { PersonsStoreTransaction } from './persons-store-transaction'+import { PersonsStoreTransactionForBatch } from './persons-store-for-batch'export const mergeFinalFailuresCounter = new Counter({name: 'person_merge_final_failure_total',@@ -547,7 +547,7 @@ export class PersonMergeService {}private async moveDistinctIdsBasedOnMode(- tx: PersonsStoreTransaction,+ tx: PersonsStoreTransactionForBatch,currentSourcePerson: InternalPerson,currentTargetPerson: InternalPerson): Promise<PersonMessage[]> {@@ -568,7 +568,7 @@ export class PersonMergeService {}private async moveDistinctIdsInBatches(- tx: PersonsStoreTransaction,+ tx: PersonsStoreTransactionForBatch,currentSourcePerson: InternalPerson,currentTargetPerson: InternalPerson,batchSize: number@@ -612,7 +612,7 @@ export class PersonMergeService {}private async moveDistinctIdsWithLimit(- tx: PersonsStoreTransaction,+ tx: PersonsStoreTransactionForBatch,currentSourcePerson: InternalPerson,currentTargetPerson: InternalPerson,limit: number | undefined@@ -736,7 +736,7 @@ export class PersonMergeService {person: InternalPerson,distinctId: string,version: number,- tx?: PersonsStoreTransaction+ tx?: PersonsStoreTransactionForBatch): Promise<void> {const kafkaMessages = await (tx || this.context.personStore).addDistinctId(person, distinctId, version)await this.context.produceMessages(kafkaMessages)diff --git a/nodejs/src/worker/ingestion/persons/persons-store-for-batch.ts b/nodejs/src/worker/ingestion/persons/persons-store-for-batch.tsnew file mode 100644index 000000000000..045f5e414a9d--- /dev/null+++ b/nodejs/src/worker/ingestion/persons/persons-store-for-batch.ts@@ -0,0 +1,392 @@+import { DateTime } from 'luxon'++import { Properties } from '~/plugin-scaffold'++import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '../../../types'+import { CreatePersonResult, MoveDistinctIdsResult } from '../../../utils/db/db'+import { PersonMessage } from './person-message'+import { FlushResult, PersonsStore } from './persons-store'+import { PersonsStoreTransaction } from './persons-store-transaction'+import { PersonRepositoryTransaction } from './repositories/person-repository-transaction'++export interface PersonsStoreTransactionForBatch {+ createPerson(+ createdAt: DateTime,+ properties: Properties,+ propertiesLastUpdatedAt: PropertiesLastUpdatedAt,+ propertiesLastOperation: PropertiesLastOperation,+ teamId: number,+ isUserId: number | null,+ isIdentified: boolean,+ uuid: string,+ primaryDistinctId: { distinctId: string; version?: number },+ extraDistinctIds?: { distinctId: string; version?: number }[]+ ): Promise<CreatePersonResult>++ updatePersonForMerge(+ person: InternalPerson,+ update: Partial<InternalPerson>,+ distinctId: string+ ): Promise<[InternalPerson, PersonMessage[], boolean]>++ updatePersonWithPropertiesDiffForUpdate(+ person: InternalPerson,+ propertiesToSet: Properties,+ propertiesToUnset: string[],+ otherUpdates: Partial<InternalPerson>,+ distinctId: string,+ forceUpdate?: boolean+ ): Promise<[InternalPerson, PersonMessage[], boolean]>++ deletePerson(person: InternalPerson, distinctId: string): Promise<PersonMessage[]>++ addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>++ moveDistinctIds(+ source: InternalPerson,+ target: InternalPerson,+ distinctId: string,+ limit?: number+ ): Promise<MoveDistinctIdsResult>++ updateCohortsAndFeatureFlagsForMerge(+ teamID: Team['id'],+ sourcePersonID: InternalPerson['id'],+ targetPersonID: InternalPerson['id'],+ distinctId: string+ ): Promise<void>++ addPersonlessDistinctIdForMerge(teamId: number, distinctId: string): Promise<boolean>++ fetchPersonDistinctIds(person: InternalPerson, distinctId: string, limit?: number): Promise<string[]>+}++/**+ * A view of PersonsStore with batchId bound at construction time.+ * Created once per batch in the BeforeBatch hook and flows into element values+ * via batchContext, eliminating batchId? from individual step method signatures.+ *+ * Excludes root lifecycle helpers that need the underlying singleton store directly,+ * but retains flush/shutdown so callers can flush buffered writes after processing.+ */+export type PersonsStoreForBatch = Omit<+ PersonsStore,+ | 'fetchForChecking'+ | 'fetchForUpdate'+ | 'createPerson'+ | 'updatePersonForMerge'+ | 'updatePersonWithPropertiesDiffForUpdate'+ | 'addDistinctId'+ | 'moveDistinctIds'+ | 'addPersonlessDistinctIdForMerge'+ | 'prefetchPersons'+ | 'processPersonlessDistinctIdsBatch'+ | 'releaseBatch'+ | 'getFlushStats'+ | 'inTransaction'+> & {+ fetchForChecking(teamId: number, distinctId: string): Promise<InternalPerson | null>+ fetchForUpdate(teamId: number, distinctId: string): Promise<InternalPerson | null>+ createPerson(+ createdAt: DateTime,+ properties: Properties,+ propertiesLastUpdatedAt: PropertiesLastUpdatedAt,+ propertiesLastOperation: PropertiesLastOperation,+ teamId: number,+ isUserId: number | null,+ isIdentified: boolean,+ uuid: string,+ primaryDistinctId: { distinctId: string; version?: number },+ extraDistinctIds?: { distinctId: string; version?: number }[]+ ): Promise<CreatePersonResult>+ updatePersonForMerge(+ person: InternalPerson,+ update: Partial<InternalPerson>,+ distinctId: string,+ tx?: PersonRepositoryTransaction+ ): Promise<[InternalPerson, PersonMessage[], boolean]>+ updatePersonWithPropertiesDiffForUpdate(+ person: InternalPerson,+ propertiesToSet: Properties,+ propertiesToUnset: string[],+ otherUpdates: Partial<InternalPerson>,+ distinctId: string,+ forceUpdate?: boolean,+ tx?: PersonRepositoryTransaction+ ): Promise<[InternalPerson, PersonMessage[], boolean]>+ addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>+ addPersonlessDistinctIdForMerge(+ teamId: number,+ distinctId: string,+ tx?: PersonRepositoryTransaction+ ): Promise<boolean>+ moveDistinctIds(+ source: InternalPerson,+ target: InternalPerson,+ distinctId: string,+ limit: number | undefined,+ tx: PersonRepositoryTransaction+ ): Promise<MoveDistinctIdsResult>+ prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void>+ processPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[]): Promise<void>+ inTransaction<T>(description: string, transaction: (tx: PersonsStoreTransactionForBatch) => Promise<T>): Promise<T>+ readonly batchId: number+}++class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactionForBatch {+ constructor(+ private readonly tx: PersonsStoreTransaction,+ private readonly batchId: number+ ) {}++ createPerson(+ createdAt: DateTime,+ properties: Properties,+ propertiesLastUpdatedAt: PropertiesLastUpdatedAt,+ propertiesLastOperation: PropertiesLastOperation,+ teamId: number,+ isUserId: number | null,+ isIdentified: boolean,+ uuid: string,+ primaryDistinctId: { distinctId: string; version?: number },+ extraDistinctIds?: { distinctId: string; version?: number }[]+ ): Promise<CreatePersonResult> {+ return this.tx.createPerson(+ createdAt,+ properties,+ propertiesLastUpdatedAt,+ propertiesLastOperation,+ teamId,+ isUserId,+ isIdentified,+ uuid,+ primaryDistinctId,+ extraDistinctIds,+ this.batchId+ )+ }++ updatePersonForMerge(+ person: InternalPerson,+ update: Partial<InternalPerson>,+ distinctId: string+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {+ return this.tx.updatePersonForMerge(person, update, distinctId, this.batchId)+ }++ updatePersonWithPropertiesDiffForUpdate(+ person: InternalPerson,+ propertiesToSet: Properties,+ propertiesToUnset: string[],+ otherUpdates: Partial<InternalPerson>,+ distinctId: string,+ forceUpdate?: boolean+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {+ return this.tx.updatePersonWithPropertiesDiffForUpdate(+ person,+ propertiesToSet,+ propertiesToUnset,+ otherUpdates,+ distinctId,+ this.batchId,+ forceUpdate+ )+ }++ deletePerson(person: InternalPerson, distinctId: string): Promise<PersonMessage[]> {+ return this.tx.deletePerson(person, distinctId)+ }++ addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {+ return this.tx.addDistinctId(person, distinctId, version, this.batchId)+ }++ moveDistinctIds(+ source: InternalPerson,+ target: InternalPerson,+ distinctId: string,+ limit?: number+ ): Promise<MoveDistinctIdsResult> {+ return this.tx.moveDistinctIds(source, target, distinctId, limit, this.batchId)+ }++ updateCohortsAndFeatureFlagsForMerge(+ teamID: Team['id'],+ sourcePersonID: InternalPerson['id'],+ targetPersonID: InternalPerson['id'],+ distinctId: string+ ): Promise<void> {+ return this.tx.updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID, distinctId)+ }++ addPersonlessDistinctIdForMerge(teamId: number, distinctId: string): Promise<boolean> {+ return this.tx.addPersonlessDistinctIdForMerge(teamId, distinctId, this.batchId)+ }++ fetchPersonDistinctIds(person: InternalPerson, distinctId: string, limit?: number): Promise<string[]> {+ return this.tx.fetchPersonDistinctIds(person, distinctId, limit)+ }+}++export class BatchBoundPersonsStore implements PersonsStoreForBatch {+ constructor(+ private readonly store: PersonsStore,+ public readonly batchId: number+ ) {}++ fetchForChecking(teamId: number, distinctId: string): Promise<InternalPerson | null> {+ return this.store.fetchForChecking(teamId, distinctId, this.batchId)+ }++ fetchForUpdate(teamId: number, distinctId: string): Promise<InternalPerson | null> {+ return this.store.fetchForUpdate(teamId, distinctId, this.batchId)+ }++ createPerson(+ createdAt: DateTime,+ properties: Properties,+ propertiesLastUpdatedAt: PropertiesLastUpdatedAt,+ propertiesLastOperation: PropertiesLastOperation,+ teamId: number,+ isUserId: number | null,+ isIdentified: boolean,+ uuid: string,+ primaryDistinctId: { distinctId: string; version?: number },+ extraDistinctIds?: { distinctId: string; version?: number }[]+ ): Promise<CreatePersonResult> {+ return this.store.createPerson(+ createdAt,+ properties,+ propertiesLastUpdatedAt,+ propertiesLastOperation,+ teamId,+ isUserId,+ isIdentified,+ uuid,+ primaryDistinctId,+ extraDistinctIds,+ undefined,+ this.batchId+ )+ }++ addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {+ return this.store.addDistinctId(person, distinctId, version, undefined, this.batchId)+ }++ moveDistinctIds(+ source: InternalPerson,+ target: InternalPerson,+ distinctId: string,+ limit: number | undefined,+ tx: PersonRepositoryTransaction+ ): Promise<MoveDistinctIdsResult> {+ return this.store.moveDistinctIds(source, target, distinctId, limit, tx, this.batchId)+ }++ prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {+ return this.store.prefetchPersons(teamDistinctIds)+ }++ processPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[]): Promise<void> {+ return this.store.processPersonlessDistinctIdsBatch(entries, this.batchId)+ }++ inTransaction<T>(+ description: string,+ transaction: (tx: PersonsStoreTransactionForBatch) => Promise<T>+ ): Promise<T> {+ return this.store.inTransaction(description, (tx) =>+ transaction(new BatchBoundPersonsStoreTransaction(tx, this.batchId))+ )+ }++ updatePersonForMerge(+ person: InternalPerson,+ update: Partial<InternalPerson>,+ distinctId: string,+ tx?: PersonRepositoryTransaction+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {+ return this.store.updatePersonForMerge(person, update, distinctId, this.batchId, tx)+ }++ updatePersonWithPropertiesDiffForUpdate(+ person: InternalPerson,+ propertiesToSet: Properties,+ propertiesToUnset: string[],+ otherUpdates: Partial<InternalPerson>,+ distinctId: string,+ forceUpdate?: boolean,+ tx?: PersonRepositoryTransaction+ ): Promise<[InternalPerson, PersonMessage[], boolean]> {+ return this.store.updatePersonWithPropertiesDiffForUpdate(+ person,+ propertiesToSet,+ propertiesToUnset,+ otherUpdates,+ distinctId,+ this.batchId,+ forceUpdate,+ tx+ )+ }++ deletePerson(+ person: InternalPerson,+ distinctId: string,+ tx?: PersonRepositoryTransaction+ ): Promise<PersonMessage[]> {+ return this.store.deletePerson(person, distinctId, tx)+ }++ updateCohortsAndFeatureFlagsForMerge(+ teamID: Team['id'],+ sourcePersonID: InternalPerson['id'],+ targetPersonID: InternalPerson['id'],+ distinctId: string,+ tx?: PersonRepositoryTransaction+ ): Promise<void> {+ return this.store.updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID, distinctId, tx)+ }++ addPersonlessDistinctId(teamId: number, distinctId: string): Promise<boolean> {+ return this.store.addPersonlessDistinctId(teamId, distinctId)+ }++ addPersonlessDistinctIdForMerge(+ teamId: number,+ distinctId: string,+ tx?: PersonRepositoryTransaction+ ): Promise<boolean> {+ return this.store.addPersonlessDistinctIdForMerge(teamId, distinctId, tx, this.batchId)+ }++ personPropertiesSize(personId: string, teamId: number): Promise<number> {+ return this.store.personPropertiesSize(personId, teamId)+ }++ fetchPersonDistinctIds(+ person: InternalPerson,+ distinctId: string,+ limit: number | undefined,+ tx: PersonRepositoryTransaction+ ): Promise<string[]> {+ return this.store.fetchPersonDistinctIds(person, distinctId, limit, tx)+ }++ removeDistinctIdFromCache(teamId: number, distinctId: string): void {+ return this.store.removeDistinctIdFromCache(teamId, distinctId)+ }++ getPersonlessBatchResult(teamId: number, distinctId: string): boolean | undefined {+ return this.store.getPersonlessBatchResult(teamId, distinctId)+ }++ flush(): Promise<FlushResult[]> {+ return this.store.flush()+ }++ shutdown(): Promise<void> {+ return this.store.shutdown()+ }+}diff --git a/nodejs/src/worker/ingestion/persons/persons-store-transaction.ts b/nodejs/src/worker/ingestion/persons/persons-store-transaction.tsindex 3be3f5e11695..4dee1d39da00 100644--- a/nodejs/src/worker/ingestion/persons/persons-store-transaction.ts+++ b/nodejs/src/worker/ingestion/persons/persons-store-transaction.ts@@ -28,7 +28,8 @@ export class PersonsStoreTransaction {isIdentified: boolean,uuid: string,primaryDistinctId: { distinctId: string; version?: number },- extraDistinctIds?: { distinctId: string; version?: number }[]+ extraDistinctIds: { distinctId: string; version?: number }[] | undefined,+ batchId: number): Promise<CreatePersonResult> {return await this.store.createPerson(createdAt,@@ -41,16 +42,18 @@ export class PersonsStoreTransaction {uuid,primaryDistinctId,extraDistinctIds,- this.tx+ this.tx,+ batchId)}async updatePersonForMerge(person: InternalPerson,update: Partial<InternalPerson>,- distinctId: string+ distinctId: string,+ batchId: number): Promise<[InternalPerson, PersonMessage[], boolean]> {- return await this.store.updatePersonForMerge(person, update, distinctId, this.tx)+ return await this.store.updatePersonForMerge(person, update, distinctId, batchId, this.tx)}async updatePersonWithPropertiesDiffForUpdate(@@ -59,6 +62,7 @@ export class PersonsStoreTransaction {propertiesToUnset: string[],otherUpdates: Partial<InternalPerson>,distinctId: string,+ batchId: number,forceUpdate?: boolean): Promise<[InternalPerson, PersonMessage[], boolean]> {return await this.store.updatePersonWithPropertiesDiffForUpdate(@@ -67,6 +71,7 @@ export class PersonsStoreTransaction {propertiesToUnset,otherUpdates,distinctId,+ batchId,forceUpdate,this.tx)@@ -76,17 +81,23 @@ export class PersonsStoreTransaction {return await this.store.deletePerson(person, distinctId, this.tx)}- async addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {- return await this.store.addDistinctId(person, distinctId, version, this.tx)+ async addDistinctId(+ person: InternalPerson,+ distinctId: string,+ version: number,+ batchId: number+ ): Promise<PersonMessage[]> {+ return await this.store.addDistinctId(person, distinctId, version, this.tx, batchId)}async moveDistinctIds(source: InternalPerson,target: InternalPerson,distinctId: string,- limit?: number+ limit: number | undefined,+ batchId: number): Promise<MoveDistinctIdsResult> {- return await this.store.moveDistinctIds(source, target, distinctId, limit, this.tx)+ return await this.store.moveDistinctIds(source, target, distinctId, limit, this.tx, batchId)}async updateCohortsAndFeatureFlagsForMerge(@@ -104,8 +115,8 @@ export class PersonsStoreTransaction {)}- async addPersonlessDistinctIdForMerge(teamId: number, distinctId: string): Promise<boolean> {- return await this.store.addPersonlessDistinctIdForMerge(teamId, distinctId, this.tx)+ async addPersonlessDistinctIdForMerge(teamId: number, distinctId: string, batchId: number): Promise<boolean> {+ return await this.store.addPersonlessDistinctIdForMerge(teamId, distinctId, this.tx, batchId)}async fetchPersonDistinctIds(person: InternalPerson, distinctId: string, limit?: number): Promise<string[]> {diff --git a/nodejs/src/worker/ingestion/persons/persons-store.ts b/nodejs/src/worker/ingestion/persons/persons-store.tsindex cb6d2bad0add..fa166733add9 100644--- a/nodejs/src/worker/ingestion/persons/persons-store.ts+++ b/nodejs/src/worker/ingestion/persons/persons-store.ts@@ -28,13 +28,13 @@ export interface PersonsStore extends BatchWritingStore {* Fetches a person by team ID and distinct ID for checking existence* Uses read replica when available*/- fetchForChecking(teamId: number, distinctId: string): Promise<InternalPerson | null>+ fetchForChecking(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null>/*** Fetches a person by team ID and distinct ID with a row-level lock* Always uses primary database*/- fetchForUpdate(teamId: number, distinctId: string): Promise<InternalPerson | null>+ fetchForUpdate(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null>/*** Creates a new person@@ -49,8 +49,9 @@ export interface PersonsStore extends BatchWritingStore {isIdentified: boolean,uuid: string,primaryDistinctId: { distinctId: string; version?: number },- extraDistinctIds?: { distinctId: string; version?: number }[],- tx?: PersonRepositoryTransaction+ extraDistinctIds: { distinctId: string; version?: number }[] | undefined,+ tx: PersonRepositoryTransaction | undefined,+ batchId: number): Promise<CreatePersonResult>/**@@ -60,6 +61,7 @@ export interface PersonsStore extends BatchWritingStore {person: InternalPerson,update: Partial<InternalPerson>,distinctId: string,+ batchId: number,tx?: PersonRepositoryTransaction): Promise<[InternalPerson, PersonMessage[], boolean]>@@ -72,6 +74,7 @@ export interface PersonsStore extends BatchWritingStore {propertiesToUnset: string[],otherUpdates: Partial<InternalPerson>,distinctId: string,+ batchId: number,forceUpdate?: boolean,tx?: PersonRepositoryTransaction): Promise<[InternalPerson, PersonMessage[], boolean]>@@ -88,7 +91,8 @@ export interface PersonsStore extends BatchWritingStore {person: InternalPerson,distinctId: string,version: number,- tx?: PersonRepositoryTransaction+ tx: PersonRepositoryTransaction | undefined,+ batchId: number): Promise<PersonMessage[]>/**@@ -99,7 +103,8 @@ export interface PersonsStore extends BatchWritingStore {target: InternalPerson,distinctId: string,limit: number | undefined,- tx: PersonRepositoryTransaction+ tx: PersonRepositoryTransaction,+ batchId: number): Promise<MoveDistinctIdsResult>/**@@ -124,7 +129,8 @@ export interface PersonsStore extends BatchWritingStore {addPersonlessDistinctIdForMerge(teamId: number,distinctId: string,- tx?: PersonRepositoryTransaction+ tx: PersonRepositoryTransaction | undefined,+ batchId: number): Promise<boolean>/**@@ -143,15 +149,11 @@ export interface PersonsStore extends BatchWritingStore {): Promise<string[]>/**- * Reports metrics about person operations in batch- */- reportBatch(): void-- /**- * Resets the batch store state, clearing all caches and metrics.- * Should be called after flush() to prepare for the next batch.+ * Stop any background work (e.g., periodic metric emission) and flush+ * remaining accumulated metrics. Called on graceful shutdown. Does NOT+ * clear data caches.*/- reset(): void+ shutdown(): Promise<void>/*** Removes a distinct ID from the cache@@ -159,17 +161,20 @@ export interface PersonsStore extends BatchWritingStore {removeDistinctIdFromCache(teamId: number, distinctId: string): void/**- * Prefetches persons by team ID and distinct ID to warm up the cache+ * Prefetches persons by team ID and distinct ID to warm up the cache.+ * Each entry may carry its own batchId for cache eviction tracking, allowing a+ * single DB fetch to service entries that belong to different concurrent batches.* @param teamDistinctIds - A list of team IDs and distinct IDs to prefetch*/- prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string }[]): Promise<void>+ prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void>/*** Batch-inserts personless distinct IDs for events where no person exists.* Stores is_merged results in a cache for later lookup.* @param entries - A list of team IDs and distinct IDs to insert+ * @param batchId - Batch ID for cache eviction tracking*/- processPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[]): Promise<void>+ processPersonlessDistinctIdsBatch(entries: { teamId: number; distinctId: string }[], batchId: number): Promise<void>/*** Gets the is_merged result from batch personless insert.@@ -181,4 +186,11 @@ export interface PersonsStore extends BatchWritingStore {* Flushes the batch*/flush(): Promise<FlushResult[]>++ /**+ * Releases cache entries associated with the given batch ID, using reference+ * counting so entries shared across concurrent batches are only evicted when+ * all referencing batches have completed.+ */+ releaseBatch(batchId: number): void}diff --git a/nodejs/src/worker/ingestion/stores/batch-writing-store.ts b/nodejs/src/worker/ingestion/stores/batch-writing-store.tsindex fd16feb35ec5..c144610b65f7 100644--- a/nodejs/src/worker/ingestion/stores/batch-writing-store.ts+++ b/nodejs/src/worker/ingestion/stores/batch-writing-store.ts@@ -1,9 +1,33 @@import { FlushResult } from '../persons/persons-store'+export interface BatchWritingStoreFlushStats {+ dirtyEntryCount: number+ referencedBatchCount: number+ cacheEntryCount: number+}+export interface BatchWritingStore {+ /*+ * Returns a point-in-time summary of entries that would be captured by+ * flush(), plus the batch IDs that currently reference those dirty entries.+ */+ getFlushStats(): BatchWritingStoreFlushStats+/** Flushes all batch data that needs to be written* Returns Kafka messages that need to be sent*/flush(): Promise<FlushResult[]>++ /*+ * Releases cache entries associated with the given batch ID.+ * Uses reference counting so entries shared across concurrent batches+ * are only evicted when all referencing batches have completed.+ */+ releaseBatch(batchId: number): void++ /*+ * Stops background work and flushes remaining metrics. Called on graceful shutdown.+ */+ shutdown(): Promise<void>}diff --git a/nodejs/src/worker/ingestion/stores/metrics.ts b/nodejs/src/worker/ingestion/stores/metrics.tsnew file mode 100644index 000000000000..1932a1d8834e--- /dev/null+++ b/nodejs/src/worker/ingestion/stores/metrics.ts@@ -0,0 +1,58 @@+import { Counter, Histogram, exponentialBuckets } from 'prom-client'++const STORE_LABELS = ['store'] as const+const STORE_OUTCOME_LABELS = ['store', 'outcome'] as const++export const batchStoreFlushOperationsCounter = new Counter({+ name: 'batch_store_flush_operations_total',+ help: 'Total number of batch store flush operations by store and outcome',+ labelNames: STORE_OUTCOME_LABELS,+})++export const batchStoreFlushLatencyHistogram = new Histogram({+ name: 'batch_store_flush_latency_seconds',+ help: 'Latency of batch store flush operations',+ labelNames: STORE_OUTCOME_LABELS,+ buckets: exponentialBuckets(0.001, 2, 12),+})++export const batchStoreFlushTriggerBatchSizeHistogram = new Histogram({+ name: 'batch_store_flush_trigger_batch_size',+ help: 'Number of pipeline results in the completed batch that triggered a batch store flush',+ buckets: [0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000],+})++export const batchStoreFlushDirtyEntriesHistogram = new Histogram({+ name: 'batch_store_flush_dirty_entries',+ help: 'Number of dirty cache entries captured at batch store flush start',+ labelNames: STORE_LABELS,+ buckets: [0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000],+})++export const batchStoreFlushReferencedBatchesHistogram = new Histogram({+ name: 'batch_store_flush_referenced_batches',+ help: 'Number of batch IDs that reference dirty cache entries at batch store flush start',+ labelNames: STORE_LABELS,+ buckets: [0, 1, 2, 3, 4, 5, 10, 20, 50, 100],+})++export const batchStoreFlushCacheEntriesHistogram = new Histogram({+ name: 'batch_store_flush_cache_entries',+ help: 'Number of cache entries present at batch store flush start',+ labelNames: STORE_LABELS,+ buckets: [0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000],+})++export const batchStoreFlushResultRecordsHistogram = new Histogram({+ name: 'batch_store_flush_result_records',+ help: 'Number of flush result records returned by a batch store flush',+ labelNames: STORE_LABELS,+ buckets: [0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000],+})++export const batchStoreFlushKafkaMessagesHistogram = new Histogram({+ name: 'batch_store_flush_kafka_messages',+ help: 'Number of Kafka messages returned by a batch store flush for side-effect production',+ labelNames: STORE_LABELS,+ buckets: [0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000],+})diff --git a/nodejs/tests/worker/ingestion/event-pipeline/prefetchPersonsStep.test.ts b/nodejs/tests/worker/ingestion/event-pipeline/prefetchPersonsStep.test.tsindex 11d99d36d4fe..83c1f279cba8 100644--- a/nodejs/tests/worker/ingestion/event-pipeline/prefetchPersonsStep.test.ts+++ b/nodejs/tests/worker/ingestion/event-pipeline/prefetchPersonsStep.test.ts@@ -2,18 +2,18 @@ import { PipelineResultType } from '~/ingestion/pipelines/results'import { Team } from '~/types'import { prefetchPersonsStep } from '../../../../src/worker/ingestion/event-pipeline/prefetchPersonsStep'-import { PersonsStore } from '../../../../src/worker/ingestion/persons/persons-store'+import { PersonsStoreForBatch } from '../../../../src/worker/ingestion/persons/persons-store-for-batch'import { createTestPluginEvent } from '../../../helpers/plugin-event'import { createTestTeam } from '../../../helpers/team'describe('prefetchPersonsStep', () => {- let mockPersonsStore: jest.Mocked<PersonsStore>+ let mockPersonsStore: jest.Mocked<PersonsStoreForBatch>let team: Team- function createMockPersonsStore(): jest.Mocked<PersonsStore> {+ function createMockPersonsStore(): jest.Mocked<PersonsStoreForBatch> {return {prefetchPersons: jest.fn().mockResolvedValue(undefined),- } as unknown as jest.Mocked<PersonsStore>+ } as unknown as jest.Mocked<PersonsStoreForBatch>}beforeEach(() => {@@ -27,11 +27,12 @@ describe('prefetchPersonsStep', () => {team_id: (overrides.team ?? team).id,}),team: overrides.team ?? team,+ personsStoreForBatch: mockPersonsStore,})describe('when enabled', () => {it('should prefetch persons for all events', async () => {- const step = prefetchPersonsStep(mockPersonsStore, true)+ const step = prefetchPersonsStep(true)const events = [createInput('user-1'), createInput('user-2'), createInput('user-3')]const results = await step(events)@@ -46,7 +47,7 @@ describe('prefetchPersonsStep', () => {})it('should not call prefetch for empty batch', async () => {- const step = prefetchPersonsStep(mockPersonsStore, true)+ const step = prefetchPersonsStep(true)const results = await step([])@@ -55,7 +56,7 @@ describe('prefetchPersonsStep', () => {})it('should call prefetch once for all events', async () => {- const step = prefetchPersonsStep(mockPersonsStore, true)+ const step = prefetchPersonsStep(true)const events = [createInput('user-1'), createInput('user-2')]await step(events)@@ -66,7 +67,7 @@ describe('prefetchPersonsStep', () => {describe('when disabled', () => {it('should not prefetch and return all events as OK', async () => {- const step = prefetchPersonsStep(mockPersonsStore, false)+ const step = prefetchPersonsStep(false)const events = [createInput('user-1'), createInput('user-2')]const results = await step(events)diff --git a/nodejs/tests/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.test.ts b/nodejs/tests/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.test.tsindex 9ec60f594a67..685f9e782cdb 100644--- a/nodejs/tests/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.test.ts+++ b/nodejs/tests/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep.test.ts@@ -2,12 +2,12 @@ import { PipelineResultType } from '~/ingestion/pipelines/results'import { PluginEvent } from '~/plugin-scaffold'import { Team } from '~/types'-import { PersonsStore } from '../../../../src/worker/ingestion/persons/persons-store'+import { PersonsStoreForBatch } from '../../../../src/worker/ingestion/persons/persons-store-for-batch'import { createTestPluginEvent } from '../../../helpers/plugin-event'import { createTestTeam } from '../../../helpers/team'describe('processPersonlessDistinctIdsBatchStep', () => {- let mockPersonsStore: jest.Mocked<PersonsStore>+ let mockPersonsStore: jest.Mocked<PersonsStoreForBatch>let team: Teamlet processPersonlessDistinctIdsBatchStep: typeof import('../../../../src/worker/ingestion/event-pipeline/processPersonlessDistinctIdsBatchStep').processPersonlessDistinctIdsBatchStep@@ -24,13 +24,13 @@ describe('processPersonlessDistinctIdsBatchStep', () => {mockPersonsStore = {processPersonlessDistinctIdsBatch: jest.fn().mockResolvedValue(undefined),getPersonlessBatchResult: jest.fn().mockReturnValue(undefined),- } as unknown as jest.Mocked<PersonsStore>+ } as unknown as jest.Mocked<PersonsStoreForBatch>})const createInput = (distinctId: string,processPerson: boolean | undefined = undefined- ): { event: PluginEvent; team: Team } => ({+ ): { event: PluginEvent; team: Team; personsStoreForBatch: PersonsStoreForBatch } => ({event: createTestPluginEvent({distinct_id: distinctId,team_id: team.id,@@ -38,11 +38,12 @@ describe('processPersonlessDistinctIdsBatchStep', () => {uuid: `uuid-${distinctId}`,}),team,+ personsStoreForBatch: mockPersonsStore,})describe('when enabled', () => {it('should process personless events and call batch insert', async () => {- const step = processPersonlessDistinctIdsBatchStep(mockPersonsStore, true)+ const step = processPersonlessDistinctIdsBatchStep(true)const events = [createInput('user-1', false), createInput('user-2', false), createInput('user-3', false)]const results = await step(events)@@ -57,7 +58,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should skip non-personless events', async () => {- const step = processPersonlessDistinctIdsBatchStep(mockPersonsStore, true)+ const step = processPersonlessDistinctIdsBatchStep(true)const events = [createInput('user-1', true), // processPerson=truecreateInput('user-2', false), // processPerson=false (personless)@@ -73,7 +74,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should not call batch insert when no personless events', async () => {- const step = processPersonlessDistinctIdsBatchStep(mockPersonsStore, true)+ const step = processPersonlessDistinctIdsBatchStep(true)const events = [createInput('user-1', true), createInput('user-2')]const results = await step(events)@@ -85,7 +86,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {it('should return all events as OK even if batch insert fails', async () => {mockPersonsStore.processPersonlessDistinctIdsBatch.mockRejectedValue(new Error('DB error'))- const step = processPersonlessDistinctIdsBatchStep(mockPersonsStore, true)+ const step = processPersonlessDistinctIdsBatchStep(true)const events = [createInput('user-1', false)]// The step should throw since we don't handle errors gracefully@@ -95,7 +96,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {describe('when disabled', () => {it('should not process any events', async () => {- const step = processPersonlessDistinctIdsBatchStep(mockPersonsStore, false)+ const step = processPersonlessDistinctIdsBatchStep(false)const events = [createInput('user-1', false), createInput('user-2', false)]const results = await step(events)@@ -108,7 +109,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {describe('LRU cache behavior', () => {it('should deduplicate entries within same batch before hitting cache', async () => {- const step = processPersonlessDistinctIdsBatchStep(mockPersonsStore, true)+ const step = processPersonlessDistinctIdsBatchStep(true)const events = [createInput('user-1', false),createInput('user-1', false), // Duplicate - deduped before cache/insert@@ -125,7 +126,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should use cache to skip already-inserted distinct IDs across batches', async () => {- const step = processPersonlessDistinctIdsBatchStep(mockPersonsStore, true)+ const step = processPersonlessDistinctIdsBatchStep(true)// First batchawait step([createInput('user-1', false)])diff --git a/nodejs/tests/worker/ingestion/person-state-batch.test.ts b/nodejs/tests/worker/ingestion/person-state-batch.test.tsindex 18fad705141c..bb26c3131c8f 100644--- a/nodejs/tests/worker/ingestion/person-state-batch.test.ts+++ b/nodejs/tests/worker/ingestion/person-state-batch.test.ts@@ -13,7 +13,7 @@ import { PluginEvent, Properties } from '~/plugin-scaffold'import { Clickhouse } from '~/tests/helpers/clickhouse'import { ensureKafkaTopics } from '~/tests/helpers/kafka'import { fromInternalPerson } from '~/worker/ingestion/persons/person-update-batch'-import { PersonsStore } from '~/worker/ingestion/persons/persons-store'+import { BatchBoundPersonsStore, PersonsStoreForBatch } from '~/worker/ingestion/persons/persons-store-for-batch'import {ClickHousePerson,@@ -77,17 +77,6 @@ function createPersonOutputs(kafkaProducer: KafkaProducerWrapper): PersonOutputs})}-function createIngestionWarningsOutputs(kafkaProducer: KafkaProducerWrapper) {- return new IngestionOutputs({- [INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(- INGESTION_WARNINGS_OUTPUT,- KAFKA_INGESTION_WARNINGS,- kafkaProducer,- 'test'- ),- })-}-async function createPerson(hub: Hub,createdAt: DateTime,@@ -124,7 +113,7 @@ async function createPerson(async function flushPersonStoreToKafka(kafkaProducer: KafkaProducerWrapper,- personStore: PersonsStore,+ personStore: PersonsStoreForBatch,kafkaAcks: Promise<void>) {const kafkaMessages = await personStore.flush()@@ -229,10 +218,7 @@ describe('PersonState.processEvent()', () => {...event,}- const personsStore = new BatchWritingPersonsStore(- personRepository,- createIngestionWarningsOutputs(kafkaProducer)- )+ const personsStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))const context = new PersonContext(fullEvent as any,@@ -241,9 +227,11 @@ describe('PersonState.processEvent()', () => {timestampParam,processPerson,createPersonOutputs(kafkaProducer),- personsStore,+ new BatchBoundPersonsStore(personsStore, 0),0,- createDefaultSyncMergeMode()+ createDefaultSyncMergeMode(),+ false,+ false)const processor = new PersonEventProcessor(context,@@ -267,10 +255,7 @@ describe('PersonState.processEvent()', () => {...event,}- const personsStore = new BatchWritingPersonsStore(- personRepository,- createIngestionWarningsOutputs(kafkaProducer)- )+ const personsStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))const context = new PersonContext(fullEvent as PluginEvent,@@ -279,9 +264,11 @@ describe('PersonState.processEvent()', () => {timestampParam,processPerson,createPersonOutputs(kafkaProducer),- personsStore,+ new BatchBoundPersonsStore(personsStore, 0),0,- createDefaultSyncMergeMode()+ createDefaultSyncMergeMode(),+ false,+ false)context.updateIsIdentified = updateIsIdentifiedreturn new PersonPropertyService(context)@@ -294,7 +281,8 @@ describe('PersonState.processEvent()', () => {processPerson = true,timestampParam = timestamp,team = mainTeam,- mergeMode = createDefaultSyncMergeMode()+ mergeMode = createDefaultSyncMergeMode(),+ customPersonsStore?: BatchWritingPersonsStore) {const fullEvent = {team_id: teamId,@@ -302,10 +290,13 @@ describe('PersonState.processEvent()', () => {...event,}- const personsStore = new BatchWritingPersonsStore(- customPersonRepository ?? (customHub ? new PostgresPersonRepository(customHub.postgres) : personRepository),- createIngestionWarningsOutputs(kafkaProducer)- )+ const personsStore =+ customPersonsStore ??+ new BatchWritingPersonsStore(+ customPersonRepository ??+ (customHub ? new PostgresPersonRepository(customHub.postgres) : personRepository),+ createPersonOutputs(kafkaProducer)+ )const context = new PersonContext(fullEvent as any,@@ -314,9 +305,11 @@ describe('PersonState.processEvent()', () => {timestampParam,processPerson,createPersonOutputs(kafkaProducer),- personsStore,+ new BatchBoundPersonsStore(personsStore, 0),0,- mergeMode+ mergeMode,+ false,+ false)return new PersonMergeService(context)}@@ -1365,7 +1358,7 @@ describe('PersonState.processEvent()', () => {const sharedPersonsStore = new BatchWritingPersonsStore(personRepository,- createIngestionWarningsOutputs(kafkaProducer)+ createPersonOutputs(kafkaProducer))const createProcessorWithSharedStore = (event: Partial<PluginEvent>, distinctId: string) => {@@ -1381,9 +1374,11 @@ describe('PersonState.processEvent()', () => {timestamp,true,createPersonOutputs(kafkaProducer),- sharedPersonsStore,+ new BatchBoundPersonsStore(sharedPersonsStore, 0),0,- createDefaultSyncMergeMode()+ createDefaultSyncMergeMode(),+ false,+ false)return new PersonEventProcessor(context,@@ -1536,7 +1531,7 @@ describe('PersonState.processEvent()', () => {const sharedPersonsStore = new BatchWritingPersonsStore(personRepository,- createIngestionWarningsOutputs(kafkaProducer)+ createPersonOutputs(kafkaProducer))// Helper to create processor with shared store@@ -1553,9 +1548,11 @@ describe('PersonState.processEvent()', () => {timestamp,true,createPersonOutputs(kafkaProducer),- sharedPersonsStore,+ new BatchBoundPersonsStore(sharedPersonsStore, 0),0,- createDefaultSyncMergeMode()+ createDefaultSyncMergeMode(),+ false,+ false)return new PersonEventProcessor(context,@@ -1647,7 +1644,7 @@ describe('PersonState.processEvent()', () => {const sharedPersonsStore = new BatchWritingPersonsStore(personRepository,- createIngestionWarningsOutputs(kafkaProducer)+ createPersonOutputs(kafkaProducer))// Helper to create processor with shared store@@ -1664,9 +1661,11 @@ describe('PersonState.processEvent()', () => {timestamp,true,createPersonOutputs(kafkaProducer),- sharedPersonsStore,+ new BatchBoundPersonsStore(sharedPersonsStore, 0),0,- createDefaultSyncMergeMode()+ createDefaultSyncMergeMode(),+ false,+ false)return new PersonEventProcessor(context,@@ -3415,16 +3414,20 @@ describe('PersonState.processEvent()', () => {})// Create a merge service with batch writing store for a $merge_dangerously event+ const batchStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))const mergeService: PersonMergeService = personMergeService({event: '$merge_dangerously',distinct_id: secondUserDistinctId,},- hub+ hub,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ batchStore)- const context = mergeService.getContext()-- const batchStore = context.personStore as BatchWritingPersonsStorebatchStore.setCachedPersonForUpdate(teamId,@@ -3463,7 +3466,7 @@ describe('PersonState.processEvent()', () => {})}// Second call succeeds - call the original method- return originalMoveDistinctIds(source, target, distinctId, limit, tx)+ return originalMoveDistinctIds(source, target, distinctId, limit, tx, 0)})// Attempt to merge persons - this should trigger the retry logic@@ -4313,7 +4316,7 @@ describe('PersonState.processEvent()', () => {const personsStore = new BatchWritingPersonsStore(personRepository,- createIngestionWarningsOutputs(kafkaProducer)+ createPersonOutputs(kafkaProducer))const context = new PersonContext(@@ -4323,7 +4326,7 @@ describe('PersonState.processEvent()', () => {timestamp,true, // processPersoncreatePersonOutputs(kafkaProducer),- personsStore,+ new BatchBoundPersonsStore(personsStore, 0),0,mergeMode)