feat: harden cron execution recovery and expose scheduling diagnostics

Reconcile scheduled and system cron triggers, isolate concurrent executions and retain verifiable exit statistics across restarts. Add paged task history, log and script browsing, dashboard timing details and regression coverage.
This commit is contained in:
whyour committed 2026-11-17 01:01:57 +08:00
1 parent 3b6a873520
commit 8a9e70e90b
166 files changed
+18942 -1800

No files matched your search

@@ -0,0 +1,61 @@
// Run on the dedicated ext4 test disk. Two independent recovery processes have
// validated one slot. A third writer replaces just the file before either move.
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { once } = require('node:events');
const { setTimeout: delay } = require('node:timers/promises');
const { createHash } = require('node:crypto');
const volume = '/ql/data/db';
const moduleFile = '/ql/static/build/shared/managedExit.cjs';
const { receiptPath, readExit, retiringExits } = require(moduleFile);
(async () => {
const usage = await fs.statfs(volume);
assert.equal(usage.type,0xef53);
assert.ok(usage.blocks * usage.bsize <= 32 * 1024 * 1024 && usage.files <= 8192);
await fs.access(path.join(volume,'.qa-isolated-volume'));
const root = await fs.mkdtemp(path.join(volume,'.qa-slot-'));
const workers = [];
try {
process.env.QL_DATA_DIR = root;
const id = 'occupied-slot', directory = path.join(path.dirname(receiptPath(id)),'.claim.' + id + '.qaTest');
await fs.mkdir(directory,{recursive:true});
const slot = path.join(directory,'receipt');
const receipt = code => JSON.stringify({code, signal:null, time:1000, version:1,
checksum:createHash('sha256').update(JSON.stringify([id,code,null,1000])).digest('hex')});
await fs.writeFile(slot,receipt(17),{flag:'wx'});
for (const role of ['A','B']) {
const barrier = path.join(root, role);
const child = spawn(process.execPath,[path.join(__dirname,'receipt-claim-reuse-worker.cjs'),
moduleFile, slot, id, '17', '1000', barrier],{stdio:'inherit'});
workers.push({barrier,child,done:once(child,'exit')});
}
const deadline = performance.now() + 10000;
const before = await Promise.all(workers.map(async ({barrier}) => {
while (performance.now() < deadline) {
try { return JSON.parse(await fs.readFile(barrier+'.ready','utf8')); }
catch (error) { if (error.code !== 'ENOENT') throw error; }
await delay(20);
}
throw Error('Both collectors must validate the original slot');
}));
assert.equal(before[0].fileInode,before[1].fileInode);
assert.equal(before[0].directoryInode,before[1].directoryInode);
await fs.writeFile(slot+'.new',receipt(42),{flag:'wx'});
await fs.rename(slot+'.new',slot);
const inode = (await fs.stat(slot)).ino;
assert.notEqual(inode,before[0].fileInode);
for (const {barrier} of workers) await fs.writeFile(barrier+'.go','');
for (const {done} of workers) assert.deepEqual(await done,[0,null]);
const captures = await retiringExits();
assert.equal(captures.length,1);
assert.equal((await fs.stat(captures[0].file)).ino,inode);
assert.equal((await readExit(id,captures[0].file)).code,42);
console.log(JSON.stringify({before,replacementInode:inode,retained:captures[0].file}));
} finally {
for (const {child} of workers) if (child.exitCode === null) child.kill();
await fs.rm(root,{recursive:true,force:true});
}
})().catch(error => { console.error(error); process.exitCode=1; });
+68
View File
@@ -0,0 +1,68 @@
// Run real panel operations in a separate process. The parent replaces public
// files and runs two independent publishers while this worker is at the barrier.
const fs = require('node:fs');
const path = require('node:path');
const [operation, stage, side, id] = process.argv.slice(2);
const root = process.env.QL_DATA_DIR;
const load = require('./load-security-module.cjs');
const db = load('back/data/index.ts', { '../config/index': { dbPath: root } }).sequelize;
const { TriggerHistory } = require('../../back/shared/triggerHistory');
const history = new TriggerHistory(db);
const stats = load('back/data/cronStats.ts', { '.': { sequelize: db } });
const running = load('back/data/runningInstance.ts', { '.': { sequelize: db } });
const Retention = load('back/services/retention.ts', {
'../data': { sequelize: db }, '../data/cronStats': stats, '../data/runningInstance': running,
'../data/system': {}, '../config': {},
}).default;
function barrier() {
const ready = path.join(root, 'at-barrier');
fs.writeFileSync(ready + '.tmp', stage + '/' + side);
fs.renameSync(ready + '.tmp', ready);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
}
const statements = {
booking: 'INSERT OR IGNORE INTO CronLegacyExitBookings',
claim: 'UPDATE CronTriggers SET counted=1',
increment: 'INSERT INTO "CrontabStats"',
dispute: 'INSERT OR IGNORE INTO CronBoundExitConflicts',
debit: 'UPDATE CrontabStats SET run_count=run_count-1',
commit: 'COMMIT',
deleteDay: 'DELETE FROM CrontabStats WHERE date',
cutoff: 'INSERT INTO CronStatRetention',
historyCutoff: 'INSERT INTO CronHistoryRetention',
deleteHistory: 'DELETE FROM CronTriggers WHERE',
pruneBooking: 'DELETE FROM CronLegacyExitBookings WHERE day',
};
function intercept(object, method, matches) {
const original = object[method].bind(object);
object[method] = async (...args) => {
const matched = matches(...args);
if (matched && side === 'before') barrier();
const result = await original(...args);
if (matched && side === 'after') barrier();
return result;
};
}
const captured = file => path.basename(file).startsWith('.pending.' + id + '.r-');
if (stage === 'readClaim') {
const open = fs.promises.open.bind(fs.promises);
fs.promises.open = async (file, ...options) => {
const handle = await open(file, ...options);
if (captured(file)) {
if (side === 'before') barrier();
const close = handle.close.bind(handle);
handle.close = async () => { await close(); if (side === 'after') barrier(); };
}
return handle;
};
} else if (stage === 'move') intercept(fs.promises, 'rename', (src) => path.basename(src) === id);
else if (stage === 'unlink') intercept(fs.promises, 'unlink', captured);
else intercept(db, 'query', sql => String(sql).replace(/[`"]/g, '').startsWith(statements[stage].replace(/"/g, '')));
(async () => {
if (operation === 'prune') await new Retention().cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 });
else await history.complete(id, 'unknown', null, null);
throw Error('Expected barrier was never reached: ' + operation + '/' + stage);
})().catch(e => { console.error(e); process.exitCode = 1; }).finally(() => db.close());
@@ -0,0 +1,47 @@
const fs = require('node:fs');
const path = require('node:path');
const [moduleFile, file, id, outcome, time, barrier, recovery, stage] = process.argv.slice(2);
const { retireLegacyFile } = require(moduleFile);
// Both collectors have read the source and hold its directory lock at this point.
const rename = fs.promises.rename.bind(fs.promises);
let captured;
async function gate(suffix, data, release) {
fs.writeFileSync(barrier + '.tmp', JSON.stringify(data));
fs.renameSync(barrier + '.tmp', barrier + suffix);
const limit = performance.now() + 90000;
while (!fs.existsSync(barrier + release)) {
if (performance.now() > limit) throw Error('Timed out waiting for ' + release);
await new Promise(resolve => setTimeout(resolve, 25));
}
}
fs.promises.rename = async (source, target) => {
if (await fs.promises.realpath(source) !== file) return rename(source, target);
const ready = { pid: process.pid, path:file, target,
directoryInode: (await fs.promises.stat(path.dirname(source))).ino,
fileInode: (await fs.promises.stat(source)).ino };
await gate('.ready', ready, '.go');
try {
await rename(source, target);
} catch (error) {
if (stage === 'recordMoveError')
fs.writeFileSync(barrier + '.error', JSON.stringify({code:error.code, errno:error.errno, syscall:error.syscall}));
throw error;
}
captured = target;
if (stage === 'holdMoved') await gate('.moved', {target, inode:(await fs.promises.stat(target)).ino}, '.release');
};
const unlink = fs.promises.unlink.bind(fs.promises);
fs.promises.unlink = async file => {
if (stage === 'holdUnlink' && captured === file)
await gate('.checked', {target:file, inode:(await fs.promises.stat(file)).ino}, '.release');
return unlink(file);
};
const settlement = recovery
? require(recovery).triggerHistory().complete(id,'unknown',null,null)
: retireLegacyFile(id, file, {outcome, time:Number(time)});
settlement.catch(error => {
// Another collector may have already removed the same settled inode.
if (error.code !== 'ENOENT') { console.error(error); process.exitCode = 1; }
}).finally(() => {
if (recovery) return require(path.join(path.dirname(recovery),'../data')).sequelize.close();
});
+54
View File
@@ -0,0 +1,54 @@
"""Reserve or release the final receipt inode on the isolated acceptance disk."""
import json
import os
from pathlib import Path
import runpy
import shutil
import sys
helpers = runpy.run_path(str(Path(__file__).with_name('receipt-unlink-ext4.py')))
volume = helpers['VOLUME']
stats = os.statvfs(volume)
mount = next((line for line in Path('/proc/self/mountinfo').read_text().splitlines()
if line.split()[4] == str(volume)), '')
if (' - ext4 ' not in mount or not (volume / '.qa-isolated-volume').is_file()
or not 0 < stats.f_blocks * stats.f_frsize <= 32 * 1024 * 1024
or not 0 < stats.f_files <= 8192):
raise RuntimeError('Requires the marked bounded ext4 acceptance volume')
def sync_dir(directory):
fd = os.open(directory, os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
folder = volume / '.qa-empty-exit-fill'
operation = sys.argv[1]
if operation == 'fill':
folder.mkdir()
(folder / 'one-inode').touch(exist_ok=False)
fd = os.open(folder / 'blocks', os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_SYNC, 0o600)
try:
helpers['fill_inodes'](folder)
helpers['fill_blocks'](fd)
finally:
os.close(fd)
sync_dir(folder)
sync_dir(volume)
elif operation == 'lend':
(folder / 'one-inode').unlink()
sync_dir(folder)
elif operation == 'release':
shutil.rmtree(folder)
sync_dir(volume)
elif operation != 'inspect':
raise ValueError(operation)
state = helpers['capacity']()
if operation in ('fill', 'lend'):
assert state == {'blocks': 0, 'inodes': int(operation == 'lend')}, state
elif operation == 'release':
assert min(state.values()) > 0, state
print(json.dumps(dict(**state, boot=Path('/proc/sys/kernel/random/boot_id').read_text().strip(),
mount=mount)))
@@ -0,0 +1,91 @@
"""Hold a Linux test supervisor at syscall exit, before it can handle ENOSPC."""
import ctypes
import errno
import json
import os
from pathlib import Path
import platform
import signal
import sys
PTRACE_PEEKDATA = 2
PTRACE_SYSCALL = 24
PTRACE_SEIZE = 0x4206
PTRACE_INTERRUPT = 0x4207
PTRACE_GET_SYSCALL_INFO = 0x420e
pid = int(sys.argv[1])
receipt = sys.argv[2]
control = Path(sys.argv[3])
if control.parent != Path('/tmp/journal-qa') or not receipt.isascii() or not receipt.replace('-', '').isalnum():
raise ValueError('Requires isolated fixture control path and execution ID')
if b'cron-command.py' not in Path(f'/proc/{pid}/cmdline').read_bytes():
raise ValueError('Expected the real cron supervisor')
openat = {'aarch64': 56, 'x86_64': 257}[platform.machine()]
libc = ctypes.CDLL(None, use_errno=True)
libc.ptrace.argtypes = [ctypes.c_uint, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p]
libc.ptrace.restype = ctypes.c_long
def ptrace(op, addr=0, data=0):
ctypes.set_errno(0)
rc = libc.ptrace(op, pid, addr, data)
if rc == -1 and ctypes.get_errno():
raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))
return rc
def path_at(addr):
data = bytearray()
word = ctypes.sizeof(ctypes.c_long)
for offset in range(0, 4096, word):
data.extend(ptrace(PTRACE_PEEKDATA, addr + offset).to_bytes(word, sys.byteorder, signed=True))
if 0 in data:
return os.fsdecode(bytes(data[:data.index(0)]))
raise RuntimeError('Unterminated pathname')
def publish(suffix, value):
with Path(str(control) + suffix).open('x') as out:
json.dump(value, out)
out.flush()
os.fsync(out.fileno())
# TRACESYSGOOD identifies syscall stops. EXITKILL prevents an accidental tracer
# exit from releasing the supervisor into its retry path before the VM cut.
ptrace(PTRACE_SEIZE, 0, 1 | (1 << 20))
ptrace(PTRACE_INTERRUPT)
assert os.WIFSTOPPED(os.waitpid(pid, 0)[1])
publish('.ready', {'supervisor': pid, 'tracer': os.getpid()})
deliver = 0
target = None
while True:
ptrace(PTRACE_SYSCALL, 0, deliver)
_, status = os.waitpid(pid, 0)
if not os.WIFSTOPPED(status):
raise RuntimeError(f'Supervisor exited early, wait status {status}')
deliver = os.WSTOPSIG(status)
if deliver != signal.SIGTRAP | 0x80:
continue
deliver = 0
# linux/ptrace.h: op at byte 0, entry.nr / exit.rval at 24,
# entry.args at 32. Request the kernel-reported stop type, independent of
# whether attachment happened inside a previous syscall.
info = ctypes.create_string_buffer(88)
ptrace(PTRACE_GET_SYSCALL_INFO, len(info), ctypes.addressof(info))
raw = info.raw
number = int.from_bytes(raw[24:32], sys.byteorder, signed=True)
if raw[0] == 1:
target = None
if number == openat:
flags = int.from_bytes(raw[48:56], sys.byteorder)
if flags & os.O_EXCL and flags & os.O_CREAT:
name = path_at(int.from_bytes(raw[40:48], sys.byteorder))
if name.startswith('/ql/data/db/cron-exits/.pending.' + receipt + '.full-'):
target = name
elif raw[0] == 2 and target:
if number != -errno.ENOSPC:
raise RuntimeError(f'First marker creation returned {number}')
children = Path(f'/proc/{pid}/task/{pid}/children').read_text().split()
assert not children, children
publish('.stopped', dict(supervisor=pid, tracer=os.getpid(), receipt=receipt, path=target,
syscall='openat', result=number, children=children, stop='syscall-exit'))
while True:
signal.pause()
+24
View File
@@ -0,0 +1,24 @@
// Stop the real migration transaction on either side of COMMIT. The harness
// reads through a separate SQLite connection before killing the worker or VM.
const fs = require('node:fs');
const path = require('node:path');
const [modules, side, checkpoint] = process.argv.slice(2);
const { sequelize } = require(path.join(modules, 'data'));
const { migrateSchema, prunedExitMigrationId } = require(path.join(modules, 'shared/schemaMigrations'));
if (!['before', 'after'].includes(side)) throw new Error('Unknown commit boundary');
const transaction = sequelize.transaction.bind(sequelize);
sequelize.transaction = callback => transaction(async tx => {
await callback(tx);
const [rows] = await sequelize.query(`SELECT
(SELECT COUNT(*) FROM SchemaMigrations WHERE id=$id) AS marker,
(SELECT COUNT(*) FROM CronUnmatchedBoundExits) AS proofs`, { transaction: tx, bind: { id: prunedExitMigrationId } });
if (rows[0].marker !== 1 || rows[0].proofs === 0) throw new Error('No verified migration batch');
const hold = () => {
fs.writeFileSync(checkpoint + '.tmp', JSON.stringify({ side, pid: process.pid, ...rows[0] }), {flag: 'wx'});
fs.renameSync(checkpoint + '.tmp', checkpoint);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
};
if (side === 'before') hold();
else tx.afterCommit(hold);
});
migrateSchema(sequelize).catch(error => { console.error(error); process.exitCode = 1; });
@@ -0,0 +1,36 @@
const fs = require('node:fs');
const path = require('node:path');
const { writeExit } = require('../../back/shared/managedExit.cjs');
const [stage, time] = process.argv.slice(2);
const write = fs.writeFileSync;
function checkpoint(point) {
if (point !== stage) return;
const ready = path.join(process.env.QL_DATA_DIR, 'publisher-ready');
write(ready + '.tmp', point);
fs.renameSync(ready + '.tmp', ready);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
}
let writes = 0;
fs.writeFileSync = (file, contents, options) => {
if (writes++ === 0) {
checkpoint('before-write');
write(file, contents, options);
checkpoint('after-write');
} else {
checkpoint('before-mirror');
if (stage === 'partial') {
write(file, contents.slice(0, 12), options);
checkpoint('partial');
}
write(file, contents, options);
checkpoint('after-mirror');
}
};
const link = fs.linkSync;
fs.linkSync = (...args) => {
checkpoint('before-link');
link(...args);
checkpoint('after-link');
};
writeExit(process.env.QL_TRIGGER_ID, 23, null, Number(time));
checkpoint('published');
+63
View File
@@ -0,0 +1,63 @@
"""Interrupt the real Python supervisor at the requested publication boundary."""
import os
import pathlib
import runpy
import signal
import sys
import tempfile
import time
stage, finish, script, marker, owner = sys.argv[1:]
time.time_ns = lambda: int(finish) * 1_000_000
def checkpoint(point):
if point == stage:
ready = pathlib.Path(os.environ['QL_DATA_DIR']) / 'publisher-ready'
pending = ready.with_suffix('.tmp')
pending.write_text(point)
pending.replace(ready)
signal.pause()
open_temp = tempfile.NamedTemporaryFile
writes = 0
class TempFile:
def __init__(self, **kwargs):
global writes
self.first = writes == 0
writes += 1
checkpoint('before-write' if self.first else 'before-mirror')
self.file = open_temp(**kwargs)
def __enter__(self):
self.file.__enter__()
if not self.first and stage == 'partial':
self.file.write('{"code":')
self.file.flush()
checkpoint('partial')
return self.file
def __exit__(self, *args):
self.file.__exit__(*args)
checkpoint('after-write' if self.first else 'after-mirror')
link = os.link
def publish(source, dest):
checkpoint('before-link')
link(source, dest)
checkpoint('after-link')
tempfile.NamedTemporaryFile = TempFile
os.link = publish
sys.argv = [script, 'exit 23', owner, marker, '', '']
main = runpy.run_path(script)['main']
status = main()
checkpoint('published')
sys.exit(status)
+91
View File
@@ -0,0 +1,91 @@
// Run inside the dedicated bounded ext4 acceptance volume, alongside receipt-volume-full.cjs.
// Pause the actual post-commit collector before or after its filesystem call.
const fs = require('node:fs');
const path = require('node:path');
const { exhaust } = require('./receipt-volume-full.cjs');
const { sequelize } = require('/ql/static/build/data');
const { TriggerHistory } = require('/ql/static/build/shared/triggerHistory');
const [stage, id] = process.argv.slice(2);
const volume = '/ql/data/db';
const canonical = path.join(volume, 'cron-exits', id);
const control = '/tmp/journal-qa';
const capacity = () => fs.statfsSync(volume).bavail;
if (fs.statfsSync(volume).type !== 0xef53 || !/^[a-z0-9-]+$/.test(id) ||
!['rename-before','rename-after','rename-enospc','unlink-before','unlink-after','unlink-injected'].includes(stage)) {
throw Error('Expected a supported ext4 collection boundary and execution ID');
}
function hold(event) {
const target = path.join(control, stage + '-event');
fs.writeFileSync(target + '.tmp', JSON.stringify(event));
fs.renameSync(target + '.tmp', target);
// The outside observer cuts power here. A failed orchestrator has a bounded wait.
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 120000);
throw Error('Power cut did not occur');
}
async function atBoundary(source, destination, operation) {
// A hard link outside the receipt namespace keeps the allocation constant even
// if unlink succeeds.
const pin = path.join(volume, '.qa-reclaim-pin');
fs.linkSync(source, pin);
exhaust(false);
const event = {stage, id, source, destination, blocksBefore: capacity()};
if (event.blocksBefore !== 0) throw Error('Expected an exhausted data volume');
if (stage === 'rename-enospc') {
// Fill the target directory with entries the same length as the capture name.
// Hard links expend directory space without needing another inode.
const dir = path.dirname(destination);
let count = 0;
try {
for (;;) {
fs.linkSync(pin, path.join(dir, 'q' + count.toString(36).padStart(path.basename(destination).length - 1, '0')));
count++;
}
} catch (error) {
if (error.code !== 'ENOSPC') throw error;
}
event.extraDirectoryEntries = count;
}
if (stage.endsWith('-before')) hold({...event, called:false});
if (stage === 'unlink-injected') {
// Explicitly synthetic. Keep the file and let the real collector unwind.
throw Object.assign(Error('Injected unlink capacity error'), {code:'ENOSPC', event});
}
try {
await operation();
} catch (error) {
if (stage !== 'rename-enospc' || error.code !== 'ENOSPC') throw error;
hold({...event, called:true, result:error.code, errno:error.errno, syscall:error.syscall,
sourceExists:fs.existsSync(source), destinationExists:fs.existsSync(destination)});
}
if (stage === 'rename-enospc') throw Error('Expected rename to need another directory block');
hold({...event, called:true, result:'success', blocksAfter:capacity(),
sourceExists:fs.existsSync(source), destinationExists:destination && fs.existsSync(destination)});
}
const rename = fs.promises.rename.bind(fs.promises);
const unlink = fs.promises.unlink.bind(fs.promises);
let reached = false, injected;
fs.promises.rename = (from,to) => {
if (!reached && stage.startsWith('rename-') && from === canonical) {
reached = true;
const destination = path.join(fs.realpathSync(path.dirname(to)), path.basename(to));
return atBoundary(from,destination,() => rename(from,to));
}
return rename(from,to);
};
fs.promises.unlink = async file => {
if (!reached && stage.startsWith('unlink-') && path.basename(file).startsWith('.pending.' + id + '.r-')) {
reached = true;
try {return await atBoundary(fs.realpathSync(file),null,() => unlink(file));}
catch (error) { if (stage === 'unlink-injected') injected = error; throw error; }
}
return unlink(file);
};
new TriggerHistory(sequelize).complete(id,'unknown',null,null).then(() => {
if (injected?.code === 'ENOSPC') hold({...injected.event, called:false, injected:'ENOSPC',
privateFileRetained:fs.existsSync(injected.event.source)});
throw Error('Collector did not reach the expected power cut');
}).catch(error => {console.error(error); process.exitCode = 1;}).finally(() => sequelize.close());
+112
View File
@@ -0,0 +1,112 @@
"""Drive the real block/inode limits for the private-slot power-cut regression.
The controller supplies a private receipt already verified by two collectors.
Stage the writer's only copy before filling the disk, install it by rename at
zero capacity, then release only this fixture's allocations after reboot.
"""
import errno
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import sys
if not __debug__:
raise RuntimeError('The dedicated-volume checks require Python assertions')
volume = Path('/ql/data/db')
spool = volume / 'cron-exits'
filler = volume / '.qa-slot-capacity'
def capacity():
stat = os.statvfs(volume)
return dict(blocks=stat.f_bavail, freeBlocks=stat.f_bfree, inodes=stat.f_favail)
def sync(path):
fd = os.open(path, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def fill(slot, mode, body):
filler.mkdir(mode=0o700)
# Otherwise freeing the old inode or its empty parent directory could give
# ext4 enough space to pass the next stage without exercising ENOSPC.
os.link(slot, slot.parent / '.qa-old-pin')
staged = slot.parent / '.qa-staged'
with staged.open('xb') as dest:
dest.write(body.encode())
dest.flush()
os.fsync(dest.fileno())
sync(slot.parent)
errors = {}
with (filler / 'blocks').open('xb', buffering=0) as dest:
if mode == 'both':
i = 0
try:
while True:
(filler / str(i)).touch(exist_ok=False)
i += 1
except OSError as exc:
if exc.errno != errno.ENOSPC or capacity()['inodes'] != 0:
raise
errors['create'] = exc.errno
for size in (65536, os.statvfs(volume).f_frsize):
buf = bytes(size)
try:
while True:
dest.write(buf)
os.fsync(dest.fileno())
except OSError as exc:
if exc.errno != errno.ENOSPC:
raise
errors['write'] = exc.errno
sync(filler)
sync(volume)
result = capacity()
assert result['blocks'] == 0, result
assert mode != 'both' or result['inodes'] == 0
return dict(capacity=result, errno=errors, stagedInode=staged.stat().st_ino)
def main():
op, execution, mode = sys.argv[1:4]
assert re.fullmatch(r'[a-z0-9-]{1,120}', execution) and mode in ('blocks', 'both')
mounts = [line.split() for line in Path('/proc/mounts').read_text().splitlines()]
assert any(row[1:3] == [str(volume), 'ext4'] for row in mounts)
stat = os.statvfs(volume)
assert (volume / '.qa-isolated-volume').is_file()
assert 0 < stat.f_blocks * stat.f_frsize <= 32 * 1024 * 1024 and 0 < stat.f_files <= 8192
claim = spool / ('.claim.' + execution + '.qaTest')
slot = claim / 'receipt'
if op == 'fill':
return fill(slot, mode, sys.argv[4])
if op == 'replace':
before = capacity()
assert before['blocks'] == 0 and (mode == 'blocks' or before['inodes'] == 0)
os.replace(claim / '.qa-staged', slot)
sync(claim)
assert slot.stat().st_nlink == 1
return dict(directory=claim.stat().st_ino, inode=slot.stat().st_ino,
sha256=hashlib.sha256(slot.read_bytes()).hexdigest(), capacity=capacity())
if op == 'release':
before = capacity()
assert (filler / 'blocks').is_file()
shutil.rmtree(filler)
(claim / '.qa-old-pin').unlink()
sync(claim)
sync(volume)
return dict(before=before, after=capacity())
if op == 'capacity':
return capacity()
raise ValueError(op)
if __name__ == '__main__':
print(json.dumps(main()))
+38
View File
@@ -0,0 +1,38 @@
// Linux acceptance probe for the SQLite driver used in the panel image.
// cc -O2 -Wall -Werror -shared -fPIC receipt-sqlite-power.c -o probe.so -ldl
// Preload only in the dedicated receipt-volume-full.cjs commit worker.
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static void pause_failed_database_write(int fd) {
char link[64], target[256];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t size = readlink(link, target, sizeof(target) - 1);
if (size < 0) return;
target[size] = '\0';
if (strcmp(target, "/ql/data/db/database.sqlite") != 0 ||
access("/ql/data/db/.qa-isolated-volume", F_OK) != 0) return;
// The control file is on a different filesystem from the full database.
int barrier = open("/tmp/journal-qa/native-full", O_WRONLY | O_CREAT | O_EXCL, 0600);
if (barrier < 0) return;
dprintf(barrier, "{\"syscall\":\"write\",\"errno\":%d,\"pid\":%d}", ENOSPC, getpid());
close(barrier);
raise(SIGSTOP);
}
ssize_t write(int fd, const void *bytes, size_t length) {
// Call the kernel first so the fault is an actual filesystem response.
ssize_t (*real_write)(int, const void *, size_t) = dlsym(RTLD_NEXT, "write");
ssize_t written = real_write(fd, bytes, length);
int saved_errno = errno;
if (written < 0 && saved_errno == ENOSPC) pause_failed_database_write(fd);
errno = saved_errno;
return written;
}
+87
View File
@@ -0,0 +1,87 @@
"""Measure real unlink outcomes on the isolated Docker acceptance disk."""
import errno
import json
import os
from pathlib import Path
import tempfile
VOLUME = Path('/ql/data/db')
PAYLOAD = b'{"code":23,"signal":null,"time":1790000000123}'
def capacity():
stats = os.statvfs(VOLUME)
return {'blocks': stats.f_bavail, 'inodes': stats.f_favail}
def fill_inodes(directory):
try:
for index in range(os.statvfs(VOLUME).f_files + 1):
(directory / str(index)).touch(exist_ok=False)
except OSError as error:
if error.errno != errno.ENOSPC:
raise
assert capacity()['inodes'] == 0
def fill_blocks(fd):
block_size = os.statvfs(VOLUME).f_frsize
for size in (64 * 1024, block_size):
data = bytes(size)
try:
while True:
os.write(fd, data)
except OSError as error:
if error.errno != errno.ENOSPC:
raise
os.fsync(fd)
assert capacity()['blocks'] == 0
def observe(mode):
with tempfile.TemporaryDirectory(prefix='.qa-unlink-', dir=VOLUME) as folder:
root = Path(folder)
linked, opened, closed = (root / name for name in ('linked', 'opened', 'closed'))
for file in (linked, opened, closed):
file.write_bytes(PAYLOAD)
alias = root / 'other-link'
os.link(linked, alias)
filler = os.open(root / 'blocks', os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_SYNC, 0o600)
try:
if mode != 'blocks':
fill_inodes(root)
if mode != 'inodes':
fill_blocks(filler)
with opened.open('rb') as live:
rows = []
for file in (linked, opened, closed):
before = capacity()
assert mode == 'inodes' or before['blocks'] == 0
assert mode == 'blocks' or before['inodes'] == 0
links = file.stat().st_nlink
try:
file.unlink()
result = 'success'
assert not file.exists()
except OSError as error:
if error.errno != errno.ENOSPC:
raise
result = 'ENOSPC'
assert file.read_bytes() == PAYLOAD
rows.append({'layout': file.name, 'linksBefore': links, 'result': result,
'before': before, 'after': capacity()})
assert live.read() == PAYLOAD and alias.read_bytes() == PAYLOAD
return rows
finally:
os.close(filler)
if __name__ == '__main__':
mount = next((line.split(' - ')[1].split()[0] for line in Path('/proc/self/mountinfo').read_text().splitlines()
if line.split()[4] == str(VOLUME)), None)
stats = os.statvfs(VOLUME)
if (mount != 'ext4' or not (VOLUME / '.qa-isolated-volume').is_file()
or not 0 < stats.f_blocks * stats.f_frsize <= 32 * 1024 * 1024
or not 0 < stats.f_files <= 8192):
raise RuntimeError('Requires the marked bounded ext4 acceptance volume')
print(json.dumps({mode: observe(mode) for mode in ('blocks', 'inodes', 'both')}))
+128
View File
@@ -0,0 +1,128 @@
// Docker acceptance worker. Both capacity limits are checked before filling the
// explicitly mounted test filesystem. Barrier files live outside that mount.
const fs = require('node:fs');
const path = require('node:path');
const volume = '/ql/data/db';
const barriers = '/tmp/journal-qa';
const [mode, id] = process.argv.slice(2);
const capacity = fs.statfsSync(volume);
const filesystem = fs.readFileSync('/proc/self/mountinfo', 'utf8').split('\n')
.find(line => line.split(' ')[4] === volume)?.split(' - ')[1].split(' ')[0];
const ext4 = filesystem === 'ext4' && capacity.type === 0xef53;
if (!(ext4 || (filesystem === 'tmpfs' && capacity.type === 0x01021994)) || capacity.blocks <= 0 || capacity.blocks * capacity.bsize > 32 * 1024 * 1024 ||
capacity.files <= 0 || capacity.files > 8192 || !fs.existsSync(path.join(volume, '.qa-isolated-volume'))) {
throw Error('Requires a dedicated bounded ext4 or tmpfs for receipt acceptance');
}
const { sequelize: db } = require('/ql/static/build/data');
const { TriggerHistory } = require('/ql/static/build/shared/triggerHistory');
function record(name, data) {
fs.writeFileSync(path.join(barriers, name + '.tmp'), JSON.stringify(data));
fs.renameSync(path.join(barriers, name + '.tmp'), path.join(barriers, name));
}
function exhaust(inodes) {
const dir = fs.mkdtempSync(path.join(volume, '.qa-fill-'));
let fd;
try {
if (!inodes) fd = fs.openSync(path.join(dir, 'data'), 'wx');
const block = Buffer.alloc(64 * 1024);
for (let n = 0; ; n++) {
if (inodes) fs.closeSync(fs.openSync(path.join(dir, String(n)), 'wx'));
else fs.writeSync(fd, block);
}
} catch (error) {
if (error.code !== 'ENOSPC') throw error;
if (ext4) {
if (fd !== undefined) {
// A large allocation may fail while individual blocks remain usable.
try { for (;;) fs.writeSync(fd, Buffer.alloc(capacity.bsize)); }
catch (last) { if (last.code !== 'ENOSPC') throw last; }
fs.fsyncSync(fd);
}
for (const entry of [dir, volume]) {
const handle = fs.openSync(entry, fs.constants.O_DIRECTORY);
try { fs.fsyncSync(handle); } finally { fs.closeSync(handle); }
}
}
record(mode + '-capacity', { dir, error: error.code, statfs: fs.statfsSync(volume) });
} finally { if (fd !== undefined) fs.closeSync(fd); }
}
// A short receipt fits one block. Request another block beyond any ext4
// preallocation to obtain kernel ENOSPC while the original prefix is intact.
function writePartialReceipt() {
const receipt = JSON.parse(process.argv[4]);
const { writeExit } = require('/ql/static/build/shared/managedExit.cjs');
const write = fs.writeFileSync;
fs.writeFileSync = (file, content, options) => {
if (!content || path.dirname(file) !== path.join(volume, 'cron-exits')) return write(file, content, options);
const fd = fs.openSync(file, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | fs.constants.O_SYNC, 0o600);
try {
const bytes = Buffer.from(content);
fs.writeSync(fd, bytes, 0, 12, 0);
record('partial-ready', { id, file, bytes: fs.fstatSync(fd).size });
const deadline = performance.now() + 120000;
while (!fs.existsSync(path.join(barriers, 'partial-continue'))) {
if (performance.now() > deadline) throw Error('Short-write barrier expired');
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30);
}
const offset = ext4 ? (capacity.blocks + 1) * capacity.bsize : capacity.bsize;
try { fs.writeSync(fd, bytes, 12, bytes.length - 12, offset); }
catch (error) {
record('partial-error', { id, file, code: error.code, bytes: fs.fstatSync(fd).size, offset });
// Keep the torn file open across the guest power cut in the ext4 run.
if (ext4) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 120000);
throw error;
}
throw Error('Expected ENOSPC while allocating the next page');
} finally { fs.closeSync(fd); }
};
writeExit(id, receipt.code, receipt.signal, receipt.time);
}
async function main() {
if (mode === 'partial') return writePartialReceipt();
if (!['commit','collect'].includes(mode)) throw Error('Unexpected fault mode');
await db.query('CREATE TABLE IF NOT EXISTS qa_commit_payload (payload BLOB)');
const original = db.query.bind(db);
if (mode === 'commit') {
db.query = async (sql, ...args) => {
if (!String(sql).startsWith('COMMIT')) return original(sql, ...args);
exhaust(false);
try { return await original(sql, ...args); }
catch (error) {
record('commit-error', { code: error.original?.code, sql: String(sql) });
throw error;
}
};
} else {
const rename = fs.promises.rename.bind(fs.promises);
let injected = false;
fs.promises.rename = async (...args) => {
if (!injected) {
injected = true;
exhaust(true);
}
try {
await rename(...args);
record('collect-moved', { source:args[0], destination:args[1] });
}
catch (error) { record('collect-error', { code: error.code, prefix: args[0] }); throw error; }
};
}
await db.transaction(async transaction => {
if (mode === 'commit') {
await db.query('PRAGMA cache_spill=OFF', { transaction });
await db.query('INSERT INTO qa_commit_payload VALUES (zeroblob(524288))', { transaction });
}
record(mode + '-ready', { id });
const deadline = Date.now() + 86400000 * 3;
while (!fs.existsSync(path.join(barriers, mode + '-continue'))) {
if (Date.now() >= deadline) throw Error('Timed out at database barrier');
await new Promise(r => setTimeout(r, 30));
}
await new TriggerHistory(db).completeCommandExit(id, 'unknown', null, null, transaction);
});
}
module.exports = { exhaust };
if (require.main === module) main().catch(error => {
if (mode !== 'commit' || error.original?.code !== 'SQLITE_FULL') {console.error(error); process.exitCode = 1;}
}).finally(async () => { await db.close(); record(mode + '-done', { id }); });