Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/544-run-now.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
A schedule's console now has a **Run now** button: one explicit run from the current
moment, identified by the key the page rendered, so a double click starts one run
and a new page starts a new one. It never moves the schedule's next run.
18 changes: 18 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -2740,3 +2740,21 @@ and a path or key under a frozen family (`evaluator`, `evidence`, `ci`, `gate`,
`auth`, `gateway`, `capability`) is refused before the store is asked to write.
Recording `strategy_hash` and `strategy_version` on every job, the job-page diff,
canary promotion with rollback, and the global bundle are later slices.

## Run now is an occurrence, not a moved cursor (#544)

A schedule names logical instants; the tick decides which of them run. "Run now"
is the one command that starts an instant a person asked for, and it keeps the
same record: an occurrence row, settled `dispatched` with the job it started or
`skipped` with the refusal.

The occurrence's identity is the `command_key` the console form rendered, under
`UNIQUE(schedule_id, command_key)`. The same key returns the occurrence it
already wrote — a double click is one run — and a new key is a distinct
instance. The row is written before the job, so a crash between the two leaves a
row the next press reads instead of a second job, and a refused run still
settles the row so the replay answers the same refusal.

The recurrence cursor (`last_occurrence_at`) is not touched: "run this now" must
not move when the schedule next fires. `schedule_occurrences.command_key` is
null on every row the tick wrote, which is why the unique index is partial.
24 changes: 24 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1692,6 +1692,9 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
viewer: viewOf(viewer),
repo,
state,
// #544 slice 8: the run-now form carries a key rendered once, so a double
// click is one command and a fresh page is a new one.
runNowKey: randomId('cmd'),
form: {
cron: row?.expression ?? '',
every: row?.every_ms === null || row?.every_ms === undefined ? '' : intervalFieldText(row.every_ms),
Expand All @@ -1705,6 +1708,7 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
dailyRuns: row?.daily_runs === null || row?.daily_runs === undefined ? '' : String(row.daily_runs),
},
...(queryText(request, 'saved') === undefined ? {} : { notice: t('排期已保存。', 'The schedule is saved.') }),
...(queryText(request, 'ran') === undefined ? {} : { notice: t('已立即开始一次运行。', 'One run has started now.') }),
...(queryText(request, 'removed') === undefined ? {} : { notice: t('排期已删除,仓库回到旧的自动间隔。', 'The schedule was deleted; the repository is back on the legacy interval.') }),
...(refused === undefined ? {} : { error: refused }),
}))
Expand Down Expand Up @@ -1771,6 +1775,26 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
return reply.redirect(`${back}?saved=1`)
})

// #544 slice 8: Run now is one explicit occurrence. The key the page rendered
// makes a double click the same command; the recurrence cursor is untouched,
// so "run this now" never moves when the schedule next fires.
app.post('/repos/:id/schedule/run-now', async (request, reply) => {
const { repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
const back = `/repos/${repo.id}/schedule`
const t = translator(request.locale ?? 'zh')
if (repo.repo_role !== 'maintainer') {
return reply.redirect(`${back}?refused=${encodeURIComponent(t('只有 maintainer 可以立即运行排期。', 'Only a maintainer can run the schedule now.'))}`)
}
const result = await jobs.runScheduleNow(repo, form(request).command_key)
if (!result.ok) {
const message = result.code === 'schedule_missing'
? t('这个仓库还没有排期。', 'This repository has no schedule yet.')
: (result.message ?? t('这次运行没有开始。', 'The run did not start.'))
return reply.redirect(`${back}?refused=${encodeURIComponent(message)}`)
}
return reply.redirect(`${back}?ran=${encodeURIComponent(result.jobId ?? '')}`)
})

// Deleting the row hands the repository back to its legacy interval; it does
// not stop the repository, so the audit says which schedule stopped owning it.
app.post('/repos/:id/schedule/remove', async (request, reply) => {
Expand Down
70 changes: 70 additions & 0 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,12 @@ export interface ScheduleOccurrenceRow {
lease_token: string | null
/** Epoch milliseconds at which the lease lapses; null when nobody holds it. */
lease_expires_at: number | null
/**
* #544 slice 8: the command key a run-now press carried; null on an occurrence
* the tick decided. `UNIQUE(schedule_id, command_key)` is what makes the
* button idempotent.
*/
command_key: string | null
}

/** #544 slice 7: one durable notification send. */
Expand Down Expand Up @@ -2064,6 +2070,9 @@ CREATE TABLE IF NOT EXISTS schedule_occurrences (
attempts INTEGER NOT NULL DEFAULT 1,
lease_token TEXT,
lease_expires_at INTEGER,
-- #544 slice 8: a run-now occurrence is named by the command key the button
-- carried, not by a planned instant, so the same key cannot start twice.
command_key TEXT,
UNIQUE(schedule_id, logical_time, timing_revision)
);
CREATE INDEX IF NOT EXISTS schedule_occurrences_lease_idx ON schedule_occurrences(state, lease_expires_at);
Expand Down Expand Up @@ -2460,6 +2469,7 @@ export class Store {
['attempts', 'INTEGER NOT NULL DEFAULT 1'],
['lease_token', 'TEXT'],
['lease_expires_at', 'INTEGER'],
['command_key', 'TEXT'],
]
for (const [name, type] of additions) {
if (!columns.has(name)) this.run(`ALTER TABLE schedule_occurrences ADD COLUMN ${name} ${type}`)
Expand All @@ -2469,6 +2479,9 @@ export class Store {
migrateIndexes(): void {
this.run('CREATE INDEX IF NOT EXISTS quota_ledger_repo_idx ON quota_ledger(repo_id, at DESC)')
this.run('CREATE INDEX IF NOT EXISTS jobs_pr_state_idx ON jobs(pr_state, created_at DESC)')
// #544 slice 8: one occurrence per command key. Partial so the tick's rows
// (command_key NULL) are not collapsed into one another.
this.run('CREATE UNIQUE INDEX IF NOT EXISTS schedule_occurrences_command_idx ON schedule_occurrences(schedule_id, command_key) WHERE command_key IS NOT NULL')
this.ensureOneActiveJobIndex()
}

Expand Down Expand Up @@ -5281,6 +5294,63 @@ export class Store {
return { row, created: Number(result.changes) > 0 }
}

// #544 slice 8: a run-now press is an occurrence too, but its identity is the
// command key the button carried rather than a planned instant. The unique
// index on `(schedule_id, command_key)` is what makes a replay a replay; the
// row is inserted `claimed` and settled by the service with the job it started,
// so a repeated press reads the outcome of the first instead of starting again.
scheduleOccurrenceByCommandKey(scheduleId: string, commandKey: string): ScheduleOccurrenceRow | undefined {
return this.get<ScheduleOccurrenceRow>(
'SELECT * FROM schedule_occurrences WHERE schedule_id = ? AND command_key = ?',
scheduleId, commandKey,
)
}

createRunNowOccurrence(input: {
id: string
scheduleId: string
repoId: string
logicalTime: number
timingRevision: number
commandKey: string
}): { row: ScheduleOccurrenceRow; created: boolean } {
// Two explicit commands in the same millisecond are two instances, so the
// logical time steps forward until the triple is free. The command key is
// checked first: a replay must never be mistaken for a collision.
for (let offset = 0; offset < 1_000; offset += 1) {
const result = this.db.prepare(
`INSERT INTO schedule_occurrences
(id, schedule_id, repo_id, logical_time, timing_revision, state, reason, missed, job_id, decided_at, dispatched_at, lag_ms, command_key)
VALUES (?, ?, ?, ?, ?, 'claimed', NULL, 0, NULL, ?, NULL, NULL, ?)
ON CONFLICT DO NOTHING`,
).run(input.id, input.scheduleId, input.repoId, input.logicalTime + offset, input.timingRevision, nowIso(), input.commandKey)
if (Number(result.changes) > 0) {
const row = this.scheduleOccurrenceByCommandKey(input.scheduleId, input.commandKey)
if (row === undefined) throw new Error(`run-now occurrence ${input.commandKey} disappeared after insert`)
return { row, created: true }
}
const existing = this.scheduleOccurrenceByCommandKey(input.scheduleId, input.commandKey)
if (existing !== undefined) return { row: existing, created: false }
}
throw new Error(`run-now occurrence ${input.commandKey} could not take an instant`)
}

settleRunNowOccurrence(input: {
id: string
state: 'dispatched' | 'skipped'
reason?: string | null
jobId?: string | null
dispatchedAt?: number | null
}): ScheduleOccurrenceRow | undefined {
this.run(
`UPDATE schedule_occurrences
SET state = ?, reason = ?, job_id = ?, dispatched_at = ?, lag_ms = 0
WHERE id = ? AND command_key IS NOT NULL`,
input.state, input.reason ?? null, input.jobId ?? null, input.dispatchedAt ?? null, input.id,
)
return this.get<ScheduleOccurrenceRow>('SELECT * FROM schedule_occurrences WHERE id = ?', input.id)
}

// #544 slice 5: the instants one decision passed over are rows of their own, and
// the cursor that leap-frogs past them moves in the same transaction. Otherwise
// two workers deciding about the same window could both write a catch-up, and a
Expand Down
91 changes: 90 additions & 1 deletion src/jobs/service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createHash } from 'node:crypto'
import type { Config } from '../config.js'
import type { JobRow, RepoRow, SecurityFindingWrite, Store, UserRow } from '../db.js'
import type { JobRow, RepoRow, ScheduleOccurrenceRow, SecurityFindingWrite, Store, UserRow } from '../db.js'
import type { Mailer, MailMessage } from '../email/mailer.js'
import { QuotaNotifier } from '../gateway/notifier.js'
import { quotaView } from '../gateway/quota.js'
Expand Down Expand Up @@ -55,6 +55,7 @@ import { promoteDiscoveredIssue } from './discoveryPromotion.js'
import { buildCarryOver, buildRunDigest, decideNextJob, failureStreak, lastDurationMs, MIN_DISCOVERY_INTERVAL_MINUTES, parseCarryOverLink, type CarryOverReader, type OutputKind } from './continuity.js'
import { isTemporalStatus, summariseDelta, type TemporalDelta, type TemporalStatus } from '../lib/temporal.js'
import { planTick, scheduleFromRow, type TickPlan } from '../schedules/tick.js'
import { parseRunNowKey } from '../schedules/runNow.js'
import { utcDayEnd, utcDayStart } from '../schedules/budget.js'
import type { ScheduleRow } from '../db.js'
import { isImplementedWorkType, missingWorkTypeEvidence, resolveWorkType, workTypeForKind, workTypeMayAutoMerge } from '../lib/workTypes.js'
Expand Down Expand Up @@ -3764,6 +3765,94 @@ export class Jobs {
}
}

// #544 slice 8: the console's Run now button. The press is a command whose
// identity is the key the form carried, so a replay answers the first press
// instead of starting a second run. Two rules make it safe:
// - the occurrence is written before the job, so a crash between the two
// starts nothing twice: the next press with the same key reads the row;
// - the recurrence high water mark (`last_occurrence_at`) is never touched,
// because a person asking for a run now does not move the schedule.
// The occurrence records the same state the tick's rows do (`dispatched` with
// the job, `skipped` with the refusal), so the console and the ledger read one
// vocabulary. A refusal still settles the row: the same key must keep
// answering the same thing.
async runScheduleNow(repo: RepoRow, rawKey: unknown): Promise<{
ok: boolean
code?: string
message?: string
occurrence?: ScheduleOccurrenceRow
replayed?: boolean
jobId?: string | null
}> {
const schedule = this.store.scheduleForRepo(repo.id)
if (schedule === undefined) return { ok: false, code: 'schedule_missing', message: '这个仓库还没有排期。' }
const parsed = parseRunNowKey(rawKey)
if (!parsed.ok) return { ok: false, code: 'command_key_invalid', message: '这次运行的标识无效,请刷新页面后重试。' }
const existing = this.store.scheduleOccurrenceByCommandKey(schedule.id, parsed.key)
if (existing !== undefined) return this.runNowAnswer(existing, true)
const created = this.store.createRunNowOccurrence({
id: randomId('occ'),
scheduleId: schedule.id,
repoId: repo.id,
logicalTime: Date.now(),
timingRevision: schedule.timing_revision,
commandKey: parsed.key,
})
if (!created.created) return this.runNowAnswer(created.row, true)
const result = await this.enqueue(repo, 'manual', undefined, 'iterate', { ownerStarted: true })
const dispatchedAt = Date.now()
if (!result.ok || result.job === undefined) {
const reason = result.code ?? 'dispatch-refused'
const settled = this.store.settleRunNowOccurrence({ id: created.row.id, state: 'skipped', reason, dispatchedAt })
this.store.audit(repo.user_id, 'schedule.run_now', `${repo.id}: ${parsed.key} skipped ${reason}`)
return {
ok: false,
code: reason,
message: result.error ?? '这次运行没有开始。',
...(settled === undefined ? {} : { occurrence: settled }),
replayed: false,
jobId: null,
}
}
const settled = this.store.settleRunNowOccurrence({
id: created.row.id,
state: 'dispatched',
jobId: result.job.id,
dispatchedAt,
})
this.store.audit(repo.user_id, 'schedule.run_now', `${repo.id}: ${parsed.key} -> ${result.job.id}`)
return {
ok: true,
...(settled === undefined ? {} : { occurrence: settled }),
replayed: false,
jobId: result.job.id,
}
}

// A replay and a fresh dispatch answer the same shape, read from the row the
// first press settled. `replayed` is the only difference, so the page can say
// "already started" without pretending it started again.
private runNowAnswer(row: ScheduleOccurrenceRow, replayed: boolean): {
ok: boolean
code?: string
message?: string
occurrence: ScheduleOccurrenceRow
replayed: boolean
jobId: string | null
} {
if (row.state === 'dispatched') {
return { ok: true, occurrence: row, replayed, jobId: row.job_id }
}
return {
ok: false,
code: row.reason ?? 'dispatch-refused',
message: '这次运行没有开始。',
occurrence: row,
replayed,
jobId: row.job_id,
}
}

async tick(): Promise<void> {
if (this.stopped || this.ticking) return
this.ticking = true
Expand Down
3 changes: 3 additions & 0 deletions src/lib/routeClasses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ const EXPENSIVE_ROUTE_LIST = [
'POST /repos/:id/models/apply',
'POST /repos/:id/schedule',
'POST /repos/:id/schedule/remove',
// #544 slice 8: run-now starts a job the moment the maintainer asks, so it is
// a start of real work like the schedule save beside it.
'POST /repos/:id/schedule/run-now',
'POST /repos/:id/release',
'POST /repos/:id/releases/:releaseId/check',
'POST /repos/:id/gate/sessions',
Expand Down
26 changes: 26 additions & 0 deletions src/schedules/runNow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// #544 slice 8: "Run now" is an explicit command, not a moved cursor.
//
// The card asks for one property: the same command key returns the same
// occurrence, and a new key is a distinct instance. The key is the identity the
// console form carries, so it has to be bounded and opaque before it reaches a
// unique index: an empty key would make every press the same press, and an
// unbounded one would let a client grow a row key by key.
export const RUN_NOW_KEY_MAX = 80

export type RunNowKeyReason = 'empty' | 'too-long' | 'invalid'

export type RunNowKey =
| { ok: true; key: string }
| { ok: false; reason: RunNowKeyReason }

// Letters, digits, `:`, `_` and `-` — the shape `randomId('cmd')` produces, and
// narrow enough that a key cannot carry a path or a sentence into the ledger.
const KEY_SHAPE = /^[A-Za-z0-9:_-]+$/

export function parseRunNowKey(raw: unknown): RunNowKey {
const value = typeof raw === 'string' ? raw.trim() : ''
if (value === '') return { ok: false, reason: 'empty' }
if (value.length > RUN_NOW_KEY_MAX) return { ok: false, reason: 'too-long' }
if (!KEY_SHAPE.test(value)) return { ok: false, reason: 'invalid' }
return { ok: true, key: value }
}
9 changes: 8 additions & 1 deletion src/views/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4635,10 +4635,11 @@ export function scheduleConsolePage(input: {
repo: RepoRow
state: ScheduleConsoleState
form: { cron: string; every: string; timezone: string; startAt: string; endAt: string; misfire: string; grace: string; dailyRuns: string }
runNowKey: string
notice?: string
error?: string
}): string {
const { config, locale, viewer, repo, state, form, notice, error } = input
const { config, locale, viewer, repo, state, form, runNowKey, notice, error } = input
const t = translator(locale)
const iso = (at: number | null): string => (at === null ? 'unknown' : new Date(at).toISOString())
const shown = (at: number | null): string => (at === null ? t('unknown', 'unknown') : humanTimeShort(new Date(at).toISOString()))
Expand Down Expand Up @@ -4671,6 +4672,11 @@ export function scheduleConsolePage(input: {
</tr>`).join('')
const field = (name: string, label: string, value: string, placeholder: string): string =>
`<label>${escapeHtml(label)} <input name="${escapeHtml(name)}" value="${escapeHtml(value)}" placeholder="${escapeHtml(placeholder)}" /></label>`
// #544 slice 8: run-now is only offered when a schedule exists and can be read;
// a repository without one has no cadence to run out of turn.
const runNow = state.kind === 'none' || state.kind === 'unreadable'
? ''
: `<form method="post" action="/repos/${escapeHtml(repo.id)}/schedule/run-now" class="run-now">${csrf(viewer)}<input type="hidden" name="command_key" value="${escapeHtml(runNowKey)}" /><button type="submit">${escapeHtml(t('立即运行', 'Run now'))}</button><span class="fine">${escapeHtml(t('从当前时刻开始一次,不改动下次运行。', 'One run from now; the next scheduled run does not move.'))}</span></form>`
const kindNote = state.kind === 'none'
? `<p class="muted">${escapeHtml(t('这个仓库还没有排期;它仍按旧的自动间隔运行。保存一个排期后,由排期决定何时运行。', 'This repository has no schedule yet and still runs on the legacy interval. Once a schedule is saved, the schedule decides when it runs.'))}</p>`
: state.kind === 'unreadable'
Expand All @@ -4691,6 +4697,7 @@ export function scheduleConsolePage(input: {
<dt>${escapeHtml(t('宽限', 'Grace'))}</dt><dd data-schedule-grace="${escapeHtml(state.graceMs === null ? 'none' : String(state.graceMs))}">${escapeHtml(state.graceMs === null ? t('不限(默认)', 'unbounded (default)') : t(`${Math.round(state.graceMs / 60_000)} 分钟`, `${Math.round(state.graceMs / 60_000)} minutes`))}</dd>
<dt>${escapeHtml(t('每日运行上限', 'Daily run limit'))}</dt><dd data-schedule-daily-runs="${escapeHtml(state.budget.dailyRuns === null ? 'none' : String(state.budget.dailyRuns))}">${escapeHtml(state.budget.dailyRuns === null ? t('不限(默认)', 'unbounded (default)') : t(`${state.budget.dailyRuns} 次`, `${state.budget.dailyRuns} runs`))} · ${escapeHtml(state.budget.runsToday === null ? t('今天已运行 unknown', 'today unknown') : t(`今天已运行 ${state.budget.runsToday} 次`, `${state.budget.runsToday} today`))}${state.budget.remaining === null ? '' : ` · ${escapeHtml(t(`今天还剩 ${state.budget.remaining} 次`, `${state.budget.remaining} left today`))}`}</dd>
</dl>
${runNow}
</section>
<section class="card"><h2>${escapeHtml(t('编辑排期', 'Edit the schedule'))}</h2>
<p class="muted">${escapeHtml(t('排期是五字段 cron 或固定间隔,二选一;cron 需要 IANA 时区。开始/结束时间要带偏移。', 'A schedule is a five-field cron or a fixed interval, one of the two; cron needs an IANA zone. The start/end instants need an offset.'))}</p>
Expand Down
Loading
Loading