feat(server): take a database lease before a cron tick runs

waitForCompletion only kept a tick from overlapping itself inside one
process. Two processes on the same database (a rolling update's overlap,
a second replica, a dev container pointed at the same file) both ran
every job: two auto-backups, double syncs and retention sweeps, and
reminder runs racing each other.

A new migration adds scheduler_leases, and CronRegistrarService now runs
every registered tick through SchedulerLeasesRepository.acquire: one
conditional UPDATE moves the job's row to this process when it is free
(no holder, a lapsed holder, or this process already), so exactly one
process wins. A running tick renews its lease every 20 seconds, a crashed
holder frees the job after a minute, and a finished tick keeps the lease
for 30 seconds so a peer whose timer fires late does not run the same
tick again. The per-row reminder claims stay as they are; jobs need no
change of their own.
This commit is contained in:
Maurice
2026-10-08 15:39:24 +02:00
parent 8632f93c37
commit c5bc6798a9
11 changed files with 319 additions and 11 deletions
+5 -4
View File
@@ -26,17 +26,18 @@ describe('ALL_ENTITIES', () => {
});
/**
* Plan 2 Task 3: every one of the 130 entities the migrated schema
* Plan 2 Task 3: every one of the 131 entities the migrated schema
* describes (120 rewritten + the 5 document-sync tables added this task,
* + push_subscriptions and google_api_usage from legacy steps 245 and 254,
* + tour_types, tours and tour_waypoints from the Tours migration)
* + tour_types, tours and tour_waypoints from the Tours migration,
* + scheduler_leases from the cron lease migration)
* is registered, and no two share a class name (a silent duplicate would
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
* which de-duplicates by class name).
*/
it('ENT-003: exactly 130 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(130);
it('ENT-003: exactly 131 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(131);
const names = ALL_ENTITIES.map((s) => s.meta.className);
expect(new Set(names).size).toBe(names.length);
});
@@ -14,7 +14,7 @@ import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
* `scripts/generate-entities.ts`'s `RULE1d_fixNaNNumericDefaults` and
* `tests/unit/db/generate-entities.test.ts`'s `RULE1D-*` fixture tests for
* the mechanism). This file pins the OUTPUT of that rule against the real,
* committed entities — every one of the 130, not a sample — and reproduces
* committed entities — every one of the 131, not a sample — and reproduces
* the reviewer's own insert probe so a future regenerate/hand-edit that
* reintroduces a `NaN` initialiser fails loudly here, not silently at a
* caller's first `em.create()`.
@@ -22,10 +22,11 @@ import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
/** NOT NULL scalars with neither a column default nor a class-field initialiser (legitimate: the caller must supply them). */
// 424 + push_subscriptions (legacy step 245): id, user_id, endpoint, p256dh, auth, vapid_public_key.
// + Tours: tour_types label_key, icon, color; tours.tour_type; tour_waypoints id, place_id, lat, lng, role, sequence.
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 440;
// + scheduler_leases: name, owner, expires_at (the scheduler always writes all three).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 443;
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 130 entities', () => {
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 131 entities', () => {
const failures: string[] = [];
for (const schema of ALL_ENTITIES) {
const Ctor = schema.class as new () => Record<string, unknown>;
@@ -36,6 +36,7 @@ const UNNUMBERED = [
'Migration20200101042200_an_index_on_every_foreign_key',
'Migration20200101042300_every_tour_type_the_contract_names',
'Migration20200101042400_one_account_per_email_whatever_its_case',
'Migration20200101042500_a_cron_tick_runs_in_one_process',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -0,0 +1,67 @@
/**
* SchedulerLeasesRepository: the lease a cron tick takes so that two
* processes on one database never run the same tick. LEASE-001 through
* LEASE-006.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { SchedulerLeases } from '../../../../src/db/entities/SchedulerLeases.entity';
import type { SchedulerLeasesRepository } from '../../../../src/db/repositories/SchedulerLeases.repository';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let leases: SchedulerLeasesRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
leases = t.repo(SchedulerLeases);
});
beforeEach(() => {
testDb.prepare('DELETE FROM scheduler_leases').run();
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('SchedulerLeasesRepository.acquire', () => {
it('LEASE-001: the first process to ask takes a lease nobody holds', async () => {
expect(await leases.acquire('docsync', 'a', 1_000, 61_000)).toBe(true);
expect(await leases.holder('docsync')).toEqual({ owner: 'a', expires_at: 61_000 });
});
it('LEASE-002: a second process is refused while the lease runs, and the holder is untouched', async () => {
await leases.acquire('docsync', 'a', 1_000, 61_000);
expect(await leases.acquire('docsync', 'b', 2_000, 62_000)).toBe(false);
expect(await leases.holder('docsync')).toEqual({ owner: 'a', expires_at: 61_000 });
});
it('LEASE-003: the holder renews its own lease before it runs out', async () => {
await leases.acquire('docsync', 'a', 1_000, 61_000);
expect(await leases.acquire('docsync', 'a', 2_000, 62_000)).toBe(true);
expect(await leases.holder('docsync')).toEqual({ owner: 'a', expires_at: 62_000 });
});
it('LEASE-004: an expired lease goes to whoever asks next', async () => {
await leases.acquire('docsync', 'a', 1_000, 61_000);
expect(await leases.acquire('docsync', 'b', 61_000, 121_000)).toBe(true);
expect(await leases.holder('docsync')).toEqual({ owner: 'b', expires_at: 121_000 });
});
it('LEASE-005: leases are per job', async () => {
await leases.acquire('docsync', 'a', 1_000, 61_000);
expect(await leases.acquire('auto-backup', 'b', 1_000, 61_000)).toBe(true);
});
});
describe('SchedulerLeasesRepository.extend', () => {
it('LEASE-006: only the holder moves the expiry', async () => {
await leases.acquire('docsync', 'a', 1_000, 61_000);
expect(await leases.extend('docsync', 'b', 99_000)).toBe(false);
expect(await leases.extend('docsync', 'a', 91_000)).toBe(true);
expect(await leases.holder('docsync')).toEqual({ owner: 'a', expires_at: 91_000 });
expect(await leases.holder('never-ran')).toBeNull();
});
});
@@ -51,7 +51,13 @@ vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
}));
import { SchedulerRegistry } from '@nestjs/schedule';
import { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
import {
CronRegistrarService,
LEASE_HEARTBEAT_MS,
LEASE_OWNER,
LEASE_SETTLE_MS,
LEASE_TTL_MS,
} from '../../../src/nest/scheduling/cron-registrar.service';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
@@ -278,6 +284,95 @@ describe('CronRegistrarService', () => {
});
});
describe('the lease (one process per tick)', () => {
const testDb = createSnapshotTestDb();
let t: TestOrm;
beforeEach(async () => {
t = await createTestOrm(testDb, { allowGlobalContext: false });
});
afterEach(async () => {
vi.useRealTimers();
await t.close();
});
const holder = (name: string) =>
testDb.prepare('SELECT owner, expires_at FROM scheduler_leases WHERE name = ?').get(name) as
| { owner: string; expires_at: number }
| undefined;
it('CRONREG-017: a tick another process holds does not run here', async () => {
const name = 'lease-held-elsewhere';
testDb
.prepare('INSERT INTO scheduler_leases (name, owner, expires_at) VALUES (?, ?, ?)')
.run(name, 'other-host:1:peer', Date.now() + 60_000);
const registrar = new CronRegistrarService(new SchedulerRegistry(), { isTest: () => false } as RuntimeEnvService, t.orm);
let ran = false;
registrar.register(name, '* * * * *', () => {
ran = true;
});
await h.jobs[0].onTick();
expect(ran).toBe(false);
expect(holder(name)!.owner).toBe('other-host:1:peer');
});
it('CRONREG-018: a lapsed lease is taken over, and held for the settle window after the tick', async () => {
const name = 'lease-lapsed';
testDb
.prepare('INSERT INTO scheduler_leases (name, owner, expires_at) VALUES (?, ?, ?)')
.run(name, 'crashed-host:9:gone', Date.now() - 1);
const registrar = new CronRegistrarService(new SchedulerRegistry(), { isTest: () => false } as RuntimeEnvService, t.orm);
let ran = false;
registrar.register(name, '* * * * *', () => {
ran = true;
});
const before = Date.now();
await h.jobs[0].onTick();
expect(ran).toBe(true);
const row = holder(name)!;
expect(row.owner).toBe(LEASE_OWNER);
expect(row.expires_at).toBeGreaterThanOrEqual(before + LEASE_SETTLE_MS);
expect(row.expires_at).toBeLessThan(before + LEASE_TTL_MS);
});
it('CRONREG-019: this process runs its own next tick even while it still holds the lease', async () => {
const name = 'lease-own-next-tick';
const registrar = new CronRegistrarService(new SchedulerRegistry(), { isTest: () => false } as RuntimeEnvService, t.orm);
let runs = 0;
registrar.register(name, '* * * * *', () => {
runs++;
});
await h.jobs[0].onTick();
await h.jobs[0].onTick();
expect(runs).toBe(2);
});
it('CRONREG-020: a long tick renews its lease while it runs', async () => {
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
const name = 'lease-long-tick';
const registrar = new CronRegistrarService(new SchedulerRegistry(), { isTest: () => false } as RuntimeEnvService, t.orm);
let finish!: () => void;
let started!: () => void;
const running = new Promise<void>((resolve) => {
started = resolve;
});
registrar.register(name, '* * * * *', () => {
started();
return new Promise<void>((resolve) => {
finish = resolve;
});
});
const tick = h.jobs[0].onTick();
await running;
testDb.prepare('UPDATE scheduler_leases SET expires_at = 1 WHERE name = ?').run(name);
vi.advanceTimersByTime(LEASE_HEARTBEAT_MS);
await vi.waitFor(() => expect(holder(name)!.expires_at).toBeGreaterThan(Date.now()));
finish();
await tick;
});
});
describe('runOnBoot (task-6-fix-brief.md item 7 — the boot-sweep choke point)', () => {
const testDb = createSnapshotTestDb();
let t: TestOrm;