mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 15:42:24 +00:00
Merge branch 'fix/v1437-jobs' into release/v1.43.7
This commit is contained in:
commit
ea933b91cc
59 files changed
+2340
-855
No files matched your search
@@ -4,16 +4,17 @@
|
||||
* Reads inside one request are memoised on the request's wide event, so a
|
||||
* page that resolves the AI capabilities five times reads the settings row
|
||||
* once. A background job opens one wide event for its whole run, and the
|
||||
* status crons loop over every candidate inside it: memoising there meant the
|
||||
* status batch loops over every candidate inside it: memoising there meant the
|
||||
* switches, the modules and the consent kinds were read once at the start of
|
||||
* the run and served to every later user, and the wire re-check read the same
|
||||
* cached answer. Turning the Assistant off at 02:05 did not stop the 02:00
|
||||
* pass.
|
||||
*
|
||||
* Driven here over the real loop, the real capability loader and Postgres:
|
||||
* the first user's generation turns the switch off, and the remaining users
|
||||
* must not reach a generator, while the wire re-check inside the first user's
|
||||
* own run must see the change too.
|
||||
* Driven here over the real loop, the real capability loader and Postgres.
|
||||
* The batch is stubbed past its first step, the `statusText` capability it
|
||||
* resolves before building anything: the first user's run turns the switch
|
||||
* off, the remaining users must not get past that step, and the wire re-check
|
||||
* inside the first user's own run must see the change too.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -27,7 +28,30 @@ vi.mock("@/lib/jobs/status-cron-candidates", () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
import { runStatusCronGenerate } from "@/lib/jobs/reminder/insights-handlers";
|
||||
const batch = vi.hoisted(() => ({
|
||||
run: async (_userId: string): Promise<void> => {},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/insights/status-batch", async () => {
|
||||
const { aiCapabilityForJob } = await import("@/lib/ai/capabilities/gate");
|
||||
return {
|
||||
generateStatusBatchForUser: vi.fn(async (userId: string) => {
|
||||
const result = {
|
||||
served: 0,
|
||||
batched: 0,
|
||||
fellBack: 0,
|
||||
batchCallMade: false,
|
||||
};
|
||||
if (!(await aiCapabilityForJob(userId, "statusText")).available) {
|
||||
return result;
|
||||
}
|
||||
await batch.run(userId);
|
||||
return { ...result, batched: 1, batchCallMade: true };
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
import { runStatusBatchCron } from "@/lib/jobs/reminder/insights-handlers";
|
||||
import { aiEgressRefusal } from "@/lib/ai/capabilities/egress";
|
||||
|
||||
let counter = 0;
|
||||
@@ -74,7 +98,7 @@ describe("a switch turned off mid-run", () => {
|
||||
const reached: string[] = [];
|
||||
const wire: Array<string | null> = [];
|
||||
|
||||
const generate = vi.fn(async (userId: string) => {
|
||||
batch.run = async (userId: string) => {
|
||||
reached.push(userId);
|
||||
// The wire re-check before the switch moves: open.
|
||||
wire.push(
|
||||
@@ -87,9 +111,9 @@ describe("a switch turned off mid-run", () => {
|
||||
(await aiEgressRefusal("statusText", userId, ["anthropic"]))?.reason ??
|
||||
null,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
await runStatusCronGenerate("job.test.fresh_switch", generate);
|
||||
await runStatusBatchCron("job.test.fresh_switch", () => false);
|
||||
|
||||
expect(reached).toEqual([candidates.ids[0]]);
|
||||
expect(wire[0]).toBeNull();
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Migration 0412: an update of `measurements` that changes nothing keeps its
|
||||
* stamps and stays on its page.
|
||||
*
|
||||
* `updated_at` sits in the sync-feed index, so an update that moved it could
|
||||
* never be heap-only, and every provider re-sync that rewrote unchanged rows
|
||||
* grew the table by a full row version and an entry in every index. Proven
|
||||
* here against Postgres: the no-op update keeps `updated_at` and
|
||||
* `sync_version` and is counted as HOT in the transaction's own statistics,
|
||||
* a real change still moves both, and the nightly check reads the table's
|
||||
* statistics and vacuums only when dead rows pass its threshold.
|
||||
*/
|
||||
import { Client } from "pg";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveSteps,
|
||||
runMeasurementMaintenance,
|
||||
tableHealth,
|
||||
} from "@/lib/jobs/measurement-maintenance";
|
||||
|
||||
import { getPrismaClient, truncateAllTables } from "./setup";
|
||||
|
||||
const prisma = getPrismaClient();
|
||||
|
||||
async function seedReading() {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
username: "hot-update",
|
||||
email: "hot-update@example.test",
|
||||
role: "USER",
|
||||
timezone: "UTC",
|
||||
},
|
||||
});
|
||||
return prisma.measurement.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
type: "WEIGHT",
|
||||
value: 72.3,
|
||||
unit: "kg",
|
||||
measuredAt: new Date("2026-10-01T07:00:00.000Z"),
|
||||
source: "WITHINGS",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await truncateAllTables(prisma);
|
||||
});
|
||||
|
||||
describe("an update that changes nothing", () => {
|
||||
it("keeps updated_at and sync_version and stays on its page", async () => {
|
||||
const row = await seedReading();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
const hot = await prisma.$transaction(async (tx) => {
|
||||
await tx.measurement.update({
|
||||
where: { id: row.id },
|
||||
data: { value: 72.3, deletedAt: null, syncVersion: { increment: 1 } },
|
||||
});
|
||||
const [stats] = await tx.$queryRaw<Array<{ hot: bigint; upd: bigint }>>`
|
||||
SELECT n_tup_hot_upd AS hot, n_tup_upd AS upd
|
||||
FROM pg_stat_xact_user_tables WHERE relname = 'measurements'`;
|
||||
return stats;
|
||||
});
|
||||
expect(Number(hot.upd)).toBe(1);
|
||||
expect(Number(hot.hot)).toBe(1);
|
||||
|
||||
const after = await prisma.measurement.findUniqueOrThrow({
|
||||
where: { id: row.id },
|
||||
});
|
||||
expect(after.updatedAt.getTime()).toBe(row.updatedAt.getTime());
|
||||
expect(after.syncVersion).toBe(row.syncVersion);
|
||||
});
|
||||
|
||||
it("still moves both stamps when a value changes", async () => {
|
||||
const row = await seedReading();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
await prisma.measurement.update({
|
||||
where: { id: row.id },
|
||||
data: { value: 72.4, syncVersion: { increment: 1 } },
|
||||
});
|
||||
const after = await prisma.measurement.findUniqueOrThrow({
|
||||
where: { id: row.id },
|
||||
});
|
||||
expect(after.updatedAt.getTime()).toBeGreaterThan(row.updatedAt.getTime());
|
||||
expect(after.syncVersion).toBe(row.syncVersion + 1);
|
||||
});
|
||||
|
||||
it("gives the table room on each page and an earlier autovacuum", async () => {
|
||||
const [rel] = await prisma.$queryRaw<Array<{ options: string[] | null }>>`
|
||||
SELECT reloptions AS options FROM pg_class WHERE relname = 'measurements'`;
|
||||
expect(rel.options).toEqual(
|
||||
expect.arrayContaining([
|
||||
"fillfactor=85",
|
||||
"autovacuum_vacuum_scale_factor=0.05",
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the nightly check", () => {
|
||||
it("reads the statistics and does nothing while no vacuum is due", async () => {
|
||||
await seedReading();
|
||||
const db = new Client({ connectionString: process.env.DATABASE_URL });
|
||||
await db.connect();
|
||||
try {
|
||||
await db.query("ANALYZE measurements");
|
||||
const health = await tableHealth(db);
|
||||
expect(health.heapBytes).toBeGreaterThan(0);
|
||||
const steps = resolveSteps({}, health);
|
||||
expect(steps).toEqual({ vacuum: false, reindex: false });
|
||||
const summary = await runMeasurementMaintenance(db, steps);
|
||||
expect(summary.outcome).toBe("nothing_due");
|
||||
expect(summary.steps).toEqual([]);
|
||||
} finally {
|
||||
await db.end();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user