diff --git a/lib/database/models/gaqSummary.js b/lib/database/models/gaqSummary.js index 93aab8a632..f0d630511f 100644 --- a/lib/database/models/gaqSummary.js +++ b/lib/database/models/gaqSummary.js @@ -23,6 +23,15 @@ * cannot tell it: `updatedAt` changes on any write to the row, including the ones that only set or clear `invalidatedAt`. * It allows to display when the values were calculated, and to tell how old they are (`computedAt` against `invalidatedAt`) * when investigating stale summaries + * + * A summary is invalidated (once per batch of writes, in the transaction of the write) when what it is computed from changes: + * - QC flags of the data pass are created, deleted (one or all of the data pass) or verified for the first time (see QcFlagService) + * - GAQ detectors of the run in the data pass are set or reset to the default ones (see GaqDetectorsService) + * - The QC time of the run changes (see updateRun) + * + * Known gap: changing `bad` of a QC flag type (see QcFlagTypeService.update) does not invalidate the summaries computed from flags + * of this type, which stay stale until invalidated by another trigger or manually. Flag types are rarely updated, and it would have to + * invalidate the summaries of every data pass and run having flags of this type, which can be a lot of them */ module.exports = (sequelize) => { const Sequelize = require('sequelize'); diff --git a/lib/database/repositories/GaqSummaryRepository.js b/lib/database/repositories/GaqSummaryRepository.js index 98986de513..fc485f1c45 100644 --- a/lib/database/repositories/GaqSummaryRepository.js +++ b/lib/database/repositories/GaqSummaryRepository.js @@ -28,6 +28,42 @@ class GaqSummaryRepository extends Repository { constructor() { super(GaqSummary); } + + /** + * Mark the summary for a given (dataPassId, runNumber) as invalidated, creating the row if it does not yet exist + * + * @param {number} dataPassId data pass id + * @param {number} runNumber run number + * @return {Promise} resolves once the summary is invalidated + */ + async invalidate(dataPassId, runNumber) { + await this.upsert({ dataPassId, runNumber, invalidatedAt: new Date() }); + } + + /** + * Mark a list of summaries as invalidated, creating the rows which do not yet exist, with one statement + * + * Pairs are deduplicated and sorted, so that the rows are always locked in the same order: concurrent transactions invalidating + * overlapping sets of summaries then wait for each other instead of deadlocking + * + * @param {{ dataPassId: number, runNumber: number }[]} pairs the (dataPassId, runNumber) pairs to invalidate + * @return {Promise} resolves once all summaries are invalidated + */ + async invalidateMany(pairs) { + const invalidatedAt = new Date(); + + const pairsByKey = new Map(pairs.map(({ dataPassId, runNumber }) => [`${dataPassId}-${runNumber}`, { dataPassId, runNumber }])); + const uniquePairs = [...pairsByKey.values()].sort((a, b) => a.dataPassId - b.dataPassId || a.runNumber - b.runNumber); + + if (uniquePairs.length === 0) { + return; + } + + await this.insertAll( + uniquePairs.map(({ dataPassId, runNumber }) => ({ dataPassId, runNumber, invalidatedAt })), + { updateOnDuplicate: ['invalidatedAt'] }, + ); + } } module.exports = new GaqSummaryRepository(); diff --git a/lib/database/repositories/Repository.js b/lib/database/repositories/Repository.js index 05a8e6c39c..45f3a3f42a 100644 --- a/lib/database/repositories/Repository.js +++ b/lib/database/repositories/Repository.js @@ -118,10 +118,11 @@ class Repository { * Insert multiple entities * * @param {*[]} entities list of entities to be inserted + * @param {Object} [options] options to be passed to bulkCreate * @return {Promise<*[]>} promise */ - async insertAll(entities) { - return this.model.bulkCreate(entities); + async insertAll(entities, options = {}) { + return this.model.bulkCreate(entities, options); } /** diff --git a/lib/server/services/gaq/GaqDetectorsService.js b/lib/server/services/gaq/GaqDetectorsService.js index 99108bfddd..d34194147e 100644 --- a/lib/server/services/gaq/GaqDetectorsService.js +++ b/lib/server/services/gaq/GaqDetectorsService.js @@ -12,7 +12,7 @@ */ const { gaqDetectorAdapter, detectorAdapter } = require('../../../database/adapters'); -const { GaqDetectorRepository, RunRepository, DetectorRepository } = require('../../../database/repositories'); +const { GaqDetectorRepository, RunRepository, DetectorRepository, GaqSummaryRepository } = require('../../../database/repositories'); const { BadParameterError } = require('../../errors/BadParameterError'); const { dataSource } = require('../../../database/DataSource.js'); const { Op } = require('sequelize'); @@ -57,6 +57,9 @@ class GaqDetectorService { .flatMap((runNumber) => detectorIds .map((detectorId) => ({ dataPassId, runNumber, detectorId }))); const createdEntries = await GaqDetectorRepository.insertAll(gaqEntries); + + await GaqSummaryRepository.invalidateMany(runNumbers.map((runNumber) => ({ dataPassId, runNumber }))); + return createdEntries.map(gaqDetectorAdapter.toEntity); }); } @@ -101,6 +104,9 @@ class GaqDetectorService { .flatMap(({ runNumber, detectors }) => detectors .map(({ id: detectorId }) => ({ dataPassId, runNumber, detectorId }))); const createdEntries = await GaqDetectorRepository.insertAll(gaqEntries); + + await GaqSummaryRepository.invalidateMany(runNumbers.map((runNumber) => ({ dataPassId, runNumber }))); + return createdEntries.map(gaqDetectorAdapter.toEntity); }, { transaction }); } diff --git a/lib/server/services/qualityControlFlag/QcFlagService.js b/lib/server/services/qualityControlFlag/QcFlagService.js index 0c5bcda6b5..5df7f94a49 100644 --- a/lib/server/services/qualityControlFlag/QcFlagService.js +++ b/lib/server/services/qualityControlFlag/QcFlagService.js @@ -20,6 +20,7 @@ const { RunRepository, QcFlagVerificationRepository, QcFlagEffectivePeriodRepository, + GaqSummaryRepository, }, } = require('../../../database/index.js'); const { dataSource } = require('../../../database/DataSource.js'); @@ -155,6 +156,7 @@ class QcFlagService { ); const createdFlags = []; + let someFlagWasWritten = false; for (const qcFlag of qcFlags) { const { comment, flagTypeId, origin, verify } = qcFlag; // Each flag should be treated separately and the for loop should not fail on the first error @@ -172,6 +174,7 @@ class QcFlagService { runNumber, detectorId: detector.id, }); + someFlagWasWritten = true; if (dataPass) { await newInstance.addDataPass(dataPass); } else if (simulationPass) { @@ -196,7 +199,8 @@ class QcFlagService { }); if (verify) { - await this.verifyFlag({ flagId: newInstance.id }, relations, { transaction }); + // GAQ summary is invalidated once for the whole batch, after the loop + await this.verifyFlag({ flagId: newInstance.id }, relations, { transaction, invalidateGaqSummary: false }); } createdFlag = await QcFlagRepository.findOne({ @@ -214,6 +218,18 @@ class QcFlagService { this._logger.warnMessage(`Failed to create QC flag with properties: ${JSON.stringify(qcFlag)}. Error: ${error}`); } } + + /** + * Invalidate GAQ summary of the dataPass and runNumber once for the whole batch, and not once per flag: a batch can contain + * tens of thousands of flags, all of them concerning the same (dataPassId, runNumber). + * It is done as soon as a flag was written, and not only when some were reported as created, because a flag failing midway + * (caught above) is already partially written. It is not done when nothing was written (all flags rejected), to not trigger a + * useless recomputation + */ + if (dataPass && someFlagWasWritten) { + await GaqSummaryRepository.invalidate(dataPass.id, runNumber); + } + return createdFlags; }); } @@ -284,6 +300,12 @@ class QcFlagService { { const { id, from, to, origin, createdById, runNumber, detectorId, flagTypeId, createdAt } = qcFlag; + + if (dataPassId) { + // Invalidate GAQ summary for the dataPass and runNumber of the deleted flag + await GaqSummaryRepository.invalidate(dataPassId, runNumber); + } + const qcFlagPropertiesToLog = { id, from, @@ -338,8 +360,8 @@ class QcFlagService { await QcFlagEffectivePeriodRepository.removeAll({ where: { id: { [Op.in]: effectivePeriodIds } } }); // Sequelize update requires a where and can't work only using association - const qcFlagIds = (await QcFlagRepository.findAll({ - attributes: ['id'], + const qcFlagIdsToRunNumbers = (await QcFlagRepository.findAll({ + attributes: ['id', 'runNumber'], include: { association: 'dataPasses', attributes: [], @@ -348,14 +370,21 @@ class QcFlagService { id: dataPassId, }, }, + where: { deleted: false }, raw: true, - })).map(({ id }) => id); + })).map(({ id, runNumber }) => ({ id, runNumber })); + + const qcFlagIds = qcFlagIdsToRunNumbers.map(({ id }) => id); + const runNumbers = new Set(qcFlagIdsToRunNumbers.map(({ runNumber }) => runNumber)); await QcFlagRepository.updateAll( { deleted: true }, { where: { id: qcFlagIds } }, ); + // Invalidate GAQ summary for the dataPass and all runNumbers of the deleted flags + await GaqSummaryRepository.invalidateMany(Array.from(runNumbers, (runNumber) => ({ dataPassId, runNumber }))); + return qcFlagIds.length; }); } @@ -368,9 +397,11 @@ class QcFlagService { * @return {Promise} promise * @param {object} [options] options * @param {sequelize.Transaction} [options.transaction] sequelize transaction + * @param {boolean} [options.invalidateGaqSummary = true] if false, the GAQ summary is not invalidated, in which case the caller + * is responsible for invalidating it (used when verifying many flags of the same run, to invalidate once) * @throws {NotFoundError|AccessDeniedError} */ - async verifyFlag({ flagId, comment }, relations, { transaction } = {}) { + async verifyFlag({ flagId, comment }, relations, { transaction, invalidateGaqSummary = true } = {}) { return dataSource.transaction(async () => { const qcFlag = await this.getOneOrFail(flagId); if (qcFlag.deleted) { @@ -389,7 +420,21 @@ class QcFlagService { createdById: user.id, }); - return await this.getOneOrFail(flagId); + const updatedQcFlag = await this.getOneOrFail(flagId); + + // Only the first verification changes the GAQ summary (a flag is verified as soon as it has one verification) + const isFirstVerification = !qcFlag.verifications || qcFlag.verifications.length === 0; + if (invalidateGaqSummary && isFirstVerification) { + // Get data pass id for the flag (if exists) to invalidate only related GAQ summaries + const dataPassQcFlag = await DataPassQcFlagRepository.findOne({ where: { qualityControlFlagId: flagId } }); + const dataPassId = dataPassQcFlag?.dataPassId; + + if (dataPassId) { + await GaqSummaryRepository.invalidate(dataPassId, updatedQcFlag.runNumber); + } + } + + return updatedQcFlag; }, { transaction }); } diff --git a/lib/server/services/qualityControlFlag/QcFlagTypeService.js b/lib/server/services/qualityControlFlag/QcFlagTypeService.js index 57f2a62e2d..aae0e581d5 100644 --- a/lib/server/services/qualityControlFlag/QcFlagTypeService.js +++ b/lib/server/services/qualityControlFlag/QcFlagTypeService.js @@ -129,6 +129,11 @@ class QcFlagTypeService { throw new ConflictError(`A QC flag with ${failureReason} already exists`); } + /* + * Known gap: changing `bad` changes the quality of every flag of this type, hence the GAQ summaries (see GaqSummary model) + * computed from them, but these summaries are not invalidated here: they stay stale until invalidated by another trigger + * or manually + */ await QcFlagTypeRepository.update(qcFlagType, { name, method, diff --git a/lib/server/services/run/updateRun.js b/lib/server/services/run/updateRun.js index 2e8b50048c..f4b9f0e69a 100644 --- a/lib/server/services/run/updateRun.js +++ b/lib/server/services/run/updateRun.js @@ -12,6 +12,8 @@ */ const RunRepository = require('../../../database/repositories/RunRepository.js'); +const GaqSummaryRepository = require('../../../database/repositories/GaqSummaryRepository.js'); +const DataPassRunRepository = require('../../../database/repositories/DataPassRunRepository.js'); const { getRunOrFail } = require('./getRunOrFail.js'); const { utilities: { TransactionHelper } } = require('../../../database'); const { checkLhcFill } = require('../../../usecases/lhcFill/checkLhcFill.js'); @@ -35,6 +37,20 @@ const { logSpecificRunTag } = require('./logEntriesCreation/logSpecificRunTag.js */ const TAGS_TO_LOG = ['Not for physics']; +/** + * Run patch fields whose values feed the qc_time_start / qc_time_end virtual columns + * + * @type {string[]} + */ +const QC_TIME_SOURCE_FIELDS = [ + 'firstTfTimestamp', + 'lastTfTimestamp', + 'timeTrgStart', + 'timeTrgEnd', + 'timeO2Start', + 'timeO2End', +]; + /** * Update the given run * @@ -82,7 +98,12 @@ exports.updateRun = async (identifier, payload, transaction) => { } // Store the run quality to create a log if it changed - const previousRun = { runQuality: runModel?.runQuality, calibrationStatus: runModel?.calibrationStatus }; + const previousRun = { + runQuality: runModel?.runQuality, + calibrationStatus: runModel?.calibrationStatus, + qcTimeStart: runModel?.qcTimeStart, + qcTimeEnd: runModel?.qcTimeEnd, + }; runPatch.definition = runPatch.definition ?? getRunDefinition({ ...runModel.dataValues, @@ -204,6 +225,20 @@ exports.updateRun = async (identifier, payload, transaction) => { } } + // Only check for invalidation when the patch could have changed them + if (QC_TIME_SOURCE_FIELDS.some((field) => field in runPatch)) { + // Reload because qcTimeStart/qcTimeEnd are virtual columns not in the patch and stay stale after update + await runModel.reload(); + if (previousRun.qcTimeStart?.getTime() !== runModel.qcTimeStart?.getTime() + || previousRun.qcTimeEnd?.getTime() !== runModel.qcTimeEnd?.getTime()) { + const dataPassRuns = await DataPassRunRepository.findAll({ + attributes: ['dataPassId'], + where: { runNumber: runModel.runNumber }, + }); + await GaqSummaryRepository.invalidateMany(dataPassRuns.map(({ dataPassId }) => ({ dataPassId, runNumber: runModel.runNumber }))); + } + } + return runModel; }, { transaction }); }; diff --git a/test/api/qcFlags.test.js b/test/api/qcFlags.test.js index 2b557e8184..bf7c3a992e 100644 --- a/test/api/qcFlags.test.js +++ b/test/api/qcFlags.test.js @@ -1104,13 +1104,29 @@ module.exports = () => { ]); }); - it('should successfully delete all QC flags for a given data pass', async () => { + it('should successfully delete all QC flags for a given data pass, counting only flags which were not already deleted', async () => { const dataPassId = 1; + const countNotDeletedFlags = () => QcFlagRepository.count({ + where: { deleted: false }, + include: { association: 'dataPasses', required: true, where: { id: dataPassId } }, + }); + + const notDeletedFlagsCount = await countNotDeletedFlags(); + expect(notDeletedFlagsCount).to.be.greaterThan(0); + const response = await request(server) .delete(`/api/qcFlags/perDataPass?dataPassId=${dataPassId}&token=${BkpRoles.DPG_ASYNC_QC_ADMIN}`); expect(response.status).to.be.equal(200); - expect(response.body.data.deletedCount).to.equal(11); // 9 from seeders, 2 created in POST requests previously in this test + expect(response.body.data.deletedCount).to.equal(notDeletedFlagsCount); + expect(await countNotDeletedFlags()).to.equal(0); + + // Flags are already deleted, so there is nothing left to delete + const secondResponse = await request(server) + .delete(`/api/qcFlags/perDataPass?dataPassId=${dataPassId}&token=${BkpRoles.DPG_ASYNC_QC_ADMIN}`); + + expect(secondResponse.status).to.be.equal(200); + expect(secondResponse.body.data.deletedCount).to.equal(0); }); }); diff --git a/test/lib/server/services/gaq/GaqSummary.test.js b/test/lib/server/services/gaq/GaqSummary.test.js new file mode 100644 index 0000000000..68a03637ee --- /dev/null +++ b/test/lib/server/services/gaq/GaqSummary.test.js @@ -0,0 +1,419 @@ +/** + * @license + * Copyright CERN and copyright holders of ALICE O2. This software is + * distributed under the terms of the GNU General Public License v3 (GPL + * Version 3), copied verbatim in the file "COPYING". + * + * See http://alice-o2.web.cern.ch/license for full licensing information. + * + * In applying this license CERN does not waive the privileges and immunities + * granted to it by virtue of its status as an Intergovernmental Organization + * or submit itself to any jurisdiction. + */ + +const { expect } = require('chai'); +const assert = require('assert'); +const { resetDatabaseContent } = require('../../../../utilities/resetDatabaseContent.js'); +const { repositories: { GaqSummaryRepository, QcFlagRepository, RunRepository } } = require('../../../../../lib/database'); +const { qcFlagService } = require('../../../../../lib/server/services/qualityControlFlag/QcFlagService.js'); +const { gaqDetectorService } = require('../../../../../lib/server/services/gaq/GaqDetectorsService.js'); +const { updateRun } = require('../../../../../lib/server/services/run/updateRun.js'); +const { runService } = require('../../../../../lib/server/services/run/RunService.js'); +const { dataPassService } = require('../../../../../lib/server/services/dataPasses/DataPassService.js'); + +/** + * Get unix timestamp for given time on 2024-07-16 + * + * @param {string} timeString time string in hh:mm:ss format + * @return {number} unix timestamp + */ +const t = (timeString) => new Date(`2024-07-16 ${timeString}`).getTime(); + +module.exports = () => { + /* + * The tests below do not depend on seeded QC flags, runs or summaries: they use runs created for this suite, and each test starts + * with the summaries of these runs existing and up to date, so that "not invalidated" can be told from "no row at all" + */ + const dataPassId = 3; // LHC22a_apass1 + const simulationPassId = 1; + const detectorId = 1; // CPV + const goodFlagTypeId = 3; + + // Run in the data pass, to which QC flags are added + const runNumber = 778801; + + // Run in the data pass with no QC flags, used where only the run matters + const idleRunNumber = 778802; + + const relations = { user: { roles: ['admin'], externalUserId: 456 } }; + const dataPassScope = { runNumber, dataPassIdentifier: { id: dataPassId }, detectorIdentifier: { detectorId } }; + const simulationPassScope = { runNumber, simulationPassIdentifier: { id: simulationPassId }, detectorIdentifier: { detectorId } }; + const synchronousScope = { runNumber, detectorIdentifier: { detectorId } }; + + /** + * Fetch the GAQ summary of a run in the data pass + * + * @param {number} runNumberToFetch the run number + * @return {Promise} the summary + */ + const getSummary = (runNumberToFetch) => GaqSummaryRepository.findOne({ where: { dataPassId, runNumber: runNumberToFetch } }); + + /** + * Create (or reset if it exists) the summary of a run, as up to date, i.e. not invalidated + * + * @param {number} runNumberToReset the run number + * @return {Promise} resolves once done + */ + const setUpToDate = async (runNumberToReset) => { + await GaqSummaryRepository.upsert({ dataPassId, runNumber: runNumberToReset, invalidatedAt: null }); + }; + + /** + * Expect the summary of a run to be invalidated + * + * @param {number} runNumberToCheck the run number + * @return {Promise} resolves once checked + */ + const expectInvalidated = async (runNumberToCheck) => { + const summary = await getSummary(runNumberToCheck); + expect(summary, `Expected a GAQ summary for run ${runNumberToCheck}`).to.not.be.null; + expect(summary.invalidatedAt, `Expected GAQ summary of run ${runNumberToCheck} to be invalidated`).to.be.an.instanceOf(Date); + }; + + /** + * Expect the summary of a run to exist and to not be invalidated + * + * @param {number} runNumberToCheck the run number + * @return {Promise} resolves once checked + */ + const expectNotInvalidated = async (runNumberToCheck) => { + const summary = await getSummary(runNumberToCheck); + expect(summary, `Expected a GAQ summary for run ${runNumberToCheck}`).to.not.be.null; + expect(summary.invalidatedAt, `Expected GAQ summary of run ${runNumberToCheck} to not be invalidated`).to.be.null; + }; + + /** + * Count the number of times `GaqSummaryRepository.invalidate` is called while running an action + * + * @param {function(): Promise<*>} action the action to run + * @return {Promise} the number of calls + */ + const countInvalidateCalls = async (action) => { + const hadOwnProperty = Object.hasOwn(GaqSummaryRepository, 'invalidate'); + const original = GaqSummaryRepository.invalidate; + let calls = 0; + GaqSummaryRepository.invalidate = function (...args) { + calls++; + return original.apply(this, args); + }; + try { + await action(); + } finally { + if (hadOwnProperty) { + GaqSummaryRepository.invalidate = original; + } else { + delete GaqSummaryRepository.invalidate; + } + } + return calls; + }; + + /** + * Create a QC flag in the data pass + * + * @param {object} [flag] properties of the flag + * @return {Promise} the created flag + */ + const createDataPassFlag = async (flag = {}) => { + const [created] = await qcFlagService.create([{ flagTypeId: goodFlagTypeId, ...flag }], dataPassScope, relations); + return created; + }; + + before(async () => { + await resetDatabaseContent(); + + for (const number of [runNumber, idleRunNumber]) { + await runService.create({ runNumber: number, timeTrgStart: t('06:00:00'), timeTrgEnd: t('22:00:00') }); + const run = await RunRepository.findOne({ where: { runNumber: number } }); + await run.addDataPass(dataPassId); + await run.addDetector(detectorId); + } + await (await RunRepository.findOne({ where: { runNumber } })).addSimulationPasses(simulationPassId); + }); + + after(async () => { + await resetDatabaseContent(); + }); + + beforeEach(async () => { + await setUpToDate(runNumber); + await setUpToDate(idleRunNumber); + }); + + describe('Invalidation on creation of QC flags', () => { + it('should invalidate the GAQ summary of the run in the data pass, and only this one', async () => { + await createDataPassFlag(); + + await expectInvalidated(runNumber); + await expectNotInvalidated(idleRunNumber); + + const summariesOfRun = await GaqSummaryRepository.findAll({ where: { runNumber } }); + expect(summariesOfRun.map(({ dataPassId }) => dataPassId)).to.eql([dataPassId]); + }); + + it('should invalidate the GAQ summary only once when creating many QC flags', async () => { + let created; + const calls = await countInvalidateCalls(async () => { + created = await qcFlagService.create( + [ + { flagTypeId: goodFlagTypeId, from: t('07:00:00'), to: t('08:00:00') }, + { flagTypeId: goodFlagTypeId, from: t('08:00:00'), to: t('09:00:00') }, + { flagTypeId: goodFlagTypeId, from: t('09:00:00'), to: t('10:00:00') }, + { flagTypeId: goodFlagTypeId, from: t('10:00:00'), to: t('11:00:00') }, + { flagTypeId: goodFlagTypeId, from: t('11:00:00'), to: t('12:00:00') }, + ], + dataPassScope, + relations, + ); + }); + + expect(created).to.lengthOf(5); + expect(calls).to.equal(1); + await expectInvalidated(runNumber); + }); + + it('should invalidate the GAQ summary only once when creating many verified QC flags', async () => { + let created; + const calls = await countInvalidateCalls(async () => { + created = await qcFlagService.create( + [ + { flagTypeId: goodFlagTypeId, from: t('07:00:00'), to: t('08:00:00'), verify: true }, + { flagTypeId: goodFlagTypeId, from: t('08:00:00'), to: t('09:00:00'), verify: true }, + { flagTypeId: goodFlagTypeId, from: t('09:00:00'), to: t('10:00:00'), verify: true }, + ], + dataPassScope, + relations, + ); + }); + + expect(created).to.lengthOf(3); + created.forEach(({ verifications }) => expect(verifications).to.lengthOf(1)); + expect(calls).to.equal(1); + await expectInvalidated(runNumber); + }); + + it('should not invalidate the GAQ summary when no QC flag could be created', async () => { + const created = await qcFlagService.create( + [{ flagTypeId: goodFlagTypeId, from: t('01:00:00'), to: t('02:00:00') }], // Before the start of the run + dataPassScope, + relations, + ); + + expect(created).to.lengthOf(0); + await expectNotInvalidated(runNumber); + }); + + it('should not invalidate the GAQ summary when creating a QC flag fails because the data pass is frozen', async () => { + await dataPassService.setFrozenState({ id: dataPassId }, true); + try { + await assert.rejects(() => createDataPassFlag()); + } finally { + await dataPassService.setFrozenState({ id: dataPassId }, false); + } + + await expectNotInvalidated(runNumber); + }); + + it('should not invalidate the GAQ summary when creating a QC flag for a simulation pass', async () => { + const created = await qcFlagService.create([{ flagTypeId: goodFlagTypeId }], simulationPassScope, relations); + + expect(created).to.lengthOf(1); + await expectNotInvalidated(runNumber); + }); + + it('should not invalidate the GAQ summary when creating a synchronous QC flag', async () => { + const created = await qcFlagService.create([{ flagTypeId: goodFlagTypeId }], synchronousScope, relations); + + expect(created).to.lengthOf(1); + await expectNotInvalidated(runNumber); + }); + }); + + describe('Invalidation on verification of QC flags', () => { + it('should invalidate the GAQ summary when a QC flag is verified for the first time, but not for the next verifications', async () => { + const { id: flagId } = await createDataPassFlag(); + await setUpToDate(runNumber); + + await qcFlagService.verifyFlag({ flagId }, relations); + await expectInvalidated(runNumber); + + await setUpToDate(runNumber); + await qcFlagService.verifyFlag({ flagId, comment: 'Verified again' }, relations); + await expectNotInvalidated(runNumber); + }); + }); + + describe('Invalidation on deletion of QC flags', () => { + it('should invalidate the GAQ summary when a QC flag of a data pass is deleted', async () => { + const { id: flagId } = await createDataPassFlag(); + await setUpToDate(runNumber); + + await qcFlagService.delete(flagId); + + await expectInvalidated(runNumber); + }); + + it('should not invalidate the GAQ summary when a QC flag of a simulation pass is deleted', async () => { + const [{ id: flagId }] = await qcFlagService.create([{ flagTypeId: goodFlagTypeId }], simulationPassScope, relations); + await setUpToDate(runNumber); + + await qcFlagService.delete(flagId); + + await expectNotInvalidated(runNumber); + }); + + it('should invalidate the GAQ summaries of the runs having QC flags when all QC flags of a data pass are deleted', async () => { + await createDataPassFlag(); + const { id: alreadyDeletedFlagId } = await createDataPassFlag(); + await qcFlagService.delete(alreadyDeletedFlagId); + await setUpToDate(runNumber); + + const notDeletedFlagsCount = await QcFlagRepository.count({ + where: { deleted: false }, + include: { association: 'dataPasses', required: true, where: { id: dataPassId } }, + }); + const deletedCount = await qcFlagService.deleteAllForDataPass(dataPassId); + + // Flags which were already deleted are neither counted, nor deleted again + expect(deletedCount).to.equal(notDeletedFlagsCount); + await expectInvalidated(runNumber); + await expectNotInvalidated(idleRunNumber); // The run has no QC flag + }); + }); + + describe('Invalidation on change of GAQ detectors', () => { + it('should invalidate the GAQ summary when GAQ detectors are explicitly set for a data pass and run', async () => { + await gaqDetectorService.setGaqDetectors(dataPassId, [idleRunNumber], [detectorId]); + + await expectInvalidated(idleRunNumber); + await expectNotInvalidated(runNumber); + }); + + it('should invalidate the GAQ summary when default GAQ detectors are used for a data pass and run', async () => { + await gaqDetectorService.useDefaultGaqDetectors(dataPassId, [idleRunNumber]); + + await expectInvalidated(idleRunNumber); + await expectNotInvalidated(runNumber); + }); + }); + + describe('Invalidation on change of QC time of runs', () => { + it('should invalidate the GAQ summaries of the run when its QC time changes', async () => { + await updateRun({ runNumber: idleRunNumber }, { runPatch: { timeTrgStart: new Date(t('07:00:00')) } }); + + await expectInvalidated(idleRunNumber); + await expectNotInvalidated(runNumber); + }); + + it('should not invalidate the GAQ summary when the patch does not touch QC time source fields', async () => { + await updateRun({ runNumber: idleRunNumber }, { runPatch: { definition: 'PHYSICS' } }); + + await expectNotInvalidated(idleRunNumber); + }); + + it('should not invalidate the GAQ summary when a QC time source field is patched but the QC time does not change', async () => { + // The run has a time_trg_start, hence its qc_time_start is time_trg_start whatever time_o2_start is + await updateRun({ runNumber: idleRunNumber }, { runPatch: { timeO2Start: new Date(t('05:00:00')) } }); + + await expectNotInvalidated(idleRunNumber); + }); + }); + + describe('GaqSummaryRepository.invalidateMany', () => { + /** + * Run an action while recording the calls to `bulkCreate` and `upsert`, which are the ways to write GAQ summaries + * + * @param {function(): Promise<*>} action the action to run + * @return {Promise<{ bulkCreateCalls: Array[], upsertCalls: number }>} the recorded calls + */ + const recordWrites = async (action) => { + const { model } = GaqSummaryRepository; + const originalBulkCreate = model.bulkCreate; + const originalUpsert = model.upsert; + const bulkCreateCalls = []; + let upsertCalls = 0; + model.bulkCreate = function (...args) { + bulkCreateCalls.push(args); + return originalBulkCreate.apply(this, args); + }; + model.upsert = function (...args) { + upsertCalls++; + return originalUpsert.apply(this, args); + }; + try { + await action(); + } finally { + model.bulkCreate = originalBulkCreate; + model.upsert = originalUpsert; + } + return { bulkCreateCalls, upsertCalls }; + }; + + it('should invalidate existing summaries and create missing ones', async () => { + await GaqSummaryRepository.removeAll({ where: { dataPassId, runNumber: idleRunNumber } }); + expect(await getSummary(idleRunNumber)).to.be.null; + + await GaqSummaryRepository.invalidateMany([ + { dataPassId, runNumber }, + { dataPassId, runNumber: idleRunNumber }, + ]); + + await expectInvalidated(runNumber); + await expectInvalidated(idleRunNumber); + }); + + it('should invalidate all summaries with the same timestamp, and keep the other values of existing summaries', async () => { + await GaqSummaryRepository.updateAll({ badRunCoverage: 0.25, notComputable: false }, { where: { dataPassId, runNumber } }); + + await GaqSummaryRepository.invalidateMany([ + { dataPassId, runNumber }, + { dataPassId, runNumber: idleRunNumber }, + ]); + + const summary = await getSummary(runNumber); + const idleSummary = await getSummary(idleRunNumber); + expect(summary.invalidatedAt.getTime()).to.equal(idleSummary.invalidatedAt.getTime()); + expect(summary.badRunCoverage).to.equal(0.25); + }); + + it('should write all summaries with only one statement, in a deterministic order, ignoring duplicates', async () => { + const { bulkCreateCalls, upsertCalls } = await recordWrites(() => GaqSummaryRepository.invalidateMany([ + { dataPassId, runNumber: idleRunNumber }, + { dataPassId, runNumber }, + { dataPassId, runNumber: idleRunNumber }, + ])); + + expect(upsertCalls).to.equal(0); + expect(bulkCreateCalls).to.lengthOf(1); + + const [[rows, options]] = bulkCreateCalls; + expect(rows.map(({ dataPassId, runNumber }) => ({ dataPassId, runNumber }))).to.eql([ + { dataPassId, runNumber }, + { dataPassId, runNumber: idleRunNumber }, + ]); + expect(options.updateOnDuplicate).to.include('invalidatedAt'); + + await expectInvalidated(runNumber); + await expectInvalidated(idleRunNumber); + }); + + it('should do nothing when there is nothing to invalidate', async () => { + const { bulkCreateCalls, upsertCalls } = await recordWrites(() => GaqSummaryRepository.invalidateMany([])); + + expect(bulkCreateCalls).to.lengthOf(0); + expect(upsertCalls).to.equal(0); + await expectNotInvalidated(runNumber); + await expectNotInvalidated(idleRunNumber); + }); + }); +}; diff --git a/test/lib/server/services/gaq/index.js b/test/lib/server/services/gaq/index.js index 985f80fe84..93e10b2ac6 100644 --- a/test/lib/server/services/gaq/index.js +++ b/test/lib/server/services/gaq/index.js @@ -12,7 +12,9 @@ */ const GaqDetectorServiceSuite = require('./GaqDetectorService.test.js'); +const GaqSummarySuite = require('./GaqSummary.test.js'); module.exports = () => { describe('GaqDetectorService', GaqDetectorServiceSuite); + describe('GaqSummary', GaqSummarySuite); }; diff --git a/test/lib/server/services/index.js b/test/lib/server/services/index.js index c9e7871aa2..8a8a462473 100644 --- a/test/lib/server/services/index.js +++ b/test/lib/server/services/index.js @@ -35,7 +35,7 @@ const UserSuite = require('./user/index.js'); const SimulationPassesSuite = require('./simulationPasses/index.js'); const QcFlagsSuite = require('./qualityControlFlag/index.js'); const CtpTriggerCountersSuite = require('./ctpTriggerCounters/index.js'); -const GaqDetectorSuite = require('./gaq'); +const GaqSuite = require('./gaq'); module.exports = () => { before(resetDatabaseContent); @@ -50,7 +50,7 @@ module.exports = () => { describe('Environment history item', EnvironmentHistoryItemSuite); describe('EOS report', EosReportSuite); describe('Flp role', FlpRoleSuite); - describe('GaqDetector', GaqDetectorSuite); + describe('GAQ', GaqSuite); describe('LHC fill suite', LhcFillSuite); describe('Logs', LogSuite); describe('RunType', RunTypeSuite);