Skip to content
Open
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
9 changes: 9 additions & 0 deletions lib/database/models/gaqSummary.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
36 changes: 36 additions & 0 deletions lib/database/repositories/GaqSummaryRepository.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>} 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<void>} 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();
5 changes: 3 additions & 2 deletions lib/database/repositories/Repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down
8 changes: 7 additions & 1 deletion lib/server/services/gaq/GaqDetectorsService.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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);
});
}
Expand Down Expand Up @@ -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 });
}
Expand Down
57 changes: 51 additions & 6 deletions lib/server/services/qualityControlFlag/QcFlagService.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const {
RunRepository,
QcFlagVerificationRepository,
QcFlagEffectivePeriodRepository,
GaqSummaryRepository,
},
} = require('../../../database/index.js');
const { dataSource } = require('../../../database/DataSource.js');
Expand Down Expand Up @@ -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
Expand All @@ -172,6 +174,7 @@ class QcFlagService {
runNumber,
detectorId: detector.id,
});
someFlagWasWritten = true;
if (dataPass) {
await newInstance.addDataPass(dataPass);
} else if (simulationPass) {
Expand All @@ -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({
Expand All @@ -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;
});
}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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: [],
Expand All @@ -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;
});
}
Expand All @@ -368,9 +397,11 @@ class QcFlagService {
* @return {Promise<QcFlag>} 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) {
Expand All @@ -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 });
}

Expand Down
5 changes: 5 additions & 0 deletions lib/server/services/qualityControlFlag/QcFlagTypeService.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
37 changes: 36 additions & 1 deletion lib/server/services/run/updateRun.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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
*
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 });
};
20 changes: 18 additions & 2 deletions test/api/qcFlags.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

Expand Down
Loading