feat: add scheduling anomaly drill-down and improve dev startup

This commit is contained in:
whyour committed 2026-11-19 23:11:20 +08:00
1 parent d9e9e083ab
commit 2070931c82
21 files changed
+1185 -54

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
import { createHash } from 'crypto';
export type AnomalyKind = 'missing' | 'skipped' | 'unconfirmed';
export interface ScheduleAnomaly {
task: number;
name?: string;
rule: string | null;
time: number | null;
source: 'node' | 'recovery' | 'system';
trigger: string | null;
observed: number | null;
reason: string | null;
logPath: string | null;
ruleIndex?: number;
}
// Keep only the requested page and the first page. If late evidence changes
// the result between requests, return the new first page instead of mixing scans.
export class AnomalyPage {
private hash = createHash('sha256');
private total = 0;
private first: ScheduleAnomaly[] = [];
private selected: ScheduleAnomaly[] = [];
static readonly size = 25;
constructor(readonly kind: AnomalyKind, private page: number, private previous?: string) {}
add(row: ScheduleAnomaly) {
this.hash.update(JSON.stringify(row)).update('\n');
const page = Math.floor(this.total++ / AnomalyPage.size) + 1;
if (page === 1) this.first.push(row);
if (page === this.page) this.selected.push(row);
}
result() {
const revision = this.hash.digest('hex');
const changed = !!this.previous && revision !== this.previous;
const reset = changed || (this.page > 1 && !this.selected.length);
return { rows: reset ? this.first : this.selected, total: this.total,
page: reset ? 1 : this.page, pageSize: AnomalyPage.size, revision, changed };
}
}
+27 -5
View File
@@ -1,3 +1,4 @@
import { AnomalyPage } from './scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { AddCronRequest, DeleteCronRequest } from '../protos/cron';
import { upcomingSlots } from './cronScheduler';
@@ -19,6 +20,9 @@ type Receipt = {
scheduled_at: number;
observed_at: number;
state: string;
reason: string | null;
log_path: string | null;
source: 'node' | 'recovery';
command_started_at: number | null;
verified_exit: number;
script_started_at: number | null;
@@ -158,6 +162,7 @@ export async function auditSchedule(
db: Sequelize,
dayStart: number,
now = Date.now(),
details?: AnomalyPage,
) {
// All counts use the same settled plan window and the same committed snapshot.
const nextDay = new Date(dayStart);
@@ -180,14 +185,14 @@ export async function auditSchedule(
CASE WHEN c.token IS NULL THEN COALESCE(r.until,$through) ELSE COALESCE(c.last_at,$through) END AS close_latest
FROM CronPlanRules r LEFT JOIN CronPlanSwitches o ON o.token=r.opened_by
LEFT JOIN CronPlanSwitches c ON c.token=r.closed_by
WHERE r.since < $through AND close_latest >= $since`,
WHERE r.since < $through AND close_latest >= $since ORDER BY r.cron_id,r.rule_index,r.since,r.rowid`,
{ transaction, bind, type: QueryTypes.SELECT },
);
const receipts = await db.query<Receipt>(
`SELECT id,cron_id,scheduled_at,observed_at,state,
`SELECT id,cron_id,scheduled_at,observed_at,state,${details ? 'source,reason,log_path,' : ''}
command_started_at,script_started_at,queued_at,COALESCE(dequeued_at,started_at) AS started_at,
EXISTS(SELECT 1 FROM CronLegacyExitBookings b WHERE b.trigger_id=CronTriggers.id AND b.bound=1) AS verified_exit FROM CronTriggers
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery')`,
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery') ${details ? 'ORDER BY cron_id,scheduled_at,id' : ''}`,
{ transaction, bind, type: QueryTypes.SELECT },
);
return { since: coverage.since, rules, receipts };
@@ -235,6 +240,7 @@ export async function auditSchedule(
);
if (certain < possible) partial = true;
expected += certain;
const received = details?.kind === 'missing' && certain ? new Set<number>() : null;
for (const row of byTaskBlock.get(rule.cron_id + '/' + block) ?? []) {
const time = row.scheduled_at;
if (
@@ -244,6 +250,7 @@ export async function auditSchedule(
row.id !== slotId(rule.cron_id, rule.rule_index, rule.schedule, time)
)
continue;
received?.add(time);
const deviation = Math.abs(row.observed_at - time);
deviations.push(deviation);
if (deviation <= 5000) onTime++;
@@ -255,13 +262,28 @@ export async function auditSchedule(
dispatched++;
if (row.command_started_at != null && row.command_started_at >= time)
starts.push(row.command_started_at - time);
} else if (row.state === 'skipped') skipped++;
else if (row.state === 'queued') queued++;
} else if (row.state === 'queued') {
queued++;
} else {
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
if (kind === 'skipped') skipped++;
if (details?.kind === kind) details.add({
task: row.cron_id, rule: rule.schedule, ruleIndex: rule.rule_index, time, source: row.source,
trigger: row.id, observed: row.observed_at, reason: row.reason, logPath: row.log_path,
});
}
if (row.script_started_at != null && row.script_started_at >= time)
entries.push(row.script_started_at - time);
if (row.started_at != null && row.queued_at != null && row.started_at >= row.queued_at)
waits.push(row.started_at - row.queued_at);
}
if (details && received && received.size < certain) {
for (let i = lowerBound(times, certainFirst); i < times.length && times[i] <= certainLast; i++) {
if (!received.has(times[i])) details.add({ task: Number(rule.cron_id), rule: rule.schedule,
ruleIndex: rule.rule_index, time: times[i], source: 'node', trigger: null,
observed: null, reason: null, logPath: null });
}
}
}
}
const observed = deviations.length;
+13
View File
@@ -0,0 +1,13 @@
import Logger from '../loaders/logger';
import { performance } from 'perf_hooks';
export async function startupStage<T>(name: string, operation: () => Promise<T>): Promise<T> {
if (process.env.QL_STARTUP_TIMING !== '1') return operation();
const started = performance.now();
try {
return await operation();
} finally {
const role = process.env.SERVICE_TYPE || 'primary';
Logger.info(`[boot:timing] ${role}:${name} ${Math.round(performance.now() - started)}ms (PID: ${process.pid})`);
}
}
+24 -4
View File
@@ -1,3 +1,4 @@
import { AnomalyPage } from './scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { blockSize, blockSlots } from './scheduleAudit';
@@ -15,6 +16,8 @@ type Receipt = {
system_rule: string | null;
observed_at: number;
system_dispatch_at: number | null;
reason: string | null;
log_path: string | null;
launched: number;
state: string;
};
@@ -83,6 +86,7 @@ export async function systemScheduleAudit(
db: Sequelize,
dayStart: number,
now = Date.now(),
details?: AnomalyPage,
) {
const next = new Date(dayStart);
next.setHours(24, 0, 0, 0);
@@ -101,7 +105,7 @@ export async function systemScheduleAudit(
{ transaction, bind: { since, now }, type: QueryTypes.SELECT },
);
const receipts = await db.query<Receipt>(
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,${details ? 'reason,log_path,' : ''}
(command_started_at IS NOT NULL OR script_started_at IS NOT NULL OR
(started_at IS NOT NULL AND EXISTS (SELECT 1 FROM CronLegacyExitBookings b
WHERE b.trigger_id=CronTriggers.id AND b.bound=1 AND b.disputed=0))) AS launched
@@ -133,6 +137,7 @@ export async function systemScheduleAudit(
(JSON.parse(plan.rules) as SystemRule[]).map((rule) => [rule.id, rule]),
),
}));
const matched = details && details.kind !== 'missing' ? new Map<string, { time: number; name?: string }>() : null;
const groups = new Map<string, Receipt[]>();
const dispatchedTasks = new Set<string>();
const legacyThrough = new Map<string, number>();
@@ -247,10 +252,11 @@ export async function systemScheduleAudit(
);
let status: string;
const launched = group.find((row) => row.launched === 1);
const skip = group.find((row) => row.state === 'skipped');
const skip = group.find((row) => !row.launched && row.state === 'skipped');
if (group.length) {
++expected;
++observed;
if (matched) for (const row of group) matched.set(row.id, { time, name });
matchedReceipts += group.length;
duplicates += group.length - 1;
if (launched) ++dispatched;
@@ -277,6 +283,8 @@ export async function systemScheduleAudit(
status = 'awaiting';
} else {
++missing;
if (details?.kind === 'missing') details.add({ task, name, rule: schedule, time, source: 'system',
trigger: null, observed: null, reason: null, logPath: null });
status = 'missing';
}
}
@@ -287,7 +295,7 @@ export async function systemScheduleAudit(
status,
triggerCount: group.length,
startCount: group.filter((row) => row.launched === 1).length,
skipCount: group.filter((row) => row.state === 'skipped').length,
skipCount: group.filter((row) => !row.launched && row.state === 'skipped').length,
unknownExitCount: group.filter((row) => row.launched === 1 && row.state === 'unknown').length,
id: (launched || skip || group[0])?.id,
});
@@ -296,6 +304,18 @@ export async function systemScheduleAudit(
recent.unshift(...entries.sort((a, b) => a.task - b.task).slice(0, 25));
recent.splice(25);
}
let actualSkips = 0, actualUnconfirmed = 0;
for (const row of receipts) {
if (row.launched === 1) continue;
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
if (kind === 'skipped') actualSkips++;
else actualUnconfirmed++;
if (details?.kind === kind) {
const slot = matched?.get(row.id);
details.add({ task: row.cron_id, name: slot?.name, rule: row.system_rule, time: slot?.time ?? null,
source: 'system', trigger: row.id, observed: row.observed_at, reason: row.reason, logPath: row.log_path });
}
}
return {
since: Math.max(since, plans[0]?.staged ?? since),
through,
@@ -312,7 +332,7 @@ export async function systemScheduleAudit(
uncertain,
awaiting,
switchSlots,
actualSkips: receipts.filter((row) => row.state === 'skipped').length,
actualSkips, actualUnconfirmed,
actualStarts: receipts.filter((row) => row.launched === 1).length,
unmatched: receipts.length - matchedReceipts,
recent,