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

+195 -8
View File
@@ -1,7 +1,6 @@
"""Wait for launch authorization, then preserve a command's exit across worker restarts."""
import errno
import os
import subprocess
import sys
import threading
import time
@@ -58,6 +57,195 @@ def sync_directory(directory):
os.close(fd)
def start_log_relay(source, log_path):
# Keep draining after the supervisor or its task tree is terminated. The
# relay owns no execution permission and exits at pipe EOF. Double-fork
# before launching Bash so it is outside the task's cancellation tree.
ready, done = os.pipe()
try:
intermediate = os.fork()
except BaseException:
os.close(ready)
os.close(done)
raise
if intermediate == 0:
try:
os.close(ready)
os.setsid()
if os.fork():
os._exit(0)
# Never retain the authorization/telemetry pipes, stdout, or the
# write end of our own input. EOF must mean all writers have gone.
keep = {source.fileno(), done, 2}
if sys.platform == 'linux':
for entry in os.listdir('/proc/self/fd'):
fd = int(entry)
if fd not in keep:
try:
os.close(fd)
except OSError as error:
if error.errno != errno.EBADF:
raise
else:
import resource
previous = 0
for fd in sorted(keep):
os.closerange(previous, fd)
previous = fd + 1
maximum = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
if maximum == resource.RLIM_INFINITY:
maximum = os.sysconf('SC_OPEN_MAX')
os.closerange(previous, maximum)
os.write(done, b'R')
relay_log(source, log_path)
# EPIPE is expected if the supervisor was killed while we drained.
try:
os.write(done, b'D')
except BrokenPipeError:
pass
except BaseException as error:
report_log_error(error)
finally:
os._exit(0)
os.close(done)
source.close()
os.waitpid(intermediate, 0)
if os.read(ready, 1) != b'R':
os.close(ready)
raise OSError('Could not start command log relay')
def join():
try:
if os.read(ready, 1) != b'D':
raise OSError('Command log relay ended before draining output')
finally:
os.close(ready)
return join
def spawn_command(command, merged, log_path=None):
if not log_path:
return spawn_command_pipes(command, merged)
read_fd, write_fd = os.pipe()
source = os.fdopen(read_fd, 'rb')
join = None
try:
# Ready handshake precedes command side effects, including fast writers.
join = start_log_relay(source, log_path)
output, error, wait_command = spawn_command_pipes(command, True, write_fd)
except BaseException:
os.close(write_fd)
source.close()
if join:
join()
raise
os.close(write_fd)
def wait():
status = wait_command()
# A background writer is still part of this run. Keep the supervisor's
# birth identity, global permit and cancellation target until EOF; only
# then may main publish a terminal receipt.
join()
return status
return output, error, wait
def spawn_command_pipes(command, merged, destination=None):
libc = None
if sys.platform == 'linux':
import ctypes
# Both launch paths must adopt orphaned grandchildren. Output EOF is
# insufficient: a background command can redirect or close its output.
# The log relay detached before this flag is enabled.
libc = ctypes.CDLL(None, use_errno=True)
previous_reaper = ctypes.c_int()
if libc.prctl(37, ctypes.byref(previous_reaper), 0, 0, 0) != 0 or libc.prctl(36, 1, 0, 0, 0) != 0:
raise OSError(ctypes.get_errno(), 'Could not supervise command descendants')
# Keep native Linux launch without importing subprocess/locale/selectors.
# File writes belong to the relay: ENOSPC/EFBIG must not reach the script.
if (sys.platform != 'linux' or not hasattr(os, 'posix_spawn')
or not hasattr(os, 'waitstatus_to_exitcode')):
import subprocess
try:
child = subprocess.Popen(['/bin/bash', '-c', command], stdin=subprocess.DEVNULL,
stdout=destination if destination is not None else subprocess.PIPE,
stderr=destination if destination is not None else (subprocess.STDOUT if merged else subprocess.PIPE))
except BaseException:
if libc is not None:
libc.prctl(36, previous_reaper.value, 0, 0, 0)
raise
def wait_fallback():
status = child.wait()
if libc is not None:
while True:
try:
os.waitpid(-1, 0)
except ChildProcessError:
break
return status
return child.stdout, child.stderr, wait_fallback
import signal
descriptors = []
try:
if destination is not None:
output = error = None
output_write = error_write = destination
else:
output, output_write = os.pipe()
descriptors.extend((output, output_write))
if merged:
error, error_write = None, output_write
else:
error, error_write = os.pipe()
descriptors.extend((error, error_write))
actions = [(os.POSIX_SPAWN_OPEN, 0, os.devnull, os.O_RDONLY, 0),
(os.POSIX_SPAWN_DUP2, output_write, 1),
(os.POSIX_SPAWN_DUP2, error_write, 2)]
# Include the start telemetry pipe and any descriptors inherited from the
# caller. The readdir descriptor is already closed; skip that stale entry.
for entry in os.listdir('/proc/self/fd'):
fd = int(entry)
if fd < 3:
continue
try:
os.fstat(fd)
except OSError as exc:
if exc.errno == errno.EBADF:
continue
raise
actions.append((os.POSIX_SPAWN_CLOSE, fd))
defaults = tuple(getattr(signal, name) for name in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
if hasattr(signal, name))
pid = os.posix_spawn('/bin/bash', ['/bin/bash', '-c', command], os.environ,
file_actions=actions, setsigdef=defaults)
except BaseException:
libc.prctl(36, previous_reaper.value, 0, 0, 0)
for fd in descriptors:
os.close(fd)
raise
if destination is None:
os.close(output_write)
if error_write != output_write:
os.close(error_write)
def wait():
status = os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1])
while True:
try:
os.waitpid(-1, 0)
except ChildProcessError:
break
return status
return os.fdopen(output, 'rb') if output is not None else None, os.fdopen(error, 'rb') if error is not None else None, wait
def main():
command, owner, marker, node, reporter = sys.argv[1:6]
if sys.stdin.buffer.read() != b'run\n':
@@ -67,21 +255,19 @@ def main():
if report_start:
options = options[1:]
log_path = options[1] if len(options) == 2 and options[0] == 'log-output' else None
child = subprocess.Popen(['/bin/bash', '-c', command], stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT if log_path else subprocess.PIPE)
output, error, wait = spawn_command(command, bool(log_path), log_path)
if report_start:
try:
with os.fdopen(3, 'wb', buffering=0) as timing:
timing.write(str(time.time_ns() // 1000000).encode('ascii'))
except OSError:
pass
streams = ([threading.Thread(target=relay_log, args=(child.stdout, log_path))]
if log_path else [threading.Thread(target=relay, args=(child.stdout, 1)),
threading.Thread(target=relay, args=(child.stderr, 2))])
streams = (([] if output is None else [threading.Thread(target=relay_log, args=(output, log_path))])
if log_path else [threading.Thread(target=relay, args=(output, 1)),
threading.Thread(target=relay, args=(error, 2))])
for stream in streams:
stream.start()
status = child.wait()
status = wait()
finished = time.time_ns() // 1000000
import hashlib
@@ -143,6 +329,7 @@ def main():
needs_report = True
print('[scheduler] Could not save command exit:', error, file=sys.stderr)
if needs_report or os.getppid() != int(owner):
import subprocess
env = os.environ.copy()
env.pop('NODE_OPTIONS', None)
# Even with a live parent its child-close callback has no exit timestamp.
+34 -6
View File
@@ -4,10 +4,25 @@ const path = require('path');
const client = require('./client.js');
require(`./env.js`);
// 注册 ESM loader,使全局安装的包也可通过 import 导入
// Node 22.15+ can resolve ESM on the current thread, without a loader worker.
// CommonJS keeps preferGlobalNodeModules and its panel-dependency isolation.
try {
Module.register(new URL('esm-loader.mjs', `file://${__dirname}/`).href);
} catch (_) {}
if (typeof Module.registerHooks !== 'function') {
throw new Error('Synchronous module hooks unavailable');
}
const { resolve } = require('./esm-loader.mjs');
Module.registerHooks({
resolve(specifier, context, nextResolve) {
return context.conditions.includes('require')
? nextResolve(specifier, context)
: resolve(specifier, context, nextResolve);
},
});
} catch (_) {
try {
Module.register(new URL('esm-loader.mjs', `file://${__dirname}/`).href);
} catch (_) {}
}
function preferGlobalNodeModules() {
const { QL_NODE_GLOBAL_PATH } = process.env;
@@ -78,14 +93,15 @@ function run() {
`${dir_scripts}/`,
'',
);
const tempFile = `/tmp/env_${process.pid}.json`;
const tempFile = `/tmp/env_${process.pid}.data`;
// Pass paths as arguments: shell syntax in a filename must stay literal.
const command = `file="$1"; output="$2"; inline="$3"; shift 3
source "$file" "$@" &&
{ if [ -n "$inline" ]; then eval "$inline"; fi; } &&
printf '%s\\n' '__sitecustomize__' &&
node -e 'require("fs").writeFileSync(process.argv[1], JSON.stringify(process.env))' "$output"`;
{ command env -0 > "$output" 2>/dev/null ||
node -e 'require("fs").writeFileSync(process.argv[1], JSON.stringify(process.env))' "$output"; }`;
if (task_before) {
console.log(
@@ -113,7 +129,19 @@ node -e 'require("fs").writeFileSync(process.argv[1], JSON.stringify(process.env
try {
const envStr = require('fs').readFileSync(tempFile, 'utf-8');
const newEnvObject = JSON.parse(envStr);
// NUL separates environment entries without escaping Unicode, newlines
// or '=' in values. Keep JSON for env implementations without -0.
const newEnvObject = envStr.includes('\0')
? Object.fromEntries(
envStr
.split('\0')
.filter(Boolean)
.map((entry) => {
const separator = entry.indexOf('=');
return [entry.slice(0, separator), entry.slice(separator + 1)];
}),
)
: JSON.parse(envStr);
if (typeof newEnvObject === 'object' && newEnvObject !== null) {
for (const key in newEnvObject) {
if (
+9 -4
View File
@@ -46,7 +46,7 @@ def run():
file_name = sys.argv[0].replace(f"{os.getenv('dir_scripts')}/", "")
# 创建临时文件路径
temp_file = f"/tmp/env_{os.getpid()}.json"
temp_file = f"/tmp/env_{os.getpid()}.data"
if task_before:
print("Executing before command\n" if os.environ.get("QL_LANG") == "en" else "执行前置命令\n")
@@ -55,7 +55,8 @@ def run():
source "$file" "$@" &&
{ if [ -n "$inline" ]; then eval "$inline"; fi; } &&
printf '%s\\n' '__sitecustomize__' &&
python3 -c 'import os,json,sys; f=open(sys.argv[1],"w"); json.dump(dict(os.environ),f); f.close()' "$output"
{ command env -0 > "$output" 2>/dev/null ||
python3 -c 'import os,json,sys; f=open(sys.argv[1],"w"); json.dump(dict(os.environ),f); f.close()' "$output"; }
"""
res = subprocess.check_output(
["/bin/bash", "-c", command, "ql-before", os.environ["file_task_before"],
@@ -65,8 +66,12 @@ python3 -c 'import os,json,sys; f=open(sys.argv[1],"w"); json.dump(dict(os.envir
output = res.split(split_str)[0]
try:
with open(temp_file, 'r') as f:
env_json = json.loads(f.read())
with open(temp_file, 'rb') as f:
data = f.read()
# fsdecode retains undecodable Unix environment bytes, as os.environ does.
env_json = (dict((os.fsdecode(key), os.fsdecode(value))
for key, _, value in (entry.partition(b'=') for entry in data.split(b'\0') if entry))
if b'\0' in data else json.loads(data))
for key, value in env_json.items():
os.environ[key] = value
+18 -4
View File
@@ -100,7 +100,7 @@ import_config() {
if [[ -n "${DefaultCronRule}" ]]; then
default_cron="${DefaultCronRule}"
else
default_cron="$(random_range 0 59) $(random_range 0 23) * * *"
default_cron="$((RANDOM % 59)) $((RANDOM % 23)) * * *"
fi
}
@@ -148,7 +148,11 @@ detect_termux() {
}
detect_macos() {
[[ $(uname -s) == Darwin ]] && is_macos=1 || is_macos=0
case ${OSTYPE:-} in
darwin*) is_macos=1 ;;
linux*) is_macos=0 ;;
*) [[ $(uname -s) == Darwin ]] && is_macos=1 || is_macos=0 ;;
esac
}
gen_random_num() {
@@ -405,7 +409,9 @@ clear_env() {
handle_task_start() {
local error_message=""
if [[ $ID ]]; then
# Manual managed launches bind the PID, instance and log before permission.
# Scheduled/standalone wrappers still publish their shell-selected log path.
if [[ $ID && ( ${QL_SUPERVISOR_LOG_BOUND:-} != 1 || -z ${QL_TRIGGER_ID:-} ) ]]; then
local error=$(update_cron "\"$ID\"" "0" "$$" "$log_path" "$begin_timestamp")
if [[ $error ]]; then
error_message=$(t ', 任务状态更新失败(%s)' "$error")
@@ -436,7 +442,10 @@ run_task_after() {
handle_task_end() {
local etime end_time end_timestamp
if [[ $is_macos -ne 1 && $time_format == '%Y-%m-%d %H:%M:%S' ]]; then
if [[ $is_macos -ne 1 && ${BASH_VERSINFO[0]} -ge 5 && ${EPOCHSECONDS:-} =~ ^[0-9]+$ && $time_format == '%Y-%m-%d %H:%M:%S' ]]; then
end_timestamp=$EPOCHSECONDS
printf -v end_time '%(%Y-%m-%d %H:%M:%S)T' "$end_timestamp"
elif [[ $is_macos -ne 1 && $time_format == '%Y-%m-%d %H:%M:%S' ]]; then
IFS='|' read -r end_time end_timestamp < <(date "+$time_format|%s")
else
etime=$(date "+$time_format")
@@ -447,6 +456,10 @@ handle_task_end() {
local exit_code="${_task_exit_code:-0}"
[[ "$diff_time" == 0 ]] && diff_time=1
# The authorized supervisor publishes the command exit durably, including
# after hooks, and the worker/recovery books its statistics exactly once.
# Standalone/legacy wrappers still send their identified HTTP receipts.
if [[ ${QL_SUPERVISOR_RECEIPT:-} != 1 || -z ${QL_TRIGGER_ID:-} ]]; then
if [[ $ID ]]; then
local error=$(update_cron "\"$ID\"" "1" "$$" "$log_path" "$begin_timestamp" "$diff_time" "$exit_code" "$end_timestamp")
if [[ $error ]]; then
@@ -455,6 +468,7 @@ handle_task_end() {
fi
record_cron_stat "$ID" "${exit_code:-0}" "$diff_time" "$end_timestamp"
fi
if [[ "${MANUAL:=}" == "true" ]]; then
t '\n## 已停止 🛑... %s 耗时 %s 秒%s' "$end_time" "$diff_time" "${error_message:=}     "
+18 -4
View File
@@ -58,6 +58,7 @@ define_program() {
handle_log_path() {
local file_param=$1
ql_task_clock_seconds=""
if [[ -z $file_param ]]; then
file_param="task"
@@ -76,9 +77,18 @@ handle_log_path() {
fi
if [[ $is_macos -ne 1 && $mtime_format == '%Y-%m-%d %H:%M:%S.%3N' ]]; then
# Render both representations from one clock snapshot, without parsing it
# again in a second date process.
IFS='|' read -r time log_time < <(date "+$mtime_format|%Y-%m-%d-%H-%M-%S-%3N")
local clock=${EPOCHREALTIME:-}
if [[ ${BASH_VERSINFO[0]} -ge 5 && $clock =~ ^[0-9]+\.[0-9]{6}$ ]]; then
ql_task_clock_seconds=${clock%.*}
local millis=${clock#*.}
millis=${millis:0:3}
printf -v time '%(%Y-%m-%d %H:%M:%S)T' "$ql_task_clock_seconds"
printf -v log_time '%(%Y-%m-%d-%H-%M-%S)T' "$ql_task_clock_seconds"
time+=".$millis"; log_time+="-$millis"
else
# Older Bash retains the original external clock path.
IFS='|' read -r time log_time < <(date "+$mtime_format|%Y-%m-%d-%H-%M-%S-%3N")
fi
else
time=$(date "+$mtime_format")
log_time=$(format_log_time "$mtime_format" "$time")
@@ -155,7 +165,11 @@ init_begin_time() {
else
begin_time=$(format_time "$time_format" "$time")
fi
begin_timestamp=$(format_timestamp "$time_format" "$time")
if [[ ${ql_task_clock_seconds:-} =~ ^[0-9]+$ ]]; then
begin_timestamp=$ql_task_clock_seconds
else
begin_timestamp=$(format_timestamp "$time_format" "$time")
fi
}
import_config "$@"