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

+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);
},
);