perf(cron): share global concurrency budget and streamline execution

Share durable permits across manual, scheduled and recovered runs, prioritize
short ready tasks with aging, and record global queue occupancy.

Reduce launch, log polling, dashboard and SQLite overhead while preserving
transactional receipts, cancellation, recovery and script hook compatibility.
Keep ordinary CRUD in ORM and bound SQL on measured execution hot paths.

Fix supervisor descendant tracking, asynchronous log draining, concurrent log
directory creation, Linux fallback launches and snapshot clock rollback.
Include regression coverage, SQL audits and evolution/review documentation.

Validation: five review rounds; local full suite 1478 passed, 28 platform skips;
dev suites 415 passed, no failures/skips; backend types and formatting passed.
This commit is contained in:
whyour committed 2026-11-25 00:54:41 +08:00
1 parent cddabbaf0e
commit 2f01f756d7
74 files changed
+6891 -837

No files matched your search

+38 -29
View File
@@ -1,4 +1,6 @@
import { executionModel } from '../data/executionModels';
import config from '../config';
import { dashboardSnapshot } from '../shared/dashboardSnapshot';
import { stat } from 'fs/promises';
import { resolveFileAccess } from '../shared/fileAccess';
import { AnomalyPage, AnomalyKind } from '../cron/queries/scheduleAnomalies';
@@ -15,7 +17,7 @@ import { containerResources } from '../shared/containerResources';
import { TriggerHistory } from '../cron/history';
import { Router, Request, Response, NextFunction } from 'express';
import { Container } from 'typedi';
import { fn, col, where, Op, QueryTypes } from 'sequelize';
import { fn, col, where, Op } from 'sequelize';
import { CrontabModel } from '../data/cron';
import { CrontabStatModel } from '../data/cronStats';
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
@@ -96,26 +98,33 @@ export default (app: Router) => {
const day = dayjs(serverNow).startOf('day');
const today = day.format('YYYY-MM-DD');
const [total, enabled, disabled, stats, triggers] = await Promise.all([
CrontabModel.count(),
CrontabModel.count({ where: { isDisabled: 0 } }),
CrontabModel.count({ where: { isDisabled: 1 } }),
CrontabStatModel.findOne({
attributes: [
[fn('SUM', col('run_count')), 'total_runs'],
[fn('SUM', col('success_count')), 'total_success'],
[fn('SUM', col('fail_count')), 'total_fail'],
[fn('SUM', col('untimed_count')), 'untimed_count'],
[fn('SUM', col('total_time')), 'total_time'],
],
where: { date: today },
raw: true,
const snapshot = await dashboardSnapshot(
CrontabStatModel.sequelize!,
today,
async () => ({
sampledAt: Date.now(),
values: await Promise.all([
CrontabModel.count(),
CrontabModel.count({ where: { isDisabled: 0 } }),
CrontabModel.count({ where: { isDisabled: 1 } }),
CrontabStatModel.findOne({
attributes: [
[fn('SUM', col('run_count')), 'total_runs'],
[fn('SUM', col('success_count')), 'total_success'],
[fn('SUM', col('fail_count')), 'total_fail'],
[fn('SUM', col('untimed_count')), 'untimed_count'],
[fn('SUM', col('total_time')), 'total_time'],
],
where: { date: today },
raw: true,
}),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(
day.valueOf(),
),
]),
}),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(
day.valueOf(),
),
]);
);
const [total, enabled, disabled, stats, triggers] = snapshot.values;
const row = stats as any;
const totalRuns = Number(row?.total_runs) || 0;
const totalSuccess = Number(row?.total_success) || 0;
@@ -126,6 +135,7 @@ export default (app: Router) => {
code: 200,
data: {
serverNow,
sampledAt: snapshot.sampledAt,
expiresAt: day.add(1, 'day').valueOf(),
total,
enabled,
@@ -176,10 +186,10 @@ export default (app: Router) => {
)
return res.status(400).send({ code: 400 });
const [snapshotRetention] = live
? await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
'SELECT cutoff FROM CronHistoryRetention WHERE id=1',
{ type: QueryTypes.SELECT },
)
? await executionModel(
CrontabStatModel.sequelize!,
'CronHistoryRetention',
).findAll({ attributes: ['cutoff'], where: { id: 1 }, raw: true })
: [];
const details = new AnomalyPage(
kind as AnomalyKind,
@@ -228,11 +238,10 @@ export default (app: Router) => {
// Log checks can yield after the audit transaction. Do not publish that
// snapshot if history cleanup has since removed part of its plan window.
if (live) {
const [retention] = await CrontabStatModel.sequelize!.query<{
cutoff: number;
}>('SELECT cutoff FROM CronHistoryRetention WHERE id=1', {
type: QueryTypes.SELECT,
});
const [retention] = await executionModel(
CrontabStatModel.sequelize!,
'CronHistoryRetention',
).findAll({ attributes: ['cutoff'], where: { id: 1 }, raw: true });
if (retention && retention.cutoff > (snapshotRetention?.cutoff ?? 0))
return res.send({ code: 200, data: { status: 'unavailable' } });
}
+39 -8
View File
@@ -1,8 +1,10 @@
import { executionModel } from '../data/executionModels';
import { storageFull, writeExit } from '../cron/settlement/exitReceipt.cjs';
import { QueryTypes } from 'sequelize';
import { randomUUID } from 'crypto';
import { sequelize } from '../data';
import { systemOwner, TriggerHistory } from '../cron/history';
import { globalCronBudget } from '../cron/execution/globalCronBudget';
async function receipt() {
const [action, task, pid, id, status, end] = process.argv.slice(2);
@@ -23,15 +25,35 @@ async function receipt() {
rule && Number.isSafeInteger(at) && at > 0 && at <= Date.now()
? { rule, at, dispatch }
: undefined;
const acquired = await history.startSystem(
triggerId,
Number(task),
owner,
command,
wrapper,
const queued = await sequelize.query(
`INSERT INTO CronTriggers(id,cron_id,source,state,owner,queued_at,observed_at)
VALUES ($id,$cronId,'system','queued',$owner,$now,$now) ON CONFLICT(id) DO NOTHING`,
{
bind: { id: triggerId, cronId: Number(task), owner, now: Date.now() },
type: QueryTypes.BULKUPDATE,
},
);
if (!acquired) process.exitCode = 75;
else if (!id) process.stdout.write(triggerId);
const budget = globalCronBudget(sequelize);
const token =
queued === 1 &&
(await budget.acquire(triggerId, {
owner,
commandIdentity: command,
current: () => systemOwner(Number(pid)) === owner,
}));
const acquired =
token &&
(await history.startSystem(
triggerId,
Number(task),
owner,
command,
wrapper,
));
if (!acquired) {
if (token) await budget.release(triggerId, token);
process.exitCode = 75;
} else if (!id) process.stdout.write(triggerId);
} else if (action === 'finish') {
// The live wrapper inherited both IDs from the start it just claimed. A
// standalone retry must match the registered system task before writing.
@@ -77,6 +99,15 @@ async function receipt() {
? undefined
: 'legacy',
);
const [lease] = await executionModel(
sequelize,
'CronConcurrencyLeases',
).findAll({
attributes: ['token'],
where: { trigger_id: id },
raw: true,
});
if (lease) await globalCronBudget(sequelize).release(id, lease.token);
} catch (error) {
if (!journaled || !storageFull(error)) throw error;
// The regular recovery pass will settle the receipt after space returns.
+19 -10
View File
@@ -43,17 +43,26 @@ async function probeUpgrade() {
try {
await loadDatabase();
// Exercise an actual on-disk transaction as well as schema initialization.
const { DataTypes } = await import('sequelize');
const probe = sequelize.define<
import('sequelize').Model<{ value: number }>
>(
'UpgradeProbe',
{ value: DataTypes.INTEGER },
{ tableName: 'upgrade_probe', timestamps: false },
);
probe.removeAttribute('id');
await sequelize.transaction(async (transaction) => {
await sequelize.query('CREATE TABLE upgrade_probe (value INTEGER)', {
transaction,
});
await sequelize.query('INSERT INTO upgrade_probe VALUES (42)', {
transaction,
});
const [rows] = await sequelize.query('SELECT value FROM upgrade_probe', {
transaction,
});
if ((rows[0] as { value: number })?.value !== 42)
await sequelize
.getQueryInterface()
.createTable(
'upgrade_probe',
{ value: DataTypes.INTEGER },
{ transaction },
);
await probe.create({ value: 42 }, { transaction });
const row = await probe.findOne({ attributes: ['value'], transaction });
if (row?.get('value') !== 42)
throw new Error('Upgrade database readback failed');
});
inject();
+205 -114
View File
@@ -1,4 +1,16 @@
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import {
executionModel,
executionAssociation,
} from '../../data/executionModels';
import {
QueryTypes,
Sequelize,
Transaction,
Op,
literal,
fn,
col,
} from 'sequelize';
import { createHash } from 'crypto';
import { executionIdPattern } from '../identity';
import {
@@ -113,17 +125,27 @@ export class LegacyClientAdapter {
},
);
}
await this.database.query(
`UPDATE CronTriggers SET log_path=COALESCE(log_path,$log) WHERE id=$id AND cron_id=$cronId`,
{ transaction, bind: { id, cronId, log } },
await executionModel(this.database, 'CronTriggers').update(
{ log_path: fn('COALESCE', col('log_path'), log) },
{
where: { id, cron_id: cronId },
transaction,
hooks: false,
validate: false,
},
);
if (!running) {
// For a managed command the wrapper may be only the first segment.
// Only its supervisor can report the whole command's exit.
const [legacy] = await this.database.query(
'SELECT 1 FROM CronTriggers WHERE id=$id AND cron_id=$cronId AND owner IS NULL',
{ transaction, type: QueryTypes.SELECT, bind: { id, cronId } },
);
const [legacy] = await executionModel(
this.database,
'CronTriggers',
).findAll({
attributes: ['id'],
where: { id, cron_id: cronId, owner: null },
transaction,
raw: true,
});
if (legacy) {
const state = stopped
? 'stopped'
@@ -185,13 +207,59 @@ export class LegacyClientAdapter {
.update(JSON.stringify([cronId, pid, seconds, log || null]))
.digest('hex');
// A verified child stays attached to its supervisor even after the OS recycles its PID.
const [bound] = await this.database.query(
'SELECT 1 FROM CronShellBindings WHERE receipt=$receipt',
{ transaction, type: QueryTypes.SELECT, bind: { receipt } },
);
const [bound] = await executionModel(
this.database,
'CronShellBindings',
).findAll({
attributes: ['receipt'],
where: { receipt },
transaction,
raw: true,
});
if (bound) return;
const rows = await this.database.query<{
const rows = (await executionModel(
this.database,
'RunningInstances',
).findAll({
attributes: [
[col('RunningInstance.id'), 'instance'],
'status',
'finished_at',
'exit_code',
'log_path',
[col('trigger.id'), 'id'],
[col('trigger.source'), 'source'],
],
include: [
{
association: executionAssociation(this.database, 'instanceTrigger'),
attributes: [],
required: false,
},
],
where: {
cron_id: cronId,
pid,
started_at: seconds,
[Op.and]: [
{
[Op.or]: [
{ '$trigger.id$': null },
{ '$trigger.source$': 'legacy' },
{ '$trigger.owner$': { [Op.not]: null } },
],
},
...(log
? [{ [Op.or]: [{ log_path: log }, { log_path: null }] }]
: []),
],
},
limit: 2,
subQuery: false,
transaction,
raw: true,
})) as unknown as Array<{
instance: number;
status: number;
finished_at: number | null;
@@ -199,29 +267,20 @@ export class LegacyClientAdapter {
id: string | null;
source: TriggerSource | null;
log_path: string | null;
}>(
`SELECT i.id AS instance,i.status,i.finished_at,i.exit_code,i.log_path,t.id,t.source FROM RunningInstances i
LEFT JOIN CronTriggers t ON t.instance_id=i.id WHERE i.cron_id=$cronId AND i.pid=$pid
AND (t.id IS NULL OR t.source='legacy' OR t.owner IS NOT NULL)
AND i.started_at=$seconds AND (i.log_path IS $log OR $log IS NULL OR i.log_path IS NULL) LIMIT 2`,
{
transaction,
type: QueryTypes.SELECT,
bind: { cronId, pid, seconds, log: log || null },
},
);
}>;
const [old] = rows;
if (rows.length > 1) return;
if (old) {
if (!old.id && old.status === 4) {
const [expired] = await this.database.query(
'SELECT 1 FROM CronHistoryRetention WHERE cutoff>$end',
{
transaction,
type: QueryTypes.SELECT,
bind: { end: (old.finished_at ?? seconds) * 1000 },
},
);
const [expired] = await executionModel(
this.database,
'CronHistoryRetention',
).findAll({
attributes: ['id'],
where: { cutoff: { [Op.gt]: (old.finished_at ?? seconds) * 1000 } },
transaction,
raw: true,
});
if (expired) return;
}
if (old.status !== 0 && old.status !== 4) {
@@ -285,21 +344,22 @@ export class LegacyClientAdapter {
);
if (prior) return;
identity = legacyProcessOwner(pid, seconds);
const roots = await this.database.query<{
id: string;
command_identity: string;
}>(
`SELECT id,command_identity FROM CronTriggers WHERE cron_id=$cronId AND state='running'
AND command_identity IS NOT NULL AND started_at < $end`,
const roots = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: ['id', 'command_identity'],
where: {
cron_id: cronId,
state: 'running',
command_identity: { [Op.not]: null },
started_at: { [Op.lt]: start + 1000 },
},
transaction,
type: QueryTypes.SELECT,
bind: { cronId, end: start + 1000 },
raw: true,
},
);
for (const root of roots) {
if (!identity) break;
const parent = Number(root.command_identity.split(':')[1]);
const parent = Number(root.command_identity!.split(':')[1]);
try {
if (
!isProcessDescendant(pid, parent) ||
@@ -313,9 +373,9 @@ export class LegacyClientAdapter {
continue;
throw error;
}
await this.database.query(
'INSERT INTO CronShellBindings(receipt,trigger_id) VALUES ($receipt,$id)',
{ transaction, bind: { receipt, id: root.id } },
await executionModel(this.database, 'CronShellBindings').create(
{ receipt, trigger_id: root.id },
{ transaction, silent: true, hooks: false, validate: false },
);
if (running)
await this.attachShellLog(root.id, cronId, log, transaction);
@@ -326,19 +386,30 @@ export class LegacyClientAdapter {
const id = old?.id ?? receipt;
if (!old?.id) {
// A later use of the same numeric PID proves the older process is gone.
const others = await this.database.query<{
id: string;
started_at: number;
}>(
`SELECT t.id,i.started_at FROM RunningInstances i LEFT JOIN CronTriggers t ON t.instance_id=i.id
WHERE i.cron_id=$cronId AND i.pid=$pid AND i.started_at<>$seconds
AND (i.started_at>$seconds OR (i.status=0 AND t.source='legacy'))`,
{
transaction,
type: QueryTypes.SELECT,
bind: { cronId, pid, seconds },
const others = (await executionModel(
this.database,
'RunningInstances',
).findAll({
attributes: [[col('trigger.id'), 'id'], 'started_at'],
include: [
{
association: executionAssociation(this.database, 'instanceTrigger'),
attributes: [],
required: false,
},
],
where: {
cron_id: cronId,
pid,
started_at: { [Op.ne]: seconds },
[Op.or]: [
{ started_at: { [Op.gt]: seconds } },
{ status: 0, '$trigger.source$': 'legacy' },
],
},
);
transaction,
raw: true,
})) as unknown as Array<{ id: string | null; started_at: number }>;
if (running && old) identity = legacyProcessOwner(pid, seconds);
const historical =
!running ||
@@ -347,46 +418,42 @@ export class LegacyClientAdapter {
let instance = old?.instance;
if (!instance) {
[instance] = await this.database.query(
`INSERT INTO RunningInstances(cron_id,pid,log_path,started_at,status,finished_at,createdAt,updatedAt)
VALUES ($cronId,$pid,$log,$seconds,$status,$finished,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`,
{
transaction,
type: QueryTypes.INSERT,
bind: {
cronId,
[instance] = await executionModel(this.database, 'RunningInstances')
.create(
{
cron_id: cronId,
pid,
log: log || null,
seconds,
log_path: log || null,
started_at: seconds,
status: historical ? 4 : 0,
finished: historical ? Math.floor(Date.now() / 1000) : null,
finished_at: historical ? Math.floor(Date.now() / 1000) : null,
createdAt: literal('CURRENT_TIMESTAMP'),
updatedAt: literal('CURRENT_TIMESTAMP'),
},
},
);
{ transaction, silent: true, hooks: false, validate: false },
)
.then((row) => [row.id] as const);
}
const unknown = historical || old?.status === 4;
await this.database.query(
`INSERT INTO CronTriggers
(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,log_path,process_identity,reason)
VALUES ($id,$cronId,'legacy',$state,$start,$start,$end,$instance,$log,$identity,$reason)`,
await executionModel(this.database, 'CronTriggers').create(
{
transaction,
bind: {
id,
cronId,
start,
instance,
log: old?.log_path ?? (log || null),
identity: !unknown && running ? identity ?? null : null,
reason: old && running && !unknown ? 'restart' : null,
state: unknown ? 'unknown' : 'running',
end: unknown
? old?.finished_at
? old.finished_at * 1000
: Date.now()
: null,
},
id,
cron_id: cronId,
source: 'legacy',
state: unknown ? 'unknown' : 'running',
observed_at: start,
started_at: start,
finished_at: unknown
? old?.finished_at
? old.finished_at * 1000
: Date.now()
: null,
instance_id: instance,
log_path: old?.log_path ?? (log || null),
process_identity: !unknown && running ? identity ?? null : null,
reason: old && running && !unknown ? 'restart' : null,
},
{ transaction, silent: true, hooks: false, validate: false },
);
await this.lifecycle.claimSummary(
cronId,
@@ -398,7 +465,7 @@ export class LegacyClientAdapter {
for (const other of others) {
if (other.started_at < seconds)
await this.settlement.completeInTransaction(
other.id,
other.id!,
'unknown',
null,
null,
@@ -441,9 +508,9 @@ export class LegacyClientAdapter {
{ transaction, type: QueryTypes.BULKUPDATE, bind: { id, cronId, log } },
);
if (attached) {
await this.database.query(
'UPDATE CronTriggers SET log_path=COALESCE(log_path,$log) WHERE id=$id',
{ transaction, bind: { id, log } },
await executionModel(this.database, 'CronTriggers').update(
{ log_path: fn('COALESCE', col('log_path'), log) },
{ where: { id }, transaction, hooks: false, validate: false },
);
await this.database.query(
`UPDATE Crontabs SET log_path=$log WHERE id=$cronId AND status=0 AND pid=(
@@ -484,15 +551,19 @@ export class LegacyClientAdapter {
finishedAt,
);
if (accepted === false) return;
const [row] = await this.database.query<{
state: TriggerState;
started_at: number | null;
instance_id: number | null;
command_identity: string | null;
owner: string | null;
}>(
'SELECT state,started_at,instance_id,command_identity,owner FROM CronTriggers WHERE id=$id AND cron_id=$cronId',
{ transaction, bind: { id, cronId }, type: QueryTypes.SELECT },
const [row] = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: [
'state',
'started_at',
'instance_id',
'command_identity',
'owner',
],
where: { id, cron_id: cronId },
transaction,
raw: true,
},
);
if (!row) return;
const startSeconds =
@@ -520,9 +591,15 @@ export class LegacyClientAdapter {
},
);
if (instance) {
await this.database.query(
'UPDATE CronTriggers SET instance_id=$instance WHERE id=$id',
{ transaction, bind: { instance, id } },
await executionModel(this.database, 'CronTriggers').update(
{ instance_id: instance },
{
where: { id },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
await this.lifecycle.claimSummary(
cronId,
@@ -547,19 +624,33 @@ export class LegacyClientAdapter {
/* A short child may have exited. */
}
}
const [instance] = await this.database.query(
`INSERT INTO RunningInstances(cron_id,pid,log_path,started_at,status,createdAt,updatedAt)
VALUES ($cronId,$pid,$log,$seconds,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`,
const [instance] = await executionModel(
this.database,
'RunningInstances',
)
.create(
{
cron_id: cronId,
pid,
log_path: log,
started_at: startSeconds,
status: 0,
createdAt: literal('CURRENT_TIMESTAMP'),
updatedAt: literal('CURRENT_TIMESTAMP'),
},
{ transaction, silent: true, hooks: false, validate: false },
)
.then((row) => [row.id] as const);
await executionModel(this.database, 'CronTriggers').update(
{ instance_id: instance, process_identity: identity },
{
where: { id },
transaction,
type: QueryTypes.INSERT,
bind: { cronId, pid, log, seconds: startSeconds },
silent: true,
hooks: false,
validate: false,
},
);
await this.database.query(
'UPDATE CronTriggers SET instance_id=$instance,process_identity=$identity WHERE id=$id',
{ transaction, bind: { instance, identity, id } },
);
await this.lifecycle.claimSummary(
cronId,
instance,
+6 -1
View File
@@ -31,7 +31,12 @@ export function spawnCronCommand(
if (onCommandStart) args.push('report-start');
if (outputPath) args.push('log-output', outputPath);
const child = spawn('python3', args, {
env: { ...process.env, QL_TRIGGER_ID: triggerId },
env: {
...process.env,
QL_TRIGGER_ID: triggerId,
QL_SUPERVISOR_RECEIPT: '1',
QL_SUPERVISOR_LOG_BOUND: outputPath ? '1' : '',
},
stdio: onCommandStart ? ['pipe', 'pipe', 'pipe', 'pipe'] : 'pipe',
}) as ChildProcessWithoutNullStreams;
if (onCommandStart && child.stdio[3]) {
+105 -46
View File
@@ -1,20 +1,36 @@
import type { Logger } from 'winston';
import { randomUUID } from 'crypto';
import dayjs from 'dayjs';
import fs from 'fs/promises';
import path from 'path';
import {
Op,
where,
col as colFn,
FindOptions,
QueryTypes,
Op,
Transaction,
col,
col as colFn,
where,
} from 'sequelize';
import type { Logger } from 'winston';
import config from '../../config/index';
import { getUniqPath, killTask } from '../../config/util';
import { Crontab, CrontabModel, CrontabStatus } from '../../data/cron';
import {
RunningInstanceModel,
executionAssociation,
executionModel,
} from '../../data/executionModels';
import {
InstanceStatus,
RunningInstanceModel,
} from '../../data/runningInstance';
import { asError, observeChildProcess } from '../../shared/childProcess';
import { resolveFileAccess } from '../../shared/fileAccess';
import { t } from '../../shared/i18n';
import { resolveLogPath } from '../../shared/logPath';
import { logStreamManager } from '../../shared/logStreamManager';
import { TriggerHistory, TriggerState } from '../history';
import { shellValue } from '../scheduling/cronScheduling';
import { releaseCronCommand, spawnCronCommand } from './cronCommandProcess';
import taskLimit from './cronLimit';
import {
finishStoppedTree,
hasLiveCronProcess,
@@ -22,18 +38,6 @@ import {
systemOwner,
verifyCronProcess,
} from './cronProcess';
import { killTask, getUniqPath } from '../../config/util';
import { resolveLogPath } from '../../shared/logPath';
import { resolveFileAccess } from '../../shared/fileAccess';
import { shellValue } from '../scheduling/cronScheduling';
import taskLimit from './cronLimit';
import { logStreamManager } from '../../shared/logStreamManager';
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
import { observeChildProcess, asError } from '../../shared/childProcess';
import { t } from '../../shared/i18n';
import fs from 'fs/promises';
import path from 'path';
import dayjs from 'dayjs';
type BatchStopSnapshot = {
docs: Array<
@@ -120,6 +124,17 @@ export class CronExecution {
});
} else {
accepted.push(row.get({ plain: true }));
await database.query(
'INSERT INTO CronManualSubmissions(trigger_id,token,snapshot) VALUES ($id,$token,$snapshot)',
{
transaction,
bind: {
id: trigger,
token,
snapshot: JSON.stringify(row.get({ plain: true })),
},
},
);
triggers.push({
taskId: id,
triggerId: trigger,
@@ -146,6 +161,40 @@ export class CronExecution {
return submission.triggers;
}
public async recoverQueued() {
const rows = await executionModel(
CrontabModel.sequelize!,
'CronManualSubmissions',
).findAll({
attributes: ['trigger_id', 'token', 'snapshot'],
include: [
{
association: executionAssociation(
CrontabModel.sequelize!,
'submissionTrigger',
),
attributes: [],
required: true,
where: {
state: 'queued',
[Op.or]: [{ stop_requested: null }, { stop_requested: 0 }],
},
},
],
order: [
[col('trigger.queued_at'), 'ASC'],
[col('trigger.id'), 'ASC'],
],
raw: true,
});
for (const row of rows) {
const snapshot: Crontab = JSON.parse(row.snapshot);
void this.host
.runSingle(snapshot.id!, row.token, row.trigger_id, snapshot)
.catch((error) => this.logger.error(String(error)));
}
}
private readonly stoppingBatches = new Map<string, Promise<void>>();
public async stop(ids: number[], requestId?: string) {
@@ -171,14 +220,15 @@ export class CronExecution {
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction): Promise<BatchStopSnapshot | null> => {
if (requestId) {
const [existing] = await database.query<{
cron_ids: string;
snapshot: string | null;
status_code: number;
}>(
'SELECT cron_ids,snapshot,status_code FROM CronStopBatches WHERE request_id=$requestId',
{ transaction, bind: { requestId }, type: QueryTypes.SELECT },
);
const [existing] = await executionModel(
database,
'CronStopBatches',
).findAll({
attributes: ['cron_ids', 'snapshot', 'status_code'],
where: { request_id: requestId },
transaction,
raw: true,
});
if (existing) {
if (existing.cron_ids !== cronIds)
throw Object.assign(
@@ -254,12 +304,13 @@ export class CronExecution {
identityConflict,
};
if (requestId) {
await database.query(
'INSERT INTO CronStopBatches(request_id,cron_ids,snapshot) VALUES ($requestId,$cronIds,$snapshot)',
await executionModel(database, 'CronStopBatches').create(
{
transaction,
bind: { requestId, cronIds, snapshot: JSON.stringify(batch) },
request_id: requestId,
cron_ids: cronIds,
snapshot: JSON.stringify(batch),
},
{ transaction, silent: true, hooks: false, validate: false },
);
}
return batch;
@@ -328,9 +379,14 @@ export class CronExecution {
if (failure) throw failure;
// Retain the key after success. Even a much later retry must never take a new snapshot.
if (requestId)
await database.query(
'UPDATE CronStopBatches SET snapshot=NULL,status_code=$status WHERE request_id=$requestId AND snapshot IS NOT NULL',
{ bind: { requestId, status: identityConflict ? 409 : 200 } },
await executionModel(database, 'CronStopBatches').update(
{ snapshot: null, status_code: identityConflict ? 409 : 200 },
{
where: { request_id: requestId, snapshot: { [Op.not]: null } },
silent: true,
hooks: false,
validate: false,
},
);
if (identityConflict)
throw Object.assign(new Error(t('实例不存在或已停止')), { status: 409 });
@@ -378,16 +434,16 @@ export class CronExecution {
});
}
for (const command of commands) {
const pid = Number(command.command_identity.split(':')[1]);
const pid = Number(command.command_identity!.split(':')[1]);
const key = command.cron_id + '/' + pid;
if (!registered.has(key))
legacy.set(key, {
pid,
cronId: command.cron_id,
trigger: command.id,
identity: command.command_identity,
started: Math.floor(command.started_at / 1000),
log: command.log_path,
identity: command.command_identity!,
started: Math.floor(command.started_at! / 1000),
log: command.log_path ?? undefined,
});
}
let identityConflict = false;
@@ -424,11 +480,14 @@ export class CronExecution {
{ transaction },
);
if (target.trigger)
await CrontabModel.sequelize!.query(
"UPDATE CronTriggers SET instance_id=$id,process_identity=$identity WHERE id=$trigger AND state='running'",
await executionModel(CrontabModel.sequelize!, 'CronTriggers').update(
{ instance_id: row.id, process_identity: identity },
{
where: { id: target.trigger, state: 'running' },
transaction,
bind: { id: row.id, identity, trigger: target.trigger },
silent: true,
hooks: false,
validate: false,
},
);
await history.queueInstanceStop(
@@ -506,9 +565,8 @@ export class CronExecution {
where: { id: instanceId, cron_id: cronId },
});
if (!instance) {
await CrontabModel.sequelize!.query(
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId AND cron_id=$cronId',
{ bind: { instanceId, cronId } },
await executionModel(CrontabModel.sequelize!, 'CronStopRequests').destroy(
{ where: { instance_id: instanceId, cron_id: cronId }, hooks: false },
);
return { code: 404, message: t('实例不存在或已停止') };
}
@@ -736,9 +794,10 @@ export class CronExecution {
)
: await getUniqPath(command, `${id}`);
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
logPath = `${uniqPath}/${logTime}${
independent ? '-' + expectedToken : ''
}.log`;
// Different tasks can share a script/log directory and start in
// the same millisecond. Every launch needs its own log identity.
// The submission token can also be shared by different tasks.
logPath = `${uniqPath}/${logTime}-${randomUUID()}.log`;
absolutePath = resolveFileAccess(config.logPath, [logPath]);
if (!absolutePath)
throw new Error('Log path is outside the log directory');
+55 -36
View File
@@ -2,10 +2,7 @@ import { EventEmitter } from 'events';
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
import os from 'os';
import type { Sequelize } from 'sequelize';
import {
QueueOccupants,
recordQueueAdmission,
} from '../queries/queueDiagnostics';
import { QueueOccupants } from '../queries/queueDiagnostics';
import { CronWaitQueue, CronQueueOptions } from './cronWaitQueue';
import { AuthDataType, SystemModel } from '../../data/system';
import Logger from '../../loaders/logger';
@@ -15,6 +12,7 @@ import config from '../../config';
import { credentials } from '@grpc/grpc-js';
import { ApiClient } from '../../protos/api';
import { getGrpcCerts } from '../../config/grpcCerts';
import { globalCronBudget } from './globalCronBudget';
// One scheduler/manual queue owner per process; services and execution share it.
class CronLimit {
@@ -192,43 +190,62 @@ class CronLimit {
return;
}
this.queuedCrons.set(cron.id, result);
const dispatch = (job: () => Promise<T | void>) => {
if (!waitingSignal) return this.cronLimit.add(job, options);
return new Promise<T | void>((resolve, reject) => {
this.cronLimit
.add(job, {
...options,
waitingSignal,
onRemoved: () => {
this.scheduledOccupants.forget(triggerId);
resolve();
},
})
.then(resolve, reject);
});
};
const run = this.trackAdmission(
this.scheduledOccupants,
this.cronLimit.concurrency,
fn,
{ id: triggerId, name: cron.name || cron.id },
db,
isCurrent,
waitingSignal,
triggerId && db ? dispatch : undefined,
);
if (!waitingSignal) return this.cronLimit.add(run, options);
return new Promise<T | void>((resolve, reject) => {
this.cronLimit
.add(run, {
...options,
waitingSignal,
onRemoved: () => {
this.scheduledOccupants.forget(triggerId);
resolve();
},
})
.then(resolve, reject);
});
// Durable requests are scheduled together by the global budget. A local
// FIFO in front of it hides short jobs behind long-running tasks.
if (triggerId && db) return run();
return dispatch(run);
}
private trackAdmission<T>(
pool: QueueOccupants,
limit: number,
fn: () => Promise<T>,
occupant: { id?: string; name: string },
db?: Sequelize,
current?: () => boolean,
signal?: EventEmitter,
dispatch?: (job: () => Promise<T>) => Promise<T | void>,
) {
const admission = pool.admission(limit);
if (occupant.id && admission && db) {
pool.watch(occupant.id, db);
void recordQueueAdmission(db, occupant.id, admission).catch((error) =>
Logger.warn('[queue] Failed to record wait reason: %s', error.message),
);
}
return pool.track(fn, occupant, db);
// Durable wait diagnostics come from the shared budget, before local
// dispatch. Local occupancy cannot see other workers or a fresh batch.
const tracked = pool.track(fn, occupant, db);
return async () => {
try {
return occupant.id && db
? await globalCronBudget(db).run(
occupant.id,
() => (dispatch ? dispatch(tracked) : tracked()),
current,
signal,
)
: await tracked();
} finally {
pool.forget(occupant.id);
}
};
}
public async manualRunWithCronLimit<T>(
@@ -237,16 +254,18 @@ class CronLimit {
occupant: { id?: string; name: string } = { name: '—' },
db?: Sequelize,
): Promise<T | void> {
return this.manualCronoLimit.add(
this.trackAdmission(
this.manualOccupants,
this.manualCronoLimit.concurrency,
fn,
occupant,
db,
),
options,
const run = this.trackAdmission(
this.manualOccupants,
fn,
occupant,
db,
undefined,
undefined,
occupant.id && db
? (job) => this.manualCronoLimit.add(job, options)
: undefined,
);
return occupant.id && db ? run() : this.manualCronoLimit.add(run, options);
}
}
+460
View File
@@ -0,0 +1,460 @@
import { randomUUID } from 'crypto';
import { EventEmitter } from 'events';
import os from 'os';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { systemOwner } from './cronProcess';
import { GlobalQueueDiagnostics } from '../queries/queueDiagnostics';
type Lease = {
trigger_id: string;
token: string;
owner: string;
command_identity: string | null;
targets?: string | null;
name?: string;
at?: number;
};
const leaseQuery = `SELECT l.*,s.targets,COALESCE(NULLIF(c.name,''),c.command,l.trigger_id) AS name,
COALESCE(t.started_at,t.queued_at,t.observed_at) AS at FROM CronConcurrencyLeases l
LEFT JOIN CronTriggers t ON t.id=l.trigger_id LEFT JOIN CronStopRequests s ON s.instance_id=t.instance_id
LEFT JOIN Crontabs c ON c.id=t.cron_id`;
function liveLease(lease: Lease) {
return (
budgetOwnerAlive(lease.command_identity || lease.owner) ||
Boolean(
lease.targets &&
(JSON.parse(lease.targets) as string[]).some(budgetOwnerAlive),
)
);
}
type Waiter = {
id: string;
token: string;
owner: string;
commandIdentity?: string;
registered?: boolean;
current: () => boolean;
resolve: (acquired: boolean) => void;
reject: (error: unknown) => void;
};
// Birth identities include the boot ID and start ticks; a reused PID is not a
// surviving execution. Permission/I/O failures fail closed, never free a slot.
export function budgetOwnerAlive(identity: string) {
try {
return systemOwner(Number(identity.split(':')[1])) === identity;
} catch (error) {
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!))
return false;
throw error;
}
}
const budgets = new WeakMap<Sequelize, GlobalCronBudget>();
export function globalCronBudget(db: Sequelize) {
let budget = budgets.get(db);
if (!budget) budgets.set(db, (budget = new GlobalCronBudget(db)));
return budget;
}
// Admission polling and handoff use bound SQL: model query construction here
// repeats for each ready task and extends the single-writer critical section.
// Ordinary management queries remain ORM; see docs/SQL_ORM_AUDIT.txt.
// Only admissions use a write transaction. A saturated queue shares one read
// poll per worker, independent of its backlog size; idle workers do no polling.
export class GlobalCronBudget {
private waiting = new Set<Waiter>();
private pumping = false;
private scheduled = false;
private wakePending = false;
private heldTokens = new Set<string>();
private timer?: NodeJS.Timeout;
private diagnostics = new GlobalQueueDiagnostics(this.db);
constructor(private db: Sequelize) {}
async acquire(
id: string,
options: {
current?: () => boolean;
signal?: EventEmitter;
owner?: string;
commandIdentity?: string;
} = {},
) {
let expired = false;
const expire = () => {
expired = true;
this.wake();
};
options.signal?.once('expired', expire);
const token = randomUUID();
let acquired = false;
try {
acquired = await new Promise<boolean>((resolve, reject) => {
this.waiting.add({
id,
token,
owner: options.owner ?? systemOwner(process.pid),
commandIdentity: options.commandIdentity,
current: () => !expired && (options.current?.() ?? true),
resolve,
reject,
});
this.wake();
});
if (acquired) this.heldTokens.add(token);
return acquired ? token : undefined;
} finally {
options.signal?.off('expired', expire);
// Successful admission removes the wait in the same transaction as its
// lease. A later cleanup error must never hide an acquired permit.
if (!acquired)
await this.db.query(
'DELETE FROM CronConcurrencyWaiters WHERE trigger_id=$id AND token=$token',
{ bind: { id, token } },
);
}
}
async run<T>(
id: string,
fn: () => Promise<T>,
current?: () => boolean,
signal?: EventEmitter,
) {
const token = await this.acquire(id, { current, signal });
if (!token) return;
try {
return await fn();
} finally {
await this.release(id, token);
}
}
async release(id: string, token: string) {
// Once the callback returns, a still-live command needs normal recovery
// polling: there is no longer a local completion that can wake us.
this.heldTokens.delete(token);
const [lease] = await this.db.query<Lease>(
leaseQuery + ' WHERE l.trigger_id=$id AND l.token=$token',
{ bind: { id, token }, type: QueryTypes.SELECT },
);
// A failed callback or a stop request is not proof that its child exited.
if (lease && (!lease.command_identity || !liveLease(lease))) {
await this.db.query(
'DELETE FROM CronConcurrencyLeases WHERE trigger_id=$id AND token=$token',
{ bind: { id, token } },
);
}
this.wake();
}
private wake() {
if (!this.waiting.size) return;
if (this.pumping) {
this.wakePending = true;
return;
}
clearTimeout(this.timer);
this.timer = undefined;
if (this.scheduled) return;
// A batch submission calls acquire synchronously for each accepted task.
// Publish the whole batch before choosing its first permit, so the first
// long task cannot bypass the same batch's shorter ready tasks.
this.scheduled = true;
queueMicrotask(() => {
this.scheduled = false;
if (this.waiting.size) void this.pump();
});
}
private async snapshot(transaction?: Transaction) {
// An upgrade can restart workers while supervisors from the previous
// version are still alive. Their existing birth identities also consume
// capacity, even though that version did not create budget reservations.
const leases = await this.db.query<Lease>(
leaseQuery +
`
UNION ALL SELECT t.id,'inherited',COALESCE(t.command_identity,t.process_identity),
COALESCE(t.command_identity,t.process_identity),s.targets,
COALESCE(NULLIF(c.name,''),c.command,t.id),COALESCE(t.started_at,t.queued_at,t.observed_at)
FROM CronTriggers t LEFT JOIN CronStopRequests s ON s.instance_id=t.instance_id
LEFT JOIN Crontabs c ON c.id=t.cron_id
WHERE t.state='running' AND COALESCE(t.command_identity,t.process_identity) IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM CronConcurrencyLeases l WHERE l.trigger_id=t.id)`,
{
type: QueryTypes.SELECT,
transaction,
},
);
const [config] = await this.db.query<{ info: string }>(
"SELECT info FROM Auths WHERE type='systemConfig' LIMIT 1",
{ type: QueryTypes.SELECT, transaction },
);
const configured = config?.info && JSON.parse(config.info).cronConcurrency;
const limit =
Number.isSafeInteger(configured) && configured > 0
? configured
: Math.max(os.cpus().length, 4);
const stale = leases.filter((lease) => !liveLease(lease));
return {
leases,
stale,
limit,
free: Math.max(0, limit - leases.length + stale.length),
};
}
private async pump() {
this.pumping = true;
this.wakePending = false;
const batch = [...this.waiting];
const results = new Map<Waiter, boolean>();
let pollInterval = 100;
try {
// Publish all ready requests, including those behind long local jobs.
// Tokens prevent a duplicate submitter from deleting the original wait.
const fresh = batch.filter((waiter) => !waiter.registered);
if (fresh.length) {
await this.db.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction) => {
const owners = await this.db.query<{
trigger_id: string;
token: string;
owner: string;
}>(
'SELECT * FROM CronConcurrencyWaiters WHERE trigger_id IN (:ids)',
{
replacements: { ids: fresh.map((w) => w.id) },
transaction,
type: QueryTypes.SELECT,
},
);
for (const owner of owners)
if (!budgetOwnerAlive(owner.owner)) {
await this.db.query(
'DELETE FROM CronConcurrencyWaiters WHERE trigger_id=$id AND token=$token',
{
bind: { id: owner.trigger_id, token: owner.token },
transaction,
},
);
}
// Keep a burst in the same transaction, but avoid one SQLite
// round trip per waiter. Three binds per row stay below even
// SQLite's older 999-variable limit; values never enter SQL text.
for (let offset = 0; offset < fresh.length; offset += 200) {
const chunk = fresh.slice(offset, offset + 200);
const bind: string[] = [];
const values = chunk.map((waiter) => {
const start = bind.length;
bind.push(waiter.id, waiter.token, waiter.owner);
return `($${start + 1},$${start + 2},$${start + 3})`;
});
await this.db.query(
`WITH incoming(trigger_id,token,owner) AS (VALUES ${values.join(
',',
)})
INSERT INTO CronConcurrencyWaiters(trigger_id,token,owner)
SELECT i.trigger_id,i.token,i.owner FROM incoming i
JOIN CronTriggers t ON t.id=i.trigger_id WHERE t.state='queued'
ON CONFLICT(trigger_id) DO NOTHING`,
{
bind,
transaction,
},
);
}
},
);
for (const waiter of fresh) waiter.registered = true;
}
const queued = await this.db.query<{ id: string; token: string }>(
"SELECT t.id,w.token FROM CronTriggers t JOIN CronConcurrencyWaiters w ON w.trigger_id=t.id WHERE t.id IN (:ids) AND t.state='queued' AND COALESCE(t.stop_requested,0)=0",
{
replacements: { ids: batch.map((w) => w.id) },
type: QueryTypes.SELECT,
},
);
const ids = new Set(queued.map((row) => row.token));
for (const waiter of batch)
if (!waiter.current() || !ids.has(waiter.token))
results.set(waiter, false);
const view = await this.snapshot();
// Local callbacks wake the budget immediately on completion. While all
// slots are held by this exact budget instance, avoid scanning SQLite
// ten times per second for changes those callbacks will report anyway.
// Foreign/inherited permits and released-but-live descendants retain
// the short recovery poll; runtime limit changes remain bounded at 500 ms.
if (
!view.free &&
!view.stale.length &&
view.leases.length &&
view.leases.every((lease) => this.heldTokens.has(lease.token))
)
pollInterval = 500;
for (const waiter of batch) {
if (
view.leases.some(
(lease) =>
lease.trigger_id === waiter.id && !view.stale.includes(lease),
)
)
results.set(waiter, false);
}
if (view.free || view.stale.length) {
await this.db.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction) => {
const { leases, stale, free } = await this.snapshot(transaction);
for (const lease of stale)
await this.db.query(
'DELETE FROM CronConcurrencyLeases WHERE trigger_id=$id AND token=$token',
{
bind: { id: lease.trigger_id, token: lease.token },
transaction,
},
);
// Only live, ready owners take part in ordering. A dead worker's
// request must not block recovery or unrelated tasks.
const ready = await this.db.query<{
trigger_id: string;
token: string;
owner: string;
}>(
`
SELECT w.* FROM CronConcurrencyWaiters w JOIN CronTriggers t ON t.id=w.trigger_id
LEFT JOIN Crontabs c ON c.id=t.cron_id
WHERE t.state='queued' AND COALESCE(t.stop_requested,0)=0
AND NOT EXISTS(SELECT 1 FROM CronConcurrencyLeases l WHERE l.trigger_id=w.trigger_id)
ORDER BY CASE WHEN t.queued_at <= $aged THEN 0 ELSE 1 END,
CASE WHEN t.queued_at <= $aged THEN t.queued_at
ELSE CASE WHEN c.last_execution_time > 0 AND c.last_running_time IS NOT NULL
THEN MAX(0,c.last_running_time)*1000 ELSE 10000 END END,
t.queued_at,t.observed_at,t.id`,
{
bind: { aged: Date.now() - 30000 },
transaction,
type: QueryTypes.SELECT,
},
);
const selected = new Set<string>();
for (const request of ready) {
if (!budgetOwnerAlive(request.owner)) {
await this.db.query(
'DELETE FROM CronConcurrencyWaiters WHERE trigger_id=$id AND token=$token',
{
bind: { id: request.trigger_id, token: request.token },
transaction,
},
);
} else if (selected.size < free) selected.add(request.token);
}
// Resolve local permits in the same order as the shared ranking.
// Set membership alone would start a long task first again when
// both it and a short task fit into the remaining free slots.
const priority = new Map(
[...selected].map((token, index) => [token, index]),
);
batch.sort(
(a, b) =>
(priority.get(a.token) ?? selected.size) -
(priority.get(b.token) ?? selected.size),
);
let available = free;
for (const waiter of batch) {
if (results.has(waiter)) continue;
if (
!waiter.current() ||
leases.some(
(lease) =>
lease.trigger_id === waiter.id && !stale.includes(lease),
)
) {
results.set(waiter, false);
continue;
}
if (!available) break;
if (!selected.has(waiter.token)) continue;
const inserted = await this.db.query(
`INSERT INTO CronConcurrencyLeases(trigger_id,token,owner,command_identity)
SELECT $id,$token,$owner,$command FROM CronTriggers WHERE id=$id AND state='queued' AND COALESCE(stop_requested,0)=0
ON CONFLICT(trigger_id) DO NOTHING`,
{
bind: {
id: waiter.id,
token: waiter.token,
owner: waiter.owner,
command: waiter.commandIdentity ?? null,
},
transaction,
type: QueryTypes.BULKUPDATE,
},
);
results.set(waiter, inserted === 1);
if (inserted) {
await this.db.query(
'DELETE FROM CronConcurrencyWaiters WHERE trigger_id=$id AND token=$token',
{
bind: { id: waiter.id, token: waiter.token },
transaction,
},
);
available--;
}
}
},
);
}
const occupied = view.leases.filter(
(lease) => !view.stale.includes(lease),
);
this.diagnostics.observe(
batch
.filter((waiter) => !results.has(waiter))
.map((waiter) => waiter.id),
!view.free && occupied.length
? {
queue: 'global',
limit: view.limit,
occupied: occupied.length,
holders: occupied
.sort(
(a, b) =>
(a.at ?? 0) - (b.at ?? 0) ||
a.trigger_id.localeCompare(b.trigger_id),
)
.slice(0, 8)
.map((lease) => ({
id: lease.trigger_id,
name: lease.name || lease.trigger_id,
})),
}
: undefined,
);
for (const [waiter, acquired] of results) {
this.waiting.delete(waiter);
waiter.resolve(acquired);
}
} catch (error) {
this.diagnostics.observe([]);
for (const waiter of batch) {
this.waiting.delete(waiter);
waiter.reject(error);
}
} finally {
this.pumping = false;
if (this.waiting.size) {
// An arrival, expiration or release while a query was pending must not
// lose its wakeup and wait for the saturated-queue polling interval.
if (this.wakePending) this.wake();
else
this.timer = setTimeout(() => {
this.timer = undefined;
this.wake();
}, pollInterval);
}
}
}
}
+7 -2
View File
@@ -27,10 +27,15 @@ export async function runCron(
cmd: string,
cron: ICron,
isCurrent: () => boolean = () => true,
trigger?: { id: string; time: number; source: 'node' | 'recovery' },
trigger?: {
id: string;
time: number;
source: 'node' | 'recovery';
queuedAt?: number;
},
): Promise<number | void> {
const history = trigger && triggerHistory();
const queuedAt = Date.now();
const queuedAt = trigger?.queuedAt ?? Date.now();
if (trigger && history) {
const cronId = Number(cron.id);
const admitted = await historyWrites.add(() =>
+315 -139
View File
@@ -1,11 +1,15 @@
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { Op, QueryTypes, Sequelize, Transaction, col, fn } from 'sequelize';
import type { Crontab } from '../../data/cron';
import {
executionAssociation,
executionModel,
} from '../../data/executionModels';
import type { readExit } from '../settlement/exitReceipt.cjs';
import type {
TriggerSource,
TriggerState,
VerifiedSupervisorExit,
} from '../types';
import type { readExit } from '../settlement/exitReceipt.cjs';
import {
hasLiveCronProcess,
pidNamespaceOwner,
@@ -38,6 +42,8 @@ export interface TriggerLifecycleEvidence {
replayPublishedExits(transaction: Transaction): Promise<void>;
}
// Launch/command binding uses bound SQL to keep write transactions short.
// Preserve the state predicates and caller transaction when changing a query.
// Persisted transitions shared by manual, Node and system-crond executions.
// In particular, recovery may reclaim an unstarted slot, never an unknown result.
export class TriggerLifecycle {
@@ -48,11 +54,22 @@ export class TriggerLifecycle {
// Only unclaimed scheduler work can expire; its owner controls claimed runs.
async skipQueued(id: string, reason: string, finishedAt: number) {
await this.database.query(
`UPDATE CronTriggers SET state='skipped', reason=$reason, finished_at=$finishedAt
WHERE id=$id AND source IN ('node','recovery') AND state='queued' AND started_at IS NULL`,
{ bind: { id, reason, finishedAt }, type: QueryTypes.BULKUPDATE },
);
await executionModel(this.database, 'CronTriggers')
.update(
{ state: 'skipped', reason, finished_at: finishedAt },
{
where: {
id,
source: { [Op.in]: ['node', 'recovery'] },
state: 'queued',
started_at: null,
},
silent: true,
hooks: false,
validate: false,
},
)
.then(([changed]) => changed);
}
async enqueue(
@@ -69,7 +86,7 @@ export class TriggerLifecycle {
VALUES ($id,$cronId,$source,$scheduledAt,$now,$now,$owner,'queued')
ON CONFLICT(id) DO UPDATE SET state='queued', reason=NULL, finished_at=NULL,
queued_at=excluded.queued_at, dequeued_at=NULL, queue_context=NULL, queue_live_context=NULL,
source=excluded.source, owner=excluded.owner
source=excluded.source, owner=excluded.owner, resume_pending=NULL
WHERE excluded.source='recovery' AND state='skipped' AND reason='restart' AND started_at IS NULL`,
{
bind: {
@@ -102,16 +119,24 @@ export class TriggerLifecycle {
)
return false;
await this.recoverSystemOwners(cronId, transaction);
const pending = await this.database.query(
`SELECT 1 FROM CronTriggers WHERE cron_id=$cronId AND id<>$id
AND source IN ('node','recovery','system')
AND (state='running' OR (state='queued' AND queued_at >= $revision)) LIMIT 1`,
{
transaction,
bind: { cronId, id, revision },
type: QueryTypes.SELECT,
const pending = await executionModel(
this.database,
'CronTriggers',
).findAll({
attributes: ['id'],
where: {
cron_id: cronId,
id: { [Op.ne]: id },
source: { [Op.in]: ['node', 'recovery', 'system'] },
[Op.or]: [
{ state: 'running' },
{ state: 'queued', queued_at: { [Op.gte]: revision } },
],
},
);
limit: 1,
transaction,
raw: true,
});
if (!pending.length) return true;
await this.finish(id, 'skipped', 'pending', null, transaction);
return false;
@@ -137,10 +162,14 @@ export class TriggerLifecycle {
);
let changed = await claim();
if (!changed && !multiple && !transaction) {
const [task] = await this.database.query<{ cron_id: number }>(
"SELECT cron_id FROM CronTriggers WHERE id=$id AND state='queued'",
{ bind: { id }, type: QueryTypes.SELECT },
);
const [task] = await executionModel(
this.database,
'CronTriggers',
).findAll({
attributes: ['cron_id'],
where: { id, state: 'queued' },
raw: true,
});
if (task && (await this.recoverSystemOwners(task.cron_id)))
changed = await claim();
}
@@ -258,18 +287,63 @@ export class TriggerLifecycle {
}
async cancelQueuedInTransaction(ids: number[], transaction: Transaction) {
await this.database.query(
"UPDATE CronTriggers SET stop_requested=1 WHERE cron_id IN (:ids) AND state='running' AND command_identity IS NULL AND instance_id IS NULL",
{ replacements: { ids }, transaction },
await executionModel(this.database, 'CronTriggers').update(
{ stop_requested: 1 },
{
where: {
cron_id: { [Op.in]: ids },
state: 'running',
command_identity: null,
instance_id: null,
},
transaction,
silent: true,
hooks: false,
validate: false,
},
);
const rows = await this.database.query<{ id: string }>(
"SELECT id FROM CronTriggers WHERE cron_id IN (:ids) AND state='queued'",
{ replacements: { ids }, transaction, type: QueryTypes.SELECT },
);
await this.database.query(
`UPDATE CronTriggers SET state='stopped',reason='cancelled',finished_at=:now
WHERE cron_id IN (:ids) AND state='queued'`,
{ replacements: { ids, now: Date.now() }, transaction },
const rows = await executionModel(this.database, 'CronTriggers').findAll({
attributes: ['id'],
where: {
cron_id: { [Op.in]: ids },
[Op.or]: [
{ state: 'queued' },
{
state: 'skipped',
reason: 'restart',
resume_pending: 1,
started_at: null,
},
],
},
transaction,
raw: true,
});
await executionModel(this.database, 'CronTriggers').update(
{
state: 'stopped',
reason: 'cancelled',
finished_at: Date.now(),
resume_pending: null,
},
{
where: {
cron_id: { [Op.in]: ids },
[Op.or]: [
{ state: 'queued' },
{
state: 'skipped',
reason: 'restart',
resume_pending: 1,
started_at: null,
},
],
},
transaction,
silent: true,
hooks: false,
validate: false,
},
);
return rows.map((r) => r.id);
}
@@ -300,36 +374,38 @@ export class TriggerLifecycle {
}
async pendingStop(instanceId: number, transaction?: Transaction) {
const [row] = await this.database.query<{
targets: string | null;
signalled: number;
signalled_at: number | null;
root_identity: string | null;
namespace_owner: string | null;
}>(
'SELECT targets,signalled,signalled_at,root_identity,namespace_owner FROM CronStopRequests WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
);
const [row] = await executionModel(
this.database,
'CronStopRequests',
).findAll({
attributes: [
'targets',
'signalled',
'signalled_at',
'root_identity',
'namespace_owner',
],
where: { instance_id: instanceId },
transaction,
raw: true,
});
return row;
}
async pendingStopBatches() {
return this.database.query<{ request_id: string; cron_ids: string }>(
'SELECT request_id,cron_ids FROM CronStopBatches WHERE snapshot IS NOT NULL',
{ type: QueryTypes.SELECT },
);
return executionModel(this.database, 'CronStopBatches').findAll({
attributes: ['request_id', 'cron_ids'],
where: { snapshot: { [Op.not]: null } },
raw: true,
});
}
async pendingStops() {
return this.database.query<{
instance_id: number;
cron_id: number;
pid: number;
targets: string | null;
}>(
'SELECT instance_id,cron_id,pid,targets FROM CronStopRequests ORDER BY instance_id',
{ type: QueryTypes.SELECT },
);
return executionModel(this.database, 'CronStopRequests').findAll({
attributes: ['instance_id', 'cron_id', 'pid', 'targets'],
order: [['instance_id', 'ASC']],
raw: true,
});
}
async forgetStop(
@@ -337,10 +413,11 @@ export class TriggerLifecycle {
onEnded?: (tx: Transaction) => Promise<void>,
) {
return this.database.transaction(async (transaction) => {
await this.database.query(
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId AND signalled=0',
{ transaction, bind: { instanceId } },
);
await executionModel(this.database, 'CronStopRequests').destroy({
where: { instance_id: instanceId, signalled: 0 },
transaction,
hooks: false,
});
const claimed = await this.pendingStop(instanceId, transaction);
if (!claimed && onEnded) await onEnded(transaction);
return claimed;
@@ -357,10 +434,14 @@ export class TriggerLifecycle {
// The outer command can outlive any of its task wrappers.
async recordCommandStart(id: string, at: number) {
await this.database.query(
`UPDATE CronTriggers SET command_started_at=$at
WHERE id=$id AND command_started_at IS NULL AND started_at IS NOT NULL`,
{ bind: { id, at } },
await executionModel(this.database, 'CronTriggers').update(
{ command_started_at: at },
{
where: { id, command_started_at: null, started_at: { [Op.not]: null } },
silent: true,
hooks: false,
validate: false,
},
);
}
@@ -383,6 +464,10 @@ export class TriggerLifecycle {
{ transaction, bind: { id }, type: QueryTypes.SELECT },
);
if (!row) return false;
await this.database.query(
'UPDATE CronConcurrencyLeases SET command_identity=$identity WHERE trigger_id=$id',
{ transaction, bind: { identity, id } },
);
await this.database.query(
'UPDATE CronTriggers SET command_identity=$identity WHERE id=$id',
{ transaction, bind: { identity, id } },
@@ -448,25 +533,31 @@ export class TriggerLifecycle {
async activeCommands(ids: number[], transaction?: Transaction) {
if (!ids.length) return [];
return this.database.query<{
id: string;
cron_id: number;
command_identity: string;
started_at: number;
log_path: string;
}>(
"SELECT id,cron_id,command_identity,started_at,log_path FROM CronTriggers WHERE cron_id IN (:ids) AND state='running' AND instance_id IS NULL AND command_identity IS NOT NULL",
{ replacements: { ids }, transaction, type: QueryTypes.SELECT },
);
return executionModel(this.database, 'CronTriggers').findAll({
attributes: [
'id',
'cron_id',
'command_identity',
'started_at',
'log_path',
],
where: {
cron_id: { [Op.in]: ids },
state: 'running',
instance_id: null,
command_identity: { [Op.not]: null },
},
transaction,
raw: true,
});
}
async instanceIdentity(instanceId: number) {
const [row] = await this.database.query<{
process_identity: string | null;
}>(
'SELECT process_identity FROM CronTriggers WHERE instance_id=$instanceId',
{ bind: { instanceId }, type: QueryTypes.SELECT },
);
const [row] = await executionModel(this.database, 'CronTriggers').findAll({
attributes: ['process_identity'],
where: { instance_id: instanceId },
raw: true,
});
return row?.process_identity;
}
@@ -490,17 +581,37 @@ export class TriggerLifecycle {
const result = await this.database.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction) => {
const [row] = await this.database.query<{
const [row] = (await executionModel(
this.database,
'RunningInstances',
).findAll({
attributes: [
[col('trigger.id'), 'id'],
'pid',
'status',
[col('trigger.state'), 'state'],
[col('trigger.stop_requested'), 'stop_requested'],
],
where: { id: instanceId },
include: [
{
association: executionAssociation(
this.database,
'instanceTrigger',
),
attributes: [],
required: false,
},
],
transaction,
raw: true,
})) as unknown as Array<{
id: string | null;
pid: number;
status: number;
state: TriggerState | null;
state: string | null;
stop_requested: number | null;
}>(
`SELECT t.id,i.pid,i.status,t.state,t.stop_requested FROM RunningInstances i
LEFT JOIN CronTriggers t ON t.instance_id=i.id WHERE i.id=$instanceId`,
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
);
}>;
if (
!row ||
row.status !== 0 ||
@@ -554,14 +665,26 @@ export class TriggerLifecycle {
);
}
const signalledAt = Date.now();
await this.database.query(
'UPDATE CronStopRequests SET signalled=1,signalled_at=$signalledAt WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId, signalledAt } },
await executionModel(this.database, 'CronStopRequests').update(
{ signalled: 1, signalled_at: signalledAt },
{
where: { instance_id: instanceId },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
if (row.state)
await this.database.query(
"UPDATE CronTriggers SET stop_requested=1 WHERE instance_id=$instanceId AND state='running'",
{ bind: { instanceId }, transaction },
await executionModel(this.database, 'CronTriggers').update(
{ stop_requested: 1 },
{
where: { instance_id: instanceId, state: 'running' },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
// Root delivery failure rolls back. After successful root delivery, retain
// the stop marker even if some descendants still need recovery.
@@ -580,10 +703,12 @@ export class TriggerLifecycle {
}
async instanceStopRequested(instanceId: number, transaction?: Transaction) {
const [row] = await this.database.query<{ stop_requested: number | null }>(
'SELECT stop_requested FROM CronTriggers WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
);
const [row] = await executionModel(this.database, 'CronTriggers').findAll({
attributes: ['stop_requested'],
where: { instance_id: instanceId },
transaction,
raw: true,
});
return row && Boolean(row.stop_requested);
}
@@ -592,23 +717,28 @@ export class TriggerLifecycle {
settleLegacy?: (transaction: Transaction) => Promise<boolean>,
) {
return this.database.transaction(async (transaction) => {
const [row] = await this.database.query<{
id: string;
owner: string | null;
command_identity: string | null;
reason: string | null;
state: TriggerState;
stop_exit_at: number | null;
exit_code: number | null;
exit_pending: number | null;
}>(
'SELECT id,owner,command_identity,reason,state,stop_exit_at,exit_code,exit_pending FROM CronTriggers WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
);
await this.database.query(
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId } },
const [row] = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: [
'id',
'owner',
'command_identity',
'reason',
'state',
'stop_exit_at',
'exit_code',
'exit_pending',
],
where: { instance_id: instanceId },
transaction,
raw: true,
},
);
await executionModel(this.database, 'CronStopRequests').destroy({
where: { instance_id: instanceId },
transaction,
hooks: false,
});
if (!row) return settleLegacy ? settleLegacy(transaction) : false;
if (row.state !== 'running') return row.state === 'stopped';
const legacyCrond =
@@ -645,13 +775,14 @@ export class TriggerLifecycle {
async queueCounts() {
await this.recoverSystemOwners();
const [row] = await this.database.query<{
triggers: number;
tasks: number;
}>(
"SELECT COUNT(*) AS triggers, COUNT(DISTINCT cron_id) AS tasks FROM CronTriggers WHERE state='queued' AND dequeued_at IS NULL",
{ type: QueryTypes.SELECT },
);
const [row] = (await executionModel(this.database, 'CronTriggers').findAll({
attributes: [
[fn('COUNT', col('id')), 'triggers'],
[fn('COUNT', fn('DISTINCT', col('cron_id'))), 'tasks'],
],
where: { state: 'queued', dequeued_at: null },
raw: true,
})) as unknown as Array<{ triggers: number; tasks: number }>;
return row;
}
@@ -664,20 +795,21 @@ export class TriggerLifecycle {
) {
// crond only tells us when the wrapper starts. It supplies no scheduled or queued time.
return this.database.transaction(async (transaction) => {
const [task] = await this.database.query<{
allow_multiple_instances: number;
status: number;
pid: number | null;
isDisabled: number;
}>(
'SELECT allow_multiple_instances, status, pid, isDisabled FROM Crontabs WHERE id=$cronId',
{ bind: { cronId }, type: QueryTypes.SELECT, transaction },
);
const [task] = await executionModel(this.database, 'Crontabs').findAll({
attributes: ['allow_multiple_instances', 'status', 'pid', 'isDisabled'],
where: { id: cronId },
transaction,
raw: true,
});
if (!task || (task.isDisabled && !wrapper?.dispatch)) return false;
const now = Date.now();
const inserted = await this.database.query(
`INSERT INTO CronTriggers(id,cron_id,source,state,owner,command_identity,observed_at,system_rule,system_dispatch_at)
VALUES ($id,$cronId,'system','queued',$owner,$commandIdentity,$observed,$rule,$dispatch) ON CONFLICT(id) DO NOTHING`,
VALUES ($id,$cronId,'system','queued',$owner,$commandIdentity,$observed,$rule,$dispatch)
ON CONFLICT(id) DO UPDATE SET command_identity=excluded.command_identity,
system_rule=excluded.system_rule,system_dispatch_at=excluded.system_dispatch_at
WHERE state='queued' AND source='system' AND owner=$owner
AND EXISTS (SELECT 1 FROM CronConcurrencyLeases WHERE trigger_id=$id AND command_identity=$commandIdentity)`,
{
bind: {
id,
@@ -699,12 +831,22 @@ export class TriggerLifecycle {
}
const multiple = task.allow_multiple_instances === 1;
const claimed =
(multiple || !hasLiveCronProcess(task.status, task.pid)) &&
(multiple ||
!hasLiveCronProcess(
task.status ?? undefined,
task.pid ?? undefined,
)) &&
(await this.start(id, now, multiple, transaction));
if (claimed && wrapper)
await this.database.query(
'UPDATE CronTriggers SET command_started_at=$now WHERE id=$id',
{ transaction, bind: { id, now } },
await executionModel(this.database, 'CronTriggers').update(
{ command_started_at: now },
{
where: { id },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
if (claimed && owner.startsWith('crond:')) {
await this.registerCommandInstance(
@@ -729,8 +871,12 @@ export class TriggerLifecycle {
instanceId?: number,
) {
// HTTP may restart while crond children keep running. Match process birth, including across reboots.
const active = await this.database.query<{ id: string; owner: string }>(
`SELECT id,CASE WHEN owner LIKE 'crond:%' THEN owner ELSE COALESCE(command_identity,process_identity) END AS owner FROM CronTriggers WHERE state='running' AND (owner LIKE 'crond:%' OR reason='restart')
const active = await this.database.query<{
id: string;
owner: string;
state: string;
}>(
`SELECT id,state,CASE WHEN owner LIKE 'crond:%' THEN owner ELSE COALESCE(command_identity,process_identity) END AS owner FROM CronTriggers WHERE (state='running' OR (state='queued' AND source='system' AND owner LIKE 'crond:%')) AND (owner LIKE 'crond:%' OR reason='restart')
AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=CronTriggers.instance_id AND s.targets IS NOT NULL)
AND ($cronId IS NULL OR cron_id=$cronId) AND ($instanceId IS NULL OR instance_id=$instanceId)`,
{
@@ -749,6 +895,10 @@ export class TriggerLifecycle {
if (code !== 'ENOENT' && code !== 'ESRCH') throw error;
}
const close = async (tx: Transaction) => {
if (row.state === 'queued') {
await this.finish(row.id, 'skipped', 'restart', null, tx);
return;
}
const [current] = await this.database.query<{
stop_requested: number;
exit_code: number | null;
@@ -788,16 +938,42 @@ export class TriggerLifecycle {
{ transaction },
);
// No process was bound and its launch gate closed when the worker exited.
await executionModel(this.database, 'CronTriggers').update(
{
state: 'stopped',
reason: 'cancelled',
started_at: null,
finished_at: Date.now(),
},
{
where: {
owner,
state: 'running',
stop_requested: 1,
instance_id: null,
command_identity: null,
},
transaction,
silent: true,
hooks: false,
validate: false,
},
);
await this.database.query(
`UPDATE CronTriggers SET state='stopped',reason='cancelled',started_at=NULL,finished_at=$now
WHERE owner=$owner AND state='running' AND stop_requested=1 AND instance_id IS NULL AND command_identity IS NULL`,
{ transaction, bind: { owner, now: Date.now() } },
`UPDATE CronTriggers SET state='queued',started_at=NULL,reason=NULL
WHERE owner=$owner AND state='running' AND COALESCE(stop_requested,0)=0
AND command_identity IS NULL AND process_identity IS NULL AND instance_id IS NULL
AND (EXISTS (SELECT 1 FROM CronManualSubmissions WHERE trigger_id=CronTriggers.id)
OR EXISTS (SELECT 1 FROM CronConcurrencyLeases WHERE trigger_id=CronTriggers.id AND command_identity IS NULL))`,
{ transaction, bind: { owner } },
);
await this.database.query(
`UPDATE CronTriggers SET reason='restart',
resume_pending=CASE WHEN state='queued' AND source IN ('node','recovery') THEN 1 ELSE resume_pending END,
state=CASE WHEN state='queued' THEN 'skipped' WHEN COALESCE(command_identity,process_identity) IS NOT NULL THEN 'running' ELSE 'unknown' END,
finished_at=CASE WHEN state='running' AND COALESCE(command_identity,process_identity) IS NOT NULL THEN NULL ELSE $now END
WHERE (owner=$owner OR (source IN ('system','legacy','client') AND owner IS NULL AND $owner='http')) AND state IN ('queued','running')`,
WHERE (owner=$owner OR (source IN ('system','legacy','client') AND owner IS NULL AND $owner='http')) AND state IN ('queued','running')
AND NOT (state='queued' AND EXISTS (SELECT 1 FROM CronManualSubmissions WHERE trigger_id=CronTriggers.id))`,
{ transaction, bind: { owner, now: Date.now() } },
);
await this.recoverSystemOwners(undefined, transaction);
+203 -46
View File
@@ -1,8 +1,14 @@
import { QueryTypes, Sequelize } from 'sequelize';
import { Op, Sequelize, col, fn } from 'sequelize';
import {
executionAssociation,
executionModel,
} from '../../data/executionModels';
type Occupant = { id?: string; name: string };
type WaitingSample = { db: Sequelize; context?: string };
const LIVE_SAMPLE_INTERVAL_MS = 250;
export type Admission = {
queue: 'manual' | 'scheduled';
queue: 'manual' | 'scheduled' | 'global';
limit: number;
occupied: number;
holders: Occupant[];
@@ -11,9 +17,10 @@ export type Admission = {
// Each object belongs to exactly one execution pool in its owning process.
export class QueueOccupants {
private active = new Set<Occupant>();
private waiting = new Map<string, Sequelize>();
private waiting = new Map<string, WaitingSample>();
private writing = false;
private changed = false;
private timer?: NodeJS.Timeout;
constructor(
private queue: Admission['queue'],
@@ -22,45 +29,74 @@ export class QueueOccupants {
) {}
watch(id: string, db: Sequelize) {
this.waiting.set(id, db);
this.waiting.set(id, { db });
this.refresh();
}
forget(id?: string) {
if (id) this.waiting.delete(id);
if (!this.waiting.size) {
clearTimeout(this.timer);
this.timer = undefined;
this.changed = false;
}
}
refresh() {
if (!this.waiting.size) return;
this.changed = true;
if (this.writing) return;
if (this.writing || this.timer) return;
// Bound diagnostic write frequency across asynchronous admissions/handoffs.
// Execution and its durable admission/dequeue records never wait for this timer.
this.timer = setTimeout(() => {
this.timer = undefined;
void this.flush();
}, LIVE_SAMPLE_INTERVAL_MS);
this.timer.unref();
}
private async flush() {
this.writing = true;
// Coalesce synchronous PQueue handoffs and keep SQLite writes in observation order.
void Promise.resolve().then(async () => {
try {
while (this.changed) {
this.changed = false;
const context = JSON.stringify(this.snapshot(this.limit()));
const groups = new Map<Sequelize, string[]>();
for (const [id, db] of this.waiting) {
const ids = groups.get(db);
if (ids) ids.push(id);
else groups.set(db, [id]);
}
for (const [db, ids] of groups) {
await db
.query(
`UPDATE CronTriggers SET queue_live_context=$context
WHERE state='queued' AND dequeued_at IS NULL AND id IN (SELECT value FROM json_each($ids))`,
{ bind: { context, ids: JSON.stringify(ids) } },
)
.catch(this.warn);
}
}
} finally {
this.writing = false;
this.changed = false;
try {
const context = JSON.stringify(this.snapshot(this.limit()));
const groups = new Map<Sequelize, Map<string, WaitingSample>>();
for (const [id, sample] of this.waiting) {
if (sample.context === context) continue;
let group = groups.get(sample.db);
if (!group) groups.set(sample.db, (group = new Map()));
group.set(id, sample);
}
});
for (const [db, samples] of groups) {
try {
await executionModel(db, 'CronTriggers').update(
{ queue_live_context: context },
{
where: {
state: 'queued',
dequeued_at: null,
[Op.or]: [
{ queue_live_context: null },
{ queue_live_context: { [Op.ne]: context } },
],
id: { [Op.in]: [...samples.keys()] },
},
hooks: false,
validate: false,
},
);
for (const [id, sample] of samples) {
// A removed/re-admitted ID belongs to a different observation.
if (this.waiting.get(id) === sample) sample.context = context;
}
} catch (error) {
this.warn(error as Error);
}
}
} finally {
this.writing = false;
if (this.changed) this.refresh();
}
}
admission(limit: number): Admission | undefined {
@@ -104,24 +140,145 @@ export function recordQueueAdmission(
id: string,
admission: Admission,
) {
return db.query(
'UPDATE CronTriggers SET queue_context=$context WHERE id=$id AND queued_at <= $at AND queue_context IS NULL',
{ bind: { id, at: Date.now(), context: JSON.stringify(admission) } },
return executionModel(db, 'CronTriggers').update(
{ queue_context: JSON.stringify(admission) },
{
where: { id, queued_at: { [Op.lte]: Date.now() }, queue_context: null },
silent: true,
hooks: false,
validate: false,
},
);
}
export function oldestQueued(db: Sequelize) {
return db.query<{
id: string;
name: string;
source: string;
queued_at: number;
queue_context: string | null;
queue_live_context: string | null;
}>(
`SELECT t.id, COALESCE(NULLIF(c.name,''), c.command, '#' || t.cron_id) AS name, t.source,t.queued_at,t.queue_context,t.queue_live_context
FROM CronTriggers t LEFT JOIN Crontabs c ON c.id=t.cron_id
WHERE t.state='queued' AND t.dequeued_at IS NULL AND t.queued_at IS NOT NULL ORDER BY t.queued_at,t.id LIMIT 25`,
{ type: QueryTypes.SELECT },
);
return executionModel(db, 'CronTriggers').findAll({
attributes: [
'id',
[
fn(
'COALESCE',
fn('NULLIF', col('task.name'), ''),
col('task.command'),
fn('printf', '#%s', col('CronTriggers.cron_id')),
),
'name',
],
'source',
'queued_at',
'queue_context',
'queue_live_context',
],
where: {
state: 'queued',
dequeued_at: null,
queued_at: { [Op.not]: null },
},
include: [
{
association: executionAssociation(db, 'triggerTask'),
attributes: [],
required: false,
},
],
order: [
['queued_at', 'ASC'],
['id', 'ASC'],
],
limit: 25,
raw: true,
}) as unknown as Promise<
Array<{
id: string;
name: string;
source: string;
queued_at: number;
queue_context: string | null;
queue_live_context: string | null;
}>
>;
}
// The shared budget supplies its existing occupancy snapshot, including foreign
// workers. Diagnostics never open a transaction on the admission critical path.
export class GlobalQueueDiagnostics {
private pending = new Map<string, string>();
private sampled = new Map<string, string>();
private timer?: NodeJS.Timeout;
private writing = false;
constructor(private db: Sequelize) {}
observe(ids: string[], admission?: Admission) {
const context = admission && JSON.stringify(admission);
this.pending = new Map(
ids.map((id) => [id, context ?? this.pending.get(id) ?? '']),
);
for (const id of this.sampled.keys())
if (!this.pending.has(id)) this.sampled.delete(id);
if (!ids.length) {
clearTimeout(this.timer);
this.timer = undefined;
} else this.schedule();
}
private schedule() {
if (
this.timer ||
this.writing ||
![...this.pending].some(
([id, value]) => value && this.sampled.get(id) !== value,
)
)
return;
this.timer = setTimeout(() => {
this.timer = undefined;
void this.flush();
}, LIVE_SAMPLE_INTERVAL_MS);
this.timer.unref();
}
private async flush() {
this.writing = true;
const groups = new Map<string, string[]>();
for (const [id, context] of this.pending) {
if (!context || this.sampled.get(id) === context) continue;
const group = groups.get(context) ?? [];
group.push(id);
groups.set(context, group);
}
try {
for (const [context, ids] of groups) {
await executionModel(this.db, 'CronTriggers').update(
{
queue_context: fn('COALESCE', col('queue_context'), context),
queue_live_context: context,
},
{
where: {
id: { [Op.in]: ids },
state: 'queued',
dequeued_at: null,
[Op.or]: [
{ queue_live_context: null },
{ queue_live_context: { [Op.ne]: context } },
],
},
hooks: false,
validate: false,
},
);
for (const id of ids)
if (this.pending.get(id) === context) this.sampled.set(id, context);
}
} catch (error) {
console.warn('[queue] Could not save global occupancy:', error);
// A later observation retries a failed sample, without a timer that can
// outlive the budget/database after the last waiter has left.
return;
} finally {
this.writing = false;
}
this.schedule();
}
}
+5 -1
View File
@@ -53,7 +53,11 @@ export class TriggerQueries {
scriptStartP95: number | null;
scriptOnTime: number;
}>(
`WITH today AS (SELECT * FROM CronTriggers WHERE observed_at >= $since),
// Reuse a narrow snapshot: inlining this CTE makes each count/percentile
// revisit the wide trigger rows, including their queue diagnostics.
`WITH today AS MATERIALIZED (
SELECT state,observed_at,scheduled_at,started_at,script_started_at,dequeued_at,queued_at
FROM CronTriggers WHERE observed_at >= $since),
triggers AS (SELECT ABS(observed_at - scheduled_at) AS deviation FROM today WHERE scheduled_at IS NOT NULL),
scripts AS (SELECT script_started_at - scheduled_at AS delay FROM today
WHERE scheduled_at IS NOT NULL AND script_started_at >= scheduled_at),
@@ -0,0 +1,51 @@
import { executionModel } from '../../data/executionModels';
import { Op } from 'sequelize';
import type { ICron } from '../../protos/cron';
import { CrontabModel } from '../../data/cron';
import { slotId } from '../identity';
import { runCron } from '../execution/runCron';
// Accepted work is distinct from catching up timers missed while offline.
// Keep its identity and original queue deadline; never replay a bound command.
export async function resumeAcceptedCrons(item: ICron, current: () => boolean) {
const rows = await executionModel(
CrontabModel.sequelize!,
'CronTriggers',
).findAll({
attributes: ['id', 'scheduled_at', 'queued_at'],
where: {
cron_id: Number(item.id),
source: { [Op.in]: ['node', 'recovery'] },
state: 'skipped',
reason: 'restart',
resume_pending: 1,
started_at: null,
queued_at: { [Op.gte]: item.recovery_from || 0 },
},
order: [
['queued_at', 'ASC'],
['id', 'ASC'],
],
raw: true,
});
const rules = [
item.schedule,
...(item.extra_schedules || []).map((s) => s.schedule),
];
await Promise.all(
rows
.filter((row) =>
rules.some(
(rule, i) => slotId(item.id, i, rule, row.scheduled_at!) === row.id,
),
)
.map((row) =>
runCron(item.command, item, current, {
id: row.id,
time: row.scheduled_at!,
queuedAt: row.queued_at!,
source: 'recovery',
}),
),
);
}
+16 -10
View File
@@ -1,3 +1,4 @@
import { executionModel } from '../../data/executionModels';
import { AnomalyPage } from '../queries/scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { AddCronRequest, DeleteCronRequest } from '../../protos/cron';
@@ -61,14 +62,14 @@ export async function saveSchedulePlan(
token: token ?? null,
};
if (token)
await db.query(
'INSERT INTO CronPlanSwitches(token,staged_at) VALUES($token,$now)',
{ transaction, bind: { token, now } },
await executionModel(db, 'CronPlanSwitches').create(
{ token, staged_at: now },
{ transaction, silent: true, hooks: false, validate: false },
);
if (replace)
await db.query(
'INSERT OR IGNORE INTO CronPlanCoverage(id,since) VALUES(1,$now)',
{ transaction, bind: { now } },
await executionModel(db, 'CronPlanCoverage').bulkCreate(
[{ id: 1, since: now }],
{ transaction, ignoreDuplicates: true, hooks: false },
);
const desired = `WITH desired AS (SELECT json_extract(value,'$.task') AS task, json_extract(value,'$.index') AS idx,
json_extract(value,'$.schedule') AS schedule FROM json_each($rules))`;
@@ -105,10 +106,15 @@ export async function confirmSchedulePlan(
replace: boolean,
) {
await db.transaction(async (transaction) => {
await db.query(
`UPDATE CronPlanSwitches SET first_at=$first,last_at=$last
WHERE token=$token AND last_at IS NULL`,
{ transaction, bind: { token, first, last } },
await executionModel(db, 'CronPlanSwitches').update(
{ first_at: first, last_at: last },
{
where: { token, last_at: null },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
if (replace) {
// After a crash the former worker's switch time is unknowable. A complete
+39 -19
View File
@@ -1,3 +1,4 @@
import { executionModel } from '../../data/executionModels';
import { AnomalyPage } from '../queries/scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { blockSize, blockSlots } from './scheduleAudit';
@@ -35,20 +36,29 @@ export async function stageSystemPlan(
return db.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction) => {
const [pending] = await db.query<{ id: number }>(
`SELECT id FROM (SELECT * FROM CronSystemPlans ORDER BY id DESC LIMIT 1)
WHERE confirmed IS NULL AND zone=$zone AND rules=$rules`,
{
bind: { zone: bind.zone, rules: bind.rules },
const [pending] = await executionModel(db, 'CronSystemPlans')
.findAll({
attributes: ['id', 'confirmed', 'zone', 'rules'],
order: [['id', 'DESC']],
limit: 1,
transaction,
type: QueryTypes.SELECT,
},
);
raw: true,
})
.then((rows) =>
rows.filter(
(row) =>
row.confirmed === null &&
row.zone === bind.zone &&
row.rules === bind.rules,
),
);
if (pending) return pending.id;
const [id] = await db.query(
'INSERT INTO CronSystemPlans(staged,zone,rules) VALUES ($at,$zone,$rules)',
{ bind, transaction, type: QueryTypes.INSERT },
);
const [id] = await executionModel(db, 'CronSystemPlans')
.create(
{ staged: bind.at, zone: bind.zone, rules: bind.rules },
{ transaction, silent: true, hooks: false, validate: false },
)
.then((row) => [row.id] as const);
return id;
},
);
@@ -70,9 +80,15 @@ export async function confirmSystemPlan(
at = Date.now(),
) {
await db.transaction(async (transaction) => {
await db.query(
'UPDATE CronSystemPlans SET confirmed=$at WHERE id=$id AND confirmed IS NULL',
{ transaction, bind: { id, at } },
await executionModel(db, 'CronSystemPlans').update(
{ confirmed: at },
{
where: { id, confirmed: null },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
// Keep the effective snapshot preceding the retention window.
await db.query(
@@ -94,10 +110,14 @@ export async function systemScheduleAudit(
const { since, installs, receipts } = await db.transaction(
{ type: Transaction.TYPES.DEFERRED },
async (transaction) => {
const [retention] = await db.query<{ since: number }>(
'SELECT MAX($dayStart,COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)) AS since',
{ transaction, bind: { dayStart }, type: QueryTypes.SELECT },
);
const [retention] = await executionModel(db, 'CronHistoryRetention')
.findAll({
attributes: ['cutoff'],
where: { id: 1 },
transaction,
raw: true,
})
.then(([row]) => [{ since: Math.max(dayStart, row?.cutoff ?? 0) }]);
const since = retention.since;
const installs = await db.query<Install>(
`SELECT * FROM CronSystemPlans WHERE id >= COALESCE((SELECT MAX(id) FROM CronSystemPlans
+201 -59
View File
@@ -1,4 +1,10 @@
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import {
QueryTypes,
Sequelize,
Transaction,
DataTypes,
ModelAttributes,
} from 'sequelize';
export async function installTriggerHistory(
database: Sequelize,
@@ -7,46 +13,143 @@ export async function installTriggerHistory(
const conflictTable = `CREATE TABLE IF NOT EXISTS CronBoundExitConflicts (
trigger_id TEXT NOT NULL, outcome TEXT NOT NULL, finished_at INTEGER NOT NULL,
PRIMARY KEY(trigger_id,outcome,finished_at)) WITHOUT ROWID`;
const statements = [
`CREATE TABLE IF NOT EXISTS CronPlanSwitches (seq INTEGER PRIMARY KEY, token TEXT UNIQUE NOT NULL,
staged_at INTEGER NOT NULL, first_at INTEGER, last_at INTEGER)`,
const statements: Array<
string | { table: string; attributes: ModelAttributes }
> = [
`CREATE TABLE IF NOT EXISTS CronConcurrencyLeases (
trigger_id TEXT PRIMARY KEY, token TEXT NOT NULL, owner TEXT NOT NULL,
command_identity TEXT) WITHOUT ROWID`,
`CREATE TABLE IF NOT EXISTS CronConcurrencyWaiters (
trigger_id TEXT PRIMARY KEY REFERENCES CronTriggers(id) ON DELETE CASCADE,
token TEXT NOT NULL, owner TEXT NOT NULL) WITHOUT ROWID`,
{
table: 'CronPlanSwitches',
attributes: {
seq: { type: DataTypes.INTEGER, primaryKey: true },
token: { type: DataTypes.TEXT, allowNull: false, unique: true },
staged_at: { type: DataTypes.INTEGER, allowNull: false },
first_at: { type: DataTypes.INTEGER },
last_at: { type: DataTypes.INTEGER },
},
},
'CREATE TABLE IF NOT EXISTS CronPlanCoverage (id INTEGER PRIMARY KEY CHECK(id=1), since INTEGER NOT NULL)',
`CREATE TABLE IF NOT EXISTS CronPlanRules (
cron_id TEXT NOT NULL, rule_index INTEGER NOT NULL, schedule TEXT NOT NULL, zone TEXT NOT NULL,
since INTEGER NOT NULL, until INTEGER)`,
{
table: 'CronPlanRules',
attributes: {
cron_id: { type: DataTypes.TEXT, allowNull: false },
rule_index: { type: DataTypes.INTEGER, allowNull: false },
schedule: { type: DataTypes.TEXT, allowNull: false },
zone: { type: DataTypes.TEXT, allowNull: false },
since: { type: DataTypes.INTEGER, allowNull: false },
until: { type: DataTypes.INTEGER },
},
},
'CREATE UNIQUE INDEX IF NOT EXISTS cron_plan_active ON CronPlanRules(cron_id,rule_index) WHERE until IS NULL',
`CREATE TABLE IF NOT EXISTS CronTriggers (
id TEXT PRIMARY KEY, cron_id INTEGER NOT NULL, source TEXT NOT NULL, state TEXT NOT NULL,
scheduled_at INTEGER, queued_at INTEGER, started_at INTEGER, finished_at INTEGER,
reason TEXT, exit_code INTEGER, log_path TEXT, counted INTEGER NOT NULL DEFAULT 0,
owner TEXT, observed_at INTEGER NOT NULL)`,
`CREATE TABLE IF NOT EXISTS CronShellBindings (
receipt TEXT PRIMARY KEY, trigger_id TEXT NOT NULL REFERENCES CronTriggers(id) ON DELETE CASCADE)`,
{
table: 'CronTriggers',
attributes: {
id: { type: DataTypes.TEXT, primaryKey: true },
cron_id: { type: DataTypes.INTEGER, allowNull: false },
source: { type: DataTypes.TEXT, allowNull: false },
state: { type: DataTypes.TEXT, allowNull: false },
scheduled_at: { type: DataTypes.INTEGER },
queued_at: { type: DataTypes.INTEGER },
started_at: { type: DataTypes.INTEGER },
finished_at: { type: DataTypes.INTEGER },
reason: { type: DataTypes.TEXT },
exit_code: { type: DataTypes.INTEGER },
log_path: { type: DataTypes.TEXT },
counted: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
owner: { type: DataTypes.TEXT },
observed_at: { type: DataTypes.INTEGER, allowNull: false },
},
},
`CREATE TABLE IF NOT EXISTS CronManualSubmissions (
trigger_id TEXT PRIMARY KEY REFERENCES CronTriggers(id) ON DELETE CASCADE,
token TEXT NOT NULL, snapshot TEXT NOT NULL) WITHOUT ROWID`,
{
table: 'CronShellBindings',
attributes: {
receipt: { type: DataTypes.TEXT, primaryKey: true },
trigger_id: {
type: DataTypes.TEXT,
allowNull: false,
references: { model: 'CronTriggers', key: 'id' },
onDelete: 'CASCADE',
},
},
},
'CREATE INDEX IF NOT EXISTS cron_shell_binding_trigger ON CronShellBindings(trigger_id)',
`CREATE TABLE IF NOT EXISTS CronExitObservations (
trigger_id TEXT NOT NULL REFERENCES CronTriggers(id) ON DELETE CASCADE,
outcome TEXT NOT NULL, finished_at INTEGER NOT NULL,
PRIMARY KEY(trigger_id,outcome,finished_at)) WITHOUT ROWID`,
`CREATE TABLE IF NOT EXISTS CronLegacyExitBookings (
trigger_id TEXT PRIMARY KEY, cron_id INTEGER NOT NULL, source TEXT NOT NULL, started_at INTEGER NOT NULL,
finished_at INTEGER NOT NULL, outcome TEXT NOT NULL, day TEXT NOT NULL, stopped INTEGER NOT NULL DEFAULT 0,
stat_id INTEGER REFERENCES CrontabStats(id) ON DELETE SET NULL, disputed INTEGER NOT NULL DEFAULT 0)`,
{
table: 'CronLegacyExitBookings',
attributes: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
cron_id: { type: DataTypes.INTEGER, allowNull: false },
source: { type: DataTypes.TEXT, allowNull: false },
started_at: { type: DataTypes.INTEGER, allowNull: false },
finished_at: { type: DataTypes.INTEGER, allowNull: false },
outcome: { type: DataTypes.TEXT, allowNull: false },
day: { type: DataTypes.TEXT, allowNull: false },
stopped: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
stat_id: {
type: DataTypes.INTEGER,
references: { model: 'CrontabStats', key: 'id' },
onDelete: 'SET NULL',
},
disputed: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
},
},
`CREATE TABLE IF NOT EXISTS CronPrunedUnknownRuns (
trigger_id TEXT PRIMARY KEY, cron_id INTEGER NOT NULL REFERENCES Crontabs(id) ON DELETE CASCADE,
source TEXT NOT NULL, started_at INTEGER NOT NULL, last_possible_day TEXT NOT NULL) WITHOUT ROWID`,
'CREATE INDEX IF NOT EXISTS cron_pruned_unknown_day ON CronPrunedUnknownRuns(last_possible_day)',
`CREATE TABLE IF NOT EXISTS CronSystemPlans (id INTEGER PRIMARY KEY, staged INTEGER NOT NULL, confirmed INTEGER, zone TEXT NOT NULL, rules TEXT NOT NULL)`,
{
table: 'CronSystemPlans',
attributes: {
id: { type: DataTypes.INTEGER, primaryKey: true },
staged: { type: DataTypes.INTEGER, allowNull: false },
confirmed: { type: DataTypes.INTEGER },
zone: { type: DataTypes.TEXT, allowNull: false },
rules: { type: DataTypes.TEXT, allowNull: false },
},
},
conflictTable,
`CREATE TABLE IF NOT EXISTS CronUnmatchedBoundExits (
trigger_id TEXT PRIMARY KEY, outcome TEXT NOT NULL, finished_at INTEGER NOT NULL) WITHOUT ROWID`,
'CREATE INDEX IF NOT EXISTS cron_legacy_booking_stat ON CronLegacyExitBookings(stat_id) WHERE stat_id IS NOT NULL',
'CREATE TABLE IF NOT EXISTS CronStatRetention (id INTEGER PRIMARY KEY CHECK(id=1), first_day TEXT NOT NULL)',
'CREATE TABLE IF NOT EXISTS CronHistoryRetention (id INTEGER PRIMARY KEY CHECK(id=1), cutoff INTEGER NOT NULL)',
`CREATE TABLE IF NOT EXISTS CronStopBatches (
request_id TEXT PRIMARY KEY, cron_ids TEXT NOT NULL, snapshot TEXT)`,
{
table: 'CronStopBatches',
attributes: {
request_id: { type: DataTypes.TEXT, primaryKey: true },
cron_ids: { type: DataTypes.TEXT, allowNull: false },
snapshot: { type: DataTypes.TEXT },
},
},
'CREATE INDEX IF NOT EXISTS cron_stop_batch_pending ON CronStopBatches(request_id) WHERE snapshot IS NOT NULL',
`CREATE TABLE IF NOT EXISTS CronStopRequests (
instance_id INTEGER PRIMARY KEY, cron_id INTEGER NOT NULL, pid INTEGER NOT NULL, targets TEXT, signalled INTEGER NOT NULL DEFAULT 0)`,
{
table: 'CronStopRequests',
attributes: {
instance_id: { type: DataTypes.INTEGER, primaryKey: true },
cron_id: { type: DataTypes.INTEGER, allowNull: false },
pid: { type: DataTypes.INTEGER, allowNull: false },
targets: { type: DataTypes.TEXT },
signalled: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
},
},
'CREATE INDEX IF NOT EXISTS cron_trigger_recent ON CronTriggers(cron_id, observed_at DESC)',
"CREATE INDEX IF NOT EXISTS cron_trigger_running_task ON CronTriggers(cron_id) WHERE state='running'",
"CREATE INDEX IF NOT EXISTS cron_trigger_queued_task ON CronTriggers(cron_id) WHERE state='queued'",
@@ -54,27 +157,41 @@ export async function installTriggerHistory(
'CREATE INDEX IF NOT EXISTS cron_trigger_slot ON CronTriggers(scheduled_at) WHERE scheduled_at IS NOT NULL',
'CREATE INDEX IF NOT EXISTS cron_trigger_active ON CronTriggers(source, state) WHERE finished_at IS NULL',
];
for (const sql of statements) await database.query(sql, { transaction });
for (const statement of statements) {
if (typeof statement === 'string')
await database.query(statement, { transaction });
else
await database
.getQueryInterface()
.createTable(statement.table, statement.attributes, { transaction });
}
// Sequelize 6 describeTable cannot inspect expression indexes (the indexed
// column name is null). Keep PRAGMA introspection for upgrade compatibility.
const planFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronPlanRules)',
{ transaction, type: QueryTypes.SELECT },
);
for (const column of ['opened_by', 'closed_by']) {
if (!planFields.some((field) => field.name === column))
await database.query(
`ALTER TABLE CronPlanRules ADD COLUMN ${column} TEXT`,
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronPlanRules',
column,
{ type: DataTypes.TEXT },
{ transaction },
);
}
const conflictFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronBoundExitConflicts)',
{ transaction, type: QueryTypes.SELECT },
);
if (conflictFields.some((field) => field.name === 'other_outcome')) {
await database.query(
'ALTER TABLE CronBoundExitConflicts RENAME TO CronBoundExitConflictPairs',
{ transaction },
);
await database
.getQueryInterface()
.renameTable('CronBoundExitConflicts', 'CronBoundExitConflictPairs', {
transaction,
});
await database.query(conflictTable, { transaction });
await database.query(
`INSERT INTO CronBoundExitConflicts(trigger_id,outcome,finished_at)
@@ -82,47 +199,67 @@ export async function installTriggerHistory(
SELECT trigger_id,other_outcome,other_finished_at FROM CronBoundExitConflictPairs`,
{ transaction },
);
await database.query('DROP TABLE CronBoundExitConflictPairs', {
transaction,
});
await database
.getQueryInterface()
.dropTable('CronBoundExitConflictPairs', { transaction });
}
const bookingFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronLegacyExitBookings)',
{ transaction, type: QueryTypes.SELECT },
);
if (!bookingFields.some((field) => field.name === 'bound'))
await database.query(
'ALTER TABLE CronLegacyExitBookings ADD COLUMN bound INTEGER NOT NULL DEFAULT 0',
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronLegacyExitBookings',
'bound',
{ type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
{ transaction },
);
const batchFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronStopBatches)',
{ transaction, type: QueryTypes.SELECT },
);
if (!batchFields.some((column) => column.name === 'status_code'))
await database.query(
'ALTER TABLE CronStopBatches ADD COLUMN status_code INTEGER NOT NULL DEFAULT 200',
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronStopBatches',
'status_code',
{ type: DataTypes.INTEGER, allowNull: false, defaultValue: 200 },
{ transaction },
);
const stopFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronStopRequests)',
{ transaction, type: QueryTypes.SELECT },
);
if (!stopFields.some((column) => column.name === 'signalled_at'))
await database.query(
'ALTER TABLE CronStopRequests ADD COLUMN signalled_at INTEGER',
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronStopRequests',
'signalled_at',
{ type: DataTypes.INTEGER },
{ transaction },
);
if (!stopFields.some((column) => column.name === 'root_identity'))
await database.query(
'ALTER TABLE CronStopRequests ADD COLUMN root_identity TEXT',
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronStopRequests',
'root_identity',
{ type: DataTypes.TEXT },
{ transaction },
);
if (!stopFields.some((column) => column.name === 'namespace_owner'))
await database.query(
'ALTER TABLE CronStopRequests ADD COLUMN namespace_owner TEXT',
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronStopRequests',
'namespace_owner',
{ type: DataTypes.TEXT },
{ transaction },
);
const fields = await database.query<{ name: string }>(
'PRAGMA table_info(CronTriggers)',
{ transaction, type: QueryTypes.SELECT },
@@ -137,6 +274,7 @@ export async function installTriggerHistory(
['instance_id', 'INTEGER'],
['script_started_at', 'INTEGER'],
['stop_requested', 'INTEGER'],
['resume_pending', 'INTEGER'],
['process_identity', 'TEXT'],
['command_identity', 'TEXT'],
['stop_exit_at', 'INTEGER'],
@@ -144,10 +282,14 @@ export async function installTriggerHistory(
['exit_pending', 'INTEGER'],
]) {
if (!fields.some((field) => field.name === column))
await database.query(
`ALTER TABLE CronTriggers ADD COLUMN ${column} ${type}`,
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronTriggers',
column,
{ type: type === 'TEXT' ? DataTypes.TEXT : DataTypes.INTEGER },
{ transaction },
);
}
await database.query(
`CREATE TRIGGER IF NOT EXISTS cron_exit_observations_settled AFTER UPDATE OF counted ON CronTriggers
+1
View File
@@ -1,6 +1,7 @@
import dayjs from 'dayjs';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
// This per-exit claim stays bound SQL; its affected-row count gates the increment.
// Hold the receipt claim and the daily increment in the same write transaction.
export async function recordCronResult(
database: Sequelize,
+183 -104
View File
@@ -1,3 +1,28 @@
import dayjs from 'dayjs';
import { promises as fs } from 'fs';
import { basename, join } from 'path';
import {
Op,
QueryTypes,
Sequelize,
Transaction,
col,
fn,
literal,
where,
} from 'sequelize';
import { executionModel } from '../../data/executionModels';
import type {
TriggerLifecycle,
TriggerLifecycleEvidence,
} from '../execution/triggerLifecycle';
import type {
Trigger,
TriggerSource,
TriggerState,
VerifiedSupervisorExit,
} from '../types';
import { addDailyExit, recordCronResult } from './cronStatistics';
import {
isLegacyCapture,
isMetadataReceipt,
@@ -9,21 +34,6 @@ import {
retiringExits,
validExit,
} from './exitReceipt.cjs';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import dayjs from 'dayjs';
import { addDailyExit, recordCronResult } from './cronStatistics';
import { promises as fs } from 'fs';
import { basename, join } from 'path';
import type {
Trigger,
TriggerSource,
TriggerState,
VerifiedSupervisorExit,
} from '../types';
import type {
TriggerLifecycle,
TriggerLifecycleEvidence,
} from '../execution/triggerLifecycle';
// The lifecycle owns transition guards; settlement must use its caller's transaction.
export type TriggerSettlementLifecycle = Pick<
@@ -56,6 +66,8 @@ function isBoundPublication(file: string) {
);
}
// High-frequency receipt/instance updates use bound SQL to avoid model query
// construction while the writer is held. Infrequent recovery reads stay ORM.
// Receipt verification, disputes and statistics are one transactional unit.
// Durable evidence is retired only after the committed outcome is checked again.
export class TriggerSettlement implements TriggerLifecycleEvidence {
@@ -402,22 +414,24 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
transaction,
},
);
await this.database.query(
'DELETE FROM CrontabStats WHERE id=$stat AND run_count=0',
{ bind: { stat }, transaction },
);
await executionModel(this.database, 'CrontabStats').destroy({
where: { id: stat, run_count: 0 },
transaction,
hooks: false,
});
}
}
private async invalidateBookedTrigger(id: string, transaction: Transaction) {
const [trigger] = await this.database.query<{
instance_id: number | null;
state: TriggerState;
cron_id: number;
}>(
'SELECT instance_id,state,cron_id FROM CronTriggers WHERE id=$id AND started_at IS NOT NULL',
{ bind: { id }, type: QueryTypes.SELECT, transaction },
);
const [trigger] = await executionModel(
this.database,
'CronTriggers',
).findAll({
attributes: ['instance_id', 'state', 'cron_id'],
where: { id, started_at: { [Op.not]: null } },
transaction,
raw: true,
});
if (!trigger) return false;
const ref = trigger.cron_id;
await this.database.query(
@@ -426,13 +440,25 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
{ bind: { id }, transaction },
);
if (trigger.instance_id !== null && trigger.state !== 'running') {
await this.database.query(
'UPDATE RunningInstances SET status=4,exit_code=NULL,updatedAt=CURRENT_TIMESTAMP WHERE id=$instance AND cron_id=$ref',
{ bind: { instance: trigger.instance_id, ref }, transaction },
await executionModel(this.database, 'RunningInstances').update(
{ status: 4, exit_code: null, updatedAt: literal('CURRENT_TIMESTAMP') },
{
where: { id: trigger.instance_id, cron_id: ref },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
await this.database.query(
'UPDATE Crontabs SET last_running_time=NULL WHERE id=$ref AND last_instance_id=$instance',
{ bind: { ref, instance: trigger.instance_id }, transaction },
await executionModel(this.database, 'Crontabs').update(
{ last_running_time: null },
{
where: { id: ref, last_instance_id: trigger.instance_id },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
}
return true;
@@ -444,10 +470,13 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
transaction: Transaction,
) {
if (!tuples.length) return;
await this.database.query(
`INSERT OR IGNORE INTO CronBoundExitConflicts(trigger_id,outcome,finished_at)
SELECT $id,json_extract(value,'$.outcome'),json_extract(value,'$.time') FROM json_each($tuples)`,
{ bind: { id, tuples: JSON.stringify(tuples) }, transaction },
await executionModel(this.database, 'CronBoundExitConflicts').bulkCreate(
tuples.map((tuple) => ({
trigger_id: id,
outcome: tuple.outcome,
finished_at: tuple.time,
})),
{ transaction, ignoreDuplicates: true, hooks: false },
);
}
@@ -502,9 +531,15 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
const retained = await this.invalidateBookedTrigger(id, transaction);
if (!retained) {
if (!bound) {
await this.database.query(
'UPDATE CronLegacyExitBookings SET disputed=1,stat_id=NULL WHERE trigger_id=$id',
{ bind: { id }, transaction },
await executionModel(this.database, 'CronLegacyExitBookings').update(
{ disputed: 1, stat_id: null },
{
where: { trigger_id: id },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
} else {
await this.bookPrunedExit(
@@ -516,18 +551,21 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
}
return false;
}
await this.database.query(
'DELETE FROM CronLegacyExitBookings WHERE trigger_id=$id',
{ bind: { id }, transaction },
);
await executionModel(this.database, 'CronLegacyExitBookings').destroy({
where: { trigger_id: id },
transaction,
hooks: false,
});
if (!bound)
await this.database.query(
`INSERT OR IGNORE INTO CronExitObservations(trigger_id,outcome,finished_at)
VALUES($id,$outcome,$time)`,
{
bind: { id, outcome: booking.outcome, time: booking.finished_at },
transaction,
},
await executionModel(this.database, 'CronExitObservations').bulkCreate(
[
{
trigger_id: id,
outcome: booking.outcome,
finished_at: booking.finished_at,
},
],
{ transaction, ignoreDuplicates: true, hooks: false },
);
return true;
}
@@ -575,13 +613,15 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
// Sequelize also invokes this hook after a failed COMMIT. Verify the
// specific tuple in a separate snapshot, including on an existing dispute.
try {
const rows = await this.database.query<{
outcome: string;
finished_at: number;
}>(
'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id',
{ bind: { id }, transaction: null, type: QueryTypes.SELECT },
);
const rows = await executionModel(
this.database,
'CronBoundExitConflicts',
).findAll({
attributes: ['outcome', 'finished_at'],
where: { trigger_id: id },
transaction: null,
raw: true,
});
const committed = new Set(
rows.map((row) => JSON.stringify([row.outcome, row.finished_at])),
);
@@ -699,11 +739,21 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
if (unreadable.size) {
// Retention runs this scan before deletion. Keep unresolved history for
// later repair without ending a live process solely on damaged bytes.
await this.database.query(
`UPDATE CronTriggers SET exit_pending=1 WHERE counted=0 AND state='unknown'
AND exit_pending IS NOT 1 AND owner IS NOT NULL AND started_at IS NOT NULL
AND id IN (SELECT value FROM json_each($ids))`,
{ transaction, bind: { ids: JSON.stringify([...unreadable]) } },
await executionModel(this.database, 'CronTriggers').update(
{ exit_pending: 1 },
{
where: {
counted: 0,
state: 'unknown',
owner: { [Op.not]: null },
started_at: { [Op.not]: null },
id: { [Op.in]: [...unreadable] },
[Op.or]: [{ exit_pending: null }, { exit_pending: { [Op.ne]: 1 } }],
},
transaction,
hooks: false,
validate: false,
},
);
}
for (const [id, copies] of byId) {
@@ -753,11 +803,23 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
exit: ExitObservation,
transaction?: Transaction,
) {
const [match] = await this.database.query(
`SELECT 1 FROM CronExitObservations WHERE trigger_id=$id GROUP BY trigger_id
HAVING COUNT(*)=1 AND MAX(outcome)=$outcome AND MAX(finished_at)=$time`,
{ bind: observationKey(id, exit), type: QueryTypes.SELECT, transaction },
);
const [match] = await executionModel(
this.database,
'CronExitObservations',
).findAll({
attributes: ['trigger_id'],
where: { trigger_id: id },
group: ['trigger_id'],
having: {
[Op.and]: [
where(fn('COUNT', col('trigger_id')), 1),
where(fn('MAX', col('outcome')), observationKey(id, exit).outcome),
where(fn('MAX', col('finished_at')), observationKey(id, exit).time),
],
},
transaction,
raw: true,
});
return Boolean(match);
}
@@ -782,9 +844,18 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
) {
if (observation)
await this.saveExitObservation(id, observation, transaction);
await this.database.query(
'UPDATE CronTriggers SET exit_pending=1 WHERE id=$id AND exit_pending IS NOT 1',
{ bind: { id }, transaction },
await executionModel(this.database, 'CronTriggers').update(
{ exit_pending: 1 },
{
where: {
id,
[Op.or]: [{ exit_pending: { [Op.ne]: 1 } }, { exit_pending: null }],
},
transaction,
silent: true,
hooks: false,
validate: false,
},
);
// A signalled stop remains running until all of its descendants are gone.
await this.database.query(
@@ -850,18 +921,15 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
if (!files.length) return;
// Only probe existing executions. Keep live markers in place so another
// instrumented command in the same execution cannot replace the first sample.
const rows = await this.database.query<{
id: string;
counted: number;
script_started_at: number | null;
}>(
`SELECT id,counted,script_started_at FROM CronTriggers WHERE id IN (SELECT value FROM json_each($ids))
AND started_at IS NOT NULL AND (script_started_at IS NULL OR counted=1)`,
{
bind: { ids: JSON.stringify(files.map(({ id }) => id)) },
type: QueryTypes.SELECT,
const rows = await executionModel(this.database, 'CronTriggers').findAll({
attributes: ['id', 'counted', 'script_started_at'],
where: {
id: { [Op.in]: files.map(({ id }) => id) },
started_at: { [Op.not]: null },
[Op.or]: [{ script_started_at: null }, { counted: 1 }],
},
);
raw: true,
});
for (const row of rows) {
const sample = await this.readScriptSample(row.id);
if (!sample) continue;
@@ -885,14 +953,14 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
// exit file was already deleted. An unregistered entry may still be live.
const exits = new Set(await publishedExits());
for (const { id, file } of await publishedScriptStarts()) {
const [row] = await this.database.query<{
counted: number;
script_started_at: number | null;
}>('SELECT counted,script_started_at FROM CronTriggers WHERE id=$id', {
bind: { id },
transaction,
type: QueryTypes.SELECT,
});
const [row] = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: ['counted', 'script_started_at'],
where: { id },
transaction,
raw: true,
},
);
// After pruning the trigger, a matching supervisor exit still identifies
// this panel's retired run. A start file alone cannot establish that.
if (row ? row.counted && row.script_started_at !== null : exits.has(id)) {
@@ -1018,10 +1086,15 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
}
async hasBoundConflict(id: string, transaction: Transaction) {
const [conflict] = await this.database.query(
'SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=$id',
{ bind: { id }, transaction, type: QueryTypes.SELECT },
);
const [conflict] = await executionModel(
this.database,
'CronBoundExitConflicts',
).findAll({
attributes: ['trigger_id'],
where: { trigger_id: id },
transaction,
raw: true,
});
return Boolean(conflict);
}
@@ -1037,19 +1110,25 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
) {
return this.database.transaction(async (transaction) => {
if (await this.hasBoundConflict(id, transaction)) return;
const [row] = await this.database.query<{
owner: string | null;
state: TriggerState;
}>(
'SELECT owner,state FROM CronTriggers WHERE id=$id AND cron_id=$cronId',
{ transaction, type: QueryTypes.SELECT, bind: { id, cronId } },
const [row] = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: ['owner', 'state'],
where: { id, cron_id: cronId },
transaction,
raw: true,
},
);
if (!row) {
if (finishedAt && finishedAt <= now) {
const [pruned] = await this.database.query(
'SELECT 1 FROM CronHistoryRetention WHERE id=1 AND cutoff>$end',
{ transaction, type: QueryTypes.SELECT, bind: { end: finishedAt } },
);
const [pruned] = await executionModel(
this.database,
'CronHistoryRetention',
).findAll({
attributes: ['id'],
where: { id: 1, cutoff: { [Op.gt]: finishedAt } },
transaction,
raw: true,
});
if (pruned) return;
}
throw new Error('Unknown trigger');
+3 -39
View File
@@ -1,5 +1,6 @@
import { defineCrontabModel } from './executionModelDefinitions';
import { sequelize } from '.';
import { DataTypes, Model, ModelDefined } from 'sequelize';
import { Model } from 'sequelize';
export class Crontab {
name?: string;
@@ -72,41 +73,4 @@ export enum CrontabStatus {
}
export interface CronInstance extends Model<Crontab, Crontab>, Crontab {}
export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
name: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
command: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
schedule: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
timestamp: DataTypes.STRING,
saved: DataTypes.BOOLEAN,
status: DataTypes.NUMBER,
isSystem: DataTypes.NUMBER,
pid: DataTypes.NUMBER,
isDisabled: DataTypes.NUMBER,
isPinned: DataTypes.NUMBER,
log_path: DataTypes.STRING,
queued_token: DataTypes.STRING,
labels: DataTypes.JSON,
last_instance_id: DataTypes.INTEGER,
last_running_time: DataTypes.NUMBER,
last_execution_time: DataTypes.NUMBER,
sub_id: { type: DataTypes.NUMBER, allowNull: true },
extra_schedules: DataTypes.JSON,
task_before: DataTypes.STRING,
task_after: DataTypes.STRING,
log_name: DataTypes.STRING,
allow_multiple_instances: DataTypes.NUMBER,
skip_if_pending: DataTypes.BOOLEAN,
max_queue_wait: DataTypes.INTEGER,
catchup_seconds: DataTypes.INTEGER,
recovery_from: DataTypes.BIGINT,
work_dir: DataTypes.STRING,
});
export const CrontabModel = defineCrontabModel(sequelize);
+3 -51
View File
@@ -1,4 +1,5 @@
import { DataTypes, Model } from 'sequelize';
import { defineCrontabStatModel } from './executionModelDefinitions';
import { Model } from 'sequelize';
import { sequelize } from '.';
export class CrontabStat {
@@ -30,53 +31,4 @@ export interface CrontabStatInstance
extends Model<CrontabStat, CrontabStat>,
CrontabStat {}
export const CrontabStatModel = sequelize.define<CrontabStatInstance>(
'CrontabStat',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
ref_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
date: {
type: DataTypes.STRING,
allowNull: false,
},
run_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
success_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fail_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
untimed_count: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
total_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fixed_max_time: { type: DataTypes.NUMBER, allowNull: true },
max_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
},
{
indexes: [
{ unique: true, fields: ['ref_id', 'date'] },
{ fields: ['date'] },
],
},
);
export const CrontabStatModel = defineCrontabStatModel(sequelize);
+160
View File
@@ -0,0 +1,160 @@
import { DataTypes, Sequelize } from 'sequelize';
import type { CronInstance } from './cron';
import type { RunningInstanceModel } from './runningInstance';
import type { CrontabStatInstance } from './cronStats';
import type { SystemInstance } from './system';
export function defineCrontabModel(database: Sequelize) {
return database.define<CronInstance>('Crontab', {
name: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
command: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
schedule: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
timestamp: DataTypes.STRING,
saved: DataTypes.BOOLEAN,
status: DataTypes.NUMBER,
isSystem: DataTypes.NUMBER,
pid: DataTypes.NUMBER,
isDisabled: DataTypes.NUMBER,
isPinned: DataTypes.NUMBER,
log_path: DataTypes.STRING,
queued_token: DataTypes.STRING,
labels: DataTypes.JSON,
last_instance_id: DataTypes.INTEGER,
last_running_time: DataTypes.NUMBER,
last_execution_time: DataTypes.NUMBER,
sub_id: { type: DataTypes.NUMBER, allowNull: true },
extra_schedules: DataTypes.JSON,
task_before: DataTypes.STRING,
task_after: DataTypes.STRING,
log_name: DataTypes.STRING,
allow_multiple_instances: DataTypes.NUMBER,
skip_if_pending: DataTypes.BOOLEAN,
max_queue_wait: DataTypes.INTEGER,
catchup_seconds: DataTypes.INTEGER,
recovery_from: DataTypes.BIGINT,
work_dir: DataTypes.STRING,
});
}
export function defineRunningInstanceModel(database: Sequelize) {
return database.define<RunningInstanceModel>(
'RunningInstance',
{
cron_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
pid: {
type: DataTypes.NUMBER,
allowNull: true,
},
log_path: {
type: DataTypes.STRING,
allowNull: true,
},
started_at: {
type: DataTypes.NUMBER,
allowNull: false,
},
finished_at: {
type: DataTypes.NUMBER,
allowNull: true,
},
status: {
type: DataTypes.NUMBER,
allowNull: false,
defaultValue: 0,
},
exit_code: {
type: DataTypes.NUMBER,
allowNull: true,
},
},
{
indexes: [
{ fields: ['cron_id', 'pid', 'started_at'] },
{ fields: ['cron_id', 'id'] },
// Settlement looks for live siblings while holding the writer transaction.
// Finished history must not make that lookup scan every past execution.
{
name: 'running_instances_active_cron_id',
fields: ['cron_id', 'id'],
where: { status: 0 },
},
],
},
);
}
export function defineCrontabStatModel(database: Sequelize) {
return database.define<CrontabStatInstance>(
'CrontabStat',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
ref_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
date: {
type: DataTypes.STRING,
allowNull: false,
},
run_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
success_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fail_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
untimed_count: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
total_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fixed_max_time: { type: DataTypes.NUMBER, allowNull: true },
max_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
},
{
indexes: [
{ unique: true, fields: ['ref_id', 'date'] },
{ fields: ['date'] },
],
},
);
}
export function defineSystemModel(database: Sequelize) {
return database.define<SystemInstance>('Auth', {
ip: DataTypes.STRING,
type: DataTypes.STRING,
info: {
type: DataTypes.JSON,
allowNull: true,
},
});
}
+390
View File
@@ -0,0 +1,390 @@
import {
defineCrontabModel,
defineRunningInstanceModel,
defineCrontabStatModel,
defineSystemModel,
} from './executionModelDefinitions';
import {
DataTypes,
Model,
ModelStatic,
Sequelize,
ModelAttributes,
} from 'sequelize';
import type { Literal, Fn, Col } from 'sequelize/types/utils';
import type { CronInstance } from './cron';
import type { RunningInstanceModel } from './runningInstance';
import type { CrontabStatInstance } from './cronStats';
import type { SystemInstance } from './system';
import type { TriggerSource, TriggerState } from '../cron/types';
// Ledger tables are installed by versioned migrations, not Model.sync().
// Bind each mapping to its caller's connection: workers and test databases must
// never share the application's singleton or silently open another transaction.
interface LedgerRows {
CronPlanCoverage: { id: number; since: number };
CronTriggers: {
id: string;
source: TriggerSource;
state: TriggerState;
reason: string | null;
log_path: string | null;
owner: string | null;
queue_context: string | null;
queue_live_context: string | null;
system_rule: string | null;
process_identity: string | null;
command_identity: string | null;
cron_id: number;
scheduled_at: number | null;
queued_at: number | null;
started_at: number | null;
finished_at: number | null;
exit_code: number | null;
counted: number;
observed_at: number;
dequeued_at: number | null;
system_dispatch_at: number | null;
command_started_at: number | null;
instance_id: number | null;
script_started_at: number | null;
stop_requested: number | null;
resume_pending: number | null;
stop_exit_at: number | null;
stop_exit_verified: number | null;
exit_pending: number | null;
};
CronConcurrencyLeases: {
trigger_id: string;
token: string;
owner: string;
command_identity: string | null;
};
CronConcurrencyWaiters: {
trigger_id: string;
token: string;
owner: string;
};
CronStopRequests: {
targets: string | null;
root_identity: string | null;
namespace_owner: string | null;
instance_id: number;
cron_id: number;
pid: number | null;
signalled: number;
signalled_at: number | null;
};
CronStopBatches: {
request_id: string;
cron_ids: string;
snapshot: string | null;
status_code: number;
};
CronManualSubmissions: {
trigger_id: string;
token: string;
snapshot: string;
};
CronShellBindings: {
receipt: string;
trigger_id: string | null;
};
CronExitObservations: {
trigger_id: string;
outcome: string;
finished_at: number;
};
CronBoundExitConflicts: {
trigger_id: string;
outcome: string;
finished_at: number;
};
CronUnmatchedBoundExits: {
trigger_id: string;
outcome: string | null;
finished_at: number | null;
};
CronLegacyExitBookings: {
trigger_id: string;
source: TriggerSource;
outcome: string | null;
day: string | null;
cron_id: number;
started_at: number | null;
finished_at: number | null;
stopped: number | null;
stat_id: number | null;
disputed: number | null;
bound: number | null;
};
CronPrunedUnknownRuns: {
trigger_id: string;
source: TriggerSource;
last_possible_day: string;
cron_id: number;
started_at: number;
};
CronHistoryRetention: {
id: number;
cutoff: number;
};
CronPlanSwitches: {
token: string;
seq: number;
staged_at: number | null;
first_at: number | null;
last_at: number | null;
};
CronSystemPlans: {
zone: string;
rules: string;
id: number;
staged: number;
confirmed: number | null;
};
SchemaMigrations: {
id: string;
applied_at: string;
};
}
type Persisted<T> = {
[K in keyof T]-?: undefined extends T[K]
? Exclude<T[K], undefined> | null
: T[K];
} & { id: number; createdAt: Date; updatedAt: Date };
type ExistingRows = {
Crontabs: Persisted<CronInstance['_attributes']>;
RunningInstances: Persisted<RunningInstanceModel['_attributes']>;
CrontabStats: Persisted<CrontabStatInstance['_attributes']>;
Auths: Persisted<SystemInstance['_attributes']>;
};
type Rows = LedgerRows & ExistingRows;
type Creation<T> = { [K in keyof T]?: T[K] | Literal | Fn | Col };
type RowModel<T extends object> = Model<T, Creation<T>> & T;
const definitions: {
[K in keyof LedgerRows]: ModelAttributes<RowModel<LedgerRows[K]>>;
} = {
CronPlanCoverage: {
id: { type: DataTypes.INTEGER, primaryKey: true },
since: DataTypes.BIGINT,
},
CronTriggers: {
id: { type: DataTypes.TEXT, primaryKey: true },
source: DataTypes.TEXT,
state: DataTypes.TEXT,
reason: DataTypes.TEXT,
log_path: DataTypes.TEXT,
owner: DataTypes.TEXT,
queue_context: DataTypes.TEXT,
queue_live_context: DataTypes.TEXT,
system_rule: DataTypes.TEXT,
process_identity: DataTypes.TEXT,
command_identity: DataTypes.TEXT,
cron_id: DataTypes.BIGINT,
scheduled_at: DataTypes.BIGINT,
queued_at: DataTypes.BIGINT,
started_at: DataTypes.BIGINT,
finished_at: DataTypes.BIGINT,
exit_code: DataTypes.BIGINT,
counted: DataTypes.BIGINT,
observed_at: DataTypes.BIGINT,
dequeued_at: DataTypes.BIGINT,
system_dispatch_at: DataTypes.BIGINT,
command_started_at: DataTypes.BIGINT,
instance_id: DataTypes.BIGINT,
script_started_at: DataTypes.BIGINT,
stop_requested: DataTypes.BIGINT,
resume_pending: DataTypes.BIGINT,
stop_exit_at: DataTypes.BIGINT,
stop_exit_verified: DataTypes.BIGINT,
exit_pending: DataTypes.BIGINT,
},
CronConcurrencyLeases: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
token: DataTypes.TEXT,
owner: DataTypes.TEXT,
command_identity: DataTypes.TEXT,
},
CronConcurrencyWaiters: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
token: DataTypes.TEXT,
owner: DataTypes.TEXT,
},
CronStopRequests: {
targets: DataTypes.TEXT,
root_identity: DataTypes.TEXT,
namespace_owner: DataTypes.TEXT,
instance_id: { type: DataTypes.INTEGER, primaryKey: true },
cron_id: DataTypes.BIGINT,
pid: DataTypes.BIGINT,
signalled: DataTypes.BIGINT,
signalled_at: DataTypes.BIGINT,
},
CronStopBatches: {
request_id: { type: DataTypes.TEXT, primaryKey: true },
cron_ids: DataTypes.TEXT,
snapshot: DataTypes.TEXT,
status_code: DataTypes.BIGINT,
},
CronManualSubmissions: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
token: DataTypes.TEXT,
snapshot: DataTypes.TEXT,
},
CronShellBindings: {
receipt: { type: DataTypes.TEXT, primaryKey: true },
trigger_id: DataTypes.TEXT,
},
CronExitObservations: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
outcome: { type: DataTypes.TEXT, primaryKey: true },
finished_at: { type: DataTypes.INTEGER, primaryKey: true },
},
CronBoundExitConflicts: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
outcome: { type: DataTypes.TEXT, primaryKey: true },
finished_at: { type: DataTypes.INTEGER, primaryKey: true },
},
CronUnmatchedBoundExits: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
outcome: DataTypes.TEXT,
finished_at: DataTypes.BIGINT,
},
CronLegacyExitBookings: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
source: DataTypes.TEXT,
outcome: DataTypes.TEXT,
day: DataTypes.TEXT,
cron_id: DataTypes.BIGINT,
started_at: DataTypes.BIGINT,
finished_at: DataTypes.BIGINT,
stopped: DataTypes.BIGINT,
stat_id: DataTypes.BIGINT,
disputed: DataTypes.BIGINT,
bound: DataTypes.BIGINT,
},
CronPrunedUnknownRuns: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
source: DataTypes.TEXT,
last_possible_day: DataTypes.TEXT,
cron_id: DataTypes.BIGINT,
started_at: DataTypes.BIGINT,
},
CronHistoryRetention: {
id: { type: DataTypes.INTEGER, primaryKey: true },
cutoff: DataTypes.BIGINT,
},
CronPlanSwitches: {
token: DataTypes.TEXT,
seq: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
staged_at: DataTypes.BIGINT,
first_at: DataTypes.BIGINT,
last_at: DataTypes.BIGINT,
},
CronSystemPlans: {
zone: DataTypes.TEXT,
rules: DataTypes.TEXT,
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
staged: DataTypes.BIGINT,
confirmed: DataTypes.BIGINT,
},
SchemaMigrations: {
id: { type: DataTypes.TEXT, primaryKey: true },
applied_at: DataTypes.TEXT,
},
};
const existingNames: Record<keyof ExistingRows, string> = {
Crontabs: 'Crontab',
RunningInstances: 'RunningInstance',
CrontabStats: 'CrontabStat',
Auths: 'Auth',
};
export function executionModel<K extends keyof Rows>(
database: Sequelize,
table: K,
): ModelStatic<RowModel<Rows[K]>> {
const name =
table in existingNames ? existingNames[table as keyof ExistingRows] : table;
if (!database.isDefined(name)) {
if (table === 'Crontabs') defineCrontabModel(database);
else if (table === 'RunningInstances') defineRunningInstanceModel(database);
else if (table === 'CrontabStats') defineCrontabStatModel(database);
else if (table === 'Auths') defineSystemModel(database);
else
database.define(
name,
definitions[table as keyof LedgerRows] as ModelAttributes,
{ tableName: table, timestamps: false, freezeTableName: true },
);
}
return database.model(name) as ModelStatic<RowModel<Rows[K]>>;
}
const relationships = {
leaseTrigger: [
'CronConcurrencyLeases',
'CronTriggers',
'trigger',
'trigger_id',
'id',
],
waiterTrigger: [
'CronConcurrencyWaiters',
'CronTriggers',
'trigger',
'trigger_id',
'id',
],
submissionTrigger: [
'CronManualSubmissions',
'CronTriggers',
'trigger',
'trigger_id',
'id',
],
triggerStop: [
'CronTriggers',
'CronStopRequests',
'stop',
'instance_id',
'instance_id',
],
triggerTask: ['CronTriggers', 'Crontabs', 'task', 'cron_id', 'id'],
instanceTrigger: [
'RunningInstances',
'CronTriggers',
'trigger',
'instance_id',
'id',
],
} as const;
// Associations describe existing joins only; migrations own foreign keys.
export function executionAssociation(
database: Sequelize,
relation: keyof typeof relationships,
) {
const [from, to, as, foreignKey, key] = relationships[relation];
const source: ModelStatic<Model> = executionModel(database, from);
if (!source.associations[as]) {
const target: ModelStatic<Model> = executionModel(database, to);
if (relation === 'instanceTrigger')
source.hasOne(target, {
as,
foreignKey,
sourceKey: key,
constraints: false,
});
else
source.belongsTo(target, {
as,
foreignKey,
targetKey: key,
constraints: false,
});
}
return source.associations[as];
}
+9 -1
View File
@@ -8,7 +8,11 @@ export const sequelize = new Sequelize({
storage: join(config.dbPath, 'database.sqlite'),
logging: false,
retry: {
max: 10,
// Keep a bounded 15-second wait in JS. Constant delays let a burst of
// writers make progress without exponential retries stretching the queue.
max: 301,
backoffBase: 50,
backoffExponent: 1,
match: ['SQLITE_BUSY: database is locked'],
},
pool: {
@@ -29,6 +33,10 @@ sequelize.addHook('beforeQuery', async (_options, query) => {
let ready = initialized.get(connection);
if (!ready) {
ready = new Promise<void>((resolve, reject) => {
// Native busy waits occupy libuv workers. Concurrent BEGINs can exhaust
// that pool and prevent the lock holder's next query or COMMIT from
// running. Let Sequelize's asynchronous SQLITE_BUSY retries wait instead.
connection.configure('busyTimeout', 0);
connection.run('PRAGMA synchronous=EXTRA', (error) =>
error ? reject(error) : resolve(),
);
+3 -41
View File
@@ -1,5 +1,6 @@
import { defineRunningInstanceModel } from './executionModelDefinitions';
import { sequelize } from '.';
import { DataTypes, Model } from 'sequelize';
import { Model } from 'sequelize';
export enum InstanceStatus {
'running' = 0,
@@ -46,43 +47,4 @@ export interface RunningInstanceModel
extends Model<RunningInstanceAttributes, RunningInstanceAttributes>,
RunningInstanceAttributes {}
export const RunningInstanceModel = sequelize.define<RunningInstanceModel>(
'RunningInstance',
{
cron_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
pid: {
type: DataTypes.NUMBER,
allowNull: true,
},
log_path: {
type: DataTypes.STRING,
allowNull: true,
},
started_at: {
type: DataTypes.NUMBER,
allowNull: false,
},
finished_at: {
type: DataTypes.NUMBER,
allowNull: true,
},
status: {
type: DataTypes.NUMBER,
allowNull: false,
defaultValue: InstanceStatus.running,
},
exit_code: {
type: DataTypes.NUMBER,
allowNull: true,
},
},
{
indexes: [
{ fields: ['cron_id', 'pid', 'started_at'] },
{ fields: ['cron_id', 'id'] },
],
},
);
export const RunningInstanceModel = defineRunningInstanceModel(sequelize);
+38 -25
View File
@@ -1,7 +1,8 @@
import { executionModel } from './executionModels';
import dayjs from 'dayjs';
import { installTriggerHistory } from '../cron/schema';
import { repairLegacyDailyStatistics } from '../cron/settlement/legacyDailyStatistics';
import { QueryTypes, Sequelize } from 'sequelize';
import { QueryTypes, Sequelize, literal, DataTypes } from 'sequelize';
export const prunedExitMigrationId = 'preserve-pruned-bound-exits-v1';
@@ -45,15 +46,20 @@ const columns = [
export async function migrateSchema(database: Sequelize): Promise<void> {
await database.transaction(async (transaction) => {
await database.query(
'CREATE TABLE IF NOT EXISTS "SchemaMigrations" ("id" TEXT PRIMARY KEY, "applied_at" TEXT NOT NULL)',
await database.getQueryInterface().createTable(
'SchemaMigrations',
{
id: { type: DataTypes.TEXT, primaryKey: true },
applied_at: { type: DataTypes.TEXT, allowNull: false },
},
{ transaction },
);
await installTriggerHistory(database, transaction);
const applied = await database.query<{ id: string }>(
'SELECT "id" FROM "SchemaMigrations"',
{ type: QueryTypes.SELECT, transaction },
);
const applied = await executionModel(database, 'SchemaMigrations').findAll({
attributes: ['id'],
transaction,
raw: true,
});
const appliedIds = new Set(applied.map(({ id }) => id));
for (const { table, column, type } of columns) {
const id = `add-${table}-${column}`;
@@ -68,18 +74,22 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
throw new Error(`Migration table is missing: ${table}`);
if (!fields.some((field) => field.name === column)) {
// table/column/type come only from the static migration manifest above.
await database.query(
`ALTER TABLE "${table}" ADD COLUMN "${column}" ${type}`,
await database.getQueryInterface().addColumn(
table,
column,
{
type: type.replace(' NOT NULL DEFAULT 0', ''),
...(type.includes('NOT NULL')
? { allowNull: false, defaultValue: 0 }
: {}),
},
{ transaction },
);
}
if (!appliedIds.has(id)) {
await database.query(
'INSERT INTO "SchemaMigrations" ("id", "applied_at") VALUES (:id, :appliedAt)',
{
replacements: { id, appliedAt: new Date().toISOString() },
transaction,
},
await executionModel(database, 'SchemaMigrations').create(
{ id, applied_at: new Date().toISOString() },
{ transaction, silent: true, hooks: false, validate: false },
);
}
}
@@ -107,19 +117,22 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
},
);
}
await database.query(
'INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
{ bind: { id: retentionId }, transaction },
await executionModel(database, 'SchemaMigrations').create(
{ id: retentionId, applied_at: literal('CURRENT_TIMESTAMP') },
{ transaction, silent: true, hooks: false, validate: false },
);
}
if (!appliedIds.has(repairId)) {
await repairLegacyDailyStatistics(database, transaction, prior);
// This reconciliation includes v1 and v2. Record all on fresh installations
// so rolling back and upgrading again cannot replay the superseded repair.
await database.query(
`INSERT OR IGNORE INTO SchemaMigrations(id,applied_at)
VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP),('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP),($id,CURRENT_TIMESTAMP)`,
{ transaction, bind: { id: repairId } },
await executionModel(database, 'SchemaMigrations').bulkCreate(
[
'repair-legacy-daily-statistics-v1',
'repair-legacy-daily-statistics-v2',
repairId,
].map((id) => ({ id, applied_at: literal('CURRENT_TIMESTAMP') })),
{ transaction, ignoreDuplicates: true, hooks: false },
);
}
@@ -133,9 +146,9 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
AND NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=b.trigger_id)`,
{ transaction },
);
await database.query(
'INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
{ bind: { id: prunedExitMigrationId }, transaction },
await executionModel(database, 'SchemaMigrations').create(
{ id: prunedExitMigrationId, applied_at: literal('CURRENT_TIMESTAMP') },
{ transaction, silent: true, hooks: false, validate: false },
);
}
+3 -9
View File
@@ -1,5 +1,6 @@
import { defineSystemModel } from './executionModelDefinitions';
import { sequelize } from '.';
import { DataTypes, Model, ModelDefined } from 'sequelize';
import { Model } from 'sequelize';
import { NotificationInfo } from './notify';
export class SystemInfo {
@@ -109,11 +110,4 @@ export type SystemModelInfo = SystemConfigInfo &
export interface SystemInstance
extends Model<SystemInfo, SystemInfo>,
SystemInfo {}
export const SystemModel = sequelize.define<SystemInstance>('Auth', {
ip: DataTypes.STRING,
type: DataTypes.STRING,
info: {
type: DataTypes.JSON,
allowNull: true,
},
});
export const SystemModel = defineSystemModel(sequelize);
+1
View File
@@ -225,6 +225,7 @@ export default async () => {
await systemService.restoreCronConcurrency();
});
await cronClient.readiness.recover();
await cronService.recoverQueuedTasks();
const authInfo = await userService.getAuthInfo();
await shareStore.updateAuthInfo(authInfo);
+6
View File
@@ -8,6 +8,7 @@ import { slotId } from '../cron/history';
import { runCron } from '../cron/execution/runCron';
import Logger from '../loaders/logger';
import { t, tf } from '../shared/i18n';
import { resumeAcceptedCrons } from '../cron/scheduling/resumeAcceptedCrons';
// Validate the entire batch before replacing any existing jobs.
const isValidCronField = (cron: string): boolean => {
@@ -77,6 +78,11 @@ const addCron = (
const jobs: CronJob[] = [];
definitions.set(jobs, signature);
prepared.set(item.id, jobs);
if (call.request.replace && savePlan) {
recoveries.push(() =>
resumeAcceptedCrons(item, () => scheduleStacks.get(item.id) === jobs),
);
}
for (const [ruleIndex, schedule] of [
item.schedule,
...(item.extra_schedules || []).map((x) => x.schedule),
+25
View File
@@ -0,0 +1,25 @@
import type {
UntypedServiceImplementation,
sendUnaryData,
} from '@grpc/grpc-js';
import { ApiService } from '../protos/api';
// Registration/health never need the script API's HTTP-oriented services.
// Keep their dependency graph out of an ordinary scheduler's resident heap.
// Dynamic import shares initialization across simultaneous first calls; the
// normal handlers retain validation, callback errors and service singletons.
export function lazyApiHandlers(): UntypedServiceImplementation {
return Object.fromEntries(
Object.keys(ApiService).map((method) => [
method,
(call: unknown, callback: sendUnaryData<unknown>) => {
void import('./api')
.then((handlers) => {
const handler = handlers[method as keyof typeof ApiService];
return handler(call as never, callback);
})
.catch(callback);
},
]),
);
}
+4
View File
@@ -907,4 +907,8 @@ export default class CronService {
);
}
}
public async recoverQueuedTasks() {
await this.execution.recoverQueued();
}
}
+3 -3
View File
@@ -1,5 +1,6 @@
import { sequelize } from '../data';
import groupBy from 'lodash/groupBy';
import { FindOptions, Op } from 'sequelize';
import { FindOptions, Op, fn, col } from 'sequelize';
import { Inject, Service } from 'typedi';
import winston from 'winston';
import config from '../config';
@@ -13,7 +14,6 @@ import {
stepPosition,
} from '../data/env';
import { writeFileWithLock } from '../shared/utils';
import { sequelize } from '../data';
import {
assertAllowedTaskEnvName,
isAllowedTaskEnvName,
@@ -153,7 +153,7 @@ export default class EnvService {
}
try {
const result = await this.find(condition, [
[sequelize.literal('COALESCE(`isPinned`, 0)'), 'DESC'],
[fn('COALESCE', col('isPinned'), 0), 'DESC'],
['position', 'DESC'],
['createdAt', 'ASC'],
]);
+2 -2
View File
@@ -5,7 +5,7 @@ import { ApiService } from '../protos/api';
import { registeredAdd, registeredDelete } from '../schedule/registeredPlans';
import { setConcurrency } from '../schedule/setConcurrency';
import { check } from '../schedule/health';
import * as Api from '../schedule/api';
import { lazyApiHandlers } from '../schedule/lazyApiHandlers';
import Logger from '../loaders/logger';
import { promisify } from 'util';
import config from '../config';
@@ -32,7 +32,7 @@ export class GrpcServerService {
delCron: registeredDelete,
setConcurrency,
});
this.server.addService(ApiService, Api);
this.server.addService(ApiService, lazyApiHandlers());
const tlsConfig = await initGrpcCerts();
const credentials = ServerCredentials.createSsl(
+35
View File
@@ -0,0 +1,35 @@
import type { Sequelize } from 'sequelize';
import { performance } from 'perf_hooks';
// Per database and day: concurrent viewers share one computation. Rejections
// are never cached; a new day cannot reuse yesterday's summary. Runtime/task
// control endpoints remain live and never read this display-only snapshot.
const snapshots = new WeakMap<
Sequelize,
{ key: string; until: number; value: Promise<unknown> }
>();
export function dashboardSnapshot<T>(
db: Sequelize,
key: string,
compute: () => Promise<T>,
): Promise<T> {
const existing = snapshots.get(db);
if (existing?.key === key && performance.now() < existing.until)
return existing.value as Promise<T>;
const entry = {
key,
until: Infinity,
value: Promise.resolve().then(compute),
};
snapshots.set(db, entry);
entry.value.then(
() => {
// Wall-clock corrections must not stretch a one-second cache for minutes.
entry.until = performance.now() + 1000;
},
() => {
if (snapshots.get(db) === entry) snapshots.delete(db);
},
);
return entry.value;
}
+6 -2
View File
@@ -39,8 +39,12 @@ export function resolveFileAccess(
while (!fs.existsSync(existing)) {
// existsSync is false for a dangling symlink; never treat one as absent.
try {
fs.lstatSync(existing);
return '';
const entry = fs.lstatSync(existing);
if (entry.isSymbolicLink()) return '';
// Another task may have created this directory after existsSync.
// Canonicalize the now-existing entry below, with the same root and
// blacklist checks, rather than rejecting a legitimate concurrent run.
break;
} catch (error: any) {
if (error.code !== 'ENOENT') return '';
}
+73
View File
@@ -1,5 +1,6 @@
import fs from 'fs/promises';
import { createHash } from 'crypto';
import type { BigIntStats } from 'fs';
export const DEFAULT_LOG_CHUNK_BYTES = 256 * 1024;
export const MAX_LOG_CHUNK_BYTES = 1024 * 1024;
@@ -7,6 +8,37 @@ export const MAX_LOG_CHUNK_BYTES = 1024 * 1024;
// The viewer retains at most one Mi UTF-16 code units.
const CURSOR_WINDOW_BYTES = 4 * MAX_LOG_CHUNK_BYTES;
// Cache only a server-verified EOF, never client-supplied file metadata or log
// contents. Bound both the number of viewers retained and verification lifetime.
const EOF_CACHE_LIMIT = 256;
const EOF_CACHE_TTL_MS = 30_000;
const EOF_CACHE_SETTLE_MS = 2_000;
const verifiedEnds = new Map<
string,
{ version: string; cursor: string; offset: number; verifiedAt: number }
>();
function fileVersion(stat: BigIntStats) {
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
}
function rememberEnd(
filePath: string,
version: string,
cursor: string,
offset: number,
) {
verifiedEnds.delete(filePath);
verifiedEnds.set(filePath, {
version,
cursor,
offset,
verifiedAt: Date.now(),
});
if (verifiedEnds.size > EOF_CACHE_LIMIT)
verifiedEnds.delete(verifiedEnds.keys().next().value!);
}
export interface LogReadOptions {
offset?: number;
limit?: number;
@@ -68,6 +100,15 @@ export async function readLogChunk(
const stat = await handle.stat({ bigint: true });
const total = Number(stat.size);
const identity = `${stat.dev}:${stat.ino}`;
const version = fileVersion(stat);
const observedAt = Date.now();
// Even nanosecond stat fields can repeat across writes within a filesystem
// clock tick. Never cache content read while that timestamp is still fresh.
const metadataSettled =
Number(stat.mtimeMs) > 0 &&
Number(stat.ctimeMs) > 0 &&
observedAt - Number(stat.mtimeMs) >= EOF_CACHE_SETTLE_MS &&
observedAt - Number(stat.ctimeMs) >= EOF_CACHE_SETTLE_MS;
const limit = normalizeLimit(options.limit);
const requestedOffset = Number.isFinite(options.offset)
? Math.max(0, Math.trunc(options.offset!))
@@ -78,6 +119,30 @@ export async function readLogChunk(
: Math.min(requestedOffset, total);
const resume =
options.cursor && !options.tail && requestedOffset !== undefined;
const verified = verifiedEnds.get(filePath);
if (
resume &&
verified?.version === version &&
verified.cursor === options.cursor &&
verified.offset === requestedOffset &&
requestedOffset === total &&
observedAt >= verified.verifiedAt &&
observedAt - verified.verifiedAt < EOF_CACHE_TTL_MS
) {
// A cache hit does not extend the deadline: even an unchanged file is
// periodically verified again. Keep the entry recent without retaining bytes.
verifiedEnds.delete(filePath);
verifiedEnds.set(filePath, verified);
return {
content: '',
offset: total,
nextOffset: total,
total,
truncated: total > 0,
cursor: options.cursor,
reset: false,
};
}
const [fromText, digest] = resume ? options.cursor!.split('.') : [];
let from = resume ? Number(fromText) : start;
let reset = Boolean(
@@ -136,6 +201,13 @@ export async function readLogChunk(
)}`;
}
if (cursor && nextOffset === total && metadataSettled) {
// Do not trust an EOF read that raced with append, truncate or overwrite.
// ctime also detects rewrites that restore mtime; inode detects replacement.
if (fileVersion(await handle.stat({ bigint: true })) === version)
rememberEnd(filePath, version, cursor, nextOffset);
}
return {
...(cursor && { cursor, reset }),
content: buffer.subarray(leadingBytes, contentEnd).toString('utf8'),
@@ -146,6 +218,7 @@ export async function readLogChunk(
};
} catch (error: any) {
if (error?.code === 'ENOENT') {
verifiedEnds.delete(filePath);
return {
content: '',
offset: 0,
+210
View File
@@ -0,0 +1,210 @@
# 青龙产品与架构演进方案
日期:2026 年 11 月 22 日
状态:演进提案
首期目标:交付最小项目工作台
青龙下一阶段的方向是从定时脚本管理发展为轻量自动化工作台。围绕用户想完成的一件事,把脚本、任务、配置、运行过程和结果组织起来,再逐步支持多个任务协作以及完整方案的复用。
产品主线按三个阶段推进:**项目工作台 → 任务编排 → 订阅版本与方案模板**。架构演进贯穿三个阶段,围绕实际交付逐步明确模块职责。
## 产品目标
用户使用青龙,最终希望某件事情能按预期完成。例如每日采集数据并生成报告、同步多个来源的数据,或者定期检查状态并发送通知。脚本、依赖、变量和定时规则都是完成这件事所需的组成部分。
演进后的主要使用路径是:创建或导入一个项目,补齐运行配置,调试其中的任务,观察执行结果,再持续更新和复用这个项目。
产品应让用户容易回答四个问题:
- 这件事需要哪些任务、脚本和配置?
- 当前执行到哪里,等待或失败发生在哪一步?
- 修改脚本、规则或订阅后,会影响哪些任务?
- 如何把已经跑通的方案迁移到另一台青龙,或交给其他人使用?
## 现有基础与演进切口
青龙已经具备定时与手动执行、脚本管理、订阅、环境变量、依赖管理、运行历史、日志、CLI 和多架构交付等基础。后续能力可以在这些基础上组合和扩展。
| 当前使用方式 | 演进切口 | 用户获得的变化 |
| --- | --- | --- |
| 在任务、脚本、变量、依赖等页面之间切换 | 增加项目组织层和统一入口 | 在一个地方管理完成同一件事所需的资源 |
| 多个任务主要由用户或脚本自行衔接 | 增加简单工作流 | 能看到步骤关系、整体进度和具体失败位置 |
| 通过订阅获取和更新脚本 | 增加更新预览、版本记录和回退 | 更新前知道变化,更新后能追溯来源 |
| 分享脚本后,接收者继续手动配置环境 | 增加可导入的方案模板 | 按说明填写参数并验证后即可运行 |
| 面板和 CLI 分别提供操作入口 | 收敛共同的业务契约 | 相同操作得到一致的结果和运行记录 |
## 核心产品模型
| 概念 | 职责 | 与现有能力的关系 |
| --- | --- | --- |
| 项目 | 组织完成同一目标的任务、脚本和相关资源 | 作为可选组织层关联现有资源 |
| 任务 | 定义一次可以独立执行的工作 | 延续现有命令、运行规则、并发策略和执行能力 |
| 工作流 | 定义多个任务之间的先后、并行和结果关系 | 将已有任务组合为步骤,由现有执行器运行 |
| 运行 | 记录一次任务或工作流的实际执行 | 复用触发历史、实例、时间线、日志和退出结果 |
| 模板 | 描述可以导入和复用的项目方案 | 携带脚本引用、任务定义、依赖声明和变量填写说明 |
例如,“每日数据汇总”项目包含采集、清洗、报告和通知四个任务。第一阶段可以集中管理并分别运行它们;第二阶段把它们串成工作流;第三阶段将整个方案导出为模板。
项目首期以资源关联为基础。环境变量和依赖继续采用当前解析规则,项目资源页明确显示它们的来源和作用范围。项目专属变量覆盖、独立依赖环境等行为在后续需求明确后单独设计。
## 阶段安排
| 阶段 | 主要交付 | 完成条件 |
| --- | --- | --- |
| 第一阶段 项目工作台 | 项目分组、资源关联、运行概览、失败定位入口 | 用户能把已有任务组织成项目,并在项目内完成查看、运行、定位问题的流程 |
| 第二阶段 任务编排 | 串行、并行、结果分支、有限重试、指定步骤重跑 | 多任务协作有清晰的运行记录,步骤状态与真实执行结果一致 |
| 第三阶段 订阅版本与模板 | 更新预览、版本固定与回退、项目导入导出 | 一个方案可以被更新、复现和迁移,导入前能看清将发生的变化 |
阶段推进以交付结果为依据。前一阶段的资源模型、操作路径和运行语义稳定后,再扩展下一阶段。
## 第一阶段 项目工作台
### 首期范围
首期交付项目列表、项目详情和资源关联能力。用户可以从现有任务创建项目,也可以先创建空项目,再逐步添加资源。项目详情提供以下入口:
- **概览**:当前运行与等待情况,以及选定时间范围内的结果摘要。
- **任务**:关联任务的规则、状态、最近结果和运行操作。
- **资源**:关联脚本、订阅,以及运行所需变量和依赖的查看入口。
- **运行记录**:查看项目相关任务的已有触发历史、实例和日志。
首期的运行操作仍针对单个任务。项目级多步骤执行由第二阶段的工作流承接。
### 典型操作路径
用户选择现有的采集、清洗、报告和通知任务,创建“每日数据汇总”项目。进入项目后,可以看到任务使用的脚本及其来源,直接运行一个任务,并进入对应的执行记录。
某次执行失败时,用户从运行记录查看日志,再定位到关联脚本或配置。修改后发起一次新运行,并保留前一次运行的结果供比较。
这一阶段的价值是缩短查找和操作路径,让分散的能力形成完整的工作过程。
### 资源关联规则
首期建议一个任务归属零个或一个项目,脚本和订阅可以作为共享资源被引用。未归属项目的任务继续保留独立入口。
资源关联保留原有任务 ID、配置和执行历史。删除项目仅解除关联;删除任务、脚本或订阅仍通过对应资源的操作入口完成。资源失效时,项目显示可定位的问题及修复入口。
首期项目概览按当前关联的任务聚合,并明确统计时间范围。任务移动项目后,原始执行历史仍跟随任务保留。第二阶段的工作流运行另行保存创建时的项目与定义版本。
### 状态展示
项目概览分别展示当前活动情况和历史执行结果。正在等待、正在运行、执行失败、主动停止、策略跳过和结果未知等信息,沿用现有执行记录的含义。
概览、任务列表与运行详情应能相互核对。聚合结果指向原始记录,避免项目页形成另一套独立结算逻辑。
### 首期验收
- 能将已有任务加入项目、移出项目,并继续通过原有入口操作。
- 从项目详情进入失败运行的日志,最多经过两次明确导航。
- 在项目中修改任务或脚本后,其他入口能看到相同内容。
- 项目展示的运行状态和统计结果,与对应任务的原始记录一致。
- 删除项目后,原有任务、脚本、配置和执行历史仍然可用。
- 桌面和移动端均能完成创建项目、关联任务、运行任务和查看日志。
## 第二阶段 任务编排
### 编排能力
第一版工作流采用无环的步骤关系,支持串行、并行、成功后继续、失败分支和有限重试。创建时明确每个步骤引用的任务,以及并行步骤汇合时的继续条件。
先提供清晰的步骤列表、关系配置和运行视图。图形编辑器可以在编排语义稳定后增加,后端定义与执行能力保持独立。
例如,“每日数据汇总”可以先并行采集两个来源,等待两者成功后清洗数据,再生成报告和发送通知。用户在一条运行记录中看到整体进度,同时能进入每一步的日志。
### 执行语义
工作流负责决定下一步何时可以执行;进程启动、停止、并发控制和结果结算复用现有执行能力。
每次工作流运行保存固定的定义版本。步骤执行记录关联任务运行 ID,重试使用独立的尝试记录。配置修改作用于新运行,执行记录保留当次使用的定义和参数信息。
重试次数默认设为零,由用户为具体步骤配置。明确失败且满足重试条件的步骤可以自动重试;结果未知的步骤保留待确认状态。指定步骤重跑创建新运行记录,并明确哪些后续步骤会再次执行。
停止工作流时,应阻止尚未开始的步骤,并分别反馈运行中步骤的停止结果。工作流汇总状态由各步骤实际结果推导。
### 验收重点
重点覆盖串行与并行结果、分支选择、重试计数、停止操作、重启恢复和指定步骤重跑。每次实际启动都应能关联到步骤记录,汇总结果与步骤结果能够逐项核对。
## 第三阶段 订阅版本与方案模板
### 订阅更新
订阅更新增加预览步骤,列出脚本和任务的新增、修改、删除,以及涉及的本地改动。用户可以区分来源更新、排除规则和需要保留的本地配置。
一次应用更新应形成可追溯的版本记录,包含来源版本、变更清单和处理结果。版本固定与回退复用这些记录;回退预览说明将恢复哪些脚本或定义,以及会影响哪些任务。
### 项目模板
模板描述一个完整方案,包括项目说明、脚本来源或内容、任务与工作流定义、依赖声明、变量填写说明及推荐运行方式。
导入时先预览将创建或关联的资源,并处理名称冲突、路径差异和变量缺项。变量的实际值由目标实例填写或映射。导入完成后提供试运行入口,帮助用户确认方案在目标环境中能够工作。
模板需要独立的格式版本。后续格式升级通过显式转换规则处理,旧模板保留可识别的兼容范围。
### 验收重点
使用同一模板在两套独立青龙实例中完成导入和试运行,核对任务关系、步骤结果和配置映射。订阅更新与回退分别验证本地改动保留、任务引用变化以及失败后的可继续操作状态。
## 架构演进
保持当前完整应用的部署方式,以模块化单体承接产品演进。继续使用现有 Web、CLI、Express、Sequelize、SQLite、调度及脚本运行基础,随着新能力交付逐步明确职责。
```mermaid
flowchart TD
Web[Web 面板] --> App[共同的应用服务]
CLI[CLI] --> App
API[API 接入] --> App
App --> Project[项目与资源关联]
App --> Workflow[工作流定义与推进]
App --> Subscription[订阅版本与模板]
Project --> Task[任务定义]
Workflow --> Task
Subscription --> Project
Task --> Execution[现有调度与执行能力]
Execution --> History[运行记录与日志]
History --> App
```
| 模块 | 主要职责 | 演进方式 |
| --- | --- | --- |
| 项目服务 | 项目定义、资源关联、概览查询 | 首期增加轻量的项目与关联模型,引用已有资源 |
| 任务服务 | 命令、规则、配置及任务级操作 | 保留现有任务身份和行为,逐步提取稳定的调用接口 |
| 工作流服务 | 定义版本、步骤依赖、推进与恢复 | 新增编排状态,通过任务执行接口启动步骤 |
| 执行服务 | 入队、派发、进程管理、停止和结果结算 | 收敛现有执行路径,提供一致的结果契约 |
| 运行记录服务 | 触发、实例、日志和统计查询 | 支持任务与工作流引用同一份执行事实 |
| 订阅与模板服务 | 来源版本、更新计划、导入导出 | 将获取内容、预览变化和应用变化分成明确步骤 |
Web 和 CLI 共同调用应用服务,使用一致的参数、结果和错误语义。界面负责呈现操作过程,业务规则由服务层统一处理。
数据模型随各阶段逐步增加。项目及资源关联先落地;工作流定义、定义版本、运行和步骤尝试记录在编排阶段加入。迁移保留现有资源 ID、任务配置和执行历史。
## 交付与衡量
每个阶段都应交付完整的用户操作路径,并通过真实运行验证结果。现有构建、回归、镜像和升级验证继续作为交付基础,新增功能补充对应的 API、CLI 和浏览器场景。
| 维度 | 观察指标 | 用途 |
| --- | --- | --- |
| 上手成本 | 从创建或导入项目到首次成功运行的时间、需要手动填写的配置项数量 | 判断项目和模板是否真正减少配置成本 |
| 排障效率 | 从失败概览到找到日志、脚本或配置的操作次数 | 判断项目工作台是否缩短定位路径 |
| 编排正确性 | 实际启动次数与步骤记录的一致性、重试和恢复结果 | 判断工作流是否可靠推进 |
| 更新可控性 | 预览与实际变更的一致性、本地改动保留和回退结果 | 判断订阅版本能力是否可用 |
| 操作一致性 | Web、CLI、API 对同一操作的结果一致性 | 防止入口之间产生行为差异 |
| 规模表现 | 固定数据量和硬件下的页面响应、查询耗时及运行资源占用 | 为项目聚合和编排扩展建立性能基线 |
性能目标应在首期基线测量后确定,比较时保持硬件、数据量和负载一致。运行效率同时观察完成数、等待时间和资源使用。
## 首期实施顺序
首期按可独立验证的交付拆分,每一步都保留现有任务的使用路径。
| 顺序 | 工作项 | 交付结果 |
| --- | --- | --- |
| 1 | 明确项目资源模型与操作路径 | 确定任务归属、共享引用、移除与删除语义,形成项目列表和详情的信息结构 |
| 2 | 实现项目及资源关联服务 | 完成项目管理、关联查询与操作接口,以及对应 CLI 操作和迁移验证 |
| 3 | 实现项目列表和任务入口 | 可以从已有任务创建项目,在项目内查看、运行和编辑关联任务 |
| 4 | 接入资源与运行记录 | 可以从项目进入脚本、订阅、运行详情和日志,聚合结果与原记录一致 |
| 5 | 完成桌面与移动端验收 | 跑通创建、关联、执行、排障、移出和删除项目的完整路径 |
**第一阶段交付名称:最小项目工作台。** 其完成标志是用户可以围绕一个自动化目标组织已有任务、查看运行结果并定位问题。这个基础稳定后,再进入工作流编排。
+50
View File
@@ -0,0 +1,50 @@
五轮 Review → 修复 → 验证记录(2026-11-24,Asia/Shanghai)
范围与方法
- 审查当前累计工作区修改,未提交、未发布;保留既有修改。
- 每轮按链路检查代码,发现问题先复现、再修复、再验证;没有问题的轮次不制造代码修改。
- GitNexus 对 spawn_command_pipes 和 dashboardSnapshot 做 upstream impact,均为 LOW,各 1 个直接调用者。
- 对 develop 做 detect-changes:累计 47 个已跟踪文件、148 个符号、96 个流程,整体 CRITICAL;这是此前累计工作区影响面,不是本轮新增两处修复的影响面。另人工检查未跟踪的新模块和测试。
第 1 轮:全局并发预算、取消、恢复和排队诊断
- 核对共享租约、活进程身份、重复请求、分批注册回滚、长短任务排序和跨连接诊断。
- 未发现新增缺陷,未修改生产代码。
- 本地 27 通过、1 项 Linux 场景跳过;dev 28/28 通过。
第 2 轮:进程启动、后台后代与日志
- 确认缺陷:Linux 缺少 posix_spawn 或 waitstatus_to_exitcode 而回退到 subprocess 时,只等待 Bash。后台任务关闭输出后,supervisor 提前退出并写回执,名额可能提前释放,取消也无法再通过 supervisor 找到后代。
- 修复:Linux 两种启动方式共同设置 child subreaper;回退方式等待并收割后代后才完成。启动失败恢复原 subreaper 状态。非 Linux 路径保持兼容,原生 Linux 仍使用 posix_spawn。
- 新增 6 项 Linux 回归:原生/两种能力缺失 × 正常完成/强制取消;验证静默后台后代仍属于 supervisor、回执不会提前发布、取消后无存活后代、前台真实退出码保留。
- dev 修复前:2 通过、4 失败;修复后连同既有启动与日志测试 25/25 通过。本地 13 通过、12 项平台跳过。
第 3 轮:仪表盘快照、日志空轮询与文件访问
- 确认缺陷:快照 TTL 用 Date.now,系统时间回拨会使 1 秒缓存延长数十秒甚至更久。
- 修复:用 performance.now 计算缓存过期;并发请求合并、跨日键隔离和失败不缓存保持不变。
- 回拨回归在本地和 dev 修复前均失败,修复后通过。
- 本地与 dev 各 15/15 通过,覆盖 EOF 缓存命中、追加、同尺寸覆写、截断重长、换文件、UTF-8 边界和目录安全。
第 4 轮:SQL/ORM、SQLite 事务和升级兼容
- 检查状态保护条件、NULL 语义、模型连接隔离、时间戳、关联别名、迁移默认值、统计与回执的原子性。
- 普通 CRUD 保留 ORM;并发准入和高频回执写入继续保留既有绑定 SQL。未发现需要新增修复的问题。
- 本地 11 项事务/索引/保留期测试 + 17 项迁移/旧版兼容测试全部通过;dev 28/28 通过。
- 32 个 SQLite 竞争写者在 commit/rollback 场景均精确执行,事务回调不重放,文件 I/O 保持推进。
第 5 轮:修复复查与完整回归
- 重审本轮两处修复,并检查 JS/Python/Shell 钩子、延迟加载、启动授权、手动/定时恢复与取消边界。
- 本地完整 test/back + test/front:1506 项,1478 通过、28 项平台相关跳过、0 失败。
- dev 最终集成:319/319 通过、0 跳过、0 失败;五轮 dev 验收合计 415 项通过。
- 后端 tsc --noEmit、git diff --check、npm run prettier、npm run prettier:check 通过。
环境与证据
- dev:现有 ghcr.io/whyour/qinglong:develop,镜像 ID 382ab6e0acfbc24acfc1f6f650bb357d040b6b74ba53a89b0ded5335c0410140。
- 每组独立临时容器,--init、2 CPU、1536 MiB 内存、512 PID 上限,源码只读挂载,退出自动移除;没有替换业务容器。
- 日志、修复前失败证据、执行脚本与最终源码哈希:/tmp/ql-review-five/。
- 初次本地全量因 PATH 选择到不可执行的 Git/外部工具失败(51 项);明确系统 PATH 后完整重跑通过,没有为此修改生产代码。
- 初次回退测试注入先删除 waitstatus_to_exitcode,导致 Python 3.11 subprocess 初始化失败;修正为先导入标准库再移除能力后,确认 4 个失败均为 supervisor 提前退出。
- SSH 标准输入传输出现认证失败;改为无标准输入传输后成功,未更改凭据或主机密钥校验。
结论与限制
- 五轮完成,共修复 2 个新增缺陷。测试覆盖的并发、取消、超时、重启、日志和回执场景未发现漏跑、重复执行或名额泄漏。
- 本轮不增加进程,已有日志转发进程设计未改变;静默后台任务会持续占用名额直到实际退出。
- 本轮没有重新执行完整 CPU、内存或短任务 P95 基准,不能用可靠性测试代替性能不回退的结论。
- 本轮新增的 Linux 专属用例已在 dev 补验;不宣称本地全部平台跳过项均已覆盖,也不宣称覆盖所有故障组合。
+34
View File
@@ -0,0 +1,34 @@
Review 可靠性修复验收(2026-11-24)
修复范围
1. 日志不再直接连接业务脚本的 stdout/stderr。独立日志进程负责排空管道,写盘失败记录错误后继续排空,避免 ENOSPC/EFBIG 中断脚本。
2. supervisor 等待后台写入者及日志排空后才发布退出回执。Linux 通过 subreaper 接管孤立子进程,保留全局并发名额和可取消的进程树。
3. 排队诊断改从全局预算已有的共享快照采集,覆盖同步批量提交、其他 worker 和其他执行入口的占用。维持 250 ms 合并写入、内容去重及出队/终态写保护,界面标注“全局执行队列”。
4. 全量回归发现并修复日志目录创建竞态:existsSync 与 lstatSync 之间出现的普通目录继续经过 realpath、根目录和黑名单检查;新出现或替换成越界符号链接的路径仍拒绝访问。
验证结果
本地最终全量:1499 项,1477 通过,22 项按平台条件跳过,0 失败。
dev:3 个顺序创建并自动删除的独立容器,每轮 59/59 通过,0 跳过;退出回执故障边界及共享队列另 34/34 通过。共 211 次通过。
dev 容器限制:2 CPU、1536 MiB、512 PID。未修改既有业务容器。
真实后台任务与全局上限 1 联动:正常完成及强制取消均验证另一连接不能提前取得名额、结束后租约清空、只执行一次、日志完整。
日志故障:普通文件触及 RLIMIT_FSIZE、/dev/full、打开失败、日志接收端断开;业务后续操作及退出码不受日志错误影响。
停止/恢复:后台子进程纳入取消树、忽略 TERM 后强制停止、supervisor 被停止/杀死后已确认输出仍落盘;已有取消、超时、worker 恢复及回执 SIGKILL 边界回归通过。
进程回收:不使用 --init,以正式镜像的 Bash PID 1 连续执行 24 次任务,剩余 supervisor/日志进程为 0,僵尸进程为 0。
npm run prettier、npm run prettier:check、后端 tsc --noEmit、git diff --check 均通过。
定位过程保留
首次本地全量暴露了旧测试对日志同步可见性的假设。改为有期限等待已确认字节完整落盘,保持业务写入者存活、supervisor 已被杀死,不通过结束写入者掩盖日志丢失。
新增 dev 联动夹具最初使用默认 DEFERRED 事务,出现 SQLITE_BUSY 锁升级失败。改为加载生产 back/data/index.ts,使用实际 IMMEDIATE 事务及重试配置;未放宽生产事务或可靠性断言。
随后本地全量捕获同目录并发启动被路径检查拒绝,已用确定性目录创建竞态复现并修复,另测新建越界链接、悬空链接和目录被替换成越界链接。
一次 dev SSH 认证失败发生在容器启动之前;只读连接确认恢复后继续验收。
成本与范围
带日志的手动任务增加 1 个运行期日志进程,启动时另有立即回收的中间 fork;保留 Linux 原生 posix_spawn。日志进程按 EOF 退出,正常结束等待其排空。
磁盘无法写入时保留错误提示及业务执行,无法承诺保存物理上无法写入的日志字节。
本轮验证可靠性、诊断和进程释放,未重跑 CPU/短任务 P95 性能基准,不沿用之前基准宣称本次零性能回退。
GitNexus:执行及诊断方法分析为 LOW;共享路径函数 resolveFileAccess 为 CRITICAL,19 个直接调用者、16 条受影响流程,已先告知并补充安全回归。compare develop 包含此前全部未提交修改,不能当成本轮独立变更统计。
未提交、未发布。
证据目录
/tmp/ql-review-fix-evidence-20261124/
包含本地完整测试输出、失败定位输出、dev 三轮及回执测试日志、被测源码 SHA256 和验收脚本。
+75
View File
@@ -0,0 +1,75 @@
SQL 批量登记优化、日志碰撞修复与 dev 验证(2026-11-24)
改动与边界
1. GlobalCronBudget.pump:同一个 IMMEDIATE 写事务里的 N 次逐条排队登记,改为每块最多 200 行、600 个绑定参数的 INSERT SELECT。全部分块仍在同一事务中,提交成功后才标记 registered;queued 条件、token 和 ON CONFLICT 去重保留。
2. CronExecution.runSingle:所有手动执行日志文件名追加每次启动独立 UUID。毫秒时间戳可能相同,多实例任务的 submission token 也可能被同一批不同任务共享,因此不能用二者充当独立日志身份。普通任务和多实例任务统一使用运行专属文件名。
3. 普通 CRUD 继续 ORM;原生 query 调用点数量仍为 134。没有新增索引或迁移,没有削弱事务、回执、执行许可、取消/超时/恢复检查。
本轮源码/测试增量:2 个生产方法、4 项新增测试,见 scope.json / change.patch。
SQL 排查与取舍
批量登记有可量化的往返成本,已优化。预算快照中的进程存活、继承运行和配置读取继续保留,避免缓存滞后破坏全局上限。排队排名继续短任务优先及 30 秒老化;不截断可能包含死 owner 的排序集合。
退出结算/记账继续保留 affected-row 门控、回执冲突判断和原事务边界。已有运行实例 active 部分索引,本轮没有为局部读取增加写放大。
50000 历史记录下实际 SQL 的 18 份 EXPLAIN 见 query-plans.json:登记和退出查询走主键;预算继承运行/排队排名走 cron_trigger_running_task / cron_trigger_queued_task 部分索引。排名使用临时排序是动态老化语义所需;未新增历史表全表扫描。
dev SQLite 微基准
5 轮交替顺序,每轮预热 2 次+正式 10 次,每个规模/版本 50 次实际 pump。DELETE/EXTRA,IMMEDIATE 事务,2 CPU /1536 MiB。使用饱和许可避免执行合成任务;计时包含真实登记和快照 SQL,清理在计时之外。
18 请求:语句数 24 → 7;CPU 20.460 → 9.764 ms(-52.28%);耗时 19.749 → 10.287 ms(-47.91%)。
200 请求:语句数 206 → 7;CPU 126.039 → 22.993 ms(-81.76%);耗时 123.033 → 23.124 ms(-81.21%)。
401 请求:语句数 407 → 9;CPU 232.255 → 37.165 ms(-84.00%);耗时 233.346 → 36.244 ms(-84.47%)。
单请求补充 5 轮(50 次/版本):{"before": {"queries": 7, "cpuMs": 9.46974, "wallMs": 9.385554359999993}, "after": {"queries": 7, "cpuMs": 8.15416, "wallMs": 8.804370660000036}}
微基准降幅仅指登记链路,不能等同于整个容器 CPU 降幅。最终日志修复未修改预算模块,微基准对应的 SQL 与最终版一致。
真实脚本对比协议
隔离容器 2 CPU /1536 MiB /512 PID,全局任务上限 4。真实 Python/JS/Shell CSV、JSON、压缩、哈希及文件操作,交替 stdout/stderr UTF-8 标记,逐行校验内容及顺序。18 任务=9 长9 短;72 任务=12 长60 短,后者配比在任何 72 任务采样前固定。
CPU 为 cgroup CPU 秒/轮均值;内存为每轮采样峰值均值;短任务 P95 为提交至脚本第一行的全部短任务样本按 nearest-rank 汇总。不是各轮 P95 的平均。排队 P95 单独计算。预热只排除性能统计,仍核对可靠性。
第一阶段:本轮入口代码 vs 仅 SQL 批量优化,每个负载 before/after/after/before,4 个新容器各预热1+正式3,各版本各负载正式6轮;24轮正式+8轮预热,1440次正常执行。
最终确认:修复日志碰撞后,对照版和优化版都统一使用独立 UUID 日志名,只在 globalCronBudget.js(及 sourcemap)不同;对照保留入口逐条 SQL,优化版使用批量 SQL。18任务 before/after、72任务 after/before,每组预热1+正式3,每版本每负载3轮;12轮正式+4轮预热,720次正常执行。两阶段分别报告,不混合不同候选版本。
第一阶段结果(仅 SQL 优化候选)
18 任务:每版本 6 轮、54 个正式短任务样本
CPU 14.044883 → 13.709476 秒/轮(-2.39%)
短任务 P95 4070.667 → 3857.047 ms(-5.25%)
排队 P95 3176.0 → 3275.0 ms(+3.12%)
峰值内存均值 351.043 → 355.848 MiB(+1.37%)
探索性按轮配对 bootstrap 95% 变化区间:{"cpu": [-4.114991694521253, -0.8004019064741352], "p95": [-10.265963728063321, 7.263146056768099]}
72 任务:每版本 6 轮、360 个正式短任务样本
CPU 52.452501 → 51.383833 秒/轮(-2.04%)
短任务 P95 21747.500 → 21188.201 ms(-2.57%)
排队 P95 20768.0 → 20259.0 ms(-2.45%)
峰值内存均值 400.148 → 403.734 MiB(+0.90%)
探索性按轮配对 bootstrap 95% 变化区间:{"cpu": [-3.9243570247617487, -0.09790598261437689], "p95": [-7.464564684013119, 1.9130931086249303]}
最终代码确认结果(两版都包含日志修复)
18 任务:每版本 3 轮、27 个正式短任务样本
CPU 14.341180 → 14.266816 秒/轮(-0.52%)
短任务 P95 3958.334 → 3963.531 ms(+0.13%)
排队 P95 2954.0 → 2997.0 ms(+1.46%)
峰值内存均值 352.792 → 347.277 MiB(-1.56%)
探索性按轮配对 bootstrap 95% 变化区间:{"cpu": [-4.461225824642334, 1.5881781320550736], "p95": [-0.8674107573139356, 5.970794416359504]}
72 任务:每版本 3 轮、180 个正式短任务样本
CPU 52.720838 → 52.258215 秒/轮(-0.88%)
短任务 P95 21747.961 → 21426.560 ms(-1.48%)
排队 P95 21165.0 → 20506.0 ms(-3.11%)
峰值内存均值 395.260 → 399.633 MiB(+1.11%)
探索性按轮配对 bootstrap 95% 变化区间:{"cpu": [-1.3971369886899954, -0.23844077808578001], "p95": [-2.803988152674042, 0.38439869003523697]}
区间跨零的指标不能认定稳定提升或严格零回退保证。最终确认每组只有3轮,区间只作探索参考。性能负载走手动批量入口,定时/恢复/system 入口另做可靠性验证,不外推其全部延迟。
发现并修复的日志完整性问题
第一轮故障验收在 JS HTTP worker SIGKILL 场景中失败:cron 100 和102生成相同 perf3_fault/2026-11-24-04-21-48-274.log。各自独立账本只执行一次、输出200行,但同一文件混写400行。没有把该失败当成通过或删除它。证据:log-collision-records.json、父目录 bench/final-other-js-http 的输出/账本及 results/other-faults.log。
修复前源码的固定毫秒回归:普通任务三个执行只生成1个文件;多实例不同任务共享 token 时两个路径相同。修复后两项均通过,普通任务真实子进程日志分别完整,路径安全测试也通过。
仅修普通任务的中间日志版本补测被主动中止,发现多实例 token 也共享后统一修复;中止数据保存在 log-fix-v1-incomplete,未纳入最终版本结论。
最终可靠性与回归验收
最终确认720次正常执行全部核对唯一 trigger ID、尝试次数、终态/退出码、完整日志和并发上限;每组结束租约和排队登记清零。
最终候选另执行18次故障准备任务;7组Python+8组JS/Shell故障及钩子验证,共147个请求、140次实际执行,7个排队取消/超时按预期不启动。覆盖HTTP/manual与gRPC/timer worker SIGKILL、运行/排队取消、执行/排队超时、manual/system混合、连续取消和恢复身份。
最终候选实际执行数:正常候选360+准备18+故障140+多实例8=526次(对照版正常360次另计)。
另用4个多实例任务、相同日志目录、2批重叠提交验证:8次唯一执行、8个独立日志文件、并发峰值4,全部UTF-8日志完整,结束无名额残留。详见final-validation/bench/final-independent/result.json。
故障独立进程采样:{"peak": 4, "samples": 29479}
故障清空检查 17 次均通过;完整任务逐行对比,中断任务按独立 emitted 账本校验已发出的前缀。未发现超限、名额泄漏、非预期漏跑、重复执行、日志混写或日志丢失。
本地最终全量:1485项,1465通过、20跳过、0失败,--test-concurrency=4。此前新增测试的空目录夹具配置和一次macOS Bash setpgid瞬态失败均保留记录;夹具修正后全量重跑通过,生产代码未为测试环境错误改动。
Linux dev最终专项88/88通过,退出回执边界36/36通过(含32个SIGKILL边界);合计124/124,0跳过。详见final-validation/linux-tests.log。格式化、格式检查、后端构建和源码哈希检查见相应日志。
证据与范围
GitNexus:pump LOW,1直接调用者wake、4受影响符号、1流程;runSingle LOW,1直接调用者、2受影响符号。compare develop总体检测包含前几轮未提交工作,41文件/125符号/72流程critical;本轮用entry快照、增量patch和哈希单独限定。
首次打包漏JS脚本的启动失败发生在创建任务前,保留performance-startup-failure.log;修补测试包后从新容器重跑。SSH认证瞬态失败后只读连接恢复才重试;没有更改业务容器。
完整证据包保留协议、所有阶段原始结果/日志/采样、失败与修复复现、查询计划、测试源码、固定构建、增量补丁和SHA256。排除token、cookie和数据库。现有dev业务服务未被修改。
+489
View File
@@ -0,0 +1,489 @@
原生 SQL / ORM 审计与热点修复(2026-11-24)
当前结论
优先 ORM 适用于普通 CRUD;任务执行热路径按真实测量保留参数化 SQL。
后端原生 query 调用点:原始 228 → 全面 ORM 后 91 → 本轮 134;恢复 43 处,仍保留 94 处 ORM 转换。
8 个普通建表迁移继续使用 QueryInterface;环境排序继续使用 fn/col。模型定义、普通配置/历史查询、低频取消与恢复管理操作不随热点回退。
本轮只修改 6 个执行相关源码文件中的 18 个方法,适配 1 处故障注入测试,并更新本审计文档。没有提交、发布或修改既有 dev 业务容器。
定位方法
1. 在 dev 独立采样真实执行链路。36 次触发中,预算快照 137 次、预算 pump 112 次;启动和结算关键方法通常每次任务各调用一次。插桩数据仅用于定位,不进入性能结论。
2. 四组独立消融,每组只恢复对应方法的旧 SQL;当前 ORM 与改写前 SQL 各作基准。每个版本独立容器,预热 1 轮 + 正式 3 轮。
3. 独立 SQLite 微基准每组 5 轮交替顺序、每轮 400 次操作,预热 40 次。沿用 DELETE journal、synchronous=EXTRA、IMMEDIATE 写事务;对比双方数据库语句次数相同。
4. 最终候选与两个基准按 SQL → final → ORM → ORM → final → SQL 顺序交叉;每个批次预热 1 轮 + 正式 3 轮,各版本共 6 轮、54 个短任务样本。全部轮次保留。
分组真实混合任务结果(初筛,非最终验收)
版本 / 每轮 CPU 秒均值 / 短任务 P95 毫秒 / 峰值内存均值 MiB
orm: 14.917 / 4258.0 / 370.89
budget: 14.770 / 4195.3 / 353.11
lifecycle: 14.650 / 3811.3 / 362.82
settlement: 14.741 / 4104.3 / 359.08
diagnostics: 15.486 / 4267.3 / 355.07
sql: 14.386 / 4275.3 / 360.74
初筛单组整批 CPU 的变化很小,诊断整组没有收益;不能把每个 P95 波动直接归因于某条 SQL。最终仅恢复诊断中的每次出队更新,其余诊断查询/采样继续 ORM。
原始 SQL 与 ORM 的初筛 P95 接近;上轮两次采样的 +12.7% 不应视为稳定效应或每条 ORM 查询的代价。
SQLite 微基准(每轮 400 次操作的平均进程 CPU 毫秒)
全局名额快照、申请与释放: ORM 1916.7 → SQL 1519.8,-20.7%;语句数双方均为 1600。
手动领取、进程绑定和启动摘要: ORM 2487.3 → SQL 1923.5,-22.7%;语句数双方均为 1200。
退出回执、实例结算和幂等记账: ORM 3208.4 → SQL 2778.1,-13.4%;语句数双方均为 2000。
每次任务出队的状态写入: ORM 969.4 → SQL 633.3,-34.7%;语句数双方均为 400。
代表操作分别为 snapshot、claimSummary、recordCronResult、track。出队写入计时等待真实 afterQuery 完成,不能只计异步函数返回。
相同往返数下 CPU 下降支持 ORM 模型选项处理、条件构造和 SQL 生成存在额外开销;这些操作处于执行热路径/写事务内,可能增加其他写入者等待。微基准不是端到端收益的替代指标。
最终正式验收
同一 dev 镜像、2 CPU、1536 MiB、512 PID 限制,全局预算 4。每轮 18 个真实任务,9 长 + 9 短,Python/JS/Shell 均分。
主性能负载通过批量手动入口提交;定时、system-crond 和恢复入口的执行可靠性另做故障验收,不能把此延迟数值直接外推为所有调度入口的延迟。
P95 使用全部正式短任务提交到脚本首行时间的 nearest-rank;CPU 为完成全部脚本后再等待相同 2 秒窗口的 cgroup CPU 秒;内存为每轮峰值的均值。预热轮不计性能,但仍验收可靠性。
版本 / CPU 秒每轮 / 短任务 P95 秒 / 内存峰值均值 MiB / 匿名内存峰值均值 MiB
orm: 14.784 / 4.027 / 357.47 / 308.72
sql: 14.353 / 4.254 / 355.74 / 308.14
final: 14.146 / 4.067 / 353.69 / 309.43
final 相对 orm: CPU -4.32%,短任务 P95 +0.97%,内存峰值均值 -1.06%。
final 相对 sql: CPU -1.44%,短任务 P95 -4.41%,内存峰值均值 -0.58%。
整轮配对重采样的 95% 区间(百分比变化;6 轮样本有限,不能推断所有负载均无回退):
{"orm": {"cpuPct": [-5.966319710279377, -2.788924801039827], "shortP95Pct": [-16.81008413929368, 3.833051059970871]}, "sql": {"cpuPct": [-3.419302633873378, 0.12228126330489086], "shortP95Pct": [-17.235281932279577, 1.3769071086568996]}}
详见 acceptance-metrics.json 的逐轮耗时、CPU、内存与区间;不能只选取最好的一轮。
追加独立复测(代码不变)
主验收中候选 P95 比 ORM 高约 39 毫秒(0.97%),因此事先固定追加 ORM → final → final → ORM 四个新容器,每批预热 1 轮、正式 3 轮。追加阶段与故障/回归测试不重叠。所有原始轮次都保留,不按结果排除样本。
仅追加 6 轮:
orm: CPU 15.020 秒/轮,短任务 P95 4.165 秒,内存峰值均值 351.49 MiB。
final: CPU 14.481 秒/轮,短任务 P95 4.088 秒,内存峰值均值 356.50 MiB。
final 相对 ORM: CPU -3.59%,P95 -1.85%,短任务均值 -4.06%,内存峰值均值 +1.43%。
整轮配对重采样 95% 区间:{"cpuPct": [-5.5953269173554805, -1.0361061294987262], "shortP95Pct": [-17.222621373811485, 4.432838198416289]}
全部 12 轮合并,双方各 108 个短任务样本:
orm: CPU 14.902 秒/轮,短任务 P95 4.162 秒,内存峰值均值 354.48 MiB。
final: CPU 14.314 秒/轮,短任务 P95 4.067 秒,内存峰值均值 355.10 MiB。
final 相对 ORM: CPU -3.95%,P95 -2.30%,短任务均值 -5.42%,内存峰值均值 +0.17%。
整轮配对重采样 95% 区间:{"cpuPct": [-5.267345407712698, -2.4305917955902534], "shortP95Pct": [-10.96587562984761, 2.724986222316317]}
原始 SQL 的比较仍使用上面的同批 6 轮主验收;不将其 6 轮与候选合并后的 12 轮直接混比。区间仅描述有限样本,不能作为所有生产负载下严格零回退的证明。
追加复测 288 次触发全部恰好执行一次,日志完整,并发峰值 <=4,每个批次结束后名额清零。最终候选在主验收、追加复测及故障容器预热共执行 306 次正常脚本,另有 140 次故障场景实际执行;7 个明确取消/排队超时触发按预期不启动。
可靠性
- 正式对比 432 次触发:独立脚本记录和账本 ID 一致,每个 ID 唯一;每轮 18 次启动、18 次完成,状态均 finished/exit_code=0,中文 UTF-8 stdout/stderr 行内容和顺序完整,并发峰值 <=4。
- 每个正式容器结束后租约、等待表均为 0。初筛另有 432 次触发,所有轮次日志、唯一执行和并发断言通过。
- 最终候选真实故障验证包含 HTTP 手动 worker SIGKILL、gRPC 定时 worker SIGKILL、运行中/排队取消、执行超时 124、排队超时、system-crond 与手动混合、32 次连续取消,以及 JS/Shell 对应故障和三种语言钩子。
- Python 中断任务将已写日志行数写入独立落盘记录;与保存日志逐行相等。JS/Shell 使用独立已发出行记录核对前缀;正常完成任务要求全部行一致。故障期间采样实际进程身份,并发峰值 4;各场景结束后无 queued/running 任务、无租约和等待条目。
- 取消和排队超时属于明确终止,要求不再启动;其余已接受任务不得漏跑、重复运行。此结论限于被测执行身份、回执记账与已发出的日志,不代表任意外部业务副作用的 exactly-once 保证。
- 本地全量 1481 项:1461 通过、20 跳过、0 失败。Linux 专项 78/78 + 回执边界 36/36,共 114/114 通过、0 跳过。
- npm run prettier、npm run prettier:check、后端构建和 git diff --check 通过;690 文件无格式问题。
- GitNexus 已刷新。与 develop 比较的累计差异为 CRITICAL(40 文件、124 符号、72 流程),包括之前未提交工作;本轮独立哈希/AST 核对仅涉及选定方法,不能把累计差异全部归因于本轮。
保留边界
保留旧 SQL 的事务对象、状态/NULL 条件、受影响行数、身份 token、参数绑定、回执顺序和唯一键语义。没有缩小耐久性配置,也没有用先查后写替代条件更新。
普通 CRUD 使用原有按连接注册的模型映射;不会让独立 worker 偷用全局连接,也不会用模型 sync 代替版本迁移。
新增的 43 处性能例外按方法/链路分组验证,不表示每一个分支中的每一条 SQL 都独立带来可测的端到端收益。
其他原生片段
连接 PRAGMA、展示状态的 CASE/相关证据子查询、清理保护性子查询和 CURRENT_TIMESTAMP 保留原有语义。
CLI 原生 sqlite3 探针验证驱动本身;测试和压测的 SQL 作为独立存储判据保留。Shell/Python 执行脚本没有新增数据库 SQL 入口。
当前 134 处后端原生查询(逐项理由)
back/bootstrap/systemCron.ts:28 receipt
INSERT 条件抢占 + ON CONFLICT DO NOTHING,调用方必须取得该语句准确 changes;bulkCreate(ignoreDuplicates) 不提供等价单行抢占结果。
back/bootstrap/systemCron.ts:63 receipt
跨表 UNION ALL 存在性核验需一个快照;拆成多个模型查询无收益且增加往返。
back/cron/compatibility/legacyClient.ts:110 shellReport
INSERT…SELECT 将源行/保留水位/回执证据检查与写入合为一条语句;避免先查后写、额外锁持有及结果搬运。
back/cron/compatibility/legacyClient.ts:296 applyLegacyReceipt
INSERT…SELECT 将源行/保留水位/回执证据检查与写入合为一条语句;避免先查后写、额外锁持有及结果搬运。
back/cron/compatibility/legacyClient.ts:341 applyLegacyReceipt
跨表 UNION ALL 存在性核验需一个快照;拆成多个模型查询无收益且增加往返。
back/cron/compatibility/legacyClient.ts:476 applyLegacyReceipt
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/compatibility/legacyClient.ts:505 attachShellLog
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/compatibility/legacyClient.ts:515 attachShellLog
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/compatibility/legacyClient.ts:580 reportInstance
INSERT…SELECT 将源行/保留水位/回执证据检查与写入合为一条语句;避免先查后写、额外锁持有及结果搬运。
back/cron/compatibility/legacyClient.ts:661 reportInstance
更新许可同时检查 NULL 安全的状态和 queued_token || id 代次表达式;保留完整原子条件,不以 ORM 预读替代。
back/cron/compatibility/legacyClient.ts:679 reconcileInstances
CTE 去重未关联实例后 JOIN/NOT EXISTS 检查回执和停止请求;避免 N+1 恢复查询或全量载入。
back/cron/compatibility/legacyClient.ts:706 reconcileInstances
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/compatibility/legacyClient.ts:713 reconcileInstances
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/compatibility/legacyClient.ts:719 reconcileInstances
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/execution/cronExecution.ts:127 run
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:106 acquire
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:132 release
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:138 release
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:169 snapshot
租约与升级前遗留执行 UNION ALL 同快照合并,并关联存活后代;ORM 无直接 UNION API,拆开会增加读次数与快照差异。
back/cron/execution/globalCronBudget.ts:182 snapshot
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:213 pump
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:227 pump
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:236 pump
INSERT 条件抢占 + ON CONFLICT DO NOTHING,调用方必须取得该语句准确 changes;bulkCreate(ignoreDuplicates) 不提供等价单行抢占结果。
back/cron/execution/globalCronBudget.ts:254 pump
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:293 pump
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:302 pump
跨 worker 排名组合 CASE 老化、历史耗时、反连接及稳定顺序;ORM 需要保留多段原生表达式,保持完整排序 SQL 更容易审计。
back/cron/execution/globalCronBudget.ts:326 pump
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/globalCronBudget.ts:361 pump
INSERT 条件抢占 + ON CONFLICT DO NOTHING,调用方必须取得该语句准确 changes;bulkCreate(ignoreDuplicates) 不提供等价单行抢占结果。
back/cron/execution/globalCronBudget.ts:378 pump
性能例外:全局名额快照、申请与释放。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:84 enqueue
带 WHERE 的冲突更新,并以受影响行数决定是否取得执行/停止权;普通 upsert 无法保持相同冲突条件和回执语义。
back/cron/execution/triggerLifecycle.ts:153 start
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/execution/triggerLifecycle.ts:187 claimManual
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:225 finish
单条状态机更新使用 CASE 从同一旧行计算多个字段;保留 SQL 表达式避免多次更新、ORM 预读或拆散状态转换条件。
back/cron/execution/triggerLifecycle.ts:254 claimSummary
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:275 isRunning
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:358 queueInstanceStop
带 WHERE 的冲突更新,并以受影响行数决定是否取得执行/停止权;普通 upsert 无法保持相同冲突条件和回执语义。
back/cron/execution/triggerLifecycle.ts:428 shouldStop
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:458 bindCommand
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:467 bindCommand
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:471 bindCommand
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:476 bindCommand
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:480 bindCommand
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:484 bindCommand
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/execution/triggerLifecycle.ts:513 registerCommandInstance
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:522 registerCommandInstance
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:528 registerCommandInstance
性能例外:手动领取、进程绑定和启动摘要。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/execution/triggerLifecycle.ts:573 requestInstanceStop
条件 INSERT…SELECT + 冲突时 json_each/UNION 合并停止目标,须在同一语句去重并检查 signalled 状态。
back/cron/execution/triggerLifecycle.ts:806 startSystem
带 WHERE 的冲突更新,并以受影响行数决定是否取得执行/停止权;普通 upsert 无法保持相同冲突条件和回执语义。
back/cron/execution/triggerLifecycle.ts:874 recoverSystemOwners
证据读取组合相关 EXISTS/NOT EXISTS 和条件投影;必须同一数据库快照判断是否可恢复、可结算或可删除凭证,普通 ORM 拆查不等价。
back/cron/execution/triggerLifecycle.ts:902 recoverSystemOwners
证据读取组合相关 EXISTS/NOT EXISTS 和条件投影;必须同一数据库快照判断是否可恢复、可结算或可删除凭证,普通 ORM 拆查不等价。
back/cron/execution/triggerLifecycle.ts:934 interrupt
从执行身份提取 PID 并批量插入停止请求,含 CAST/substr 和 INSERT OR IGNORE…SELECT;保持批量执行及幂等。
back/cron/execution/triggerLifecycle.ts:962 interrupt
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/execution/triggerLifecycle.ts:970 interrupt
单条状态机更新使用 CASE 从同一旧行计算多个字段;保留 SQL 表达式避免多次更新、ORM 预读或拆散状态转换条件。
back/cron/history.ts:416 countExpired
过期条件包含对存活实例的相关 NOT EXISTS;保留同一语句中的保护条件,避免预读 ID 后竞态或批量搬运历史。
back/cron/history.ts:425 deleteExpired
清理水位采用 MAX(existing, excluded) 单调 UPSERT;Sequelize upsert 不能直接表达冲突分支累进条件。
back/cron/history.ts:432 deleteExpired
INSERT…SELECT 将源行/保留水位/回执证据检查与写入合为一条语句;避免先查后写、额外锁持有及结果搬运。
back/cron/history.ts:441 deleteExpired
过期条件包含对存活实例的相关 NOT EXISTS;保留同一语句中的保护条件,避免预读 ID 后竞态或批量搬运历史。
back/cron/queries/queueDiagnostics.ts:121 track
性能例外:每次任务出队的状态写入。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/queries/triggerQueries.ts:21 visibleTriggers
历史投影包含退出冲突/待确认 EXISTS + CASE,分页另含二元游标比较;保留同快照投影和索引友好的分页条件。
back/cron/queries/triggerQueries.ts:33 recent
历史投影包含退出冲突/待确认 EXISTS + CASE,分页另含二元游标比较;保留同快照投影和索引友好的分页条件。
back/cron/queries/triggerQueries.ts:43 metrics
CTE/UNION/窗口函数或物化统计快照;Sequelize 6 无等价完整查询 API,改为 JS 聚合会增加历史行读取、内存及查询次数。
back/cron/scheduling/scheduleAudit.ts:76 saveSchedulePlan
desired CTE + JSON 集合 + 多列元组比较,批量关闭/插入计划规则;保留集合操作避免逐项读写。
back/cron/scheduling/scheduleAudit.ts:82 saveSchedulePlan
desired CTE + JSON 集合 + 多列元组比较,批量关闭/插入计划规则;保留集合操作避免逐项读写。
back/cron/scheduling/scheduleAudit.ts:91 saveSchedulePlan
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/scheduling/scheduleAudit.ts:122 confirmSchedulePlan
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/scheduling/scheduleAudit.ts:128 confirmSchedulePlan
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/scheduling/scheduleAudit.ts:180 auditSchedule
计划审计使用子查询确定有效区间、历史水位和未确认切换边界;避免拆查造成不一致视图。
back/cron/scheduling/scheduleAudit.ts:187 auditSchedule
计划审计使用子查询确定有效区间、历史水位和未确认切换边界;避免拆查造成不一致视图。
back/cron/scheduling/scheduleAudit.ts:197 auditSchedule
证据读取组合相关 EXISTS/NOT EXISTS 和条件投影;必须同一数据库快照判断是否可恢复、可结算或可删除凭证,普通 ORM 拆查不等价。
back/cron/scheduling/systemScheduleAudit.ts:69 suspendSystemPlan
INSERT…SELECT 将源行/保留水位/回执证据检查与写入合为一条语句;避免先查后写、额外锁持有及结果搬运。
back/cron/scheduling/systemScheduleAudit.ts:94 confirmSystemPlan
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/scheduling/systemScheduleAudit.ts:122 systemScheduleAudit
计划审计使用子查询确定有效区间、历史水位和未确认切换边界;避免拆查造成不一致视图。
back/cron/scheduling/systemScheduleAudit.ts:127 systemScheduleAudit
证据读取组合相关 EXISTS/NOT EXISTS 和条件投影;必须同一数据库快照判断是否可恢复、可结算或可删除凭证,普通 ORM 拆查不等价。
back/cron/schema.ts:162 installTriggerHistory
混合迁移列表:8 个普通 CREATE TABLE 已改为 QueryInterface;剩余为 WITHOUT ROWID、CHECK 单例约束及 CREATE INDEX IF NOT EXISTS。
back/cron/schema.ts:170 installTriggerHistory
PRAGMA table_info:当前 Sequelize 6 describeTable 遇表达式索引的 null 列名会抛错,已由真实升级回归复现;保留兼容旧库的字段检查。
back/cron/schema.ts:185 installTriggerHistory
PRAGMA table_info:当前 Sequelize 6 describeTable 遇表达式索引的 null 列名会抛错,已由真实升级回归复现;保留兼容旧库的字段检查。
back/cron/schema.ts:195 installTriggerHistory
复合主键 + WITHOUT ROWID 表重建;Sequelize 建表接口不能完整表达该存储布局。
back/cron/schema.ts:196 installTriggerHistory
历史冲突表通过 INSERT…SELECT…UNION 去重并迁移双向证据,避免逐行搬运或改变去重规则。
back/cron/schema.ts:206 installTriggerHistory
PRAGMA table_info:当前 Sequelize 6 describeTable 遇表达式索引的 null 列名会抛错,已由真实升级回归复现;保留兼容旧库的字段检查。
back/cron/schema.ts:219 installTriggerHistory
PRAGMA table_info:当前 Sequelize 6 describeTable 遇表达式索引的 null 列名会抛错,已由真实升级回归复现;保留兼容旧库的字段检查。
back/cron/schema.ts:232 installTriggerHistory
PRAGMA table_info:当前 Sequelize 6 describeTable 遇表达式索引的 null 列名会抛错,已由真实升级回归复现;保留兼容旧库的字段检查。
back/cron/schema.ts:263 installTriggerHistory
PRAGMA table_info:当前 Sequelize 6 describeTable 遇表达式索引的 null 列名会抛错,已由真实升级回归复现;保留兼容旧库的字段检查。
back/cron/schema.ts:294 installTriggerHistory
数据库 AFTER UPDATE 触发器在 counted 变更时原子删除退出观察;不能换为仅在当前 Node 进程生效的 ORM hook。
back/cron/schema.ts:301 installTriggerHistory
表达式 + 条件索引 + IF NOT EXISTS;保留原表达式及并发升级幂等性。
back/cron/schema.ts:305 installTriggerHistory
条件索引/条件唯一索引,CREATE INDEX IF NOT EXISTS 原子幂等;Sequelize 6 addIndex 无等价 IF NOT EXISTS 支持,避免先查索引再创建。
back/cron/schema.ts:309 installTriggerHistory
条件索引/条件唯一索引,CREATE INDEX IF NOT EXISTS 原子幂等;Sequelize 6 addIndex 无等价 IF NOT EXISTS 支持,避免先查索引再创建。
back/cron/settlement/cronStatistics.ts:30 recordCronResult
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/cronStatistics.ts:35 recordCronResult
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/cronStatistics.ts:42 recordCronResult
证据读取组合相关 EXISTS/NOT EXISTS 和条件投影;必须同一数据库快照判断是否可恢复、可结算或可删除凭证,普通 ORM 拆查不等价。
back/cron/settlement/cronStatistics.ts:62 recordCronResult
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/settlement/cronStatistics.ts:84 addDailyExit
每日统计在 UPSERT 冲突分支累加计数/耗时并维护 MAX;必须防止并发覆盖、重复计数和保留水位回退。
back/cron/settlement/legacyDailyStatistics.ts:51 readDailyResults
CTE/UNION/窗口函数或物化统计快照;Sequelize 6 无等价完整查询 API,改为 JS 聚合会增加历史行读取、内存及查询次数。
back/cron/settlement/legacyDailyStatistics.ts:93 repairLegacyDailyStatistics
CTE/UNION/窗口函数或物化统计快照;Sequelize 6 无等价完整查询 API,改为 JS 聚合会增加历史行读取、内存及查询次数。
back/cron/settlement/legacyDailyStatistics.ts:118 repairLegacyDailyStatistics
CTE/UNION/窗口函数或物化统计快照;Sequelize 6 无等价完整查询 API,改为 JS 聚合会增加历史行读取、内存及查询次数。
back/cron/settlement/legacyDailyStatistics.ts:137 repairLegacyDailyStatistics
CTE/UNION/窗口函数或物化统计快照;Sequelize 6 无等价完整查询 API,改为 JS 聚合会增加历史行读取、内存及查询次数。
back/cron/settlement/legacyDailyStatistics.ts:221 repairLegacyDailyStatistics
每日统计在 UPSERT 冲突分支累加计数/耗时并维护 MAX;必须防止并发覆盖、重复计数和保留水位回退。
back/cron/settlement/triggerSettlement.ts:119 completeCommandExit
证据读取组合相关 EXISTS/NOT EXISTS 和条件投影;必须同一数据库快照判断是否可恢复、可结算或可删除凭证,普通 ORM 拆查不等价。
back/cron/settlement/triggerSettlement.ts:171 completeCommandExit
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:179 completeCommandExit
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:204 completeCommandExit
INSERT…SELECT 将源行/保留水位/回执证据检查与写入合为一条语句;避免先查后写、额外锁持有及结果搬运。
back/cron/settlement/triggerSettlement.ts:249 completeCommandExit
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:260 completeCommandExit
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:324 completeCommandExit
INSERT…SELECT 将源行/保留水位/回执证据检查与写入合为一条语句;避免先查后写、额外锁持有及结果搬运。
back/cron/settlement/triggerSettlement.ts:336 completeCommandExit
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:341 completeCommandExit
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:401 withdrawBooking
撤销旧统计同时重算相关记录最大耗时;算术扣减与相关 MAX 子查询必须作为一条更新提交。
back/cron/settlement/triggerSettlement.ts:437 invalidateBookedTrigger
单条状态机更新使用 CASE 从同一旧行计算多个字段;保留 SQL 表达式避免多次更新、ORM 预读或拆散状态转换条件。
back/cron/settlement/triggerSettlement.ts:503 bookPrunedExit
带统计保留水位子查询的 UPSERT,在修订回执时同步重绑定统计行;ORM upsert 无等价表达。
back/cron/settlement/triggerSettlement.ts:658 retireReceiptAfterCommit
证据读取组合相关 EXISTS/NOT EXISTS 和条件投影;必须同一数据库快照判断是否可恢复、可结算或可删除凭证,普通 ORM 拆查不等价。
back/cron/settlement/triggerSettlement.ts:781 pendingExit
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:831 saveExitObservation
插入退出观察前在同一语句限制历史观察数量,并按复合键忽略重复;不能替换为 count 后 create。
back/cron/settlement/triggerSettlement.ts:861 deferExit
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/settlement/triggerSettlement.ts:872 retryPendingExits
证据读取组合相关 EXISTS/NOT EXISTS 和条件投影;必须同一数据库快照判断是否可恢复、可结算或可删除凭证,普通 ORM 拆查不等价。
back/cron/settlement/triggerSettlement.ts:900 retryPendingExits
json_each 输入集与五张证据表执行相关存在性筛选;保持单次批量快照,避免按文件逐一查询。
back/cron/settlement/triggerSettlement.ts:1019 completeInTransaction
单条状态机更新使用 CASE 从同一旧行计算多个字段;保留 SQL 表达式避免多次更新、ORM 预读或拆散状态转换条件。
back/cron/settlement/triggerSettlement.ts:1049 completeInTransaction
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:1061 completeInTransaction
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/cron/settlement/triggerSettlement.ts:1187 saveScriptSample
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:1196 settleInstance
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:1204 settleInstance
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:1208 settleInstance
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:1221 settleInstance
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:1240 settleInstance
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:1259 settleInstance
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:1268 settleInstance
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/cron/settlement/triggerSettlement.ts:1277 settleInstance
性能例外:退出回执、实例结算和幂等记账。保留本方法原有参数绑定和事务/状态条件;依据上述分组与微基准,不将该局部收益夸大为单条语句的整批收益。
back/data/schemaMigrations.ts:66 migrateSchema
PRAGMA table_info:当前 Sequelize 6 describeTable 遇表达式索引的 null 列名会抛错,已由真实升级回归复现;保留兼容旧库的字段检查。
back/data/schemaMigrations.ts:109 migrateSchema
INSERT…SELECT 将源行/保留水位/回执证据检查与写入合为一条语句;避免先查后写、额外锁持有及结果搬运。
back/data/schemaMigrations.ts:142 migrateSchema
INSERT…SELECT 将源行/保留水位/回执证据检查与写入合为一条语句;避免先查后写、额外锁持有及结果搬运。
back/data/schemaMigrations.ts:157 migrateSchema
旧 Envs.labels 可能含无效 JSON;使用 json_valid 守卫 json_type 在数据库内修复,避免 ORM 解析损坏值失败。
back/services/retention.ts:152 cleanup
清理水位采用 MAX(existing, excluded) 单调 UPSERT;Sequelize upsert 不能直接表达冲突分支累进条件。
back/services/retention.ts:157 cleanup
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/services/retention.ts:175 cleanup
更新/删除条件或赋值含相关子查询;Sequelize 6 无原生子查询构造器,拆成预读再修改会扩大竞争窗口或数据库往返。
back/services/retention.ts:200 cleanup
VACUUM 是 SQLite 维护命令,ORM 无对应模型操作。
构建与证据
最终构建 SHA256:63042852818b92834ce33f084032c1931e53ba02de6f1bb11fc09c3e0d3b9fce
基准源、分组定义、增量补丁、原始逐轮日志/资源采样、脚本、各类回归日志与指标重算程序随证据包保存。
+195 -8
View File
@@ -1,7 +1,6 @@
"""Wait for launch authorization, then preserve a command's exit across worker restarts."""
import errno
import os
import subprocess
import sys
import threading
import time
@@ -58,6 +57,195 @@ def sync_directory(directory):
os.close(fd)
def start_log_relay(source, log_path):
# Keep draining after the supervisor or its task tree is terminated. The
# relay owns no execution permission and exits at pipe EOF. Double-fork
# before launching Bash so it is outside the task's cancellation tree.
ready, done = os.pipe()
try:
intermediate = os.fork()
except BaseException:
os.close(ready)
os.close(done)
raise
if intermediate == 0:
try:
os.close(ready)
os.setsid()
if os.fork():
os._exit(0)
# Never retain the authorization/telemetry pipes, stdout, or the
# write end of our own input. EOF must mean all writers have gone.
keep = {source.fileno(), done, 2}
if sys.platform == 'linux':
for entry in os.listdir('/proc/self/fd'):
fd = int(entry)
if fd not in keep:
try:
os.close(fd)
except OSError as error:
if error.errno != errno.EBADF:
raise
else:
import resource
previous = 0
for fd in sorted(keep):
os.closerange(previous, fd)
previous = fd + 1
maximum = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
if maximum == resource.RLIM_INFINITY:
maximum = os.sysconf('SC_OPEN_MAX')
os.closerange(previous, maximum)
os.write(done, b'R')
relay_log(source, log_path)
# EPIPE is expected if the supervisor was killed while we drained.
try:
os.write(done, b'D')
except BrokenPipeError:
pass
except BaseException as error:
report_log_error(error)
finally:
os._exit(0)
os.close(done)
source.close()
os.waitpid(intermediate, 0)
if os.read(ready, 1) != b'R':
os.close(ready)
raise OSError('Could not start command log relay')
def join():
try:
if os.read(ready, 1) != b'D':
raise OSError('Command log relay ended before draining output')
finally:
os.close(ready)
return join
def spawn_command(command, merged, log_path=None):
if not log_path:
return spawn_command_pipes(command, merged)
read_fd, write_fd = os.pipe()
source = os.fdopen(read_fd, 'rb')
join = None
try:
# Ready handshake precedes command side effects, including fast writers.
join = start_log_relay(source, log_path)
output, error, wait_command = spawn_command_pipes(command, True, write_fd)
except BaseException:
os.close(write_fd)
source.close()
if join:
join()
raise
os.close(write_fd)
def wait():
status = wait_command()
# A background writer is still part of this run. Keep the supervisor's
# birth identity, global permit and cancellation target until EOF; only
# then may main publish a terminal receipt.
join()
return status
return output, error, wait
def spawn_command_pipes(command, merged, destination=None):
libc = None
if sys.platform == 'linux':
import ctypes
# Both launch paths must adopt orphaned grandchildren. Output EOF is
# insufficient: a background command can redirect or close its output.
# The log relay detached before this flag is enabled.
libc = ctypes.CDLL(None, use_errno=True)
previous_reaper = ctypes.c_int()
if libc.prctl(37, ctypes.byref(previous_reaper), 0, 0, 0) != 0 or libc.prctl(36, 1, 0, 0, 0) != 0:
raise OSError(ctypes.get_errno(), 'Could not supervise command descendants')
# Keep native Linux launch without importing subprocess/locale/selectors.
# File writes belong to the relay: ENOSPC/EFBIG must not reach the script.
if (sys.platform != 'linux' or not hasattr(os, 'posix_spawn')
or not hasattr(os, 'waitstatus_to_exitcode')):
import subprocess
try:
child = subprocess.Popen(['/bin/bash', '-c', command], stdin=subprocess.DEVNULL,
stdout=destination if destination is not None else subprocess.PIPE,
stderr=destination if destination is not None else (subprocess.STDOUT if merged else subprocess.PIPE))
except BaseException:
if libc is not None:
libc.prctl(36, previous_reaper.value, 0, 0, 0)
raise
def wait_fallback():
status = child.wait()
if libc is not None:
while True:
try:
os.waitpid(-1, 0)
except ChildProcessError:
break
return status
return child.stdout, child.stderr, wait_fallback
import signal
descriptors = []
try:
if destination is not None:
output = error = None
output_write = error_write = destination
else:
output, output_write = os.pipe()
descriptors.extend((output, output_write))
if merged:
error, error_write = None, output_write
else:
error, error_write = os.pipe()
descriptors.extend((error, error_write))
actions = [(os.POSIX_SPAWN_OPEN, 0, os.devnull, os.O_RDONLY, 0),
(os.POSIX_SPAWN_DUP2, output_write, 1),
(os.POSIX_SPAWN_DUP2, error_write, 2)]
# Include the start telemetry pipe and any descriptors inherited from the
# caller. The readdir descriptor is already closed; skip that stale entry.
for entry in os.listdir('/proc/self/fd'):
fd = int(entry)
if fd < 3:
continue
try:
os.fstat(fd)
except OSError as exc:
if exc.errno == errno.EBADF:
continue
raise
actions.append((os.POSIX_SPAWN_CLOSE, fd))
defaults = tuple(getattr(signal, name) for name in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
if hasattr(signal, name))
pid = os.posix_spawn('/bin/bash', ['/bin/bash', '-c', command], os.environ,
file_actions=actions, setsigdef=defaults)
except BaseException:
libc.prctl(36, previous_reaper.value, 0, 0, 0)
for fd in descriptors:
os.close(fd)
raise
if destination is None:
os.close(output_write)
if error_write != output_write:
os.close(error_write)
def wait():
status = os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
while True:
try:
os.waitpid(-1, 0)
except ChildProcessError:
break
return status
return os.fdopen(output, 'rb') if output is not None else None, os.fdopen(error, 'rb') if error is not None else None, wait
def main():
command, owner, marker, node, reporter = sys.argv[1:6]
if sys.stdin.buffer.read() != b'run\n':
@@ -67,21 +255,19 @@ def main():
if report_start:
options = options[1:]
log_path = options[1] if len(options) == 2 and options[0] == 'log-output' else None
child = subprocess.Popen(['/bin/bash', '-c', command], stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT if log_path else subprocess.PIPE)
output, error, wait = spawn_command(command, bool(log_path), log_path)
if report_start:
try:
with os.fdopen(3, 'wb', buffering=0) as timing:
timing.write(str(time.time_ns() // 1000000).encode('ascii'))
except OSError:
pass
streams = ([threading.Thread(target=relay_log, args=(child.stdout, log_path))]
if log_path else [threading.Thread(target=relay, args=(child.stdout, 1)),
threading.Thread(target=relay, args=(child.stderr, 2))])
streams = (([] if output is None else [threading.Thread(target=relay_log, args=(output, log_path))])
if log_path else [threading.Thread(target=relay, args=(output, 1)),
threading.Thread(target=relay, args=(error, 2))])
for stream in streams:
stream.start()
status = child.wait()
status = wait()
finished = time.time_ns() // 1000000
import hashlib
@@ -143,6 +329,7 @@ def main():
needs_report = True
print('[scheduler] Could not save command exit:', error, file=sys.stderr)
if needs_report or os.getppid() != int(owner):
import subprocess
env = os.environ.copy()
env.pop('NODE_OPTIONS', None)
# Even with a live parent its child-close callback has no exit timestamp.
+34 -6
View File
@@ -4,10 +4,25 @@ const path = require('path');
const client = require('./client.js');
require(`./env.js`);
// 注册 ESM loader,使全局安装的包也可通过 import 导入
// Node 22.15+ can resolve ESM on the current thread, without a loader worker.
// CommonJS keeps preferGlobalNodeModules and its panel-dependency isolation.
try {
Module.register(new URL('esm-loader.mjs', `file://${__dirname}/`).href);
} catch (_) {}
if (typeof Module.registerHooks !== 'function') {
throw new Error('Synchronous module hooks unavailable');
}
const { resolve } = require('./esm-loader.mjs');
Module.registerHooks({
resolve(specifier, context, nextResolve) {
return context.conditions.includes('require')
? nextResolve(specifier, context)
: resolve(specifier, context, nextResolve);
},
});
} catch (_) {
try {
Module.register(new URL('esm-loader.mjs', `file://${__dirname}/`).href);
} catch (_) {}
}
function preferGlobalNodeModules() {
const { QL_NODE_GLOBAL_PATH } = process.env;
@@ -78,14 +93,15 @@ function run() {
`${dir_scripts}/`,
'',
);
const tempFile = `/tmp/env_${process.pid}.json`;
const tempFile = `/tmp/env_${process.pid}.data`;
// Pass paths as arguments: shell syntax in a filename must stay literal.
const command = `file="$1"; output="$2"; inline="$3"; shift 3
source "$file" "$@" &&
{ if [ -n "$inline" ]; then eval "$inline"; fi; } &&
printf '%s\\n' '__sitecustomize__' &&
node -e 'require("fs").writeFileSync(process.argv[1], JSON.stringify(process.env))' "$output"`;
{ command env -0 > "$output" 2>/dev/null ||
node -e 'require("fs").writeFileSync(process.argv[1], JSON.stringify(process.env))' "$output"; }`;
if (task_before) {
console.log(
@@ -113,7 +129,19 @@ node -e 'require("fs").writeFileSync(process.argv[1], JSON.stringify(process.env
try {
const envStr = require('fs').readFileSync(tempFile, 'utf-8');
const newEnvObject = JSON.parse(envStr);
// NUL separates environment entries without escaping Unicode, newlines
// or '=' in values. Keep JSON for env implementations without -0.
const newEnvObject = envStr.includes('\0')
? Object.fromEntries(
envStr
.split('\0')
.filter(Boolean)
.map((entry) => {
const separator = entry.indexOf('=');
return [entry.slice(0, separator), entry.slice(separator + 1)];
}),
)
: JSON.parse(envStr);
if (typeof newEnvObject === 'object' && newEnvObject !== null) {
for (const key in newEnvObject) {
if (
+9 -4
View File
@@ -46,7 +46,7 @@ def run():
file_name = sys.argv[0].replace(f"{os.getenv('dir_scripts')}/", "")
# 创建临时文件路径
temp_file = f"/tmp/env_{os.getpid()}.json"
temp_file = f"/tmp/env_{os.getpid()}.data"
if task_before:
print("Executing before command\n" if os.environ.get("QL_LANG") == "en" else "执行前置命令\n")
@@ -55,7 +55,8 @@ def run():
source "$file" "$@" &&
{ if [ -n "$inline" ]; then eval "$inline"; fi; } &&
printf '%s\\n' '__sitecustomize__' &&
python3 -c 'import os,json,sys; f=open(sys.argv[1],"w"); json.dump(dict(os.environ),f); f.close()' "$output"
{ command env -0 > "$output" 2>/dev/null ||
python3 -c 'import os,json,sys; f=open(sys.argv[1],"w"); json.dump(dict(os.environ),f); f.close()' "$output"; }
"""
res = subprocess.check_output(
["/bin/bash", "-c", command, "ql-before", os.environ["file_task_before"],
@@ -65,8 +66,12 @@ python3 -c 'import os,json,sys; f=open(sys.argv[1],"w"); json.dump(dict(os.envir
output = res.split(split_str)[0]
try:
with open(temp_file, 'r') as f:
env_json = json.loads(f.read())
with open(temp_file, 'rb') as f:
data = f.read()
# fsdecode retains undecodable Unix environment bytes, as os.environ does.
env_json = (dict((os.fsdecode(key), os.fsdecode(value))
for key, _, value in (entry.partition(b'=') for entry in data.split(b'\0') if entry))
if b'\0' in data else json.loads(data))
for key, value in env_json.items():
os.environ[key] = value
+18 -4
View File
@@ -100,7 +100,7 @@ import_config() {
if [[ -n "${DefaultCronRule}" ]]; then
default_cron="${DefaultCronRule}"
else
default_cron="$(random_range 0 59) $(random_range 0 23) * * *"
default_cron="$((RANDOM % 59)) $((RANDOM % 23)) * * *"
fi
}
@@ -148,7 +148,11 @@ detect_termux() {
}
detect_macos() {
[[ $(uname -s) == Darwin ]] && is_macos=1 || is_macos=0
case ${OSTYPE:-} in
darwin*) is_macos=1 ;;
linux*) is_macos=0 ;;
*) [[ $(uname -s) == Darwin ]] && is_macos=1 || is_macos=0 ;;
esac
}
gen_random_num() {
@@ -405,7 +409,9 @@ clear_env() {
handle_task_start() {
local error_message=""
if [[ $ID ]]; then
# Manual managed launches bind the PID, instance and log before permission.
# Scheduled/standalone wrappers still publish their shell-selected log path.
if [[ $ID && ( ${QL_SUPERVISOR_LOG_BOUND:-} != 1 || -z ${QL_TRIGGER_ID:-} ) ]]; then
local error=$(update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp")
if [[ $error ]]; then
error_message=$(t ', 任务状态更新失败(%s)' "$error")
@@ -436,7 +442,10 @@ run_task_after() {
handle_task_end() {
local etime end_time end_timestamp
if [[ $is_macos -ne 1 && $time_format == '%Y-%m-%d %H:%M:%S' ]]; then
if [[ $is_macos -ne 1 && ${BASH_VERSINFO[0]} -ge 5 && ${EPOCHSECONDS:-} =~ ^[0-9]+$ && $time_format == '%Y-%m-%d %H:%M:%S' ]]; then
end_timestamp=$EPOCHSECONDS
printf -v end_time '%(%Y-%m-%d %H:%M:%S)T' "$end_timestamp"
elif [[ $is_macos -ne 1 && $time_format == '%Y-%m-%d %H:%M:%S' ]]; then
IFS='|' read -r end_time end_timestamp < <(date "+$time_format|%s")
else
etime=$(date "+$time_format")
@@ -447,6 +456,10 @@ handle_task_end() {
local exit_code="${_task_exit_code:-0}"
[[ "$diff_time" == 0 ]] && diff_time=1
# The authorized supervisor publishes the command exit durably, including
# after hooks, and the worker/recovery books its statistics exactly once.
# Standalone/legacy wrappers still send their identified HTTP receipts.
if [[ ${QL_SUPERVISOR_RECEIPT:-} != 1 || -z ${QL_TRIGGER_ID:-} ]]; then
if [[ $ID ]]; then
local error=$(update_cron "\"$ID\"" "1" "$$" "$log_path" "$begin_timestamp" "$diff_time" "$exit_code" "$end_timestamp")
if [[ $error ]]; then
@@ -455,6 +468,7 @@ handle_task_end() {
fi
record_cron_stat "$ID" "${exit_code:-0}" "$diff_time" "$end_timestamp"
fi
if [[ "${MANUAL:=}" == "true" ]]; then
t '\n## 已停止 🛑... %s 耗时 %s 秒%s' "$end_time" "$diff_time" "${error_message:=}     "
+18 -4
View File
@@ -58,6 +58,7 @@ define_program() {
handle_log_path() {
local file_param=$1
ql_task_clock_seconds=""
if [[ -z $file_param ]]; then
file_param="task"
@@ -76,9 +77,18 @@ handle_log_path() {
fi
if [[ $is_macos -ne 1 && $mtime_format == '%Y-%m-%d %H:%M:%S.%3N' ]]; then
# Render both representations from one clock snapshot, without parsing it
# again in a second date process.
IFS='|' read -r time log_time < <(date "+$mtime_format|%Y-%m-%d-%H-%M-%S-%3N")
local clock=${EPOCHREALTIME:-}
if [[ ${BASH_VERSINFO[0]} -ge 5 && $clock =~ ^[0-9]+\.[0-9]{6}$ ]]; then
ql_task_clock_seconds=${clock%.*}
local millis=${clock#*.}
millis=${millis:0:3}
printf -v time '%(%Y-%m-%d %H:%M:%S)T' "$ql_task_clock_seconds"
printf -v log_time '%(%Y-%m-%d-%H-%M-%S)T' "$ql_task_clock_seconds"
time+=".$millis"; log_time+="-$millis"
else
# Older Bash retains the original external clock path.
IFS='|' read -r time log_time < <(date "+$mtime_format|%Y-%m-%d-%H-%M-%S-%3N")
fi
else
time=$(date "+$mtime_format")
log_time=$(format_log_time "$mtime_format" "$time")
@@ -155,7 +165,11 @@ init_begin_time() {
else
begin_time=$(format_time "$time_format" "$time")
fi
begin_timestamp=$(format_timestamp "$time_format" "$time")
if [[ ${ql_task_clock_seconds:-} =~ ^[0-9]+$ ]]; then
begin_timestamp=$ql_task_clock_seconds
else
begin_timestamp=$(format_timestamp "$time_format" "$time")
fi
}
import_config "$@"
+1
View File
@@ -845,6 +845,7 @@
"下载完成,等待重启": "Download complete, restart to update",
"升级成功": "Update successful",
"已重新启动并运行新版本,无需再次重启。": "Restarted and running the new version. No further restart is needed.",
"全局执行队列": "Global execution queue",
"手动执行队列": "Manual queue",
"定时执行队列": "Scheduled queue",
"执行 ID": "Execution ID",
+1
View File
@@ -845,6 +845,7 @@
"下载完成,等待重启": "下载完成,等待重启",
"升级成功": "升级成功",
"已重新启动并运行新版本,无需再次重启。": "已重新启动并运行新版本,无需再次重启。",
"全局执行队列": "全局执行队列",
"手动执行队列": "手动执行队列",
"定时执行队列": "定时执行队列",
"执行 ID": "执行 ID",
+5 -1
View File
@@ -26,7 +26,11 @@ export function QueueReason({
<div className="queue-reason">
<strong>
{intl.get(
admission.queue === 'manual' ? '手动执行队列' : '定时执行队列',
admission.queue === 'global'
? '全局执行队列'
: admission.queue === 'manual'
? '手动执行队列'
: '定时执行队列',
)}
</strong>
{' · '}
+35 -9
View File
@@ -35,6 +35,7 @@ async function fixture(t, usePanelDatabase = false) {
});
const models = load('back/data/cron.ts', { '.': { sequelize: db } });
load('back/data/runningInstance.ts', { '.': { sequelize: db } });
load('back/data/system.ts', { '.': { sequelize: db } });
const stats = load('back/data/cronStats.ts', { '.': { sequelize: db } });
await db.sync();
await db.transaction(async (transaction) => {
@@ -316,6 +317,10 @@ test('a wake burst settles every rejected slot without opening receipt transacti
'../../config': {},
'../../config/grpcCerts': {},
'../../protos/api': {},
// Isolate rejection bookkeeping from durable budget admission transactions.
'./globalCronBudget': {
globalCronBudget: () => ({ run: (_id, fn) => fn() }),
},
}).default;
limit.cronLimit.pause();
limit._client = { systemNotify() {} };
@@ -6926,8 +6931,8 @@ for (const rollback of [false, true]) {
const result = await query(sql, ...args);
if (
!injected &&
String(sql).includes(
'DELETE FROM CronLegacyExitBookings WHERE trigger_id=$id',
/^DELETE FROM CronLegacyExitBookings WHERE/.test(
String(sql).replace(/[`"]/g, ''),
)
) {
injected = true;
@@ -7502,7 +7507,9 @@ test('replacing the selected witness before duplicate cleanup preserves the othe
const result = await query(sql, ...args);
if (
!replaced &&
String(sql).includes('INSERT OR IGNORE INTO CronBoundExitConflicts')
String(sql)
.replace(/[`"]/g, '')
.includes('INSERT OR IGNORE INTO CronBoundExitConflicts')
) {
replaced = true;
await fs.writeFile(
@@ -10095,7 +10102,7 @@ test('system crond reconciles confirmed minutes separately, preserving duplicate
assert.equal(last.n, 2);
});
test('queue admission captures only occupants in the same execution pool and freezes the wait on dispatch', async (t) => {
test('queue admission captures shared budget holders and freezes the wait on dispatch', async (t) => {
const { db, history, models } = await fixture(t);
const limit = load('back/cron/execution/cronLimit.ts', {
'../../data/system': {
@@ -10109,6 +10116,12 @@ test('queue admission captures only occupants in the same execution pool and fre
'../../protos/api': {},
}).default;
await limit.setCustomLimit(2);
await db.query(
"INSERT INTO Auths(type,info,createdAt,updatedAt) VALUES('systemConfig','{\"cronConcurrency\":2}',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
);
await models.CrontabModel.create({ id: 1, command: 'true' });
for (const id of ['A', 'B', 'scheduled-A'])
await history.enqueue(id, 1, 'manual', null, Date.now());
const holders = [];
const hold = (id, scheduled = false) => {
const job = () => new Promise((resolve) => holders.push({ id, resolve }));
@@ -10130,7 +10143,6 @@ test('queue admission captures only occupants in the same execution pool and fre
holders.forEach((x) => x.resolve());
await Promise.all(work);
});
await models.CrontabModel.create({ id: 1, command: 'true' });
const queued = Date.now();
await history.enqueue('short', 1, 'manual', null, queued);
const short = limit.manualRunWithCronLimit(
@@ -10145,22 +10157,25 @@ test('queue admission captures only occupants in the same execution pool and fre
const { oldestQueued } = require('../../back/cron/queries/queueDiagnostics');
let row;
for (let i = 0; i < 100; i++) {
[row] = await oldestQueued(db);
row = (await oldestQueued(db)).find((entry) => entry.id === 'short');
if (row?.queue_context) break;
await new Promise((r) => setTimeout(r, 10));
}
const context = JSON.parse(row.queue_context);
assert.deepEqual(context, {
queue: 'manual',
queue: 'global',
limit: 2,
occupied: 2,
holders: [
{ id: 'A', name: 'A' },
{ id: 'B', name: 'B' },
{ id: 'A', name: 'true' },
{ id: 'B', name: 'true' },
],
});
holders.find((x) => x.id === 'A').resolve();
holders.find((x) => x.id === 'B').resolve();
await short;
holders.forEach((holder) => holder.resolve());
await Promise.all(work);
const [done] = await history.recent(1, 0);
assert.equal(done.state, 'finished');
assert.equal(done.queue_context, row.queue_context);
@@ -10182,6 +10197,11 @@ test('changing the limit resamples remaining holders and ends waiting at dequeue
'../../protos/api': {},
}).default;
await limit.setCustomLimit(3);
await db.query(
"INSERT INTO Auths(type,info,createdAt,updatedAt) VALUES('systemConfig','{\"cronConcurrency\":3}',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
);
for (const id of ['A', 'B', 'C'])
await history.enqueue(id, 1, 'manual', null, Date.now());
await models.CrontabModel.create({ id: 1, command: 'true' });
const gates = new Map(),
work = [];
@@ -10222,6 +10242,9 @@ test('changing the limit resamples remaining holders and ends waiting at dequeue
}
await sample((r) => JSON.parse(r.queue_context)?.occupied === 3);
await limit.setCustomLimit(1);
await db.query(
"UPDATE Auths SET info='{\"cronConcurrency\":1}' WHERE type='systemConfig'",
);
gates.get('B')();
const cut = await sample((r) => {
const v = JSON.parse(r.queue_live_context);
@@ -10234,6 +10257,9 @@ test('changing the limit resamples remaining holders and ends waiting at dequeue
gates.get('A')();
await sample((r) => JSON.parse(r.queue_live_context)?.occupied === 1);
await limit.setCustomLimit(2);
await db.query(
"UPDATE Auths SET info='{\"cronConcurrency\":2}' WHERE type='systemConfig'",
);
const preparing = await sample((r) => r.dequeued_at != null);
assert.equal(preparing.state, 'queued');
assert.equal(preparing.started_at, null);
@@ -0,0 +1,172 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { spawn } = require('node:child_process');
const { once } = require('node:events');
const { readExit } = require('../../back/cron/settlement/exitReceipt.cjs');
const { shellQuote } = require('../../back/shared/shellQuote');
const script = path.resolve('shell/cron-command.py');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function until(check) {
for (let i = 0; i < 500; i++) {
if (await check()) return;
await sleep(10);
}
assert.fail('condition did not become true');
}
async function fixture(t) {
const root = await fs.mkdtemp(
path.join(os.tmpdir(), 'ql-supervisor-boundaries-'),
);
t.after(() => fs.rm(root, { recursive: true, force: true }));
return {
root,
log: path.join(root, 'output.log'),
marker: path.join(root, 'db', 'cron-exits', 'boundary'),
};
}
function launch(t, f, command, { fallback = false, limited = false } = {}) {
const bootstrap = `import runpy,sys${
limited
? ',resource;resource.setrlimit(resource.RLIMIT_FSIZE,(1024,1024))'
: ''
}\n${
fallback ? "sys.platform='darwin'\n" : ''
}sys.argv=sys.argv[1:];sys.exit(runpy.run_path(sys.argv[0])['main']())`;
const child = spawn(
'python3',
[
'-I',
'-S',
'-c',
bootstrap,
script,
command,
String(process.pid),
f.marker,
process.execPath,
path.resolve('back/shared/managedExit.cjs'),
'log-output',
f.log,
],
{
env: { ...process.env, QL_TRIGGER_ID: 'boundary' },
stdio: ['pipe', 'ignore', 'pipe'],
},
);
t.after(() => child.kill('SIGKILL'));
let stderr = '';
child.stderr.on('data', (s) => (stderr += s));
const closed = once(child, 'close').then(([code, signal]) => ({
code,
signal,
stderr,
}));
child.stdin.end('run\n');
return { child, closed };
}
for (const fallback of [false, true]) {
test(
`background writer retains supervision and cannot publish an early receipt (fallback=${fallback})`,
{ timeout: 10000 },
async (t) => {
const f = await fixture(t);
const ready = path.join(f.root, 'ready');
const go = path.join(f.root, 'go');
const code = `import os,time\nopen(${JSON.stringify(
ready,
)},'w').write('ready')\nwhile not os.path.exists(${JSON.stringify(
go,
)}):time.sleep(.01)\nos.write(1,'后台尾行 stdout\\n'.encode());os.write(2,'后台尾行 stderr\\n'.encode())\n`;
const run = launch(
t,
f,
`python3 -I -S -c ${shellQuote(code)} & printf 'foreground\\n'`,
{ fallback },
);
await until(() =>
fs.access(ready).then(
() => true,
() => false,
),
);
await sleep(100);
assert.equal(run.child.exitCode, null);
await assert.rejects(fs.access(f.marker), { code: 'ENOENT' });
await fs.writeFile(go, 'continue');
assert.equal((await run.closed).code, 0);
assert.equal(
await fs.readFile(f.log, 'utf8'),
'foreground\n后台尾行 stdout\n后台尾行 stderr\n',
);
assert.equal((await readExit('boundary', f.marker)).code, 0);
},
);
test(
`regular log reaching its size limit does not interrupt script side effects (fallback=${fallback})`,
{ timeout: 10000 },
async (t) => {
const f = await fixture(t);
const done = path.join(f.root, 'business-done');
const code = `import os\nfor i in range(128):\n data=b'x'*8192\n while data:data=data[os.write(1+i%2,data):]\nopen(${JSON.stringify(
done,
)},'w').write('done')\n`;
const result = await launch(
t,
f,
`python3 -I -S -c ${shellQuote(code)}`,
{ fallback, limited: true },
).closed;
assert.equal(result.code, 0, result.stderr);
assert.equal(await fs.readFile(done, 'utf8'), 'done');
assert.equal((await fs.stat(f.log)).size, 1024);
assert.equal(
(result.stderr.match(/Could not write command log/g) || []).length,
1,
);
assert.equal((await readExit('boundary', f.marker)).code, 0);
},
);
}
test(
'Linux adopts a background task into the cancellable tree and drains acknowledged logs on forced stop',
{ timeout: 15000, skip: process.platform !== 'linux' },
async (t) => {
const f = await fixture(t);
const ready = path.join(f.root, 'ready');
const payload = '取消前已确认日志 中文🚀\n'.repeat(4000);
const code = `import os,time,signal\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\ndata=(${JSON.stringify(
'取消前已确认日志 中文🚀\n',
)}*4000).encode()\nwhile data:data=data[os.write(1,data):]\nopen(${JSON.stringify(
ready,
)},'w').write(str(os.getpid()))\ntime.sleep(30)\n`;
const run = launch(t, f, `python3 -I -S -c ${shellQuote(code)} &`);
let pid;
await until(async () => {
pid = Number(await fs.readFile(ready, 'utf8').catch(() => ''));
if (!pid) return false;
const stat = await fs.readFile(`/proc/${pid}/stat`, 'utf8');
return (
Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]) ===
run.child.pid
);
});
t.after(() => {
try {
process.kill(pid, 'SIGKILL');
} catch (_) {}
});
const { killTask } = require('../../back/config/util');
const { systemOwner } = require('../../back/cron/execution/cronProcess');
const birth = systemOwner(run.child.pid);
await killTask(run.child.pid, true, () =>
assert.equal(systemOwner(run.child.pid), birth),
);
await run.closed;
assert.throws(() => systemOwner(pid), { code: /ESRCH|ENOENT/ });
assert.equal(await fs.readFile(f.log, 'utf8'), payload);
},
);
+108
View File
@@ -0,0 +1,108 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { spawn } = require('node:child_process');
const { once } = require('node:events');
const { shellQuote } = require('../../back/shared/shellQuote');
const { readExit } = require('../../back/cron/settlement/exitReceipt.cjs');
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
for (const missing of [null, 'posix_spawn', 'waitstatus_to_exitcode']) {
for (const cancel of [false, true]) {
test(
`Linux supervises silent background children (${
missing || 'native'
}, cancel=${cancel})`,
{ timeout: 15000, skip: process.platform !== 'linux' },
async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-fallback-'));
const ready = path.join(root, 'ready');
const go = path.join(root, 'go');
const marker = path.join(root, 'db', 'cron-exits', 'silent');
const payload = `import os,time,signal\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\nopen(${JSON.stringify(
ready,
)},'w').write(str(os.getpid()))\nwhile not os.path.exists(${JSON.stringify(
go,
)}):time.sleep(.01)\n`;
const bootstrap = `import os,sys,runpy,subprocess\n${
missing
? `del os.${missing}\n${
missing === 'posix_spawn'
? 'subprocess._USE_POSIX_SPAWN=False\n'
: ''
}`
: ''
}sys.argv=sys.argv[1:];sys.exit(runpy.run_path(sys.argv[0])['main']())`;
const child = spawn(
'python3',
[
'-I',
'-S',
'-c',
bootstrap,
path.resolve('shell/cron-command.py'),
`python3 -I -S -c ${shellQuote(payload)} >/dev/null 2>&1 & exit 17`,
String(process.pid),
marker,
process.execPath,
path.resolve('back/shared/managedExit.cjs'),
'log-output',
path.join(root, 'output.log'),
],
{
env: { ...process.env, QL_TRIGGER_ID: 'silent' },
stdio: ['pipe', 'ignore', 'pipe'],
},
);
let stderr = '';
child.stderr.on('data', (data) => (stderr += data));
const closed = once(child, 'close');
let pid;
t.after(async () => {
child.kill('SIGKILL');
if (pid) {
try {
process.kill(pid, 'SIGKILL');
} catch (_) {}
}
await closed;
await fs.rm(root, { recursive: true, force: true });
});
child.stdin.end('run\n');
for (let i = 0; i < 500; i++) {
pid = Number(await fs.readFile(ready, 'utf8').catch(() => ''));
if (pid) break;
await sleep(10);
}
assert.ok(pid, stderr);
// Neither output EOF nor Bash's exit proves its silent child has ended.
await sleep(100);
assert.equal(child.exitCode, null, stderr);
await assert.rejects(fs.access(marker), { code: 'ENOENT' });
const stat = await fs.readFile(`/proc/${pid}/stat`, 'utf8');
assert.equal(
Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]),
child.pid,
);
if (cancel) {
const { killTask } = require('../../back/config/util');
const {
systemOwner,
} = require('../../back/cron/execution/cronProcess');
const birth = systemOwner(child.pid);
await killTask(child.pid, true, () =>
assert.equal(systemOwner(child.pid), birth),
);
await closed;
assert.throws(() => systemOwner(pid), { code: /ENOENT|ESRCH/ });
} else {
await fs.writeFile(go, 'go');
assert.equal((await closed)[0], 17, stderr);
assert.equal((await readExit('silent', marker)).code, 17);
}
},
);
}
}
+259
View File
@@ -0,0 +1,259 @@
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const test = require('node:test');
const { spawn } = require('node:child_process');
const { once } = require('node:events');
const { readExit } = require('../../back/cron/settlement/exitReceipt.cjs');
const script = path.resolve('shell/cron-command.py');
async function fixture(t) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-spawn-test-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
return { root, marker: path.join(root, 'db', 'cron-exits', 'launch') };
}
function launch(t, f, command, { extraFd, fallback = false } = {}) {
const args = [
script,
command,
String(process.pid),
f.marker,
process.execPath,
path.resolve('back/shared/managedExit.cjs'),
'report-start',
];
if (fallback)
args.unshift(
'-c',
"import sys,runpy;sys.argv=sys.argv[1:];sys.platform='darwin';sys.exit(runpy.run_path(sys.argv[0])['main']())",
);
const child = spawn('python3', ['-I', '-S', ...args], {
env: { ...process.env, QL_DATA_DIR: f.root, QL_TRIGGER_ID: 'launch' },
stdio: [
'pipe',
'pipe',
'pipe',
'pipe',
...(extraFd === undefined ? [] : [extraFd]),
],
});
t.after(() => child.kill('SIGKILL'));
let stdout = '',
stderr = '',
stamp = '';
child.stdout.setEncoding('utf8').on('data', (data) => (stdout += data));
child.stderr.setEncoding('utf8').on('data', (data) => (stderr += data));
child.stdio[3].setEncoding('ascii').on('data', (data) => (stamp += data));
const timing = once(child.stdio[3], 'end');
const closed = once(child, 'close').then(([code, signal]) => ({
code,
signal,
stdout,
stderr,
stamp,
}));
return { child, closed, timing };
}
test(
'launch authorization is required before Bash environment and command side effects',
{ timeout: 10000 },
async (t) => {
const f = await fixture(t);
const command = `printf forbidden > '${path.join(f.root, 'side-effect')}'`;
const run = launch(t, f, command);
await new Promise((r) => setTimeout(r, 150));
await assert.rejects(fs.access(path.join(f.root, 'side-effect')), {
code: 'ENOENT',
});
run.child.stdin.end();
const result = await run.closed;
assert.equal(result.code, 125);
await assert.rejects(fs.access(f.marker), { code: 'ENOENT' });
await assert.rejects(fs.access(path.join(f.root, 'side-effect')), {
code: 'ENOENT',
});
},
);
for (const fallback of [false, true]) {
test(
`telemetry closes before command completion and inherited descriptors stay private (fallback=${fallback})`,
{ timeout: 10000, skip: process.platform !== 'linux' },
async (t) => {
const f = await fixture(t);
const handle = await fs.open(path.join(f.root, 'private'), 'w+');
t.after(() => handle.close());
const run = launch(
t,
f,
'test ! -e /proc/self/fd/3 && test ! -e /proc/self/fd/4 || exit 90; read value && exit 91; sleep 0.5; printf "尾行 stdout\\n"; printf "stderr\\n" >&2; exit 17',
{ extraFd: handle.fd, fallback },
);
run.child.stdin.end('run\n');
await run.timing;
assert.equal(
run.child.exitCode,
null,
'telemetry must not wait for the command to close inherited fd 3',
);
const result = await run.closed;
assert.equal(result.code, 17, result.stderr);
assert.equal(result.stdout, '尾行 stdout\n');
assert.equal(result.stderr, 'stderr\n');
assert.match(result.stamp, /^\d{13}$/);
const exit = await readExit('launch', f.marker);
assert.equal(exit.version, 1);
assert.equal(exit.code, 17);
},
);
}
for (const signal of ['TERM', 'PIPE']) {
test(
`command SIG${signal} survives supervision and verified receipt publication`,
{ timeout: 10000 },
async (t) => {
const f = await fixture(t);
const run = launch(t, f, `kill -${signal} $$; exit 99`);
run.child.stdin.end('run\n');
const result = await run.closed;
assert.equal(result.code, null, result.stderr);
assert.equal(result.signal, 'SIG' + signal);
const exit = await readExit('launch', f.marker);
assert.equal(exit.version, 1);
assert.equal(exit.code, null);
assert.equal(exit.signal, 'SIG' + signal);
},
);
}
test(
'native launch failures close every pipe without executing a command',
{ timeout: 10000, skip: process.platform !== 'linux' },
async (t) => {
// Some Linux libffi builds retain a descriptor on their first load. Include
// that runtime-owned descriptor in the baseline, not in launch allocations.
const code = `import os,runpy,sys,signal,ctypes
ctypes.CDLL(None,use_errno=True)
module=runpy.run_path(sys.argv[1])
def descriptors():
result={}
for fd in os.listdir('/proc/self/fd'):
try: result[fd]=os.readlink('/proc/self/fd/'+fd)
except FileNotFoundError: pass
return result
before=descriptors()
def fail(*args,**kwargs): raise OSError(2,'injected exec failure')
os.posix_spawn=fail
for merged,log in ((False,None),(True,None),(True,os.devnull)):
try: module['spawn_command']('exit 99',merged,log)
except OSError as error: assert error.errno==2
else: raise AssertionError('launch unexpectedly succeeded')
after=descriptors()
assert after==before,(merged,log,before,after)
`;
const child = spawn('python3', ['-I', '-S', '-c', code, script], {
stdio: ['ignore', 'ignore', 'pipe'],
});
t.after(() => child.kill('SIGKILL'));
let stderr = '';
child.stderr.on('data', (data) => (stderr += data));
const [status] = await once(child, 'close');
assert.equal(status, 0, stderr);
},
);
for (const fallback of [false, true]) {
test(
`acknowledged log bytes survive killing the supervisor before its writer (fallback=${fallback})`,
{ timeout: 15000 },
async (t) => {
const f = await fixture(t);
const logfile = path.join(f.root, 'command.log');
const ready = path.join(f.root, 'ready');
const proceed = path.join(f.root, 'proceed');
const acknowledged = path.join(f.root, 'acknowledged');
const writer = path.join(f.root, 'writer.py');
const payload = '最后一行 中文🚀 stdout/stderr\n'.repeat(10);
await fs.writeFile(
writer,
`import os,time\nopen(${JSON.stringify(
ready,
)},'w').write(str(os.getpid()))\nwhile not os.path.exists(${JSON.stringify(
proceed,
)}):time.sleep(.005)\ndata=${JSON.stringify(
payload,
)}.encode('utf8')\nfor fd in (1,2):\n offset=0\n while offset<len(data):offset+=os.write(fd,data[offset:])\nopen(${JSON.stringify(
acknowledged,
)},'w').write('written')\ntime.sleep(30)\n`,
);
const args = [
script,
`exec python3 '${writer}'`,
String(process.pid),
f.marker,
process.execPath,
path.resolve('back/shared/managedExit.cjs'),
'log-output',
logfile,
];
if (fallback)
args.unshift(
'-c',
"import sys,runpy;sys.argv=sys.argv[1:];sys.platform='darwin';sys.exit(runpy.run_path(sys.argv[0])['main']())",
);
const child = spawn('python3', ['-I', '-S', ...args], {
stdio: ['pipe', 'ignore', 'pipe'],
});
let writerPid;
t.after(() => {
child.kill('SIGKILL');
if (writerPid)
try {
process.kill(writerPid, 'SIGKILL');
} catch (error) {
if (error.code !== 'ESRCH') throw error;
}
});
const closed = once(child, 'close');
child.stdin.end('run\n');
const deadline = Date.now() + 10000;
while (Date.now() < deadline) {
const value = await fs.readFile(ready, 'utf8').catch(() => '');
if (value) {
writerPid = Number(value);
break;
}
await new Promise((resolve) => setTimeout(resolve, 5));
}
assert.ok(writerPid, 'writer must start');
child.kill('SIGSTOP');
await fs.writeFile(proceed, 'write');
while (Date.now() < deadline) {
if (await fs.readFile(acknowledged, 'utf8').catch(() => '')) break;
await new Promise((resolve) => setTimeout(resolve, 5));
}
assert.equal(await fs.readFile(acknowledged, 'utf8'), 'written');
child.kill('SIGKILL');
// The independent relay must keep draining acknowledged pipe bytes even
// with the writer still alive and its supervisor gone. File visibility is
// asynchronous; neither killing the writer nor resuming the supervisor
// may be necessary to finish persisting this prefix.
while (Date.now() < deadline) {
if (
(await fs.readFile(logfile, 'utf8').catch(() => '')) ===
payload + payload
)
break;
await new Promise((resolve) => setTimeout(resolve, 5));
}
assert.equal(await fs.readFile(logfile, 'utf8'), payload + payload);
process.kill(writerPid, 'SIGKILL');
writerPid = undefined;
await closed;
},
);
}
+49
View File
@@ -0,0 +1,49 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { dashboardSnapshot } = require('../../back/shared/dashboardSnapshot');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
test('a backwards wall clock cannot extend the display snapshot lifetime', async (t) => {
let now = 100000;
t.mock.method(Date, 'now', () => now);
const db = {};
let calls = 0;
assert.equal(await dashboardSnapshot(db, 'today', async () => ++calls), 1);
now -= 60000;
await sleep(1100);
assert.equal(await dashboardSnapshot(db, 'today', async () => ++calls), 2);
});
test('eight viewers share one computation and a bounded snapshot; day/database changes and failures refresh', async () => {
const db = {};
let calls = 0,
release;
const compute = () => {
calls++;
return new Promise((r) => {
release = r;
});
};
const pending = Array.from({ length: 8 }, () =>
dashboardSnapshot(db, 'today', compute),
);
await sleep(0);
assert.equal(calls, 1);
release({ count: 50000 });
assert.deepEqual(await Promise.all(pending), Array(8).fill({ count: 50000 }));
assert.deepEqual(
await dashboardSnapshot(db, 'today', () => assert.fail('cache miss')),
{ count: 50000 },
);
await sleep(1010);
assert.equal(await dashboardSnapshot(db, 'today', async () => ++calls), 2);
assert.equal(await dashboardSnapshot(db, 'tomorrow', async () => ++calls), 3);
assert.equal(await dashboardSnapshot({}, 'tomorrow', async () => ++calls), 4);
await assert.rejects(
dashboardSnapshot(db, 'bad', async () => {
throw Error('sqlite busy');
}),
/sqlite busy/,
);
assert.equal(await dashboardSnapshot(db, 'bad', async () => ++calls), 5);
});
+134
View File
@@ -0,0 +1,134 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { Sequelize, QueryTypes } = require('sequelize');
const { executionModel } = require('../../back/data/executionModels');
const {
TriggerHistory,
installTriggerHistory,
} = require('../../back/cron/history');
const {
GlobalCronBudget,
} = require('../../back/cron/execution/globalCronBudget');
const { QueueOccupants } = require('../../back/cron/queries/queueDiagnostics');
async function fixture(t) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-orm-'));
const storage = path.join(dir, 'db.sqlite');
const db = new Sequelize({ dialect: 'sqlite', storage, logging: false });
for (const table of ['Crontabs', 'RunningInstances', 'CrontabStats', 'Auths'])
executionModel(db, table);
await db.sync();
await db.transaction((transaction) => installTriggerHistory(db, transaction));
const other = new Sequelize({ dialect: 'sqlite', storage, logging: false });
t.after(async () => {
await other.close();
await db.close();
await fs.rm(dir, { recursive: true, force: true });
});
return { db, other };
}
test('independent worker connections map existing tables without opening another database or modifying schema', async (t) => {
const { db, other } = await fixture(t);
const sql = [];
other.options.logging = (text) => sql.push(text);
for (const table of [
'Crontabs',
'RunningInstances',
'CrontabStats',
'Auths',
'CronTriggers',
])
executionModel(other, table);
assert.deepEqual(sql, []);
assert.notEqual(
executionModel(db, 'CronTriggers'),
executionModel(other, 'CronTriggers'),
);
await db.query(
"INSERT INTO Auths(type,info,createdAt,updatedAt) VALUES('systemConfig','{\"cronConcurrency\":4}',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
);
const row = await executionModel(other, 'Auths').findOne({
attributes: ['info'],
raw: true,
});
assert.deepEqual(JSON.parse(row.info), { cronConcurrency: 4 });
assert.equal((await new GlobalCronBudget(other).snapshot()).free, 4);
});
test('ORM cancellation keeps the transaction rollback boundary and updates only eligible states', async (t) => {
const { db, other } = await fixture(t);
const history = new TriggerHistory(other);
const ids = ["quote'--", 'recovery', 'finished', 'bound'];
for (let i = 0; i < ids.length; i++)
await db.query(
"INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,queued_at) VALUES($id,1,'node','queued',1,1)",
{ bind: { id: ids[i] } },
);
await db.query(
"UPDATE CronTriggers SET state='skipped',reason='restart',resume_pending=1 WHERE id='recovery'",
);
await db.query(
"UPDATE CronTriggers SET state='finished',started_at=1 WHERE id='finished'",
);
await db.query(
"UPDATE CronTriggers SET state='running',command_identity='bound' WHERE id='bound'",
);
await assert.rejects(
other.transaction(async (transaction) => {
await history.cancelQueuedInTransaction([1], transaction);
throw Error('rollback');
}),
/rollback/,
);
assert.equal(
(
await db.query('SELECT state FROM CronTriggers WHERE id=$id', {
bind: { id: ids[0] },
type: QueryTypes.SELECT,
})
)[0].state,
'queued',
);
assert.deepEqual(
new Set(await history.cancelQueued([1])),
new Set(ids.slice(0, 2)),
);
const rows = await db.query('SELECT id,state FROM CronTriggers', {
type: QueryTypes.SELECT,
});
assert.deepEqual(Object.fromEntries(rows.map((row) => [row.id, row.state])), {
[ids[0]]: 'stopped',
recovery: 'stopped',
finished: 'finished',
bound: 'running',
});
});
test('ORM live diagnostics preserve null-safe change detection and escaped payloads', async (t) => {
const { db } = await fixture(t);
const id = "odd'\n--";
await db.query(
"INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,queued_at) VALUES($id,1,'manual','queued',1,1)",
{ bind: { id } },
);
const warnings = [];
const pool = new QueueOccupants(
'manual',
() => 1,
(error) => warnings.push(error),
);
pool.watch(id, db);
// Flush deterministically; the timer is cleared when the observed wait is removed.
await pool.flush();
pool.forget(id);
const [row] = await db.query(
'SELECT queue_live_context FROM CronTriggers WHERE id=$id',
{ bind: { id }, type: QueryTypes.SELECT },
);
assert.equal(JSON.parse(row.queue_live_context).limit, 1);
assert.deepEqual(warnings, []);
});
+44
View File
@@ -48,3 +48,47 @@ test('file access enforces directory boundaries, blacklist descendants and symli
);
}
});
for (const kind of [
'directory',
'outside-link',
'dangling-link',
'swapped-directory',
]) {
test(`concurrent path creation preserves containment checks: ${kind}`, (t) => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-file-race-'));
t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
const root = path.join(tmp, 'logs');
const directory = path.join(root, 'shared-script');
const outside = path.join(tmp, 'outside');
fs.mkdirSync(root);
fs.mkdirSync(outside);
const exists = fs.existsSync;
t.mock.method(fs, 'existsSync', (file) => {
if (file === directory && !exists(directory)) {
if (kind === 'outside-link') fs.symlinkSync(outside, directory);
else if (kind === 'dangling-link')
fs.symlinkSync(path.join(outside, 'missing'), directory);
else fs.mkdirSync(directory);
// Simulate an earlier existsSync result racing with another writer.
return false;
}
return exists(file);
});
if (kind === 'swapped-directory') {
const lstat = fs.lstatSync;
t.mock.method(fs, 'lstatSync', (file, ...args) => {
const entry = lstat(file, ...args);
if (file === directory) {
fs.rmdirSync(directory);
fs.symlinkSync(outside, directory);
}
return entry;
});
}
assert.equal(
resolveFileAccess(root, ['shared-script/task.log']),
kind === 'directory' ? path.join(directory, 'task.log') : '',
);
});
}
+877
View File
@@ -0,0 +1,877 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { once, EventEmitter } = require('node:events');
const { Sequelize, QueryTypes } = require('sequelize');
const {
GlobalCronBudget,
} = require('../../back/cron/execution/globalCronBudget');
const { systemOwner } = require('../../back/cron/execution/cronProcess');
const load = require('../helpers/load-security-module.cjs');
const {
installTriggerHistory,
TriggerHistory,
} = require('../../back/cron/history');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function fixture(t, limit = 2, productionDatabase = false) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-budget-'));
const storage = path.join(root, 'database.sqlite');
const db = productionDatabase
? load('back/data/index.ts', { '../config/index': { dbPath: root } })
.sequelize
: new Sequelize({ dialect: 'sqlite', storage, logging: false });
const tasks = load('back/data/cron.ts', { '.': { sequelize: db } });
load('back/data/runningInstance.ts', { '.': { sequelize: db } });
load('back/data/cronStats.ts', { '.': { sequelize: db } });
load('back/data/system.ts', { '.': { sequelize: db } });
await db.sync();
await db.transaction((tx) => installTriggerHistory(db, tx));
await db.query(
"INSERT INTO Auths(type,info,createdAt,updatedAt) VALUES ('systemConfig',$info,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
{ bind: { info: JSON.stringify({ cronConcurrency: limit }) } },
);
const history = new TriggerHistory(db);
const budget = new GlobalCronBudget(db);
t.after(async () => {
await db.close();
await fs.rm(root, { recursive: true, force: true });
});
const enqueue = async (id, source = 'manual') => {
await history.enqueue(id, 1, source, null);
return id;
};
const leases = () =>
db.query('SELECT * FROM CronConcurrencyLeases', {
type: QueryTypes.SELECT,
});
return { db, storage, tasks, history, budget, enqueue, leases };
}
test('manual, node and recovery share the durable budget and duplicate requests cannot execute twice', async (t) => {
const { budget, enqueue, leases } = await fixture(t, 2);
let active = 0,
peak = 0,
done = 0;
const ids = await Promise.all(
Array.from({ length: 18 }, (_, i) =>
enqueue('job-' + i, ['manual', 'node', 'recovery'][i % 3]),
),
);
await Promise.all(
ids.map((id) =>
budget.run(id, async () => {
peak = Math.max(peak, ++active);
assert.equal(await budget.acquire(id), undefined);
await sleep(20);
active--;
done++;
}),
),
);
assert.equal(done, 18);
assert.equal(peak, 2);
assert.deepEqual(await leases(), []);
});
test('cancelled and expired waiters never execute or leak permits; lowering and raising the shared limit takes effect', async (t) => {
const { db, budget, enqueue, leases, history } = await fixture(t, 1);
const token = await budget.acquire(await enqueue('holder'));
const signal = new EventEmitter();
const expired = budget.run(
await enqueue('expired', 'node'),
() => assert.fail('expired ran'),
undefined,
signal,
);
const cancelled = budget.run(await enqueue('cancelled'), () =>
assert.fail('cancelled ran'),
);
signal.emit('expired');
await history.finish('cancelled', 'stopped', 'cancelled');
await Promise.all([expired, cancelled]);
assert.equal((await leases()).length, 1);
const pending = budget.acquire(await enqueue('next'));
await db.query('UPDATE Auths SET info=\'{"cronConcurrency":2}\'');
const next = await pending;
assert.equal((await leases()).length, 2);
await db.query('UPDATE Auths SET info=\'{"cronConcurrency":1}\'');
let entered = false;
const last = budget.run(await enqueue('last'), async () => {
entered = true;
});
await budget.release('next', next);
await sleep(150);
assert.equal(entered, false);
await budget.release('holder', token);
await last;
assert.deepEqual(await leases(), []);
});
test('a surviving supervisor holds its permit after worker death, and a dead or reused PID is reclaimed', async (t) => {
const { db, budget, enqueue, leases } = await fixture(t, 1);
const child = spawn(process.execPath, ['-e', 'setInterval(()=>{},1000)']);
t.after(() => child.kill('SIGKILL'));
await once(child, 'spawn');
const identity = systemOwner(child.pid);
await enqueue('orphan');
await db.query(
'INSERT INTO CronConcurrencyLeases VALUES ($id,$token,$owner,$command)',
{
bind: {
id: 'orphan',
token: 'old',
owner: identity + '-reused',
command: identity,
},
},
);
let entered = false;
const work = budget.run(await enqueue('recovery', 'recovery'), async () => {
entered = true;
});
await sleep(200);
assert.equal(entered, false);
await budget.release('orphan', 'old');
assert.equal((await leases()).length, 1);
const closed = once(child, 'close');
child.kill('SIGKILL');
await closed;
await work;
assert.equal(entered, true);
assert.deepEqual(await leases(), []);
await db.query(
'INSERT INTO CronConcurrencyLeases VALUES ($id,$token,$owner,NULL)',
{
bind: {
id: 'dead-before-bind',
token: 'stale',
owner: systemOwner(process.pid) + '-reused',
},
},
);
await budget.run(await enqueue('after-unbound'), async () => {});
assert.deepEqual(await leases(), []);
});
test('exceptions release unbound reservations and no idle polling remains', async (t) => {
const { db, budget, enqueue, leases } = await fixture(t, 1);
await assert.rejects(
budget.run(await enqueue('failed'), async () => {
throw new Error('spawn failed');
}),
/spawn failed/,
);
assert.deepEqual(await leases(), []);
let queries = 0;
db.options.logging = () => queries++;
await sleep(250);
assert.equal(queries, 0);
});
test('an upgrade counts surviving commands created before budget leases existed', async (t) => {
const { db, budget, enqueue, leases, history } = await fixture(t, 1);
await enqueue('old-version');
await history.start('old-version');
await db.query(
"UPDATE CronTriggers SET command_identity=$identity WHERE id='old-version'",
{ bind: { identity: systemOwner(process.pid) } },
);
let ran = false;
const pending = budget.run(await enqueue('new-version'), async () => {
ran = true;
});
await sleep(150);
assert.equal(ran, false);
assert.deepEqual(await leases(), []);
await history.finish('old-version', 'finished', null, 0);
await pending;
assert.equal(ran, true);
assert.deepEqual(await leases(), []);
});
test('a cancelled supervisor keeps capacity until its recorded descendants exit', async (t) => {
const { db, budget, enqueue, leases } = await fixture(t, 1);
await enqueue('stopping');
await db.query("UPDATE CronTriggers SET instance_id=9 WHERE id='stopping'");
await db.query(
'INSERT INTO CronStopRequests(instance_id,cron_id,pid,targets) VALUES (9,1,$pid,$targets)',
{
bind: {
pid: process.pid,
targets: JSON.stringify([systemOwner(process.pid)]),
},
},
);
await db.query(
'INSERT INTO CronConcurrencyLeases VALUES ($id,$token,$owner,$command)',
{
bind: {
id: 'stopping',
token: 'stop',
owner: 'crond:999999999:dead',
command: 'crond:999999999:dead',
},
},
);
await budget.release('stopping', 'stop');
assert.equal((await leases()).length, 1);
let ran = false;
const next = budget.run(await enqueue('after-stop'), async () => {
ran = true;
});
await sleep(150);
assert.equal(ran, false);
await db.query('DELETE FROM CronStopRequests WHERE instance_id=9');
await next;
assert.equal(ran, true);
assert.deepEqual(await leases(), []);
});
test('accepted scheduled recovery retains identity and queue deadline without replaying changed rules or bound commands', async (t) => {
const { db, history } = await fixture(t);
const { slotId } = require('../../back/cron/identity');
const item = {
id: '1',
command: 'true',
schedule: '* * * * * *',
recovery_from: 100,
};
const original = slotId('1', 0, item.schedule, 1000);
const historical = slotId('1', 0, item.schedule, 5000);
for (const [id, at] of [
[original, 1000],
['changed-rule', 2000],
['too-old', 3000],
['already-bound', 4000],
[historical, 5000],
]) {
await history.enqueue(id, 1, 'node', at, id === 'too-old' ? 50 : 120);
await history.finish(id, 'skipped', 'restart');
}
await db.query(
"UPDATE CronTriggers SET started_at=125 WHERE id='already-bound'",
);
await db.query(
'UPDATE CronTriggers SET resume_pending=1 WHERE id<>$historical',
{ bind: { historical } },
);
const calls = [];
const { resumeAcceptedCrons } = load(
'back/cron/scheduling/resumeAcceptedCrons.ts',
{
'../../data/cron': { CrontabModel: { sequelize: db } },
'../execution/runCron': { runCron: async (...args) => calls.push(args) },
},
);
await resumeAcceptedCrons(item, () => true);
assert.equal(calls.length, 1);
assert.deepEqual(calls[0][3], {
id: original,
time: 1000,
queuedAt: 120,
source: 'recovery',
});
});
test('restart preserves submitted manual snapshots, requeues only unbound launches and never replays bound commands', async (t) => {
const { db, history, enqueue } = await fixture(t);
for (const id of ['queued', 'unbound', 'bound', 'cancelled']) {
await enqueue(id);
await db.query(
'INSERT INTO CronManualSubmissions VALUES ($id,$token,$snapshot)',
{ bind: { id, token: id, snapshot: '{}' } },
);
}
await db.query(
"UPDATE CronTriggers SET state='running',started_at=1 WHERE id IN ('unbound','bound')",
);
await db.query(
"UPDATE CronTriggers SET command_identity=$identity WHERE id='bound'",
{ bind: { identity: systemOwner(process.pid) } },
);
await history.finish('cancelled', 'stopped', 'cancelled');
await history.interrupt('http');
const rows = await db.query(
'SELECT id,state,started_at FROM CronTriggers ORDER BY id',
{ type: QueryTypes.SELECT },
);
assert.deepEqual(
rows.map((r) => [r.id, r.state]),
[
['bound', 'running'],
['cancelled', 'stopped'],
['queued', 'queued'],
['unbound', 'queued'],
],
);
assert.equal(rows.find((r) => r.id === 'unbound').started_at, null);
});
test('cancellation between worker interruption and re-admission prevents recovery from launching the accepted slot', async (t) => {
const { db, history, enqueue } = await fixture(t);
await enqueue('interrupted', 'node');
await history.interrupt('http');
const [pending] = await db.query(
"SELECT state,resume_pending FROM CronTriggers WHERE id='interrupted'",
{ type: QueryTypes.SELECT },
);
assert.deepEqual(pending, { state: 'skipped', resume_pending: 1 });
assert.deepEqual(await history.cancelQueued([1]), ['interrupted']);
assert.equal(
await history.enqueue('interrupted', 1, 'recovery', 1000),
false,
);
const [cancelled] = await db.query(
"SELECT state,reason,resume_pending FROM CronTriggers WHERE id='interrupted'",
{ type: QueryTypes.SELECT },
);
assert.deepEqual(cancelled, {
state: 'stopped',
reason: 'cancelled',
resume_pending: null,
});
});
test('ready tasks across workers prefer short history, then age long tasks into FIFO', async (t) => {
const { db, storage, tasks, budget, history, enqueue, leases } =
await fixture(t, 1);
await tasks.CrontabModel.bulkCreate([
{
id: 1,
name: 'long',
command: 'echo long',
schedule: '* * * * *',
last_running_time: 120,
last_execution_time: 1,
},
{
id: 2,
name: 'short',
command: 'echo short',
schedule: '* * * * *',
last_running_time: 0,
last_execution_time: 1,
},
]);
const otherDb = new Sequelize({ dialect: 'sqlite', storage, logging: false });
t.after(() => otherDb.close());
const other = new GlobalCronBudget(otherDb);
const token = await budget.acquire(await enqueue('holder'));
await history.enqueue('long', 1, 'node', null);
await history.enqueue('short', 2, 'manual', null);
await history.enqueue('aged', 1, 'recovery', null, Date.now() - 31000);
const order = [];
const jobs = [
budget.run('long', async () => {
order.push('long');
}),
other.run('short', async () => {
order.push('short');
}),
budget.run('aged', async () => {
order.push('aged');
}),
];
for (let i = 0; i < 100; i++) {
const rows = await db.query('SELECT * FROM CronConcurrencyWaiters', {
type: QueryTypes.SELECT,
});
if (rows.length === 3) break;
await sleep(20);
}
await budget.release('holder', token);
await Promise.all(jobs);
assert.deepEqual(order, ['aged', 'short', 'long']);
assert.deepEqual(await leases(), []);
assert.deepEqual(
await db.query('SELECT * FROM CronConcurrencyWaiters', {
type: QueryTypes.SELECT,
}),
[],
);
});
test('recovered queued tasks replace a dead ready owner without dropping or replaying the request', async (t) => {
const { db, budget, enqueue, leases } = await fixture(t, 1);
await enqueue('recovered-ready');
await db.query(
"INSERT INTO CronConcurrencyWaiters VALUES ('recovered-ready','old','system:99999999:dead')",
);
let calls = 0;
await budget.run('recovered-ready', async () => {
calls++;
});
assert.equal(calls, 1);
assert.deepEqual(await leases(), []);
assert.deepEqual(
await db.query('SELECT * FROM CronConcurrencyWaiters', {
type: QueryTypes.SELECT,
}),
[],
);
});
test('ready-to-lease handoff is atomic and cleanup errors cannot hide a granted permit', async (t) => {
const { db, budget, enqueue, leases } = await fixture(t, 1);
await enqueue('atomic-handoff');
const query = db.query.bind(db);
let rejectHandoff = true;
t.mock.method(db, 'query', async (sql, options) => {
if (
String(sql)
.replace(/[`"]/g, '')
.startsWith('DELETE FROM CronConcurrencyWaiters') &&
options?.transaction &&
rejectHandoff
) {
rejectHandoff = false;
throw Error('injected handoff failure');
}
return query(sql, options);
});
await assert.rejects(budget.acquire('atomic-handoff'), /handoff failure/);
assert.deepEqual(await leases(), []);
t.mock.method(db, 'query', async (sql, options) => {
if (
String(sql)
.replace(/[`"]/g, '')
.startsWith('DELETE FROM CronConcurrencyWaiters') &&
!options?.transaction
)
throw Error('cleanup unavailable');
return query(sql, options);
});
const token = await budget.acquire('atomic-handoff');
assert.ok(token);
assert.equal((await leases()).length, 1);
await budget.release('atomic-handoff', token);
assert.deepEqual(await leases(), []);
});
test('an idle budget ranks the entire synchronous submission before granting its first permit', async (t) => {
const { db, tasks, history, budget, leases } = await fixture(t, 2);
await tasks.CrontabModel.bulkCreate([
{
id: 1,
name: 'long',
command: 'long',
schedule: '* * * * *',
last_running_time: 30,
last_execution_time: 1,
},
{
id: 2,
name: 'short',
command: 'short',
schedule: '* * * * *',
last_running_time: 0,
last_execution_time: 1,
},
]);
const ids = ['long-first', 'short-a', 'short-b', 'short-c'];
for (const id of ids)
await history.enqueue(id, id.startsWith('long') ? 1 : 2, 'manual', null);
const order = [];
let active = 0,
peak = 0;
await Promise.all(
ids.map((id) =>
budget.run(id, async () => {
order.push(id);
peak = Math.max(peak, ++active);
await sleep(15);
active--;
}),
),
);
assert.deepEqual(new Set(order.slice(0, 2)), new Set(['short-a', 'short-b']));
assert.ok(order.indexOf('short-c') < order.indexOf('long-first'));
assert.equal(peak, 2);
assert.deepEqual(await leases(), []);
assert.deepEqual(
await db.query('SELECT * FROM CronConcurrencyWaiters', {
type: QueryTypes.SELECT,
}),
[],
);
});
test('an arrival and expiration during registration are processed without a saturated polling delay', async (t) => {
const { db, budget, enqueue, leases } = await fixture(t, 2);
await enqueue('first');
await enqueue('late');
await enqueue('expired-late');
const signal = new EventEmitter();
let late,
expired,
injected = false;
const query = db.query.bind(db);
t.mock.method(db, 'query', async (sql, options) => {
if (
!injected &&
(/^SELECT t\.id,w\.token FROM CronTriggers t JOIN CronConcurrencyWaiters w/.test(
String(sql),
) ||
/^SELECT .* FROM CronConcurrencyWaiters AS CronConcurrencyWaiters INNER JOIN CronTriggers AS trigger/.test(
String(sql).replace(/[`"]/g, ''),
))
) {
injected = true;
late = budget.acquire('late');
expired = budget.acquire('expired-late', { signal });
signal.emit('expired');
}
return query(sql, options);
});
const first = await budget.acquire('first');
assert.equal(
injected,
true,
'the in-flight registration fault must be exercised',
);
// A 100 ms saturated poll here would postpone an already-ready arrival even
// though one permit is free. The wakeup must survive the in-flight query.
assert.equal(budget.timer, undefined);
const second = await late;
assert.ok(second);
assert.equal(await expired, undefined);
assert.equal((await leases()).length, 2);
await budget.release('first', first);
await budget.release('late', second);
assert.deepEqual(await leases(), []);
});
test('local saturation reduces fallback reads and a release immediately wakes admission', async (t) => {
const { db, budget, enqueue, leases } = await fixture(t, 1);
const first = await budget.acquire(await enqueue('local-holder'));
let snapshots = 0;
const query = db.query.bind(db);
t.mock.method(db, 'query', async (sql, options) => {
if (String(sql).startsWith('SELECT l.*,s.targets') && !options?.transaction)
snapshots++;
return query(sql, options);
});
const next = budget.acquire(await enqueue('local-next'));
await sleep(650);
assert.ok(
snapshots >= 1 && snapshots <= 3,
`saturated snapshots: ${snapshots}`,
);
assert.equal((await leases()).length, 1);
await budget.release('local-holder', first);
// Release interrupts the fallback timer; admission must not wait for it.
assert.equal(budget.timer, undefined);
const token = await next;
assert.ok(token);
await budget.release('local-next', token);
assert.equal(budget.heldTokens.size, 0);
assert.deepEqual(await leases(), []);
});
test('another budget in the same worker retains fast polling and sees releases without local notifications', async (t) => {
const { db, storage, budget, enqueue, leases } = await fixture(t, 1);
const otherDb = new Sequelize({ dialect: 'sqlite', storage, logging: false });
t.after(() => otherDb.close());
const other = new GlobalCronBudget(otherDb);
const first = await budget.acquire(await enqueue('foreign-holder'));
let snapshots = 0;
const query = otherDb.query.bind(otherDb);
t.mock.method(otherDb, 'query', async (sql, options) => {
if (String(sql).startsWith('SELECT l.*,s.targets') && !options?.transaction)
snapshots++;
return query(sql, options);
});
const next = other.acquire(await enqueue('foreign-next'));
await sleep(650);
assert.ok(snapshots >= 4, `foreign snapshots: ${snapshots}`);
await budget.release('foreign-holder', first);
const token = await next;
assert.ok(token);
await other.release('foreign-next', token);
assert.deepEqual(await leases(), []);
});
test('large admission batches preserve tokens across chunks and ignore duplicate, missing and cancelled requests', async (t) => {
const { db, budget, enqueue, leases, history } = await fixture(t, 4);
const ids = Array.from({ length: 401 }, (_, i) => `chunk-${i}`);
for (const id of ids) await enqueue(id);
await enqueue('cancelled-batch');
await history.finish('cancelled-batch', 'stopped', 'cancelled');
let active = 0;
let peak = 0;
const calls = new Map();
const jobs = ids.map((id) =>
budget.run(id, async () => {
calls.set(id, (calls.get(id) ?? 0) + 1);
peak = Math.max(peak, ++active);
await history.finish(id, 'finished', null, 0);
active--;
}),
);
for (const id of [ids[0], ids[200], 'missing-batch', 'cancelled-batch'])
jobs.push(budget.run(id, () => assert.fail(`${id} must not run`)));
await Promise.all(jobs);
assert.equal(calls.size, ids.length);
assert.ok([...calls.values()].every((count) => count === 1));
assert.ok(peak <= 4);
assert.equal(budget.heldTokens.size, 0);
assert.deepEqual(await leases(), []);
assert.deepEqual(
await db.query('SELECT * FROM CronConcurrencyWaiters', {
type: QueryTypes.SELECT,
}),
[],
);
});
test('a later registration chunk failure rolls back the entire batch and permits a clean retry', async (t) => {
const { db, budget, enqueue, leases } = await fixture(t, 4);
const ids = Array.from({ length: 201 }, (_, i) => `rollback-${i}`);
for (const id of ids) await enqueue(id);
const query = db.query.bind(db);
let chunks = 0;
const mock = t.mock.method(db, 'query', async (sql, options) => {
if (String(sql).startsWith('WITH incoming(') && ++chunks === 2)
throw new Error('injected second chunk failure');
return query(sql, options);
});
const results = await Promise.allSettled(ids.map((id) => budget.acquire(id)));
assert.equal(chunks, 2, 'failure must occur after one successful chunk');
assert.ok(
results.every(
(result) =>
result.status === 'rejected' &&
/second chunk failure/.test(result.reason.message),
),
);
mock.mock.restore();
assert.equal(budget.heldTokens.size, 0);
assert.deepEqual(await leases(), []);
assert.deepEqual(
await db.query('SELECT * FROM CronConcurrencyWaiters', {
type: QueryTypes.SELECT,
}),
[],
);
let ran = false;
await budget.run(ids[0], async () => {
ran = true;
});
assert.equal(ran, true);
assert.deepEqual(await leases(), []);
});
test('a fresh batch records shared occupancy while waiting, without rewriting unchanged samples', async (t) => {
const { db, budget, enqueue } = await fixture(t, 1);
await enqueue('a-holder');
await enqueue('b-waiter');
let release,
started = false;
const gate = new Promise((resolve) => (release = resolve));
const first = budget.run('a-holder', async () => {
started = true;
await gate;
});
const second = budget.run('b-waiter', async () => {});
t.after(async () => {
release();
await Promise.all([first, second]);
});
const read = async () =>
(
await db.query("SELECT * FROM CronTriggers WHERE id='b-waiter'", {
type: QueryTypes.SELECT,
})
)[0];
let row;
for (let i = 0; i < 150; i++) {
row = await read();
if (row.queue_live_context) break;
await sleep(10);
}
assert.equal(started, true);
assert.equal(row.state, 'queued');
assert.deepEqual(JSON.parse(row.queue_context), {
queue: 'global',
limit: 1,
occupied: 1,
holders: [{ id: 'a-holder', name: 'a-holder' }],
});
assert.equal(row.queue_context, row.queue_live_context);
let writes = 0;
db.options.logging = (sql) => {
if (/UPDATE.*queue_live_context/.test(sql)) writes++;
};
await sleep(650);
assert.equal(writes, 0);
release();
await Promise.all([first, second]);
});
test('global diagnostics include a different worker and retain its first sample through handoff', async (t) => {
const { db, storage, budget, enqueue } = await fixture(t, 1);
await enqueue('foreign-holder', 'system');
await enqueue('waiting-node', 'node');
const foreign = new Sequelize({ dialect: 'sqlite', storage, logging: false });
const other = new GlobalCronBudget(foreign);
const token = await other.acquire('foreign-holder');
const next = budget.acquire('waiting-node');
let row;
for (let i = 0; i < 150; i++) {
[row] = await db.query(
"SELECT * FROM CronTriggers WHERE id='waiting-node'",
{ type: QueryTypes.SELECT },
);
if (row.queue_live_context) break;
await sleep(10);
}
assert.equal(
JSON.parse(row.queue_live_context).holders[0].id,
'foreign-holder',
);
assert.equal(JSON.parse(row.queue_live_context).queue, 'global');
await other.release('foreign-holder', token);
await budget.release('waiting-node', await next);
await foreign.close();
});
for (const cancel of [false, true]) {
test(
`real background writers hold the global slot through ${
cancel ? 'forced cancellation' : 'normal completion'
}`,
{ timeout: 15000, skip: cancel && process.platform !== 'linux' },
async (t) => {
const { db, storage, tasks, history, budget, enqueue, leases } =
await fixture(t, 1, true);
const root = path.dirname(storage);
const previousData = process.env.QL_DATA_DIR;
process.env.QL_DATA_DIR = root;
t.after(() => {
if (previousData === undefined) delete process.env.QL_DATA_DIR;
else process.env.QL_DATA_DIR = previousData;
});
await tasks.CrontabModel.create({
id: 1,
command: 'true',
allow_multiple_instances: 1,
});
await enqueue('background');
await enqueue('after-background', 'node');
const ready = path.join(root, 'writer.pid');
const proceed = path.join(root, 'continue');
const log = path.join(root, 'background.log');
const { shellQuote } = require('../../back/shared/shellQuote');
const {
spawnCronCommand,
releaseCronCommand,
} = require('../../back/cron/execution/cronCommandProcess');
const writer = `import os,time,signal\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\nos.write(1,'唯一执行 中文🚀\\n'.encode())\nopen(${JSON.stringify(
ready,
)},'w').write(str(os.getpid()))\nwhile not os.path.exists(${JSON.stringify(
proceed,
)}):time.sleep(.01)\nos.write(2,'正常尾行\\n'.encode())\n`;
let child,
writerPid,
nextRuns = 0;
const first = budget.run('background', async () => {
assert.equal(await history.start('background'), true);
child = spawnCronCommand(
`python3 -I -S -c ${shellQuote(writer)} &`,
'background',
undefined,
log,
);
const closed = once(child, 'close');
child.stdout.resume();
child.stderr.resume();
await once(child, 'spawn');
assert.equal(
await history.bindCommand('background', child.pid, 'background.log'),
true,
);
await releaseCronCommand(child);
const [code, signal] = await closed;
await history.complete(
'background',
signal ? 'stopped' : 'finished',
signal,
code,
);
});
first.catch(() => {});
t.after(() => {
child?.kill('SIGKILL');
if (writerPid)
try {
process.kill(writerPid, 'SIGKILL');
} catch (_) {}
});
for (let i = 0; i < 500; i++) {
writerPid = Number(await fs.readFile(ready, 'utf8').catch(() => ''));
if (writerPid) break;
await sleep(10);
}
assert.ok(writerPid);
// A replacement/foreign worker sees the same durable command reservation.
const foreign = load('back/data/index.ts', {
'../config/index': { dbPath: root },
}).sequelize;
const next = new GlobalCronBudget(foreign).run(
'after-background',
async () => {
nextRuns++;
},
);
await sleep(250);
assert.equal(nextRuns, 0);
assert.equal((await leases()).length, 1);
if (cancel) {
const { killTask } = require('../../back/config/util');
const identity = systemOwner(child.pid);
const [row] = await db.query(
"SELECT instance_id FROM CronTriggers WHERE id='background'",
{ type: QueryTypes.SELECT },
);
await history.queueInstanceStop(
row.instance_id,
1,
child.pid,
undefined,
identity,
);
await killTask(
child.pid,
true,
() => assert.equal(systemOwner(child.pid), identity),
(signal, targets) =>
history.requestInstanceStop(
row.instance_id,
child.pid,
signal,
targets,
),
);
await history.stopVerifiedInstance(row.instance_id);
} else await fs.writeFile(proceed, 'go');
await Promise.all([first, next]);
assert.equal(nextRuns, 1);
assert.deepEqual(await leases(), []);
assert.equal(
await fs.readFile(log, 'utf8'),
'唯一执行 中文🚀\n' + (cancel ? '' : '正常尾行\n'),
);
const [row] = await db.query(
"SELECT state,counted FROM CronTriggers WHERE id='background'",
{ type: QueryTypes.SELECT },
);
assert.equal(row.state, cancel ? 'stopped' : 'finished');
if (!cancel) assert.equal(row.counted, 1);
await foreign.close();
},
);
}
+55
View File
@@ -0,0 +1,55 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { ApiService } = require('../../back/protos/api');
const { lazyApiHandlers } = require('../../back/schedule/lazyApiHandlers');
test('registering script APIs loads no service graph; every unary method forwards calls and errors on demand', async (t) => {
const apiPath = require.resolve('../../back/schedule/api');
assert.equal(require.cache[apiPath], undefined);
const handlers = lazyApiHandlers();
assert.deepEqual(Object.keys(handlers), Object.keys(ApiService));
assert.equal(require.cache[apiPath], undefined);
t.after(() => delete require.cache[apiPath]);
const calls = [];
const exports = Object.fromEntries(
Object.keys(ApiService).map((name) => [
name,
async (call, callback) => {
calls.push(name);
callback(null, { code: 200, data: call.request });
},
]),
);
require.cache[apiPath] = {
id: apiPath,
filename: apiPath,
loaded: true,
exports,
};
await Promise.all(
Object.keys(ApiService).map(
(name) =>
new Promise((resolve, reject) => {
const request = { test: name };
handlers[name]({ request }, (err, value) => {
try {
assert.equal(err, null);
assert.equal(value.data, request);
resolve();
} catch (e) {
reject(e);
}
});
}),
),
);
assert.equal(calls.length, Object.keys(ApiService).length);
exports.getCrons = async () => {
throw Error('load/call failed');
};
await new Promise((resolve) =>
handlers.getCrons({ request: {} }, (error) => {
assert.match(error.message, /load\/call failed/);
resolve();
}),
);
});
+258
View File
@@ -0,0 +1,258 @@
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const test = require('node:test');
const load = require('../helpers/load-security-module.cjs');
const settle = () => new Promise((resolve) => setTimeout(resolve, 2100));
async function fixture(t) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-cache-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const io = { reads: 0, bytes: 0, afterRead: undefined };
const { readLogChunk } = load('back/shared/logReader.ts', {
'fs/promises': {
...fs,
async open(...args) {
const file = await fs.open(...args);
const read = file.read.bind(file);
file.read = async (...args) => {
const result = await read(...args);
io.reads++;
io.bytes += result.bytesRead;
await io.afterRead?.();
return result;
};
return file;
},
},
});
const file = path.join(root, 'run.log');
const follow = (chunk, target = file) =>
readLogChunk(target, {
offset: chunk.nextOffset,
cursor: chunk.cursor,
follow: true,
});
return { root, file, io, readLogChunk, follow };
}
test('verified EOF polls do not read retained content; appends still deliver every UTF-8 byte', async (t) => {
const f = await fixture(t);
const initial = '原始🚀\n'.repeat(500000);
await fs.writeFile(f.file, initial);
await settle();
let chunk = await f.readLogChunk(f.file, { offset: 0, follow: true });
let received = chunk.content;
while (chunk.nextOffset < chunk.total) {
chunk = await f.follow(chunk);
received += chunk.content;
}
assert.equal(received, initial);
const bytes = f.io.bytes;
for (let i = 0; i < 50; i++) {
const empty = await f.follow(chunk);
assert.equal(empty.content, '');
assert.equal(empty.reset, false);
assert.equal(empty.cursor, chunk.cursor);
}
assert.equal(
f.io.bytes,
bytes,
'idle viewers must not reread the 4 MiB window',
);
for (const appended of ['下一行🚀\n', 'another line\n', '结束']) {
await fs.appendFile(f.file, appended);
chunk = await f.follow(chunk);
assert.equal(chunk.reset, false);
assert.equal(chunk.content, appended);
}
});
test('cached EOF detects same-size overwrite even when mtime is restored, truncation/regrowth and replacement', async (t) => {
const f = await fixture(t);
const original = 'A\n' + '共同后缀🚀\n'.repeat(20);
await fs.writeFile(f.file, original);
await settle();
let chunk = await f.readLogChunk(f.file, { offset: 0, follow: true });
await f.follow(chunk);
const stat = await fs.stat(f.file);
const replacement = 'B' + original.slice(1);
await fs.writeFile(f.file, replacement);
await fs.utimes(f.file, stat.atime, stat.mtime);
chunk = await f.follow(chunk);
assert.equal(chunk.reset, true);
assert.equal(chunk.content, replacement);
await fs.truncate(f.file);
await fs.appendFile(f.file, original + 'more');
chunk = await f.follow(chunk);
assert.equal(chunk.reset, true);
assert.equal(chunk.content, original + 'more');
await fs.rename(f.file, path.join(f.root, 'previous.log'));
await fs.writeFile(f.file, original + 'more');
chunk = await f.follow(chunk);
assert.equal(chunk.reset, true);
assert.equal(chunk.offset, 0);
assert.equal(chunk.content, original + 'more');
await fs.truncate(f.file);
chunk = await f.follow(chunk);
assert.equal(chunk.reset, true);
assert.equal(chunk.total, 0);
assert.equal((await f.follow(chunk)).content, '');
await fs.appendFile(f.file, '新文件\n');
assert.equal((await f.follow(chunk)).content, '新文件\n');
});
test('EOF cache cannot validate another viewer offset, a forged cursor or a deleted log', async (t) => {
const f = await fixture(t);
await fs.writeFile(f.file, 'abcdefghij');
await settle();
const first = await f.readLogChunk(f.file, {
offset: 0,
limit: 4,
follow: true,
});
const last = await f.follow(first);
const replay = await f.follow(first);
assert.equal(replay.content, 'efghij');
assert.equal(replay.reset, false);
const forged = await f.follow({ ...last, cursor: last.cursor + 'bad' });
assert.equal(forged.reset, true);
assert.equal(forged.content, 'abcdefghij');
await fs.unlink(f.file);
const missing = await f.follow(last);
assert.equal(missing.total, 0);
assert.equal(missing.content, '');
assert.equal(missing.cursor, undefined);
await fs.writeFile(f.file, 'ABCDEFGHIJ');
const recreated = await f.follow(last);
assert.equal(recreated.reset, true);
assert.equal(recreated.content, 'ABCDEFGHIJ');
});
test('cached EOF revalidates periodically without extending the deadline on hits', async (t) => {
const f = await fixture(t);
await fs.writeFile(f.file, 'periodic verification\n');
await settle();
let now = Date.now();
t.mock.method(Date, 'now', () => now);
const chunk = await f.readLogChunk(f.file, { offset: 0, follow: true });
const reads = f.io.reads;
now += 20000;
await f.follow(chunk);
assert.equal(f.io.reads, reads);
now += 10001;
await f.follow(chunk);
assert.ok(f.io.reads > reads);
const refreshedReads = f.io.reads;
now -= 60000;
await f.follow(chunk);
assert.ok(
f.io.reads > refreshedReads,
'a backwards clock must invalidate the cache',
);
});
test('EOF cache eviction falls back to content verification', async (t) => {
const f = await fixture(t);
await fs.writeFile(f.file, 'first');
const files = Array.from({ length: 256 }, (_, i) =>
path.join(f.root, String(i)),
);
for (const file of files) await fs.writeFile(file, 'next');
await settle();
const first = await f.readLogChunk(f.file, { offset: 0, follow: true });
for (const file of files) {
await f.readLogChunk(file, { offset: 0, follow: true });
}
const reads = f.io.reads;
assert.equal((await f.follow(first)).reset, false);
assert.ok(f.io.reads > reads);
});
test('same-tick timestamps cannot hide a rewrite, including one racing with the EOF read', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-coarse-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const file = path.join(root, 'coarse.log');
await fs.writeFile(file, 'first version');
const coarseStat = await fs.stat(file, { bigint: true });
let now = Number(coarseStat.ctimeMs);
t.mock.method(Date, 'now', () => now);
let reads = 0;
let afterRead;
const { readLogChunk } = load('back/shared/logReader.ts', {
'fs/promises': {
...fs,
async open(...args) {
const handle = await fs.open(...args);
const read = handle.read.bind(handle);
handle.stat = async () => coarseStat;
handle.read = async (...args) => {
reads++;
const value = await read(...args);
await afterRead?.();
return value;
};
return handle;
},
},
});
const follow = (chunk) =>
readLogChunk(file, {
offset: chunk.nextOffset,
cursor: chunk.cursor,
follow: true,
});
let current = await readLogChunk(file, { offset: 0, follow: true });
await fs.writeFile(file, 'other version');
current = await follow(current);
assert.equal(current.reset, true);
assert.equal(current.content, 'other version');
afterRead = async () => {
afterRead = undefined;
await fs.writeFile(file, 'third version');
};
await follow(current);
current = await follow(current);
assert.equal(current.reset, true);
assert.equal(current.content, 'third version');
now += 2100;
current = await follow(current);
const verifiedReads = reads;
await follow(current);
assert.equal(
reads,
verifiedReads,
'an old timestamp becomes cacheable only after content is verified again',
);
});
test('a rewrite racing with a read cannot cache an unverified EOF; incomplete UTF-8 is retried', async (t) => {
const f = await fixture(t);
await fs.writeFile(f.file, 'old contents\n');
f.io.afterRead = async () => {
f.io.afterRead = undefined;
await fs.writeFile(f.file, 'new contents\n');
};
let chunk = await f.readLogChunk(f.file, { offset: 0, follow: true });
chunk = await f.follow(chunk);
assert.equal(chunk.reset, true);
assert.equal(chunk.content, 'new contents\n');
const emoji = Buffer.from('🚀');
await fs.writeFile(
f.file,
Buffer.concat([Buffer.from('prefix'), emoji.subarray(0, 2)]),
);
chunk = await f.readLogChunk(f.file, { offset: 0, follow: true });
assert.equal(chunk.content, 'prefix');
assert.equal(chunk.nextOffset, 6);
assert.equal((await f.follow(chunk)).content, '');
await fs.appendFile(f.file, emoji.subarray(2));
chunk = await f.follow(chunk);
assert.equal(chunk.content, '🚀');
assert.equal(chunk.reset, false);
});
+82
View File
@@ -0,0 +1,82 @@
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const test = require('node:test');
const { readLogChunk } = require('../../back/shared/logReader');
const { observeChildProcess } = require('../../back/shared/childProcess');
const { shellQuote } = require('../../back/shared/shellQuote');
const {
spawnCronCommand,
releaseCronCommand,
} = require('../../back/cron/execution/cronCommandProcess');
test(
'a live viewer drains complete UTF-8 output across idle polls, supervised bursts and a nonzero exit',
{ timeout: 20000 },
async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-follow-'));
const file = path.join(root, 'live.log');
const previous = process.env.QL_DATA_DIR;
process.env.QL_DATA_DIR = root;
let child;
t.after(async () => {
child?.kill('SIGKILL');
if (previous === undefined) delete process.env.QL_DATA_DIR;
else process.env.QL_DATA_DIR = previous;
await fs.rm(root, { recursive: true, force: true });
});
const initial = '历史🚀\n'.repeat(500000);
await fs.writeFile(file, initial);
await new Promise((resolve) => setTimeout(resolve, 2100));
let current = { nextOffset: 0 };
const parts = [];
async function poll() {
current = await readLogChunk(file, {
offset: current.nextOffset,
cursor: current.cursor,
follow: true,
});
assert.equal(current.reset, false);
parts.push(current.content);
}
do {
await poll();
} while (current.nextOffset < current.total);
for (let i = 0; i < 10; i++) {
await poll();
assert.equal(current.content, '');
}
const bursts = Array.from({ length: 4 }, (_, i) =>
`批次${i}🚀\n`.repeat(40000),
);
const source = `const fs=require('node:fs');(async()=>{for(let i=0;i<4;i++){const b=Buffer.from(('批次'+i+'🚀\\n').repeat(40000));let offset=0;while(offset<b.length)offset+=fs.writeSync(1,b,offset,b.length-offset);await new Promise(r=>setTimeout(r,80));}fs.writeSync(2,'STDERR 尾行\\n');process.exitCode=17;})()`;
child = spawnCronCommand(
`${shellQuote(process.execPath)} -e ${shellQuote(source)}`,
'live-follow',
undefined,
file,
);
let settled = false;
const execution = observeChildProcess(child, {
onStart: () => releaseCronCommand(child),
}).completed.then((result) => {
settled = true;
return result;
});
while (!settled) {
await poll();
await new Promise((resolve) => setTimeout(resolve, 5));
}
do {
await poll();
} while (current.nextOffset < current.total);
const result = await execution;
assert.equal(result.error, undefined);
assert.equal(result.code, 17);
const expected = initial + bursts.join('') + 'STDERR 尾行\n';
assert.equal(await fs.readFile(file, 'utf8'), expected);
assert.equal(parts.join(''), expected);
assert.equal(current.nextOffset, Buffer.byteLength(expected));
},
);
+120
View File
@@ -83,3 +83,123 @@ test(
assert.equal(updates.at(-1).data.status, 1);
},
);
test('manual tasks sharing a directory and millisecond keep separate complete logs', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-manual-collision-'));
const logs = new LogStreamManager(root);
t.after(async () => {
await logs.closeAll();
await fs.rm(root, { recursive: true, force: true });
});
let child = 0;
const CronService = load(path.resolve('back/services/cron.ts'), {
dayjs: () => ({
format: () => '2026-11-24-00-00-00-000',
unix: () => 1795449600,
}),
'../config': { logPath: root },
'../data/cron': {
CrontabStatus: { queued: 3, running: 0, idle: 1 },
CrontabModel: { update: async () => [1] },
},
'../data/runningInstance': {
RunningInstanceModel: {},
InstanceStatus: {},
},
'../config/util': { getUniqPath: async () => 'shared-script' },
'../config/const': { TASK_PREFIX: 'task ', QL_PREFIX: 'ql ' },
'../schedule/client': {},
'../cron/execution/cronLimit': {
manualRunWithCronLimit: async (fn) => fn(),
},
'../shared/utils': {},
'../shared/i18n': { t: (s) => s },
'../shared/logReader': {},
'../shared/logStreamManager': { logStreamManager: logs },
'cross-spawn': {
spawn: () =>
spawn(process.execPath, [
'-e',
`process.stdout.write(${JSON.stringify(`任务-${++child}\n`)});`,
]),
},
}).default;
const errors = [];
const service = new CronService({
info() {},
error: (...args) => errors.push(args),
});
service.getDb = async ({ id }) => ({
id,
status: 3,
command: 'ignored',
log_path: '',
});
service.makeCommand = () => 'ignored';
await Promise.all([service.runSingle(1), service.runSingle(2)]);
// A subsequent launch in the same millisecond must also get a fresh path.
await service.runSingle(1);
const files = await fs.readdir(path.join(root, 'shared-script'));
assert.equal(files.length, 3);
const contents = await Promise.all(
files.map((file) =>
fs.readFile(path.join(root, 'shared-script', file), 'utf8'),
),
);
assert.deepEqual(contents.sort(), ['任务-1\n', '任务-2\n', '任务-3\n']);
assert.deepEqual(errors, []);
assert.equal(logs.getOpenStreamCount(), 0);
});
test('independent tasks sharing a submission token and timestamp allocate distinct log paths', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-independent-log-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const paths = [];
const CronService = load(path.resolve('back/services/cron.ts'), {
dayjs: () => ({ format: () => '2026-11-24-00-00-00-000' }),
'../config': { logPath: root },
'../data/cron': {
CrontabStatus: { queued: 3, running: 0, idle: 1 },
CrontabModel: { update: async () => [1] },
},
'../data/runningInstance': { RunningInstanceModel: {}, InstanceStatus: {} },
'../config/util': { getUniqPath: async () => 'shared-script' },
'../config/const': {},
'../schedule/client': {},
'../cron/history': {
TriggerHistory: class {
async claimManual() {
return 'started';
}
async complete() {}
},
},
'../cron/execution/cronLimit': {
manualRunWithCronLimit: async (fn) => fn(),
},
'../cron/execution/cronCommandProcess': {
spawnCronCommand: (_command, _trigger, _options, outputPath) => {
paths.push(outputPath);
throw new Error('stop after log allocation');
},
},
'../shared/utils': {},
'../shared/i18n': { t: (s) => s },
'../shared/logReader': {},
'../shared/logStreamManager': {
logStreamManager: { closeStream: async () => {} },
},
}).default;
const service = new CronService({ info() {}, error() {} });
service.getDb = async ({ id }) => ({ id, allow_multiple_instances: true });
service.makeCommand = () => 'ignored';
await Promise.all(
[1, 2].map((id) =>
service.runSingle(id, 'shared-token', `shared-token-${id}`, {
allow_multiple_instances: true,
}),
),
);
assert.equal(paths.length, 2);
assert.equal(new Set(paths).size, 2);
});
+97
View File
@@ -384,3 +384,100 @@ test('the panel client defers gRPC until an API call, uses panel dependencies an
.catch(error => { console.error(error); process.exitCode = 1; });
`);
});
for (const language of ['python', 'javascript']) {
for (const fallback of [false, true]) {
test(`${language} hook environment preserves NUL-framed values and legacy export fallback (${fallback})`, (t) => {
const f = fixture(t, language);
if (fallback) {
const bin = path.join(f.root, 'bin');
fs.mkdirSync(bin);
fs.writeFileSync(path.join(bin, 'env'), '#!/bin/sh\nexit 64\n', {
mode: 0o755,
});
f.env.PATH = bin + path.delimiter + process.env.PATH;
}
f.env.task_before =
"export MULTILINE=$'首行\\nnext=值\\n'; export EMPTY=''; export EQ='a=b=c'";
const output = f.run(
language === 'python'
? "import os\nassert os.environ['MULTILINE']=='首行\\nnext=值\\n'\nassert os.environ['EMPTY']==''\nassert os.environ['EQ']=='a=b=c'\nprint('VALUES_OK')\n"
: "const assert=require('node:assert/strict');assert.equal(process.env.MULTILINE,'首行\\nnext=值\\n');assert.equal(process.env.EMPTY,'');assert.equal(process.env.EQ,'a=b=c');console.log('VALUES_OK');",
);
assert.match(output, /VALUES_OK/);
assert.doesNotMatch(output, /parse environment|run task before error/);
});
}
}
for (const legacy of [false, true]) {
for (const extension of ['js', 'mjs']) {
test(`${extension} global imports preserve conditional exports and CommonJS isolation (${
legacy ? 'legacy' : 'synchronous'
} loader)`, (t) => {
if (
!legacy &&
typeof require('node:module').registerHooks !== 'function'
) {
t.skip('Synchronous module hooks unavailable');
return;
}
const f = fixture(t, 'javascript');
f.write(
'loader-mode.cjs',
legacy
? 'require("node:module").registerHooks = undefined;'
: 'require("node:module").register = () => { throw Error("unexpected loader worker"); };',
);
f.env.NODE_OPTIONS = `--require=${path.join(f.root, 'loader-mode.cjs')}`;
f.env.QL_NODE_GLOBAL_PATH = path.join(f.root, 'global/node_modules');
for (const [base, value] of [
[f.env.QL_NODE_GLOBAL_PATH, 'global'],
[path.join(f.root, 'node_modules'), 'local'],
]) {
const dir = path.join(base, '@ql-fixture/conditional');
fs.mkdirSync(path.join(dir, 'sub'), { recursive: true });
fs.writeFileSync(
path.join(dir, 'package.json'),
JSON.stringify({
name: '@ql-fixture/conditional',
exports: {
'.': { import: './import.mjs', require: './require.cjs' },
'./sub': './import.mjs',
},
}),
);
fs.writeFileSync(
path.join(dir, 'import.mjs'),
`export default '${value}-import';`,
);
fs.writeFileSync(
path.join(dir, 'require.cjs'),
`module.exports = '${value}-require';`,
);
}
f.write('relative.mjs', 'export default "relative";');
const common = `
const assert = require('node:assert/strict');
assert.equal(require('@ql-fixture/conditional'), 'global-require');
delete require.cache[require.resolve('@ql-fixture/conditional')];
const panel = require.cache[require.resolve('./client.js')];
panel.loadingPanelDependencies = true;
assert.ok(require.resolve('@ql-fixture/conditional').includes('/node_modules/@ql-fixture/conditional/'));
assert.equal(require('@ql-fixture/conditional'), 'local-require');
panel.loadingPanelDependencies = false;
assert.equal((await import('@ql-fixture/conditional')).default, 'global-import');
assert.equal((await import('@ql-fixture/conditional/sub')).default, 'global-import');
assert.equal((await import('./relative.mjs')).default, 'relative');
assert.equal((await import('node:fs')).readFileSync, require('node:fs').readFileSync);
await assert.rejects(import('ql-fixture-does-not-exist'), {code: 'ERR_MODULE_NOT_FOUND'});
console.log('IMPORTS_OK');
`;
const body =
extension === 'mjs'
? `import value from '@ql-fixture/conditional'; import {createRequire} from 'node:module'; const require = createRequire(import.meta.url); if(value !== 'global-import') throw Error(value); ${common}`
: `(async () => { ${common} })().catch(e => { console.error(e); process.exitCode = 1; });`;
assert.match(f.run(body, extension), /IMPORTS_OK/);
});
}
}
+236
View File
@@ -0,0 +1,236 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const { Sequelize, QueryTypes } = require('sequelize');
const { QueueOccupants } = require('../../back/cron/queries/queueDiagnostics');
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const tick = () => new Promise(setImmediate);
function gate() {
let release;
const promise = new Promise((resolve) => (release = resolve));
return { promise, release };
}
async function until(check) {
const deadline = Date.now() + 3000;
while (Date.now() < deadline) {
if (await check()) return;
await sleep(10);
}
assert.fail('diagnostic sample was not published');
}
async function fixture(t) {
const db = new Sequelize('sqlite::memory:', { logging: false });
await db.query(
"CREATE TABLE CronTriggers(id TEXT PRIMARY KEY, state TEXT DEFAULT 'queued', queued_at INTEGER, dequeued_at INTEGER, queue_context TEXT, queue_live_context TEXT)",
);
await db.query('CREATE TABLE Changes(id TEXT)');
await db.query(
'CREATE TRIGGER count_live_updates AFTER UPDATE OF queue_live_context ON CronTriggers BEGIN INSERT INTO Changes VALUES(NEW.id); END',
);
const warnings = [];
let liveWrites = 0;
db.options.logging = (sql) => {
if (
sql
.replace(/[`"]/g, '')
.includes('UPDATE CronTriggers SET queue_live_context=')
)
liveWrites++;
};
const pool = new QueueOccupants(
'scheduled',
() => 1,
(error) => warnings.push(error),
);
const ids = new Set();
t.after(async () => {
for (const id of ids) pool.forget(id);
await sleep(20);
await db.close();
});
return {
db,
pool,
warnings,
liveWrites: () => liveWrites,
async add(id, fields = '') {
await db.query('INSERT INTO CronTriggers(id,queued_at) VALUES ($id,1)', {
bind: { id },
});
if (fields)
await db.query('UPDATE CronTriggers SET ' + fields + ' WHERE id=$id', {
bind: { id },
});
ids.add(id);
pool.watch(id, db);
},
async rows(sql = 'SELECT * FROM CronTriggers ORDER BY id') {
return db.query(sql, { type: QueryTypes.SELECT });
},
};
}
test('asynchronous admissions share one sample and unchanged holders are not rewritten', async (t) => {
const f = await fixture(t);
for (let i = 0; i < 30; i++) {
await f.add('wait-' + i);
await tick();
}
await until(() => f.liveWrites() >= 1);
await until(
async () => (await f.rows('SELECT * FROM Changes')).length === 30,
);
assert.equal(f.liveWrites(), 1);
for (let i = 0; i < 20; i++) {
f.pool.refresh();
await tick();
}
await sleep(300);
assert.equal(f.liveWrites(), 1);
await f.add('new-wait');
await until(() => f.liveWrites() === 2);
await until(
async () => (await f.rows('SELECT * FROM Changes')).length === 31,
);
assert.equal(
(await f.rows()).every(
(row) => row.state === 'queued' && row.dequeued_at === null,
),
true,
);
assert.deepEqual(f.warnings, []);
});
test('dispatch and cancellation clear pending samples, and sampling never overwrites dispatched or terminal rows', async (t) => {
const f = await fixture(t);
await f.add('cancelled');
f.pool.forget('cancelled');
await sleep(300);
assert.equal(f.liveWrites(), 0);
await f.add('running', "state='running'");
await f.add('dequeued', 'dequeued_at=2');
await f.add('stopped', "state='stopped'");
await f.add('waiting');
await until(async () => (await f.rows('SELECT * FROM Changes')).length > 0);
const changed = await f.rows('SELECT * FROM Changes');
assert.deepEqual(
changed.map((x) => x.id),
['waiting'],
);
let ran = false;
await f.pool.track(
async () => {
ran = true;
},
{ id: 'waiting', name: 'task' },
f.db,
)();
assert.equal(ran, true);
await until(
async () =>
(
await f.rows("SELECT * FROM CronTriggers WHERE id='waiting'")
)[0].dequeued_at !== null,
);
const [row] = await f.rows("SELECT * FROM CronTriggers WHERE id='waiting'");
assert.equal(row.queue_live_context, null);
await sleep(300);
const [later] = await f.rows("SELECT * FROM CronTriggers WHERE id='waiting'");
assert.equal(later.queue_live_context, null);
assert.equal(later.dequeued_at, row.dequeued_at);
});
test('a slow sample is serialized while execution continues and newer observations are eventually published', async (t) => {
const pause = gate();
let inFlight = 0,
peak = 0,
calls = 0,
context;
const model = {
async update(values) {
inFlight++;
peak = Math.max(peak, inFlight);
calls++;
if (calls === 1) await pause.promise;
context = JSON.parse(values.queue_live_context);
inFlight--;
},
};
const db = { isDefined: () => true, model: () => model };
let limit = 1;
const pool = new QueueOccupants('manual', () => limit, assert.fail);
pool.watch('waiting', db);
await until(() => calls === 1);
const active = gate();
const work = pool.track(() => active.promise, { name: 'holder' })();
limit = 2;
for (let i = 0; i < 10; i++) pool.refresh();
await sleep(300);
assert.equal(calls, 1);
let fastRan = false;
await pool.track(
async () => {
fastRan = true;
},
{ name: 'fast' },
)();
assert.equal(fastRan, true);
pause.release();
await until(() => calls === 2 && inFlight === 0);
assert.equal(peak, 1);
assert.equal(context.limit, 2);
assert.deepEqual(context.holders, [{ name: 'holder' }]);
pool.forget('waiting');
active.release();
await work;
});
test('failed samples do not fail executions and can be retried after another refresh', async () => {
const warnings = [];
let fail = true,
calls = 0;
const model = {
async update() {
calls++;
if (fail) throw Error('busy');
},
};
const db = { isDefined: () => true, model: () => model };
const pool = new QueueOccupants(
'manual',
() => 1,
(error) => warnings.push(error.message),
);
pool.watch('waiting', db);
await until(() => warnings.length === 1);
assert.equal(await pool.track(async () => 42, { name: 'work' })(), 42);
fail = false;
pool.refresh();
await until(() => calls === 2);
await sleep(20);
pool.refresh();
await sleep(300);
assert.equal(calls, 2);
assert.deepEqual(warnings, ['busy']);
pool.forget('waiting');
});
test('removing and re-admitting an ID during an in-flight sample cannot mark the new wait as sampled', async () => {
const pause = gate();
let calls = 0;
const model = {
async update() {
calls++;
if (calls === 1) await pause.promise;
},
};
const db = { isDefined: () => true, model: () => model };
const pool = new QueueOccupants('scheduled', () => 1, assert.fail);
pool.watch('same-id', db);
await until(() => calls === 1);
pool.forget('same-id');
pool.watch('same-id', db);
pause.release();
await until(() => calls === 2);
pool.forget('same-id');
});
@@ -58,6 +58,7 @@ test('startup closes interrupted instances without inventing exit codes or rewri
getAuthInfo: async () => ({}),
initializeSystemApp: async () => {},
refreshApps: async () => {},
recoverQueuedTasks: async () => {},
};
const initData = load('back/loaders/initData.ts', {
typedi: { Container: { get: () => service } },
+4 -1
View File
@@ -57,7 +57,10 @@ test('cleanup previews first, protects running instances, and uses explicit opti
const RunningInstanceModel = {};
const CrontabStatModel = {};
const InstanceStatus = { running: 0 };
const sequelize = {};
const sequelize = {
isDefined: () => true,
model: () => ({ findAll: async () => [] }),
};
const stubModule = (modulePath, exports) => {
require.cache[require.resolve(modulePath)] = {
id: require.resolve(modulePath),
+82
View File
@@ -0,0 +1,82 @@
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const test = require('node:test');
const { Sequelize, QueryTypes } = require('sequelize');
const load = require('../helpers/load-security-module.cjs');
test('existing instance history gains a partial live index, with transactional visibility and rollback', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-live-index-'));
const db = new Sequelize({
dialect: 'sqlite',
storage: path.join(root, 'db.sqlite'),
logging: false,
});
t.after(async () => {
await db.close();
await fs.rm(root, { recursive: true, force: true });
});
const { RunningInstanceModel } = load('back/data/runningInstance.ts', {
'.': { sequelize: db },
});
await RunningInstanceModel.sync();
await db.query('DROP INDEX running_instances_active_cron_id');
await db.query(`WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n<10000)
INSERT INTO RunningInstances(id,cron_id,pid,started_at,status,createdAt,updatedAt)
SELECT n,1,n,n,1,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP FROM seq`);
await db.query('UPDATE RunningInstances SET status=0 WHERE id IN (1,2)');
await db.query(
'UPDATE RunningInstances SET cron_id=2,status=0 WHERE id=10000',
);
await RunningInstanceModel.sync();
await RunningInstanceModel.sync();
const [index] = await db.query(
"SELECT sql FROM sqlite_master WHERE type='index' AND name='running_instances_active_cron_id'",
{ type: QueryTypes.SELECT },
);
assert.match(index.sql, /WHERE\s+[`"]?status[`"]?\s*=\s*0/i);
assert.equal(await RunningInstanceModel.count(), 10000);
const sql =
'SELECT id,pid FROM RunningInstances WHERE cron_id=1 AND status=0 ORDER BY id DESC LIMIT 1';
const plan = await db.query('EXPLAIN QUERY PLAN ' + sql, {
type: QueryTypes.SELECT,
});
assert.ok(
plan.some((row) => row.detail.includes('running_instances_active_cron_id')),
);
const read = (transaction) =>
db.query(sql, { type: QueryTypes.SELECT, transaction });
assert.equal((await read())[0].id, 2);
await assert.rejects(
db.transaction(async (transaction) => {
await db.query('UPDATE RunningInstances SET status=3 WHERE id=2', {
transaction,
});
assert.equal((await read(transaction))[0].id, 1);
await db.query('UPDATE RunningInstances SET status=2 WHERE id=1', {
transaction,
});
assert.deepEqual(await read(transaction), []);
throw Error('rollback');
}),
/rollback/,
);
assert.equal((await read())[0].id, 2);
await db.transaction(async (transaction) => {
await db.query('UPDATE RunningInstances SET status=4 WHERE id IN (1,2)', {
transaction,
});
assert.deepEqual(await read(transaction), []);
});
assert.deepEqual(await read(), []);
assert.equal(
(
await db.query(
'SELECT id FROM RunningInstances WHERE cron_id=2 AND status=0',
{ type: QueryTypes.SELECT },
)
)[0].id,
10000,
);
});
+40
View File
@@ -0,0 +1,40 @@
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { once } = require('node:events');
const test = require('node:test');
for (const mode of ['commit', 'rollback']) {
test(
`32 competing SQLite writers preserve progress, exact writes and ${mode}`,
{ timeout: 35000 },
async (t) => {
const root = await fs.mkdtemp(
path.join(os.tmpdir(), 'ql-sqlite-contention-'),
);
const child = spawn(
process.execPath,
[path.resolve('test/helpers/sqlite-contention-worker.cjs'), root, mode],
{
env: { ...process.env, UV_THREADPOOL_SIZE: '4' },
stdio: ['ignore', 'pipe', 'pipe'],
},
);
t.after(async () => {
child.kill('SIGKILL');
await fs.rm(root, { recursive: true, force: true });
});
let output = '';
child.stdout.on('data', (data) => (output += data));
child.stderr.on('data', (data) => (output += data));
const watchdog = setTimeout(() => child.kill('SIGKILL'), 30000);
t.after(() => clearTimeout(watchdog));
const [code, signal] = await once(child, 'close');
assert.equal(signal, null, output);
assert.equal(code, 0, output);
assert.match(output, /"callbacks":32/);
},
);
}
@@ -0,0 +1,73 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const { spawnSync } = require('node:child_process');
const text = fs.readFileSync('shell/share.sh', 'utf8');
const start = text.indexOf('handle_task_end() {');
const helper = text.slice(start, text.indexOf('\n}', start) + 2);
test('authorized supervisor removes redundant finish HTTP calls; standalone wrappers retain receipts and log trailers', () => {
for (const [flag, trigger, expected] of [
['1', 'run-id', false],
['', 'run-id', true],
['1', '', true],
]) {
const result = spawnSync(
'bash',
[
'-c',
helper +
`\n
update_cron(){ echo STATUS >&2; }; record_cron_stat(){ echo STATS >&2; }; t(){ printf "$@"; }
ID=1; is_macos=0; time_format='%Y-%m-%d %H:%M:%S'; begin_timestamp=0; _task_exit_code=7
handle_task_end
`,
],
{
env: {
...process.env,
QL_TRIGGER_ID: trigger,
QL_SUPERVISOR_RECEIPT: flag,
},
encoding: 'utf8',
},
);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stderr.includes('STATUS'), expected);
assert.equal(result.stderr.includes('STATS'), expected);
assert.match(result.stdout, /退出码 7/);
}
});
test('only a prebound manual log skips shell start HTTP; scheduled and standalone tasks publish their log path', () => {
const offset = text.indexOf('handle_task_start() {');
const startHelper = text.slice(offset, text.indexOf('\n}', offset) + 2);
for (const [flag, trigger, expected] of [
['1', 'run-id', false],
['', 'run-id', true],
['1', '', true],
]) {
const result = spawnSync(
'bash',
[
'-c',
startHelper +
`\n
update_cron(){ echo START >&2; }; t(){ printf "$@"; }
ID=1; begin_time=now; handle_task_start
`,
],
{
env: {
...process.env,
QL_TRIGGER_ID: trigger,
QL_SUPERVISOR_LOG_BOUND: flag,
},
encoding: 'utf8',
},
);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stderr.includes('START'), expected);
assert.match(result.stdout, /开始执行/);
}
});
+56
View File
@@ -0,0 +1,56 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const { spawnSync } = require('node:child_process');
const bash = fs.existsSync('/opt/homebrew/bin/bash')
? '/opt/homebrew/bin/bash'
: 'bash';
const major = Number(
spawnSync(bash, ['-c', 'echo "$BASH_VERSINFO"'], {
encoding: 'utf8',
}).stdout.trim(),
);
function extract(file, name) {
const s = fs.readFileSync(file, 'utf8');
const a = s.indexOf(name + '() {');
return s.slice(a, s.indexOf('\n}', a) + 2);
}
const helpers = ['handle_log_path', 'init_begin_time']
.map((n) => extract('shell/task.sh', n))
.concat(extract('shell/share.sh', 'handle_task_end'))
.join('\n');
for (const zone of ['UTC', 'Asia/Shanghai'])
test(
`Bash clock preserves millisecond names and consistent epoch without date subprocesses (${zone})`,
{ skip: major < 5 },
() => {
const seconds = Date.parse('2026-09-12T23:59:59Z') / 1000;
const script =
helpers +
`\n
unset EPOCHSECONDS EPOCHREALTIME
EPOCHREALTIME=${seconds}.999321; EPOCHSECONDS=${
seconds + 1
}; TZ=${zone}; export TZ
ID=42; is_macos=0; dir_log=/tmp; log_name=task; no_tee=true
time_format='%Y-%m-%d %H:%M:%S'; mtime_format='%Y-%m-%d %H:%M:%S.%3N'
make_dir(){ :; }; date(){ echo FORBIDDEN >&2; return 99; }; format_timestamp(){ echo FORBIDDEN >&2; return 99; }
t(){ :; }; update_cron(){ printf 'STATUS:%s:%s\\n' "$5" "$8"; }; record_cron_stat(){ printf 'STATS:%s:%s\\n' "$3" "$4"; }
handle_log_path file.py; init_begin_time
printf 'START:%s:%s:%s\\n' "$begin_timestamp" "$time" "$log_path"
handle_task_end
`;
const r = spawnSync(bash, ['-eu', '-c', script], { encoding: 'utf8' });
assert.equal(r.status, 0, r.stderr);
assert.doesNotMatch(r.stderr, /FORBIDDEN/);
assert.match(
r.stdout,
new RegExp(`START:${seconds}:.*\\.999:task/.*-999\\.log`),
);
assert.match(r.stdout, new RegExp(`STATS:1:${seconds + 1}`));
assert.match(
r.stdout,
zone === 'UTC' ? /2026-09-12-23-59-59-999/ : /2026-09-13-07-59-59-999/,
);
},
);
+1
View File
@@ -27,6 +27,7 @@ function run(t, body) {
'-ec',
source +
`
unset EPOCHREALTIME EPOCHSECONDS
is_macos=0
mtime_format='%Y-%m-%d %H:%M:%S.%3N'
time_format='%Y-%m-%d %H:%M:%S'
+153
View File
@@ -0,0 +1,153 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const { Sequelize, QueryTypes } = require('sequelize');
const load = require('../helpers/load-security-module.cjs');
async function fixture(t) {
const db = new Sequelize({
dialect: 'sqlite',
storage: ':memory:',
logging: false,
});
t.after(() => db.close());
await db.query(`CREATE TABLE CronTriggers (
state TEXT, observed_at INTEGER, scheduled_at INTEGER, started_at INTEGER,
script_started_at INTEGER, dequeued_at INTEGER, queued_at INTEGER,
queue_context TEXT, queue_live_context TEXT)`);
await db.query('CREATE INDEX cron_trigger_day ON CronTriggers(observed_at)');
const audits = [];
const { TriggerQueries } = load('back/cron/queries/triggerQueries.ts', {
'../scheduling/scheduleAudit': {
auditSchedule: async (connection, since) => {
assert.equal(connection, db);
audits.push(['panel', since]);
return { kind: 'panel' };
},
},
'../scheduling/systemScheduleAudit': {
systemScheduleAudit: async (connection, since) => {
assert.equal(connection, db);
audits.push(['system', since]);
return { kind: 'system' };
},
},
});
const query = db.query.bind(db);
let captured;
db.query = (sql, options) => {
if (sql.startsWith('WITH today')) captured = { sql, options };
return query(sql, options);
};
return {
db,
queries: new TriggerQueries(db),
audits,
captured: () => captured,
};
}
function expected(rows, since) {
const today = rows.filter((r) => r.observed_at >= since);
const deviations = today
.filter((r) => r.scheduled_at != null)
.map((r) => Math.abs(r.observed_at - r.scheduled_at));
const scripts = today
.filter(
(r) =>
r.scheduled_at != null &&
r.script_started_at != null &&
r.script_started_at >= r.scheduled_at,
)
.map((r) => r.script_started_at - r.scheduled_at);
const waits = today
.filter(
(r) =>
r.queued_at != null &&
(r.dequeued_at ?? r.started_at) != null &&
(r.dequeued_at ?? r.started_at) >= r.queued_at,
)
.map((r) => (r.dequeued_at ?? r.started_at) - r.queued_at);
const p95 = (a) =>
a.length ? a.sort((a, b) => a - b)[Math.ceil(a.length * 0.95) - 1] : null;
return {
observed: today.length,
skipped: today.filter((r) => r.state === 'skipped').length,
planned: deviations.length,
onTime: today.filter(
(r) =>
r.started_at != null &&
r.scheduled_at != null &&
r.started_at <= r.scheduled_at + 5000,
).length,
triggerOnTime: deviations.filter((n) => n <= 5000).length,
triggerDeviationP95: p95(deviations),
scriptSamples: scripts.length,
scriptOnTime: scripts.filter((n) => n <= 5000).length,
scriptStartP95: p95(scripts),
samples: waits.length,
waitP95: p95(waits),
audit: { kind: 'panel' },
systemAudit: { kind: 'system' },
};
}
test('trigger metrics preserve exact counts and nearest-rank P95 across nulls, boundaries and states', async (t) => {
const { db, queries, audits } = await fixture(t);
const since = 100000;
for (const count of [0, 1, 19, 20, 21, 99, 100, 101, 257]) {
await db.query('DELETE FROM CronTriggers');
const rows = Array.from({ length: count }, (_, i) => ({
state: ['finished', 'skipped', 'unknown', 'queued', 'running', 'failed'][
i % 6
],
observed_at: since + [-1, 0, 1, 4999, 5000, 5001][i % 6],
scheduled_at: i % 7 === 0 ? null : since + (i % 3),
started_at:
i % 5 === 0 ? null : since + [-1, 0, 4999, 5000, 5001, 9000][i % 6],
script_started_at:
i % 4 === 0 ? null : since + [-1, 0, 4999, 5000, 5001, 9000][i % 6],
dequeued_at: i % 3 === 0 ? null : i % 3 === 1 ? 0 : since + 10,
queued_at: i % 8 === 0 ? null : since - 10,
}));
for (const row of rows)
await db.query(
'INSERT INTO CronTriggers(state,observed_at,scheduled_at,started_at,script_started_at,dequeued_at,queued_at) VALUES($state,$observed_at,$scheduled_at,$started_at,$script_started_at,$dequeued_at,$queued_at)',
{ bind: row },
);
for (const cutoff of [since, since + 1, since + 20000])
assert.deepEqual(
await queries.metrics(cutoff),
expected(rows, cutoff),
`count=${count},cutoff=${cutoff}`,
);
}
assert.equal(audits.length, 54);
for (let i = 0; i < audits.length; i += 2)
assert.deepEqual(audits[i + 1], ['system', audits[i][1]]);
});
test('actual metrics query reads the indexed trigger history once and reuses its narrow snapshot', async (t) => {
const { db, queries, captured } = await fixture(t);
await db.query(`WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n<1000)
INSERT INTO CronTriggers SELECT 'finished',n,n,n+10,n+20,NULL,n,hex(zeroblob(1024)),hex(zeroblob(1024)) FROM seq`);
assert.equal((await queries.metrics(1)).observed, 1000);
const { sql, options } = captured();
const plan = await db.query('EXPLAIN QUERY PLAN ' + sql, {
...options,
type: QueryTypes.SELECT,
});
const details = plan.map((r) => r.detail);
assert.equal(
details.filter((s) => /SEARCH CronTriggers\b/.test(s)).length,
1,
details.join('\n'),
);
assert.ok(
details.some((s) => s.includes('cron_trigger_day')),
details.join('\n'),
);
assert.ok(
details.some((s) => /MATERIALIZE today/.test(s)),
details.join('\n'),
);
});
+7 -1
View File
@@ -57,12 +57,18 @@ async function runProbe({
class HttpServerService {}
const modules = {
'reflect-metadata': {},
sequelize: { DataTypes: { INTEGER: 'INTEGER' } },
dns: { setDefaultResultOrder: () => {} },
'../config': {},
'../data': {
sequelize: {
transaction: async (action) => action({}),
query: async () => [[{ value: 42 }]],
getQueryInterface: () => ({ createTable: async () => {} }),
define: () => ({
removeAttribute: () => {},
create: async () => {},
findOne: async () => ({ get: () => 42 }),
}),
close: async () => {
events.push('db-close');
},
+16
View File
@@ -243,3 +243,19 @@ test('a live queue shows the resampled holders and preserves the measured dequeu
/排队等待 <b>210 ms/,
);
});
test('shared budget occupancy is labelled as the global queue', () => {
const { details } = render({
state: 'queued',
queued_at: base,
queue_live_context: JSON.stringify({
queue: 'global',
limit: 1,
occupied: 1,
holders: [{ id: 'foreign-worker-run', name: '另一个 worker 的任务' }],
}),
});
assert.match(details, /全局执行队列/);
assert.match(details, /另一个 worker 的任务/);
assert.doesNotMatch(details, /定时执行队列|手动执行队列/);
});
+2 -2
View File
@@ -31,7 +31,7 @@ function barrier() {
const statements = {
booking: 'INSERT OR IGNORE INTO CronLegacyExitBookings',
claim: 'UPDATE CronTriggers SET counted=1',
claim: 'UPDATE CronTriggers SET counted=',
increment: 'INSERT INTO "CrontabStats"',
dispute: 'INSERT OR IGNORE INTO CronBoundExitConflicts',
debit: 'UPDATE CrontabStats SET run_count=run_count-1',
@@ -73,7 +73,7 @@ if (stage === 'readClaim') {
else if (stage === 'unlink') intercept(fs.promises, 'unlink', captured);
else
intercept(db, 'query', (sql) =>
String(sql)
String(typeof sql === 'string' ? sql : sql.query)
.replace(/[`"]/g, '')
.startsWith(statements[stage].replace(/"/g, '')),
);
+79
View File
@@ -0,0 +1,79 @@
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const load = require('./load-security-module.cjs');
const [root, mode] = process.argv.slice(2);
const { sequelize: db } = load('back/data/index.ts', {
'../config/index': { dbPath: root },
});
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
(async () => {
await db.query('CREATE TABLE results (id INTEGER PRIMARY KEY)');
const owner = await db.transaction();
await db.query('INSERT INTO results VALUES (0)', { transaction: owner });
let callbacks = 0;
const contenders = Promise.all(
Array.from({ length: 32 }, (_, i) =>
db.transaction(async (transaction) => {
callbacks++;
await db.query('INSERT INTO results VALUES ($id)', {
transaction,
bind: { id: i + 1 },
});
// File work shares libuv's pool with SQLite. Waiting writers must not
// prevent either this work or the current writer's COMMIT from running.
await fs.readFile(__filename);
await delay(2);
}),
),
);
// Observe early rejections without letting the process exit before cleanup.
contenders.catch(() => {});
await delay(30);
const read = fs.readFile(__filename);
assert.equal(
await Promise.race([
read.then(() => 'read'),
delay(1000).then(() => 'blocked'),
]),
'read',
'waiting SQLite writers exhausted the shared worker pool',
);
if (mode === 'rollback') {
// Longer than the old JS-only retry budget: retain tolerance for a real
// writer, without sleeping in the native worker pool.
await delay(2000);
await owner.rollback();
} else {
await owner.commit();
}
await contenders;
const [rows] = await db.query('SELECT id FROM results ORDER BY id');
assert.deepEqual(
rows.map((row) => row.id),
Array.from({ length: mode === 'rollback' ? 32 : 33 }, (_, i) =>
mode === 'rollback' ? i + 1 : i,
),
);
assert.equal(callbacks, 32, 'transaction callbacks must not be replayed');
const [[durability]] = await db.query('PRAGMA synchronous');
assert.equal(durability.synchronous, 3);
await assert.rejects(
db.transaction(async (transaction) => {
await db.query('INSERT INTO results VALUES (99)', { transaction });
await db.query('INSERT INTO results VALUES (1)', { transaction });
}),
/Validation error/,
);
const [rolledBack] = await db.query('SELECT id FROM results WHERE id=99');
assert.deepEqual(rolledBack, []);
await db.close();
console.log(JSON.stringify({ callbacks, rows: rows.length, mode }));
})().then(
() => process.exit(0),
(error) => {
console.error(error);
process.exit(1);
},
);