Files
outline/server/queues/tasks/RollupDocumentInsightsTask.ts
Tom MoorandClaude Opus 4.7 4774fa4fd0 Weekly insights rollup (#12113)
* Weekly insights rollup

* fix: Avoid eager db instance creation in DocumentInsight model

Importing sequelize at the top level triggered createDatabaseInstance
during module load, which caused unrelated test suites that transitively
require the model to fail. Use the instance-bound this.sequelize in the
static method instead.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: Skip soft-deleted documents in weekly insights rollup

The weekly task was deleting daily rows for soft-deleted documents
without creating a weekly replacement, since rollupPeriod filters them
out. Join to documents in both the week-discovery query and the DELETE
to keep behavior consistent — historical daily rows for deleted docs are
left for the cleanup task to remove at the retention boundary.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor: Bind cutoff days param and add date predicate in weekly rollup

Moves CUTOFF_DAYS from string interpolation to a bound parameter and
adds a plain `date <` predicate so the planner can use the
(documentId, date, period) index before evaluating date_trunc.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 09:48:30 -04:00

54 lines
1.5 KiB
TypeScript

import { Day, Minute } from "@shared/utils/time";
import Logger from "@server/logging/Logger";
import { DocumentInsight } from "@server/models";
import { DocumentInsightPeriod } from "@server/models/DocumentInsight";
import { TaskPriority } from "./base/BaseTask";
import type { Props } from "./base/CronTask";
import { CronTask, TaskInterval } from "./base/CronTask";
/**
* Number of recent days to (re)compute on each run, in addition to the current
* day. Reprocessing the most recent days lets late-arriving writes (slow
* workers, out-of-order event emission) settle into the rollup. The upsert is
* idempotent.
*/
const RECOMPUTE_DAYS = 2;
export default class RollupDocumentInsightsTask extends CronTask {
public async perform({ partition }: Props) {
const [startUuid, endUuid] = this.getPartitionBounds(partition);
for (let offset = RECOMPUTE_DAYS; offset >= 0; offset--) {
const periodStart = new Date(Date.now() - offset * Day.ms)
.toISOString()
.slice(0, 10);
const upserted = await DocumentInsight.rollupPeriod({
periodStart,
intervalDays: 1,
period: DocumentInsightPeriod.Day,
startUuid,
endUuid,
});
Logger.info("task", `Rolled up document insights for ${periodStart}`, {
upserted,
});
}
}
public get cron() {
return {
interval: TaskInterval.Day,
partitionWindow: 30 * Minute.ms,
};
}
public get options() {
return {
attempts: 1,
priority: TaskPriority.Background,
};
}
}