From 3a8b3a4be39f6c59c571537cf042fb53e541eabe Mon Sep 17 00:00:00 2001 From: doswalt Date: Tue, 27 Oct 2026 11:52:52 -0400 Subject: [PATCH 1/2] no need to clone before setting items in cache. --- .../backend/src/api/services/CacheService.ts | 6 + .../test/unit/services/CacheService.test.ts | 84 ++++++++++++++ .../ExperimentAssignmentService.test.ts | 108 ++++++++++++++++++ .../unit/services/FeatureFlagService.test.ts | 35 ++++++ 4 files changed, 233 insertions(+) diff --git a/packages/backend/src/api/services/CacheService.ts b/packages/backend/src/api/services/CacheService.ts index a54f084ab..167525900 100644 --- a/packages/backend/src/api/services/CacheService.ts +++ b/packages/backend/src/api/services/CacheService.ts @@ -74,6 +74,12 @@ export class CacheService { this.cache = await caching('memory', { max: env.caching?.maxKeys || 500, ttl: this.defaultTtl * 1000, + // By default, a clone of the value is made before being set + // The danger of setting this to false is that code reading the cached value might inadvertently mutate it, affecting other consumers of the same cached object. + // The benefit of setting this to false is avoiding the overhead of deep cloning, which can improve performance, especially for large objects. + // We can pretty safely mitigate the risk with unit-tests that will scream if any cached value is mutated unexpectedly, which we shouldn't ever have a need to do on purpose. + // So we can set this to false to avoid useless constant blocking when cloning cached values. + shouldCloneBeforeSet: false, // A background refresh has no caller to return a rejection to. Without this hook // cache-manager rethrows from inside its own catch, which surfaces as an unhandled // rejection instead of a log line; the stale-but-served value is unaffected either way. diff --git a/packages/backend/test/unit/services/CacheService.test.ts b/packages/backend/test/unit/services/CacheService.test.ts index 1983ae549..865c74022 100644 --- a/packages/backend/test/unit/services/CacheService.test.ts +++ b/packages/backend/test/unit/services/CacheService.test.ts @@ -517,6 +517,90 @@ describe('CacheService', () => { }); }); + // The memory store is created with `shouldCloneBeforeSet: false`. By default it deep-clones every value it + // stores, synchronously: on a miss the loading request waits on that clone, and when a background refresh + // lands it blocks whatever is running on the event loop. These tests pin down what turning that off means: + // the store keeps the exact object the loader produced, so every caller — the loading one included — gets + // that same object, with no hidden copy anywhere. + describe('stores loaded values without copying them (real memory store)', () => { + const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + const key = CACHE_PREFIX.EXPERIMENT_KEY_PREFIX + 'nocopy'; + + beforeEach(() => { + mockedEnv.caching.enabled = true; + }); + + afterEach(() => { + mockedEnv.caching.enabled = false; + mockedEnv.caching.ttl = 60; + mockedEnv.caching.ttlExperiments = 30; + mockedEnv.caching.refreshThreshold = 0; + }); + + // Not new behavior: reads never copied. Every hit has always handed out the one stored object, which is + // why cached values must be treated as read-only by every caller (see + // ExperimentService.getCachedValidExperiments). Skipping the copy on store extends that same contract to + // the loading request; it doesn't create a new one. + it('has always given every cache hit the same stored object', async () => { + const realService = new CacheService(); + await realService.wrap(key, async () => ({ experiments: [{ id: 'exp-1' }] })); + + const firstHit = await realService.wrap(key, jest.fn()); + const secondHit = await realService.wrap(key, jest.fn()); + + expect(secondHit).toBe(firstHit); + }); + + it('stores the loaded object itself on a miss, so the loading request and later hits share it', async () => { + const loaded = { experiments: [{ id: 'exp-1', conditions: [{ id: 'cond-1' }] }] }; + const realService = new CacheService(); + + const missResult = await realService.wrap(key, async () => loaded); + const hitResult = await realService.wrap(key, jest.fn()); + + expect(missResult).toBe(loaded); + expect(hitResult).toBe(loaded); + }); + + it('stores the refreshed object itself when a background refresh lands', async () => { + // Same timing as 'background refresh against the real memory store': due for refresh at ~250ms, + // hard expiry no earlier than ~1937ms. + mockedEnv.caching.ttl = 2; + mockedEnv.caching.ttlExperiments = 2; + mockedEnv.caching.refreshThreshold = 0.25; + const first = { version: 1 }; + const refreshed = { version: 2 }; + const fetch = jest.fn().mockResolvedValueOnce(first).mockResolvedValueOnce(refreshed); + const realService = new CacheService(); + + expect(await realService.wrap(key, fetch)).toBe(first); + await sleep(500); + expect(await realService.wrap(key, fetch)).toBe(first); // kicks off the background refresh + await sleep(50); + + expect(await realService.wrap(key, fetch)).toBe(refreshed); + expect(fetch).toHaveBeenCalledTimes(2); + }); + + it('stores each loaded row itself in wrapMany, so later hits return the same objects', async () => { + const rows = new Map([ + ['seg-1', { id: 'seg-1', members: ['a'] }], + ['seg-2', { id: 'seg-2', members: ['b'] }], + ]); + const loadByKeys = jest.fn().mockImplementation(async (ids: string[]) => ids.map((id) => rows.get(id))); + const realService = new CacheService(); + + const cold = await realService.wrapMany(CACHE_PREFIX.SEGMENT_KEY_PREFIX, ['seg-1', 'seg-2'], loadByKeys); + const warm = await realService.wrapMany(CACHE_PREFIX.SEGMENT_KEY_PREFIX, ['seg-1', 'seg-2'], loadByKeys); + + expect(cold[0]).toBe(rows.get('seg-1')); + expect(cold[1]).toBe(rows.get('seg-2')); + expect(warm[0]).toBe(rows.get('seg-1')); + expect(warm[1]).toBe(rows.get('seg-2')); + expect(loadByKeys).toHaveBeenCalledTimes(1); + }); + }); + // The wrapMany tests above use a hand-written stand-in for `wrap`. These run against the real // cache-manager memory store, so they cover what a stubbed `wrap` cannot: that a stored null is // really treated as a hit, and that a key `wrap` asks for outside the prefetch is handled. diff --git a/packages/backend/test/unit/services/ExperimentAssignmentService.test.ts b/packages/backend/test/unit/services/ExperimentAssignmentService.test.ts index 8b8153d78..e5b27c01e 100644 --- a/packages/backend/test/unit/services/ExperimentAssignmentService.test.ts +++ b/packages/backend/test/unit/services/ExperimentAssignmentService.test.ts @@ -366,6 +366,114 @@ describe('Experiment Assignment Service Test', () => { }); }); + describe('cached segments and precomputed segment rows are never mutated', () => { + // Like the experiment graph above, segments (SegmentService.getSegmentByIds / getGlobalExcludeSegmentByContext) + // and precomputed segment rows (getPrecomputedSets) come out of the in-memory cache as the same objects on every + // request, so an in-place write during assignment would leak into every later request. The stubs below hand + // out the same fixture objects on every call, the way the cache does, and the test checks they come through + // two /assign requests unchanged. It covers the global exclude segment, on-the-fly resolution of include and + // exclude segments (including a sub-segment) for an experiment with no precomputed row, and the precomputed + // row path for another experiment. + it('leaves cached segments and precomputed rows unchanged across /assign requests', async () => { + const context = 'context'; + const userDoc = { id: 'user123', group: { schoolId: ['school1'] }, workingGroup: { schoolId: 'school1' } }; + + const segmentsById: Record = { + 'global-exclude': { + id: 'global-exclude', + individualForSegment: [{ userId: 'someone-else' }], + groupForSegment: [{ type: 'schoolId', groupId: 'excluded-school' }], + subSegments: [{ id: 'global-exclude-sub' }], + }, + 'global-exclude-sub': { + id: 'global-exclude-sub', + individualForSegment: [{ userId: 'another-user' }], + groupForSegment: [], + subSegments: [], + }, + 'include-segment': { + id: 'include-segment', + individualForSegment: [{ userId: 'user123' }], + groupForSegment: [{ type: 'schoolId', groupId: 'school1' }], + subSegments: [{ id: 'include-sub-segment' }], + }, + 'include-sub-segment': { + id: 'include-sub-segment', + individualForSegment: [{ userId: 'sub-user' }], + groupForSegment: [{ type: 'classId', groupId: 'class1' }], + subSegments: [], + }, + 'exclude-segment': { + id: 'exclude-segment', + individualForSegment: [{ userId: 'excluded-user' }], + groupForSegment: [{ type: 'schoolId', groupId: 'other-school' }], + subSegments: [], + }, + }; + + // Resolved on the fly (no precomputed row) from the cached segments above. + const onTheFlyExperiment: any = structuredClone(simpleIndividualAssignmentExperiment); + onTheFlyExperiment.id = 'on-the-fly-experiment'; + onTheFlyExperiment.filterMode = FILTER_MODE.EXCLUDE_ALL; + // Resolved from its precomputed row. + const precomputedExperiment: any = structuredClone(simpleIndividualAssignmentExperiment); + precomputedExperiment.id = 'precomputed-experiment'; + precomputedExperiment.filterMode = FILTER_MODE.EXCLUDE_ALL; + const precomputedRows = new Map([ + [ + precomputedExperiment.id, + { + experimentId: precomputedExperiment.id, + inclusionIds: ['user123', 'schoolId:school1'], + exclusionIds: ['classId:excluded-class'], + }, + ], + ]); + + const getSegmentByIds = sandbox + .stub() + .callsFake(async (ids: string[]) => ids.map((id) => segmentsById[id]).filter(Boolean)); + testedModule.segmentService = { + getGlobalExcludeSegmentByContext: sandbox.stub().resolves(segmentsById['global-exclude']), + getSegmentByIds, + }; + const getPrecomputedSets = sandbox.stub().resolves(precomputedRows); + testedModule.experimentPrecomputedSegmentService = { getPrecomputedSets }; + const experimentRepository = Object.create(experimentRepositoryMock); + experimentRepository.getSegmentIdsForExperiments = sandbox.stub().callsFake(async (ids: string[]) => + ids + .filter((id) => id === onTheFlyExperiment.id) + .map((id) => ({ + id, + experimentSegmentInclusion: [{ segmentId: 'include-segment' }], + experimentSegmentExclusion: [{ segmentId: 'exclude-segment' }], + })) + ); + testedModule.experimentRepository = experimentRepository; + testedModule.experimentService.getCachedValidExperiments = sandbox + .stub() + .resolves([onTheFlyExperiment, precomputedExperiment]); + testedModule.experimentUserService = { getOriginalUserDoc: sandbox.stub().resolves(userDoc) }; + + const snapshot = () => + JSON.parse(JSON.stringify({ segmentsById, precomputedRows: Object.fromEntries(precomputedRows) })); + const before = snapshot(); + + await testedModule.getAllExperimentConditions(userDoc, context, loggerMock); + await testedModule.getAllExperimentConditions(userDoc, context, loggerMock); + + // Every cached path ran: global exclude (and its sub-segment), on-the-fly include/exclude (and the + // include segment's sub-segment), and the precomputed row. + sinon.assert.calledWith(getSegmentByIds, ['global-exclude']); + sinon.assert.calledWith(getSegmentByIds, ['global-exclude-sub']); + sinon.assert.calledWith(getSegmentByIds, ['include-segment']); + sinon.assert.calledWith(getSegmentByIds, ['include-sub-segment']); + sinon.assert.calledWith(getSegmentByIds, ['exclude-segment']); + sinon.assert.called(getPrecomputedSets); + expect(snapshot()).toEqual(before); + }); + }); + describe('assignment does not depend on the order rows come back from the database', () => { // `getValidExperiments` — the assignment read path — has no `ORDER BY conditions.order`; only the // admin-side `findOneExperiment` does. So the sequence conditions arrive in is whatever Postgres diff --git a/packages/backend/test/unit/services/FeatureFlagService.test.ts b/packages/backend/test/unit/services/FeatureFlagService.test.ts index e1e601de5..cb5410db9 100644 --- a/packages/backend/test/unit/services/FeatureFlagService.test.ts +++ b/packages/backend/test/unit/services/FeatureFlagService.test.ts @@ -1116,6 +1116,41 @@ describe('Feature Flag Service Testing', () => { }); }); + describe('cached flags and precomputed segment rows are never mutated', () => { + // getCachedFlagsForKeys and getPrecomputedSets come out of the in-memory cache as the same objects on every + // request, so an in-place write during getKeys would leak into every later /featureflag request. The stubs + // hand out the same fixture objects on every call, the way the cache does. (Flags missing a precomputed row + // are resolved from getCachedFlagsFromContext, which already returns a JSON copy, and from cached segments via + // ExperimentAssignmentService.resolveSegmentsForEntities, which ExperimentAssignmentService's own tests cover.) + it('leaves the cached flag list and precomputed rows unchanged across getKeys requests', async () => { + const precomputed = module.get(FeatureFlagPrecomputedSegmentService); + const cachedFlags = [ + { id: 'include-all-flag', key: 'include-all-key', filterMode: FILTER_MODE.INCLUDE_ALL }, + { id: 'exclude-all-flag', key: 'exclude-all-key', filterMode: FILTER_MODE.EXCLUDE_ALL }, + ]; + const cachedRows = new Map([ + ['include-all-flag', { inclusionIds: [], exclusionIds: ['classId:excluded-class', 'excluded-user'] }], + ['exclude-all-flag', { inclusionIds: ['user123', 'schoolId:school1'], exclusionIds: ['classId:other-class'] }], + ]); + service.cacheService.wrap = jest.fn().mockResolvedValue(cachedFlags); + (precomputed.getPrecomputedSets as jest.Mock).mockResolvedValue(cachedRows); + + const snapshot = () => JSON.parse(JSON.stringify({ cachedFlags, cachedRows: Object.fromEntries(cachedRows) })); + const before = snapshot(); + + const includedUser = { id: 'user123', group: { schoolId: ['school1'] }, workingGroup: {} } as any; + const groupExcludedUser = { + id: 'user456', + group: { classId: ['excluded-class'], schoolId: ['school1'] }, + workingGroup: {}, + } as any; + expect(await service.getKeys(includedUser, 'context1', logger)).toEqual(['include-all-key', 'exclude-all-key']); + expect(await service.getKeys(groupExcludedUser, 'context1', logger)).toEqual(['exclude-all-key']); + + expect(snapshot()).toEqual(before); + }); + }); + describe('precomputed recompute + seed triggers', () => { it('seeds an empty precomputed row in-transaction when a flag is created', async () => { const precomputed = module.get(FeatureFlagPrecomputedSegmentService); From 8a4540dd3f6dde2a3494970617b49315b08871f1 Mon Sep 17 00:00:00 2001 From: doswalt Date: Wed, 4 Nov 2026 19:57:59 -0500 Subject: [PATCH 2/2] add mark and reward tests as they are also paths where mutations could accidentally be coded up --- .../ExperimentAssignmentService.test.ts | 168 +++++++++++++++--- .../ThompsonSamplingRewardService.test.ts | 24 +++ 2 files changed, 169 insertions(+), 23 deletions(-) diff --git a/packages/backend/test/unit/services/ExperimentAssignmentService.test.ts b/packages/backend/test/unit/services/ExperimentAssignmentService.test.ts index e5b27c01e..d125604c2 100644 --- a/packages/backend/test/unit/services/ExperimentAssignmentService.test.ts +++ b/packages/backend/test/unit/services/ExperimentAssignmentService.test.ts @@ -364,21 +364,114 @@ describe('Experiment Assignment Service Test', () => { await expectNoMutation(exp, () => testedModule.getAllExperimentConditions(userDoc, context, loggerMock)); }); + + // /mark reads the same cached graph (resolveExperimentForMarkPoint) and goes further with it than /assign: + // it hands the cached experiment, its decision point and its conditions to updateEnrollmentExclusion, which + // builds enrollment/exclusion documents around them and, for a new user or group, re-runs assignExperiment. + // Each test marks both without an experimentId (full selection pipeline) and with one (direct lookup). + describe('on /mark', () => { + const context = 'context'; + + const markBothWays = (exp: any, userDoc: any, condition: string) => async () => { + const { site, target } = exp.partitions[0]; + for (const experimentId of [undefined, exp.id]) { + await testedModule.markExperimentPoint( + userDoc, + site, + MARKED_DECISION_POINT_STATUS.CONDITION_APPLIED, + condition, + loggerMock, + context, + experimentId, + target, + 'uniquifier-1' + ); + } + }; + + beforeEach(() => { + testedModule.monitoredDecisionPointRepository = { + findOne: sandbox.stub().resolves(undefined), + saveRawJson: sandbox.stub().callsFake(async (document) => document), + }; + individualEnrollmentRepositoryMock.save = sandbox.stub().callsFake(async (document) => document); + }); + + it('should not mutate the cached experiment when enrolling a user in a simple individual experiment', async () => { + const userDoc = { id: 'user123', group: {}, workingGroup: {} }; + const exp = structuredClone(simpleIndividualAssignmentExperiment); + testedModule.experimentService.getCachedValidExperiments = sandbox.stub().resolves([exp]); + + await expectNoMutation(exp, markBothWays(exp, userDoc, 'ConditionA')); + + sinon.assert.called(individualEnrollmentRepositoryMock.save); + }); + + it('should not reorder the cached conditions when enrolling a new group in a simple group experiment', async () => { + const userDoc = { + id: 'user123', + group: { 'add-group1': ['school1'] }, + workingGroup: { 'add-group1': 'school1' }, + }; + const exp: any = structuredClone(simpleGroupAssignmentExperiment); + expect(exp.conditions.map((condition) => condition.order)).toEqual([2, 1]); + testedModule.experimentService.getCachedValidExperiments = sandbox.stub().resolves([exp]); + groupEnrollmentRepositoryMock.findOne = sandbox.stub().resolves(undefined); + groupEnrollmentRepositoryMock.save = sandbox.stub().resolves(); + groupExclusionRepositoryMock.findOne = sandbox.stub().resolves(undefined); + + await expectNoMutation(exp, markBothWays(exp, userDoc, 'add-con1')); + + sinon.assert.called(groupEnrollmentRepositoryMock.save); + }); + + it('should not mutate the cached experiment when recording a within-subjects repeated enrollment', async () => { + const userDoc = { id: 'user123', group: {}, workingGroup: {} }; + const exp = structuredClone(simpleWithinSubjectOrderedRoundRobinExperiment); + testedModule.experimentService.getCachedValidExperiments = sandbox.stub().resolves([exp]); + const saveRepeatedEnrollment = sandbox.stub().resolves(); + testedModule.repeatedEnrollmentRepository = { save: saveRepeatedEnrollment }; + + await expectNoMutation(exp, markBothWays(exp, userDoc, 'ConditionA')); + + sinon.assert.called(saveRepeatedEnrollment); + }); + }); }); describe('cached segments and precomputed segment rows are never mutated', () => { // Like the experiment graph above, segments (SegmentService.getSegmentByIds / getGlobalExcludeSegmentByContext) // and precomputed segment rows (getPrecomputedSets) come out of the in-memory cache as the same objects on every // request, so an in-place write during assignment would leak into every later request. The stubs below hand - // out the same fixture objects on every call, the way the cache does, and the test checks they come through - // two /assign requests unchanged. It covers the global exclude segment, on-the-fly resolution of include and - // exclude segments (including a sub-segment) for an experiment with no precomputed row, and the precomputed - // row path for another experiment. - it('leaves cached segments and precomputed rows unchanged across /assign requests', async () => { - const context = 'context'; - const userDoc = { id: 'user123', group: { schoolId: ['school1'] }, workingGroup: { schoolId: 'school1' } }; + // out the same fixture objects on every call, the way the cache does, and each test checks they come through + // repeated /assign or /mark requests unchanged. Both cover the global exclude segment, on-the-fly resolution + // of include and exclude segments (including a sub-segment) for an experiment with no precomputed row, and the + // precomputed row path for another experiment. + const context = 'context'; + const userDoc = { id: 'user123', group: { schoolId: ['school1'] }, workingGroup: { schoolId: 'school1' } }; + let segmentsById: Record; + let precomputedRows: Map; + let onTheFlyExperiment: any; + let precomputedExperiment: any; + let getSegmentByIds: sinon.SinonStub; + let getPrecomputedSets: sinon.SinonStub; + + const snapshot = () => + JSON.parse(JSON.stringify({ segmentsById, precomputedRows: Object.fromEntries(precomputedRows) })); + + // Every cached path ran: global exclude (and its sub-segment), on-the-fly include/exclude (and the + // include segment's sub-segment), and the precomputed row. + const assertEveryCachedPathRan = () => { + sinon.assert.calledWith(getSegmentByIds, ['global-exclude']); + sinon.assert.calledWith(getSegmentByIds, ['global-exclude-sub']); + sinon.assert.calledWith(getSegmentByIds, ['include-segment']); + sinon.assert.calledWith(getSegmentByIds, ['include-sub-segment']); + sinon.assert.calledWith(getSegmentByIds, ['exclude-segment']); + sinon.assert.called(getPrecomputedSets); + }; - const segmentsById: Record = { + beforeEach(() => { + segmentsById = { 'global-exclude': { id: 'global-exclude', individualForSegment: [{ userId: 'someone-else' }], @@ -412,14 +505,14 @@ describe('Experiment Assignment Service Test', () => { }; // Resolved on the fly (no precomputed row) from the cached segments above. - const onTheFlyExperiment: any = structuredClone(simpleIndividualAssignmentExperiment); + onTheFlyExperiment = structuredClone(simpleIndividualAssignmentExperiment); onTheFlyExperiment.id = 'on-the-fly-experiment'; onTheFlyExperiment.filterMode = FILTER_MODE.EXCLUDE_ALL; // Resolved from its precomputed row. - const precomputedExperiment: any = structuredClone(simpleIndividualAssignmentExperiment); + precomputedExperiment = structuredClone(simpleIndividualAssignmentExperiment); precomputedExperiment.id = 'precomputed-experiment'; precomputedExperiment.filterMode = FILTER_MODE.EXCLUDE_ALL; - const precomputedRows = new Map([ + precomputedRows = new Map([ [ precomputedExperiment.id, { @@ -430,14 +523,14 @@ describe('Experiment Assignment Service Test', () => { ], ]); - const getSegmentByIds = sandbox + getSegmentByIds = sandbox .stub() .callsFake(async (ids: string[]) => ids.map((id) => segmentsById[id]).filter(Boolean)); testedModule.segmentService = { getGlobalExcludeSegmentByContext: sandbox.stub().resolves(segmentsById['global-exclude']), getSegmentByIds, }; - const getPrecomputedSets = sandbox.stub().resolves(precomputedRows); + getPrecomputedSets = sandbox.stub().resolves(precomputedRows); testedModule.experimentPrecomputedSegmentService = { getPrecomputedSets }; const experimentRepository = Object.create(experimentRepositoryMock); experimentRepository.getSegmentIdsForExperiments = sandbox.stub().callsFake(async (ids: string[]) => @@ -454,22 +547,51 @@ describe('Experiment Assignment Service Test', () => { .stub() .resolves([onTheFlyExperiment, precomputedExperiment]); testedModule.experimentUserService = { getOriginalUserDoc: sandbox.stub().resolves(userDoc) }; + }); - const snapshot = () => - JSON.parse(JSON.stringify({ segmentsById, precomputedRows: Object.fromEntries(precomputedRows) })); + it('leaves cached segments and precomputed rows unchanged across /assign requests', async () => { const before = snapshot(); await testedModule.getAllExperimentConditions(userDoc, context, loggerMock); await testedModule.getAllExperimentConditions(userDoc, context, loggerMock); - // Every cached path ran: global exclude (and its sub-segment), on-the-fly include/exclude (and the - // include segment's sub-segment), and the precomputed row. - sinon.assert.calledWith(getSegmentByIds, ['global-exclude']); - sinon.assert.calledWith(getSegmentByIds, ['global-exclude-sub']); - sinon.assert.calledWith(getSegmentByIds, ['include-segment']); - sinon.assert.calledWith(getSegmentByIds, ['include-sub-segment']); - sinon.assert.calledWith(getSegmentByIds, ['exclude-segment']); - sinon.assert.called(getPrecomputedSets); + assertEveryCachedPathRan(); + expect(snapshot()).toEqual(before); + }); + + it('leaves cached segments and precomputed rows unchanged across /mark requests', async () => { + // /mark reaches the same cached segments and rows through its own entry point + // (resolveExperimentForMarkPoint): the full selection pipeline when no experimentId is sent, and a + // direct experimentLevelExclusionInclusion call for the named experiment when one is. + const { site, target } = onTheFlyExperiment.partitions[0]; + individualEnrollmentRepositoryMock.save = sandbox.stub().resolves(); + testedModule.monitoredDecisionPointRepository = { + findOne: sandbox.stub().resolves(undefined), + saveRawJson: sandbox.stub().callsFake(async (document) => document), + }; + const mark = (experimentId: string | undefined) => + testedModule.markExperimentPoint( + userDoc, + site, + MARKED_DECISION_POINT_STATUS.CONDITION_APPLIED, + 'ConditionA', + loggerMock, + context, + experimentId, + target + ); + const before = snapshot(); + + for (let i = 0; i < 2; i++) { + await mark(undefined); + await mark(onTheFlyExperiment.id); + await mark(precomputedExperiment.id); + } + + assertEveryCachedPathRan(); + // The user is included everywhere, so every mark went on to write an enrollment instead of stopping at + // an exclusion — i.e. the enrollment path below segment resolution ran too. + sinon.assert.callCount(individualEnrollmentRepositoryMock.save, 6); expect(snapshot()).toEqual(before); }); }); diff --git a/packages/backend/test/unit/services/ThompsonSamplingRewardService.test.ts b/packages/backend/test/unit/services/ThompsonSamplingRewardService.test.ts index 864b8bbde..4360a11ee 100644 --- a/packages/backend/test/unit/services/ThompsonSamplingRewardService.test.ts +++ b/packages/backend/test/unit/services/ThompsonSamplingRewardService.test.ts @@ -576,5 +576,29 @@ describe('ThompsonSamplingRewardService', () => { expect(tsConfigRepository.findOne).toHaveBeenCalledTimes(2); }); + + it('never mutates the cached config, including its posterior-state rows, across rewards and a batch flush', async () => { + const cachedConfig = { + ...makeConfig(2), + conditionPosteriorStates: [makeStateRow('state-1', CONDITION_ID)], + }; + tsConfigRepository.findOne = jest.fn().mockResolvedValue(cachedConfig); + tsConfigRepository.findByDecisionPoint = jest.fn().mockResolvedValue([cachedConfig]); + const dpRequest = { + rewardValue: BinaryRewardAllowedValue.FAILURE, + context: 'context-1', + decisionPoint: { site: 'site-1', target: 'target-1' }, + } as RewardValidator; + const before = JSON.parse(JSON.stringify(cachedConfig)); + + // batchSize is 2, so the second reward closes a batch and flushes the pending counts. + await (service as any).processReward(makeUser(), makeRequest(BinaryRewardAllowedValue.SUCCESS), logger); + await (service as any).processReward(makeUser(), dpRequest, logger); + await (service as any).processReward(makeUser(), makeRequest(BinaryRewardAllowedValue.SUCCESS), logger); + await (service as any).processReward(makeUser(), dpRequest, logger); + + expect(statesByCondition[CONDITION_ID].totalCount).toBe(4); + expect(JSON.parse(JSON.stringify(cachedConfig))).toEqual(before); + }); }); });