Move query retention beside the queue backend #78
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@hledger-reports/worker': patch
|
||||
---
|
||||
|
||||
Keep query retention SQL beside the queue backend. The worker still schedules and runs retention with the same deletion rules.
|
||||
@@ -8,9 +8,8 @@ import {
|
||||
generateSavedReport
|
||||
} from '@hledger-reports/hledger';
|
||||
import { createReportStage } from '@hledger-reports/snapshots';
|
||||
import { openJobsClient, type JobsClient } from '@hledger-reports/jobs';
|
||||
import { openJobsClient, purgeExpiredQueryRunBatch, type JobsClient } from '@hledger-reports/jobs';
|
||||
import { startWorker } from './index.js';
|
||||
import { purgeExpiredQueryRuns } from './workflows/query-retention/run.js';
|
||||
import { createPrepareReports } from './workflows/prepare-reports/run.js';
|
||||
|
||||
const { retentionMinute } = vi.hoisted(() => ({
|
||||
@@ -21,15 +20,6 @@ vi.mock('node:http', async (original) => ({
|
||||
createServer: vi.fn()
|
||||
}));
|
||||
vi.mock('./workflows/prepare-reports/run.js', () => ({ createPrepareReports: vi.fn() }));
|
||||
vi.mock('./workflows/query-retention/run.js', () => {
|
||||
const purgeExpiredQueryRuns = vi.fn();
|
||||
return {
|
||||
purgeExpiredQueryRuns,
|
||||
createQueryRetention: (directory: string) => () => ({
|
||||
deleted: purgeExpiredQueryRuns(directory)
|
||||
})
|
||||
};
|
||||
});
|
||||
vi.mock('node:crypto', async (original) => ({
|
||||
...(await original<typeof import('node:crypto')>()),
|
||||
randomInt: retentionMinute
|
||||
@@ -49,7 +39,8 @@ vi.mock('@hledger-reports/hledger', async (original) => ({
|
||||
vi.mock('@hledger-reports/snapshots', () => ({ createReportStage: vi.fn() }));
|
||||
vi.mock('@hledger-reports/jobs', async (original) => ({
|
||||
...(await original<typeof import('@hledger-reports/jobs')>()),
|
||||
openJobsClient: vi.fn()
|
||||
openJobsClient: vi.fn(),
|
||||
purgeExpiredQueryRunBatch: vi.fn()
|
||||
}));
|
||||
|
||||
type Handler = (context: {
|
||||
@@ -152,7 +143,7 @@ it('loads config and version before registering work, fixes concurrency at one,
|
||||
expect(createReportStage).not.toHaveBeenCalled();
|
||||
expect(runCostBalance).not.toHaveBeenCalled();
|
||||
expect(runHoldings).not.toHaveBeenCalled();
|
||||
expect(purgeExpiredQueryRuns).not.toHaveBeenCalled();
|
||||
expect(purgeExpiredQueryRunBatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drains the worker before closing health and client; concurrent shutdown is idempotent', async () => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
retiredBalanceQuerySpec,
|
||||
liveBalanceQuerySpec,
|
||||
queryRetentionSpec,
|
||||
purgeExpiredQueryRunBatch,
|
||||
holdingsSpec,
|
||||
prepareReportsSpec,
|
||||
retiredIncomePreparationSpec,
|
||||
@@ -12,22 +13,16 @@ import {
|
||||
} from '@hledger-reports/jobs';
|
||||
import { registerWorkflows } from './index.js';
|
||||
import { createPrepareReports } from './prepare-reports/run.js';
|
||||
import { purgeExpiredQueryRuns } from './query-retention/run.js';
|
||||
const { retentionMinute } = vi.hoisted(() => ({ retentionMinute: vi.fn() }));
|
||||
vi.mock('node:crypto', async (original) => ({
|
||||
...(await original<typeof import('node:crypto')>()),
|
||||
randomInt: retentionMinute
|
||||
}));
|
||||
vi.mock('./prepare-reports/run.js', () => ({ createPrepareReports: vi.fn() }));
|
||||
vi.mock('./query-retention/run.js', () => {
|
||||
const purgeExpiredQueryRuns = vi.fn();
|
||||
return {
|
||||
purgeExpiredQueryRuns,
|
||||
createQueryRetention: (directory: string) => () => ({
|
||||
deleted: purgeExpiredQueryRuns(directory)
|
||||
})
|
||||
};
|
||||
});
|
||||
vi.mock('@hledger-reports/jobs', async (original) => ({
|
||||
...(await original<typeof import('@hledger-reports/jobs')>()),
|
||||
purgeExpiredQueryRunBatch: vi.fn()
|
||||
}));
|
||||
vi.mock('@hledger-reports/hledger', async (original) => ({
|
||||
...(await original<typeof import('@hledger-reports/hledger')>()),
|
||||
runCostBalance: vi.fn(),
|
||||
@@ -103,9 +98,9 @@ it('registers SDK retention and returns only a deleted count', async () => {
|
||||
schedules: [{ cron: '17 0 * * *', timezone: 'UTC' }]
|
||||
});
|
||||
expect(retentionMinute).toHaveBeenCalledExactlyOnceWith(1, 60);
|
||||
vi.mocked(purgeExpiredQueryRuns).mockReturnValue(4);
|
||||
vi.mocked(purgeExpiredQueryRunBatch).mockReturnValue(4);
|
||||
expect(await registration).toEqual({ deleted: 4 });
|
||||
expect(purgeExpiredQueryRuns).toHaveBeenCalledExactlyOnceWith('/deployment/data/jobs');
|
||||
expect(purgeExpiredQueryRunBatch).toHaveBeenCalledExactlyOnceWith('/deployment/data/jobs');
|
||||
expect(runCostBalance).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,61 +1,5 @@
|
||||
import type { QueryRetentionWorkflow } from '@hledger-reports/jobs';
|
||||
import { statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
const retentionMs = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
// Temporary SDK-table access: https://github.com/openworkflowdev/openworkflow/issues/303
|
||||
const deleteExpiredStandaloneQueryRuns = `
|
||||
DELETE FROM workflow_runs
|
||||
WHERE namespace_id = 'default' AND id IN (
|
||||
SELECT r.id FROM workflow_runs r
|
||||
WHERE r.namespace_id = 'default'
|
||||
AND r.workflow_name = 'hledger.balance-query'
|
||||
AND r.version IN ('1', '2')
|
||||
AND r.status IN ('completed', 'succeeded', 'failed', 'canceled')
|
||||
AND r.finished_at IS NOT NULL
|
||||
AND r.finished_at < ?
|
||||
AND r.idempotency_key IS NULL
|
||||
AND r.workflow_schedule_id IS NULL
|
||||
AND r.parent_step_attempt_namespace_id IS NULL
|
||||
AND r.parent_step_attempt_id IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM step_attempts s
|
||||
WHERE s.namespace_id = r.namespace_id AND s.workflow_run_id = r.id
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM step_attempts s
|
||||
WHERE s.child_workflow_run_namespace_id = r.namespace_id
|
||||
AND s.child_workflow_run_id = r.id
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM workflow_signals s
|
||||
WHERE s.namespace_id = r.namespace_id AND s.workflow_run_id = r.id
|
||||
)
|
||||
ORDER BY r.finished_at, r.id
|
||||
LIMIT 100
|
||||
)
|
||||
`;
|
||||
|
||||
export function purgeExpiredQueryRuns(jobsDirectory: string, now: Date = new Date()): number {
|
||||
try {
|
||||
const cutoff = new Date(now.getTime() - retentionMs).toISOString();
|
||||
const database = join(jobsDirectory, 'queue.sqlite');
|
||||
// DatabaseSync creates missing files; retention must not.
|
||||
if (!statSync(database).isFile()) throw new Error();
|
||||
const db = new DatabaseSync(database);
|
||||
try {
|
||||
db.exec('PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 1000;');
|
||||
return Number(db.prepare(deleteExpiredStandaloneQueryRuns).run(cutoff).changes);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
} catch {
|
||||
throw new Error('Query job retention could not be completed.');
|
||||
}
|
||||
}
|
||||
import { purgeExpiredQueryRunBatch, type QueryRetentionWorkflow } from '@hledger-reports/jobs';
|
||||
|
||||
export function createQueryRetention(jobsDirectory: string): QueryRetentionWorkflow {
|
||||
return () => ({ deleted: purgeExpiredQueryRuns(jobsDirectory) });
|
||||
return () => ({ deleted: purgeExpiredQueryRunBatch(jobsDirectory) });
|
||||
}
|
||||
@@ -2,3 +2,6 @@
|
||||
|
||||
Shared job contracts and queue connections for web and worker. Web owns requesting
|
||||
work; worker owns execution. The queue contains private financial inputs and results.
|
||||
|
||||
`src/queue/query-retention.ts` deletes up to 100 eligible expired standalone
|
||||
balance-query runs per invocation, oldest first. The worker owns the schedule.
|
||||
@@ -22,3 +22,4 @@ export {
|
||||
export type { HoldingsJobErrorCode, HoldingsRequest } from './holdings.js';
|
||||
export { openJobsClient } from './queue/client.js';
|
||||
export type { JobsClient } from './queue/client.js';
|
||||
export { purgeExpiredQueryRunBatch } from './queue/query-retention.js';
|
||||
@@ -10,6 +10,10 @@ export interface JobsClient {
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export function databasePath(jobsDirectory: string): string {
|
||||
return join(jobsDirectory, 'queue.sqlite');
|
||||
}
|
||||
|
||||
/** One migrated SQLite backend per caller; stop any worker before closing. */
|
||||
export async function openJobsClient(jobsDirectory: string): Promise<JobsClient> {
|
||||
let backend: BackendSqlite | undefined;
|
||||
@@ -17,7 +21,7 @@ export async function openJobsClient(jobsDirectory: string): Promise<JobsClient>
|
||||
const directory = resolve(jobsDirectory);
|
||||
await mkdir(directory, { recursive: true, mode: 0o700 });
|
||||
await chmod(directory, 0o700);
|
||||
const database = join(directory, 'queue.sqlite');
|
||||
const database = databasePath(directory);
|
||||
// Precreation makes SQLite (and its WAL/SHM) private from the start.
|
||||
const file = await open(database, 'a', 0o600);
|
||||
await file.close();
|
||||
|
||||
+36
-23
@@ -4,7 +4,7 @@ import { join } from 'node:path';
|
||||
import { DatabaseSync, type SQLInputValue } from 'node:sqlite';
|
||||
import { BackendSqlite } from 'openworkflow/sqlite';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { purgeExpiredQueryRuns } from './run.js';
|
||||
import { purgeExpiredQueryRunBatch as purge } from './query-retention.js';
|
||||
|
||||
const now = new Date('2026-05-15T00:00:00.000Z');
|
||||
const cutoff = '2026-05-08T00:00:00.000Z';
|
||||
@@ -89,7 +89,7 @@ it('uses finished_at strictly before seven days, for both query versions and ter
|
||||
input: JSON.stringify({ query: 'type:X', asOf: '2000-01-01' })
|
||||
})
|
||||
);
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(8);
|
||||
expect(purge(path, now)).toBe(8);
|
||||
expect(
|
||||
db
|
||||
.prepare('SELECT id FROM workflow_runs')
|
||||
@@ -97,7 +97,7 @@ it('uses finished_at strictly before seven days, for both query versions and ter
|
||||
.map((row) => row.id)
|
||||
.sort()
|
||||
).toEqual(preserved.sort());
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(0);
|
||||
expect(purge(path, now)).toBe(0);
|
||||
});
|
||||
|
||||
it('preserves all non-standalone records, namespaces, keys, versions, and unknown/inflight statuses without touching graphs', async () => {
|
||||
@@ -133,17 +133,30 @@ it('preserves all non-standalone records, namespaces, keys, versions, and unknow
|
||||
).run(signaled, expired);
|
||||
const before = snapshot();
|
||||
await create();
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(1);
|
||||
expect(purge(path, now)).toBe(1);
|
||||
expect(snapshot()).toEqual(before);
|
||||
expect(db.prepare('PRAGMA foreign_key_check').all()).toEqual([]);
|
||||
});
|
||||
|
||||
it('caps each invocation at 100 deletions, leaves the rest for later calls, and is idempotent', async () => {
|
||||
const { path, create } = await setup();
|
||||
for (let i = 0; i < 105; i++) await create();
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(100);
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(5);
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(0);
|
||||
it('deletes the 100 oldest eligible runs, breaks a boundary tie by ID, and leaves the rest for later calls', async () => {
|
||||
const { path, db, create } = await setup();
|
||||
const newer: string[] = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
newer.push(await create({ finished_at: expired }));
|
||||
}
|
||||
const tiedRun = { finished_at: '2026-05-06T00:00:00.000Z' };
|
||||
const setId = db.prepare('UPDATE workflow_runs SET id = ? WHERE id = ?');
|
||||
const higherTieId = 'tie-z';
|
||||
setId.run(higherTieId, await create(tiedRun));
|
||||
for (let i = 0; i < 99; i++) await create({ finished_at: '2026-05-05T00:00:00.000Z' });
|
||||
// Insert the lower ID last so insertion order and ID order disagree.
|
||||
setId.run('tie-a', await create(tiedRun));
|
||||
|
||||
expect(purge(path, now)).toBe(100);
|
||||
const remaining = db.prepare('SELECT id FROM workflow_runs ORDER BY id').all();
|
||||
expect(remaining.map(({ id }) => id)).toEqual([...newer, higherTieId].sort());
|
||||
expect(purge(path, now)).toBe(5);
|
||||
expect(purge(path, now)).toBe(0);
|
||||
});
|
||||
|
||||
it('calculates the default cutoff at execution, including the exact boundary', async () => {
|
||||
@@ -151,9 +164,9 @@ it('calculates the default cutoff at execution, including the exact boundary', a
|
||||
await create({ finished_at: cutoff });
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(now);
|
||||
expect(purgeExpiredQueryRuns(path)).toBe(0);
|
||||
expect(purge(path)).toBe(0);
|
||||
vi.setSystemTime(new Date(now.getTime() + 1));
|
||||
expect(purgeExpiredQueryRuns(path)).toBe(1);
|
||||
expect(purge(path)).toBe(1);
|
||||
});
|
||||
|
||||
it('rolls back failed deletes and exposes only a constant error without a cause', async () => {
|
||||
@@ -166,7 +179,7 @@ it('rolls back failed deletes and exposes only a constant error without a cause'
|
||||
END`);
|
||||
let failure: unknown;
|
||||
try {
|
||||
purgeExpiredQueryRuns(path, now);
|
||||
purge(path, now);
|
||||
} catch (error) {
|
||||
failure = error;
|
||||
}
|
||||
@@ -176,7 +189,7 @@ it('rolls back failed deletes and exposes only a constant error without a cause'
|
||||
expect(String(failure)).not.toMatch(/PRIVATE|journal|financial/);
|
||||
expect(snapshot()).toEqual(before);
|
||||
db.exec('DROP TRIGGER fail_retention');
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(2);
|
||||
expect(purge(path, now)).toBe(2);
|
||||
});
|
||||
|
||||
it('enforces foreign keys on its own connection and rolls back unsafe trigger side effects', async () => {
|
||||
@@ -188,10 +201,10 @@ it('enforces foreign keys on its own connection and rolls back unsafe trigger si
|
||||
namespace_id, id, workflow_run_id, step_name, kind, status, config, created_at, updated_at
|
||||
) VALUES ('default', 'orphan', 'missing-run', 'legacy', 'function', 'completed', '{}', '', '');
|
||||
END`);
|
||||
expect(() => purgeExpiredQueryRuns(path, now)).toThrow(safeMessage);
|
||||
expect(() => purge(path, now)).toThrow(safeMessage);
|
||||
expect(snapshot()).toEqual(before);
|
||||
db.exec('DROP TRIGGER unsafe_reference');
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(1);
|
||||
expect(purge(path, now)).toBe(1);
|
||||
});
|
||||
|
||||
it('bounds writer-lock contention to one second, fails safely, and releases its connection', async () => {
|
||||
@@ -200,27 +213,27 @@ it('bounds writer-lock contention to one second, fails safely, and releases its
|
||||
db.exec('BEGIN IMMEDIATE');
|
||||
const start = performance.now();
|
||||
try {
|
||||
expect(() => purgeExpiredQueryRuns(path, now)).toThrow(safeMessage);
|
||||
expect(() => purge(path, now)).toThrow(safeMessage);
|
||||
const elapsed = performance.now() - start;
|
||||
expect(elapsed).toBeGreaterThanOrEqual(900);
|
||||
expect(elapsed).toBeLessThan(4000);
|
||||
} finally {
|
||||
db.exec('ROLLBACK');
|
||||
}
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(1);
|
||||
expect(purge(path, now)).toBe(1);
|
||||
});
|
||||
|
||||
it('does not create missing queues, open non-files, or migrate unknown schemas', async () => {
|
||||
const path = await directory();
|
||||
expect(() => purgeExpiredQueryRuns(path, now)).toThrow(safeMessage);
|
||||
expect(() => purge(path, now)).toThrow(safeMessage);
|
||||
expect(await readdir(path)).toEqual([]);
|
||||
await mkdir(join(path, 'queue.sqlite'));
|
||||
expect(() => purgeExpiredQueryRuns(path, now)).toThrow(safeMessage);
|
||||
expect(() => purge(path, now)).toThrow(safeMessage);
|
||||
expect(await readdir(join(path, 'queue.sqlite'))).toEqual([]);
|
||||
await rm(join(path, 'queue.sqlite'), { recursive: true });
|
||||
const empty = new DatabaseSync(join(path, 'queue.sqlite'));
|
||||
empty.close();
|
||||
expect(() => purgeExpiredQueryRuns(path, now)).toThrow(safeMessage);
|
||||
expect(() => purge(path, now)).toThrow(safeMessage);
|
||||
const check = new DatabaseSync(join(path, 'queue.sqlite'));
|
||||
try {
|
||||
expect(check.prepare('SELECT name FROM sqlite_master').all()).toEqual([]);
|
||||
@@ -241,7 +254,7 @@ it('leaves private journal/legacy files untouched and a live SDK connection usab
|
||||
expect(claimed?.id).toBe(running);
|
||||
const files = ['journal', 'current.json', 'legacy-result.json', 'input.json'];
|
||||
for (const name of files) await writeFile(join(path, name), `PRIVATE ${name}`, { mode: 0o600 });
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(1);
|
||||
expect(purge(path, now)).toBe(1);
|
||||
for (const name of files)
|
||||
expect(await readFile(join(path, name), 'utf8')).toBe(`PRIVATE ${name}`);
|
||||
expect((await backend.getWorkflowRun({ workflowRunId: recent }))?.status).toBe('completed');
|
||||
@@ -254,5 +267,5 @@ it('leaves private journal/legacy files untouched and a live SDK connection usab
|
||||
expect(completed.status).toBe('completed');
|
||||
expect(completed.version).toBe('2');
|
||||
await create({ status: 'pending', finished_at: null });
|
||||
expect(purgeExpiredQueryRuns(path, now)).toBe(0);
|
||||
expect(purge(path, now)).toBe(0);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { statSync } from 'node:fs';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { databasePath } from './client.js';
|
||||
|
||||
const retentionMs = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
// Temporary SDK-table access: https://github.com/openworkflowdev/openworkflow/issues/303
|
||||
const deleteExpiredStandaloneQueryRuns = `
|
||||
DELETE FROM workflow_runs
|
||||
WHERE namespace_id = 'default' AND id IN (
|
||||
SELECT r.id FROM workflow_runs r
|
||||
WHERE r.namespace_id = 'default'
|
||||
AND r.workflow_name = 'hledger.balance-query'
|
||||
AND r.version IN ('1', '2')
|
||||
AND r.status IN ('completed', 'succeeded', 'failed', 'canceled')
|
||||
AND r.finished_at IS NOT NULL
|
||||
AND r.finished_at < ?
|
||||
AND r.idempotency_key IS NULL
|
||||
AND r.workflow_schedule_id IS NULL
|
||||
AND r.parent_step_attempt_namespace_id IS NULL
|
||||
AND r.parent_step_attempt_id IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM step_attempts s
|
||||
WHERE s.namespace_id = r.namespace_id AND s.workflow_run_id = r.id
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM step_attempts s
|
||||
WHERE s.child_workflow_run_namespace_id = r.namespace_id
|
||||
AND s.child_workflow_run_id = r.id
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM workflow_signals s
|
||||
WHERE s.namespace_id = r.namespace_id AND s.workflow_run_id = r.id
|
||||
)
|
||||
ORDER BY r.finished_at, r.id
|
||||
LIMIT 100
|
||||
)
|
||||
`;
|
||||
|
||||
/** Delete up to 100 eligible expired standalone balance-query runs, oldest first. */
|
||||
export function purgeExpiredQueryRunBatch(jobsDirectory: string, now: Date = new Date()): number {
|
||||
try {
|
||||
const cutoff = new Date(now.getTime() - retentionMs).toISOString();
|
||||
const database = databasePath(jobsDirectory);
|
||||
// Retention does not initialize an absent queue.
|
||||
if (!statSync(database).isFile()) throw new Error();
|
||||
const db = new DatabaseSync(database);
|
||||
try {
|
||||
db.exec('PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 1000;');
|
||||
return Number(db.prepare(deleteExpiredStandaloneQueryRuns).run(cutoff).changes);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
} catch {
|
||||
throw new Error('Query job retention could not be completed.');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user