Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/backend/src/api/services/CacheService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
84 changes: 84 additions & 0 deletions packages/backend/test/unit/services/CacheService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,236 @@ 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 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<string, any>;
let precomputedRows: Map<string, any>;
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);
};

beforeEach(() => {
segmentsById = {
'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.
onTheFlyExperiment = structuredClone(simpleIndividualAssignmentExperiment);
onTheFlyExperiment.id = 'on-the-fly-experiment';
onTheFlyExperiment.filterMode = FILTER_MODE.EXCLUDE_ALL;
// Resolved from its precomputed row.
precomputedExperiment = structuredClone(simpleIndividualAssignmentExperiment);
precomputedExperiment.id = 'precomputed-experiment';
precomputedExperiment.filterMode = FILTER_MODE.EXCLUDE_ALL;
precomputedRows = new Map([
[
precomputedExperiment.id,
{
experimentId: precomputedExperiment.id,
inclusionIds: ['user123', 'schoolId:school1'],
exclusionIds: ['classId:excluded-class'],
},
],
]);

getSegmentByIds = sandbox
.stub()
.callsFake(async (ids: string[]) => ids.map((id) => segmentsById[id]).filter(Boolean));
testedModule.segmentService = {
getGlobalExcludeSegmentByContext: sandbox.stub().resolves(segmentsById['global-exclude']),
getSegmentByIds,
};
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) };
});

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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're making sure to have regression coverage for places where cache mutations could be added, shouldn't we also include tests for the /mark path. I only see tests for the /assign path here.


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);
});
});

describe('assignment does not depend on the order rows come back from the database', () => {
Expand Down
35 changes: 35 additions & 0 deletions packages/backend/test/unit/services/FeatureFlagService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>(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>(FeatureFlagPrecomputedSegmentService);
Expand Down
Loading