perf: Update documents popularity score (#10986)

This commit is contained in:
Tom Moor authored and GitHub committed 2025-12-22 08:10:27 -05:00
1 parent ad513250e5
commit 041c4217b2
2 files changed
+236 -26

No files matched your search

@@ -0,0 +1,200 @@
import { subDays } from "date-fns";
import { Document, Revision, View } from "@server/models";
import { sequelize, sequelizeReadOnly } from "@server/storage/database";
import {
buildDocument,
buildTeam,
buildUser,
buildComment,
} from "@server/test/factories";
import UpdateDocumentsPopularityScoreTask from "./UpdateDocumentsPopularityScoreTask";
const props = {
limit: 10000,
partition: {
partitionIndex: 0,
partitionCount: 1,
},
};
describe("UpdateDocumentsPopularityScoreTask", () => {
let task: UpdateDocumentsPopularityScoreTask;
beforeAll(() => {
jest.setTimeout(30000);
});
beforeEach(() => {
task = new UpdateDocumentsPopularityScoreTask();
jest.spyOn(Date.prototype, "getHours").mockReturnValue(0);
// Ensure calculation query sees data created in tests by redirecting to main sequelize instance.
// We only mock if the instances are different to avoid infinite recursion.
if (sequelizeReadOnly !== sequelize) {
jest
.spyOn(sequelizeReadOnly, "query")
.mockImplementation(sequelize.query.bind(sequelize));
}
});
afterEach(() => {
jest.restoreAllMocks();
});
it("should skip execution if not at a 6-hour interval", async () => {
jest.spyOn(Date.prototype, "getHours").mockReturnValue(1);
const team = await buildTeam();
const document = await buildDocument({
teamId: team.id,
publishedAt: new Date(),
});
await task.perform(props);
const updatedDocument = await Document.findByPk(document.id);
expect(updatedDocument?.popularityScore).toBe(0);
});
it("should update popularity score based on revisions", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
publishedAt: new Date(),
});
await Revision.create({
documentId: document.id,
userId: user.id,
title: document.title,
text: "Content",
createdAt: subDays(new Date(), 1),
});
await task.perform(props);
const updatedDocument = await Document.findByPk(document.id);
expect(updatedDocument?.popularityScore).toBeGreaterThan(0);
});
it("should update popularity score based on views", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
publishedAt: new Date(),
});
await View.create({
documentId: document.id,
userId: user.id,
});
await task.perform(props);
const updatedDocument = await Document.findByPk(document.id);
expect(updatedDocument?.popularityScore).toBeGreaterThan(0);
});
it("should update popularity score based on comments", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
publishedAt: new Date(),
});
await buildComment({
documentId: document.id,
userId: user.id,
});
await task.perform(props);
const updatedDocument = await Document.findByPk(document.id);
expect(updatedDocument?.popularityScore).toBeGreaterThan(0);
});
it("should handle multiple documents and give higher score to more recent activity", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const doc1 = await buildDocument({
teamId: team.id,
publishedAt: new Date(),
});
const doc2 = await buildDocument({
teamId: team.id,
publishedAt: new Date(),
});
// Recent activity for doc1
await Revision.create({
documentId: doc1.id,
userId: user.id,
title: doc1.title,
text: "Content",
createdAt: subDays(new Date(), 1),
});
// Older activity for doc2
await Revision.create({
documentId: doc2.id,
userId: user.id,
title: doc2.title,
text: "Content",
createdAt: subDays(new Date(), 5),
});
await task.perform(props);
const updatedDoc1 = await Document.findByPk(doc1.id);
const updatedDoc2 = await Document.findByPk(doc2.id);
expect(updatedDoc1?.popularityScore).toBeGreaterThan(
updatedDoc2?.popularityScore || 0
);
});
it("should only process published and non-deleted documents", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
// Unpublished document (draft)
const draft = await buildDocument({
teamId: team.id,
publishedAt: undefined,
});
await Revision.create({
documentId: draft.id,
userId: user.id,
title: draft.title,
text: "Content",
createdAt: new Date(),
});
// Deleted document
const deleted = await buildDocument({
teamId: team.id,
publishedAt: new Date(),
deletedAt: new Date(),
});
await Revision.create({
documentId: deleted.id,
userId: user.id,
title: deleted.title,
text: "Content",
createdAt: new Date(),
});
await task.perform(props);
const updatedDraft = await Document.unscoped().findByPk(draft.id);
const updatedDeleted = await Document.unscoped().findByPk(deleted.id, {
paranoid: false,
});
expect(Number(updatedDraft?.popularityScore)).toEqual(0);
expect(Number(updatedDeleted?.popularityScore)).toEqual(0);
});
});
@@ -26,9 +26,9 @@ const ACTIVITY_WEIGHTS = {
};
/**
* Batch size for processing updates - kept small to minimize query duration
* Batch size for processing updates
*/
const BATCH_SIZE = 50;
const BATCH_SIZE = 250;
/**
* Statement timeout for individual queries to prevent runaway locks
@@ -153,18 +153,20 @@ export default class UpdateDocumentsPopularityScoreTask extends CronTask {
// Populate with documents that have recent activity and are valid
// (published, not deleted). Process in chunks to avoid long-running queries.
let offset = 0;
let lastId = startUuid;
let insertedCount = 0;
const chunkSize = 500;
const chunkSize = 1000;
while (true) {
const result = await sequelize.query<{ documentId: string }>(
`
INSERT INTO ${this.workingTable} ("documentId")
SELECT DISTINCT d.id as "documentId"
SELECT d.id
FROM documents d
WHERE d."publishedAt" IS NOT NULL
AND d."deletedAt" IS NULL
${lastId ? (insertedCount === 0 ? "AND d.id >= :lastId" : "AND d.id > :lastId") : ""}
${endUuid ? "AND d.id <= :endUuid" : ""}
AND (
EXISTS (
SELECT 1 FROM revisions r
@@ -179,32 +181,32 @@ export default class UpdateDocumentsPopularityScoreTask extends CronTask {
WHERE v."documentId" = d.id AND v."updatedAt" >= :threshold
)
)
${startUuid && endUuid ? "AND d.id >= :startUuid AND d.id <= :endUuid" : ""}
ORDER BY d.id
LIMIT :limit
OFFSET :offset
ON CONFLICT ("documentId") DO NOTHING
RETURNING "documentId"
`,
{
replacements: {
threshold,
startUuid,
lastId,
endUuid,
limit: chunkSize,
offset,
},
type: QueryTypes.SELECT,
}
);
if (result.length === 0) {
break;
}
insertedCount += result.length;
lastId = result[result.length - 1].documentId;
if (result.length < chunkSize) {
break;
}
offset += chunkSize;
}
Logger.debug(
@@ -286,7 +288,7 @@ export default class UpdateDocumentsPopularityScoreTask extends CronTask {
SET LOCAL statement_timeout = '${STATEMENT_TIMEOUT_MS}ms';
WITH batch_docs AS (
SELECT unnest(ARRAY[:documentIds]::uuid[]) AS id
SELECT * FROM unnest(ARRAY[:documentIds]::uuid[]) AS t(id)
),
revision_scores AS (
SELECT
@@ -358,20 +360,28 @@ export default class UpdateDocumentsPopularityScoreTask extends CronTask {
* Uses individual updates to minimize lock duration and contention.
*/
private async updateDocumentScores(scores: DocumentScore[]): Promise<void> {
// Update documents one at a time with short statement timeout
// This prevents any single update from holding locks for too long
for (const { documentId, score } of scores) {
await sequelize.query(
`
UPDATE documents
SET "popularityScore" = :score
WHERE id = :documentId
`,
{
replacements: { documentId, score },
}
);
if (scores.length === 0) {
return;
}
// Update documents in a single batch to improve performance and reduce round-trips.
// We use unnest with multiple arrays to ensure the IDs and scores stay aligned.
await sequelize.query(
`
UPDATE documents AS d
SET "popularityScore" = s.score
FROM (
SELECT * FROM unnest(ARRAY[:ids]::uuid[], ARRAY[:scores]::double precision[]) AS s(id, score)
) AS s
WHERE d.id = s.id
`,
{
replacements: {
ids: scores.map((s) => s.documentId),
scores: scores.map((s) => s.score),
},
}
);
}
/**
@@ -382,7 +392,7 @@ export default class UpdateDocumentsPopularityScoreTask extends CronTask {
`
UPDATE ${this.workingTable}
SET processed = TRUE
WHERE "documentId" IN (SELECT unnest(ARRAY[:documentIds]::uuid[]))
WHERE "documentId" = ANY(ARRAY[:documentIds]::uuid[])
`,
{
replacements: { documentIds },