feat(ql3): establish 3.0 incubation baseline

This commit is contained in:
whyour committed 2026-08-12 00:25:26 +08:00
1 parent 4bf92dcfeb
commit c699c32461
2817 files changed
+779642 -653

No files matched your search

@@ -0,0 +1,445 @@
// PostgreSQL authority adapter for cluster run recovery claim ownership.
import { randomUUID } from 'node:crypto';
import {
ClusterControlRecoveryStoreError,
MAX_CLUSTER_CONTROL_RECOVERY_CLAIM_LEASE_MS,
MAX_CLUSTER_CONTROL_RECOVERY_CLAIMS_PER_PASS,
MAX_CLUSTER_CONTROL_RECOVERY_RETRY_DELAY_MS,
type ClusterControlRecoveryCandidate,
type ClusterControlRecoveryClaim,
type ClusterControlRecoveryClaimPage,
type ClusterControlRecoveryClaimRepository,
type ClusterControlRecoveryDisposition,
type ClusterControlRecoverySource,
type PostgresPool,
type PostgresQueryable,
} from '@qinglong/runtime-core';
import { PostgresClusterControlRecoverySource } from './clusterRecoverySource';
type ClaimRow = Record<string, unknown> & {
targetKind: unknown;
targetId: unknown;
runId: unknown;
targetStatus: unknown;
targetCreatedAtMs: unknown;
observedAtMs: unknown;
claimOwner: unknown;
claimToken: unknown;
claimVersion: unknown;
claimExpiresAtMs: unknown;
};
const UPSERT_DISCOVERED_SQL = `
INSERT INTO "ql3"."run_recovery_controls" (
target_kind, target_id, run_id, attempt_id, target_status,
target_created_at_ms, observed_at_ms, state, claim_version,
failure_count, created_at_ms, updated_at_ms
)
SELECT
discovered.kind,
discovered.id,
discovered."runId",
CASE WHEN discovered.kind = 'attempt' THEN discovered.id ELSE NULL END,
discovered.status,
discovered."createdAtMs",
$2::bigint,
'available',
0,
0,
$2::bigint,
$2::bigint
FROM jsonb_to_recordset($1::jsonb) AS discovered(
kind varchar(16),
id varchar(36),
"runId" varchar(36),
status varchar(32),
"createdAtMs" bigint
)
ON CONFLICT (target_kind, target_id) DO UPDATE
SET run_id = EXCLUDED.run_id,
attempt_id = EXCLUDED.attempt_id,
target_status = EXCLUDED.target_status,
target_created_at_ms = EXCLUDED.target_created_at_ms,
observed_at_ms = EXCLUDED.observed_at_ms,
updated_at_ms = GREATEST(
"ql3"."run_recovery_controls".updated_at_ms,
EXCLUDED.updated_at_ms
)
`.trim();
const CLAIM_DISCOVERED_SQL = `
WITH discovered AS (
SELECT kind, id
FROM jsonb_to_recordset($1::jsonb) AS payload(
kind varchar(16),
id varchar(36)
)
), eligible AS (
SELECT control.target_kind, control.target_id
FROM "ql3"."run_recovery_controls" AS control
INNER JOIN discovered
ON discovered.kind = control.target_kind
AND discovered.id = control.target_id
WHERE control.claim_version < 2147483647
AND (
control.state IN ('available', 'resolved')
OR (control.state = 'retry' AND control.next_claim_at_ms <= $2::bigint)
OR (
control.state = 'claimed'
AND control.claim_expires_at_ms <= $2::bigint
)
)
ORDER BY control.target_created_at_ms, control.target_kind, control.target_id
FOR UPDATE OF control SKIP LOCKED
LIMIT $3
)
UPDATE "ql3"."run_recovery_controls" AS control
SET state = 'claimed',
claim_owner = $4,
claim_token = $5,
claim_version = control.claim_version + 1,
claim_expires_at_ms = $2::bigint + $6::bigint,
next_claim_at_ms = NULL,
updated_at_ms = GREATEST(control.updated_at_ms, $2::bigint)
FROM eligible
WHERE control.target_kind = eligible.target_kind
AND control.target_id = eligible.target_id
RETURNING
control.target_kind AS "targetKind",
control.target_id AS "targetId",
control.run_id AS "runId",
control.target_status AS "targetStatus",
control.target_created_at_ms AS "targetCreatedAtMs",
control.observed_at_ms AS "observedAtMs",
control.claim_owner AS "claimOwner",
control.claim_token AS "claimToken",
control.claim_version AS "claimVersion",
control.claim_expires_at_ms AS "claimExpiresAtMs"
`.trim();
const SETTLE_SQL = `
WITH observation AS (
SELECT floor(
extract(epoch FROM statement_timestamp()) * 1000
)::bigint AS observed_at_ms
)
UPDATE "ql3"."run_recovery_controls" AS control
SET state = $6::varchar(16),
claim_owner = NULL,
claim_token = NULL,
claim_expires_at_ms = NULL,
next_claim_at_ms = CASE
WHEN $6::varchar(16) = 'retry' THEN observation.observed_at_ms + $7::bigint
ELSE NULL
END,
failure_count = CASE
WHEN $6::varchar(16) IN ('retry', 'manual')
THEN LEAST(control.failure_count + 1, 2147483647)
ELSE control.failure_count
END,
updated_at_ms = GREATEST(
control.updated_at_ms,
observation.observed_at_ms
)
FROM observation
WHERE control.target_kind = $1
AND control.target_id = $2
AND control.state = 'claimed'
AND control.claim_owner = $3
AND control.claim_token = $4
AND control.claim_version = $5
AND control.claim_expires_at_ms > observation.observed_at_ms
RETURNING control.target_id AS "targetId"
`.trim();
function integerInRange(
name: string,
value: number,
minimum: number,
maximum: number,
): number {
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
throw new RangeError(`${name} must be between ${minimum} and ${maximum}`);
}
return value;
}
function safeIdentifier(name: string, value: string, maximum: number): string {
const pattern = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,${maximum - 1}}$`);
if (!pattern.test(value)) {
throw new TypeError(`${name} is invalid`);
}
return value;
}
function safeInteger(name: string, value: unknown, minimum = 0): number {
const converted =
typeof value === 'string' && /^[0-9]+$/.test(value) ? Number(value) : value;
if (
typeof converted !== 'number' ||
!Number.isSafeInteger(converted) ||
converted < minimum
) {
throw new TypeError(`${name} is invalid`);
}
return converted;
}
function nonemptyString(name: string, value: unknown): string {
if (typeof value !== 'string' || value.length === 0) {
throw new TypeError(`${name} is invalid`);
}
return value;
}
function candidateFromRow(row: ClaimRow): ClusterControlRecoveryCandidate {
const kind = row.targetKind;
const id = nonemptyString('PostgreSQL recovery targetId', row.targetId);
const runId = nonemptyString('PostgreSQL recovery runId', row.runId);
const status = nonemptyString(
'PostgreSQL recovery targetStatus',
row.targetStatus,
);
const createdAtMs = safeInteger(
'PostgreSQL recovery targetCreatedAtMs',
row.targetCreatedAtMs,
);
if (
kind === 'run' &&
['created', 'dispatching', 'running'].includes(status)
) {
return Object.freeze({
kind,
id,
runId,
status: status as 'created' | 'dispatching' | 'running',
createdAtMs,
});
}
if (
kind === 'attempt' &&
['claimed', 'starting', 'running'].includes(status)
) {
return Object.freeze({
kind,
id,
runId,
status: status as 'claimed' | 'starting' | 'running',
createdAtMs,
});
}
throw new TypeError('PostgreSQL recovery claim target is invalid');
}
function claimFromRow(row: ClaimRow): ClusterControlRecoveryClaim {
const observedAtMs = safeInteger(
'PostgreSQL recovery observedAtMs',
row.observedAtMs,
);
const expiresAtMs = safeInteger(
'PostgreSQL recovery claimExpiresAtMs',
row.claimExpiresAtMs,
observedAtMs + 1,
);
return Object.freeze({
candidate: candidateFromRow(row),
observedAtMs,
ownerId: safeIdentifier(
'PostgreSQL recovery claimOwner',
nonemptyString('PostgreSQL recovery claimOwner', row.claimOwner),
128,
),
token: safeIdentifier(
'PostgreSQL recovery claimToken',
nonemptyString('PostgreSQL recovery claimToken', row.claimToken),
64,
),
version: safeInteger(
'PostgreSQL recovery claimVersion',
row.claimVersion,
1,
),
expiresAtMs,
});
}
function settlement(
disposition: ClusterControlRecoveryDisposition,
): readonly ['resolved' | 'retry' | 'manual', number] {
if (disposition.status === 'resolved' || disposition.status === 'manual') {
return [disposition.status, 0] as const;
}
if (disposition.status === 'retry') {
return [
'retry',
integerInRange(
'Cluster-control recovery retry delay',
disposition.delayMs,
0,
MAX_CLUSTER_CONTROL_RECOVERY_RETRY_DELAY_MS,
),
] as const;
}
throw new TypeError('Cluster-control recovery disposition is invalid');
}
function assertSettlementClaim(claim: ClusterControlRecoveryClaim): void {
safeIdentifier('Cluster-control recovery ownerId', claim.ownerId, 128);
safeIdentifier('Cluster-control recovery token', claim.token, 64);
integerInRange(
'Cluster-control recovery claim version',
claim.version,
1,
2147483647,
);
if (
!claim.candidate ||
!['run', 'attempt'].includes(claim.candidate.kind) ||
typeof claim.candidate.id !== 'string' ||
claim.candidate.id.length === 0
) {
throw new TypeError('Cluster-control recovery claim target is invalid');
}
}
export class PostgresClusterControlRecoveryClaimRepository
implements ClusterControlRecoveryClaimRepository
{
constructor(
private readonly pool: PostgresPool,
private readonly createToken: () => string = randomUUID,
private readonly createSource: (
queryable: PostgresQueryable,
) => ClusterControlRecoverySource = (queryable) =>
new PostgresClusterControlRecoverySource(queryable),
) {
if (
!pool ||
typeof pool.connect !== 'function' ||
typeof createToken !== 'function' ||
typeof createSource !== 'function'
) {
throw new TypeError('PostgreSQL recovery claim repository is invalid');
}
}
async claim(
options: Readonly<{
ownerId: string;
limit: number;
leaseMs: number;
}>,
): Promise<ClusterControlRecoveryClaimPage> {
const ownerId = safeIdentifier(
'Cluster-control recovery ownerId',
options.ownerId,
128,
);
const limit = integerInRange(
'Cluster-control recovery claim limit',
options.limit,
1,
MAX_CLUSTER_CONTROL_RECOVERY_CLAIMS_PER_PASS,
);
const leaseMs = integerInRange(
'Cluster-control recovery claim lease',
options.leaseMs,
1_000,
MAX_CLUSTER_CONTROL_RECOVERY_CLAIM_LEASE_MS,
);
const token = safeIdentifier(
'Cluster-control recovery generated token',
this.createToken(),
64,
);
if (token.length < 16) {
throw new TypeError(
'Cluster-control recovery generated token must be at least 16 characters',
);
}
const client = await this.pool.connect().catch((error: unknown) => {
throw new ClusterControlRecoveryStoreError(error);
});
let transactionOpen = false;
try {
await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
transactionOpen = true;
await client.query("SET LOCAL statement_timeout = '5000ms'");
await client.query("SET LOCAL lock_timeout = '1000ms'");
const source = this.createSource(client);
if (!source || typeof source.listOutstanding !== 'function') {
throw new TypeError('PostgreSQL recovery source factory is invalid');
}
const page = await source.listOutstanding(limit);
const payload = JSON.stringify(page.candidates);
if (page.candidates.length > 0) {
await client.query(UPSERT_DISCOVERED_SQL, [payload, page.observedAtMs]);
}
const result =
page.candidates.length === 0
? { rows: [] as readonly ClaimRow[] }
: await client.query<ClaimRow>(CLAIM_DISCOVERED_SQL, [
payload,
page.observedAtMs,
limit,
ownerId,
token,
leaseMs,
]);
const claims = result.rows.map(claimFromRow);
if (claims.length > page.candidates.length || claims.length > limit) {
throw new TypeError(
'PostgreSQL recovery claim query violated its bounded result contract',
);
}
await client.query('COMMIT');
transactionOpen = false;
return Object.freeze({
claims: Object.freeze(claims),
discovered: page.candidates.length,
hasMore: page.hasMore,
});
} catch (error) {
if (transactionOpen) {
try {
await client.query('ROLLBACK');
} catch {
// Preserve the originating failure; the connection is released below.
}
}
if (error instanceof ClusterControlRecoveryStoreError) throw error;
throw new ClusterControlRecoveryStoreError(error);
} finally {
client.release();
}
}
async settle(
claim: ClusterControlRecoveryClaim,
disposition: ClusterControlRecoveryDisposition,
): Promise<'settled' | 'fenced'> {
assertSettlementClaim(claim);
const [state, delayMs] = settlement(disposition);
try {
const result = await this.pool.query(SETTLE_SQL, [
claim.candidate.kind,
claim.candidate.id,
claim.ownerId,
claim.token,
claim.version,
state,
delayMs,
]);
const rowCount = result.rowCount ?? result.rows.length;
if (rowCount === 0) return 'fenced';
if (rowCount === 1) return 'settled';
throw new TypeError(
'PostgreSQL recovery settlement updated more than one target',
);
} catch (error) {
if (error instanceof ClusterControlRecoveryStoreError) throw error;
throw new ClusterControlRecoveryStoreError(error);
}
}
}
@@ -0,0 +1,640 @@
// PostgreSQL authority adapter for cluster run recovery resolution.
import { randomUUID } from 'node:crypto';
import {
ClusterControlRecoveryStoreError,
buildClusterControlRecoveryLostTransition,
buildPluginPackageWorkflowTaskRecovery,
type ClusterControlRecoveryClaim,
type ClusterControlRecoveryLostAction,
type ClusterControlRecoveryResolutionRepository,
type ClusterControlRecoverySnapshot,
type PostgresClient,
type PostgresPool,
type RunAttemptRecord,
type RunEventRecord,
type RunRecord,
} from '@qinglong/runtime-core';
import type {
PluginPackageWorkflowTaskAttemptAdmissionReceipt,
} from '@qinglong/runtime-core/plugin-package-workflow-task-attempt-admission';
import type {
StepRunMutation,
StepRunRecord,
} from '@qinglong/runtime-core/step-run';
import { lockAttemptAuthority } from '../run/attemptAuthorityLock';
import { PostgresRunTransaction } from '../run/runRepository';
type ObservationRow = Record<string, unknown> & {
observedAtMs: unknown;
};
type WorkflowTaskRow = Record<string, unknown> & {
admissionJson: unknown;
stepRunJson: unknown;
};
const LOAD_FENCE_SQL = `
WITH observation AS (
SELECT floor(
extract(epoch FROM statement_timestamp()) * 1000
)::bigint AS observed_at_ms
)
SELECT observation.observed_at_ms AS "observedAtMs"
FROM "ql3"."run_recovery_controls" AS control
CROSS JOIN observation
WHERE control.target_kind = $1
AND control.target_id = $2
AND control.state = 'claimed'
AND control.claim_owner = $3
AND control.claim_token = $4
AND control.claim_version = $5
AND control.claim_expires_at_ms > observation.observed_at_ms
`.trim();
const LOCK_FENCE_SQL = `${LOAD_FENCE_SQL}
FOR UPDATE OF control`.trim();
const TRANSACTION_STATEMENT_TIMEOUT_MS = 5_000;
const TRANSACTION_LOCK_TIMEOUT_MS = 1_000;
const TRANSACTION_IDLE_TIMEOUT_MS = 10_000;
class RecoverySnapshotStaleError extends Error {}
function observedAtMs(value: unknown): number {
const converted =
typeof value === 'string' && /^[0-9]+$/.test(value) ? Number(value) : value;
if (
typeof converted !== 'number' ||
!Number.isSafeInteger(converted) ||
converted < 0
) {
throw new TypeError(
'PostgreSQL recovery resolution observation is invalid',
);
}
return converted;
}
function oneObservation(rows: readonly ObservationRow[]): number | null {
if (rows.length === 0) return null;
if (rows.length !== 1) {
throw new TypeError(
'PostgreSQL recovery resolution returned duplicate control rows',
);
}
return observedAtMs(rows[0]!.observedAtMs);
}
function frozenRun(run: RunRecord | null): Readonly<RunRecord> | null {
return run === null ? null : Object.freeze({ ...run });
}
function frozenAttempt(
attempt: RunAttemptRecord | null,
): Readonly<RunAttemptRecord> | null {
return attempt === null ? null : Object.freeze({ ...attempt });
}
async function readSnapshot(
client: PostgresClient,
runs: PostgresRunTransaction,
claim: ClusterControlRecoveryClaim,
observation: number,
): Promise<ClusterControlRecoverySnapshot> {
const run = await runs.findRunById(claim.candidate.runId);
const attempt =
claim.candidate.kind === 'attempt'
? await runs.findAttemptById(claim.candidate.id)
: await runs.findLatestAttemptByRunId(claim.candidate.runId);
let workflowTask:
| Readonly<{
admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
stepRun: Readonly<StepRunRecord>;
}>
| null = null;
if (claim.candidate.kind === 'attempt') {
const result = await client.query<WorkflowTaskRow>(
`SELECT admission.receipt_json AS "admissionJson",
step.step_run_json AS "stepRunJson"
FROM "ql3"."plugin_package_workflow_task_attempt_admissions"
AS admission
JOIN "ql3"."step_runs" AS step
ON step.id = admission.step_run_id
AND step.run_id = admission.run_id
WHERE admission.attempt_id = $1
AND admission.run_id = $2
LIMIT 2`,
[claim.candidate.id, claim.candidate.runId],
);
if (result.rows.length > 1) {
throw new TypeError(
'PostgreSQL recovery returned duplicate Workflow Task authority',
);
}
const row = result.rows[0];
if (row) {
if (
!row.admissionJson ||
typeof row.admissionJson !== 'object' ||
Array.isArray(row.admissionJson) ||
!row.stepRunJson ||
typeof row.stepRunJson !== 'object' ||
Array.isArray(row.stepRunJson)
) {
throw new TypeError(
'PostgreSQL recovery returned invalid Workflow Task authority',
);
}
workflowTask = Object.freeze({
admission: Object.freeze({
...(row.admissionJson as
PluginPackageWorkflowTaskAttemptAdmissionReceipt),
}),
stepRun: Object.freeze({
...(row.stepRunJson as StepRunRecord),
}),
});
}
}
return Object.freeze({
observedAtMs: observation,
run: frozenRun(run),
attempt: frozenAttempt(attempt),
workflowTask,
});
}
function sameRun(
expected: Readonly<RunRecord> | null,
current: Readonly<RunRecord> | null,
): boolean {
if (expected === null || current === null) return expected === current;
return (
expected.id === current.id &&
expected.executionOwner === current.executionOwner &&
expected.status === current.status &&
expected.version === current.version &&
expected.eventSequence === current.eventSequence &&
expected.createdAtMs === current.createdAtMs &&
expected.startedAtMs === current.startedAtMs &&
expected.cancelRequestedAtMs === current.cancelRequestedAtMs &&
expected.cancelReason === current.cancelReason
);
}
function sameAttempt(
expected: Readonly<RunAttemptRecord> | null,
current: Readonly<RunAttemptRecord> | null,
): boolean {
if (expected === null || current === null) return expected === current;
return (
expected.id === current.id &&
expected.runId === current.runId &&
expected.stepRunId === current.stepRunId &&
expected.attempt === current.attempt &&
expected.status === current.status &&
expected.executorType === current.executorType &&
expected.workerId === current.workerId &&
expected.workerSessionId === current.workerSessionId &&
expected.workerGeneration === current.workerGeneration &&
expected.executorHandle === current.executorHandle &&
expected.pid === current.pid &&
expected.leaseToken === current.leaseToken &&
expected.leaseTokenDigest === current.leaseTokenDigest &&
expected.leaseGeneration === current.leaseGeneration &&
expected.leaseVersion === current.leaseVersion &&
expected.leaseExpiresAtMs === current.leaseExpiresAtMs &&
expected.offerId === current.offerId &&
expected.deadlineAtMs === current.deadlineAtMs &&
expected.callbackTokenHash === current.callbackTokenHash &&
expected.callbackSequence === current.callbackSequence &&
expected.createdAtMs === current.createdAtMs &&
expected.startedAtMs === current.startedAtMs &&
expected.finishedAtMs === current.finishedAtMs &&
expected.exitCode === current.exitCode &&
expected.errorCode === current.errorCode &&
expected.errorSummary === current.errorSummary
);
}
function sameWorkflowTask(
expected: ClusterControlRecoverySnapshot['workflowTask'],
current: ClusterControlRecoverySnapshot['workflowTask'],
): boolean {
const left = expected ?? null;
const right = current ?? null;
if (left === null || right === null) return left === right;
return (
left.admission.receiptDigest === right.admission.receiptDigest &&
left.admission.attemptId === right.admission.attemptId &&
left.admission.runId === right.admission.runId &&
left.admission.stepRunId === right.admission.stepRunId &&
left.stepRun.id === right.stepRun.id &&
left.stepRun.runId === right.stepRun.runId &&
left.stepRun.status === right.stepRun.status &&
left.stepRun.version === right.stepRun.version &&
left.stepRun.stepRunDigest === right.stepRun.stepRunDigest
);
}
function sameSnapshot(
expected: ClusterControlRecoverySnapshot,
current: ClusterControlRecoverySnapshot,
): boolean {
return (
sameRun(expected.run, current.run) &&
sameAttempt(expected.attempt, current.attempt) &&
sameWorkflowTask(expected.workflowTask, current.workflowTask)
);
}
function eventRecord(
id: string,
ownerId: string,
createdAtMs: number,
draft: Readonly<
Omit<RunEventRecord, 'id' | 'actorType' | 'actorId' | 'createdAtMs'>
>,
): RunEventRecord {
return {
...draft,
id,
actorType: 'reconciler',
actorId: ownerId,
createdAtMs,
};
}
function eventId(createEventId: () => string): string {
const id = createEventId();
if (typeof id !== 'string' || id.length < 1 || id.length > 36) {
throw new TypeError('PostgreSQL recovery event id is invalid');
}
return id;
}
async function releaseExpiredDispatchLease(
client: PostgresClient,
attempt: Readonly<RunAttemptRecord>,
observation: number,
): Promise<number | undefined> {
if (
attempt.leaseVersion === undefined ||
attempt.leaseGeneration === undefined
) {
return undefined;
}
if (attempt.leaseVersion >= 2_147_483_647) {
throw new RecoverySnapshotStaleError();
}
const nextVersion = attempt.leaseVersion + 1;
const result = await client.query(
`UPDATE "ql3"."run_dispatch_leases"
SET status = 'released', version = $2, released_at_ms = $3,
release_reason = 'lease_expired', completed_at_ms = NULL,
updated_at_ms = $3
WHERE attempt_id = $1
AND status = 'leased'
AND version = $4
AND lease_generation = $5
AND expires_at_ms <= $3`,
[
attempt.id,
nextVersion,
observation,
attempt.leaseVersion,
attempt.leaseGeneration,
],
);
if ((result.rowCount ?? result.rows.length) !== 1) {
throw new RecoverySnapshotStaleError();
}
return nextVersion;
}
function withReleasedLeaseVersion(
attempt: Readonly<RunAttemptRecord>,
leaseVersion: number | undefined,
): Readonly<RunAttemptRecord> {
return leaseVersion === undefined
? attempt
: Object.freeze({ ...attempt, leaseVersion });
}
async function compareAndSetWorkflowRun(
client: PostgresClient,
current: Readonly<RunRecord>,
next: Readonly<RunRecord>,
): Promise<boolean> {
const result = await client.query(
`UPDATE "ql3"."runs"
SET version = $2, event_sequence = $3
WHERE id = $1 AND status = 'running'
AND execution_owner = 'runtime'
AND trigger_type = 'plugin_package_workflow'
AND cancel_requested_at_ms IS NULL
AND version = $4 AND event_sequence = $5`,
[
current.id,
next.version,
next.eventSequence,
current.version,
current.eventSequence,
],
);
return (result.rowCount ?? result.rows.length) === 1;
}
async function updateWorkflowStepRun(
client: PostgresClient,
mutation: Readonly<StepRunMutation>,
): Promise<void> {
const stepRun = mutation.stepRun;
const updated = await client.query(
`UPDATE "ql3"."step_runs"
SET status = $1, version = $2, attempt_count = $3, output_ref = $4,
approval_request_id = $5, ready_at_ms = $6, started_at_ms = $7,
finished_at_ms = $8, result_code = $9, error_summary = $10,
updated_at_ms = $11, last_mutation_id = $12,
step_run_digest = $13, step_run_json = $14::jsonb
WHERE id = $15 AND run_id = $16 AND version = $17
AND step_run_digest = $18 AND status = $19`,
[
stepRun.status,
stepRun.version,
stepRun.attemptCount,
stepRun.outputRef,
stepRun.approvalRequestId,
stepRun.readyAtMs,
stepRun.startedAtMs,
stepRun.finishedAtMs,
stepRun.resultCode,
stepRun.errorSummary,
stepRun.updatedAtMs,
stepRun.lastMutationId,
stepRun.stepRunDigest,
JSON.stringify(stepRun),
stepRun.id,
stepRun.runId,
mutation.expectedStepRunVersion,
mutation.expectedStepRunDigest,
mutation.previousStatus,
],
);
if ((updated.rowCount ?? updated.rows.length) !== 1) {
throw new RecoverySnapshotStaleError();
}
}
async function appendWorkflowStepMutation(
client: PostgresClient,
mutation: Readonly<StepRunMutation>,
committedAtMs: number,
): Promise<void> {
const event = mutation.event;
await client.query(
`INSERT INTO "ql3"."run_events" (
id, run_id, sequence, type, dedupe_key, actor_type, actor_id,
attempt_id, step_run_id, payload, created_at_ms
) VALUES ($1, $2, $3, $4, $5, $6, $7, NULL, $8, $9::jsonb, $10)`,
[
event.id,
event.runId,
event.sequence,
event.type,
event.dedupeKey ?? null,
event.actorType,
event.actorId ?? null,
mutation.stepRun.id,
JSON.stringify(event.payload),
event.createdAtMs,
],
);
await client.query(
`INSERT INTO "ql3"."step_run_mutations" (
mutation_id, mutation_digest, run_id, step_run_id, step_run_digest,
event_id, event_sequence, run_version, step_run_json, committed_at_ms
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10)`,
[
mutation.mutationId,
mutation.mutationDigest,
mutation.runId,
mutation.stepRun.id,
mutation.stepRun.stepRunDigest,
event.id,
event.sequence,
mutation.expectedRunVersion + 1,
JSON.stringify(mutation.stepRun),
committedAtMs,
],
);
}
export class PostgresClusterControlRecoveryResolutionRepository
implements ClusterControlRecoveryResolutionRepository
{
constructor(
private readonly pool: PostgresPool,
private readonly createEventId: () => string = randomUUID,
) {}
load(
claim: ClusterControlRecoveryClaim,
): Promise<ClusterControlRecoverySnapshot | 'fenced'> {
return this.transaction(async (client, runs) => {
const result = await client.query<ObservationRow>(LOAD_FENCE_SQL, [
claim.candidate.kind,
claim.candidate.id,
claim.ownerId,
claim.token,
claim.version,
]);
const observation = oneObservation(result.rows);
if (observation === null) return 'fenced';
return readSnapshot(client, runs, claim, observation);
});
}
async applyLost(
claim: ClusterControlRecoveryClaim,
snapshot: ClusterControlRecoverySnapshot,
action: ClusterControlRecoveryLostAction,
): Promise<'applied' | 'stale' | 'fenced'> {
try {
return await this.transaction(async (client, runs) => {
const result = await client.query<ObservationRow>(LOCK_FENCE_SQL, [
claim.candidate.kind,
claim.candidate.id,
claim.ownerId,
claim.token,
claim.version,
]);
const observation = oneObservation(result.rows);
if (observation === null) return 'fenced';
if (claim.candidate.kind === 'attempt') {
await lockAttemptAuthority(client, claim.candidate.id);
}
const current = await readSnapshot(
client,
runs,
claim,
observation,
);
if (!sameSnapshot(snapshot, current)) return 'stale';
if (!current.run) return 'stale';
if (action.kind === 'recover_workflow_task') {
if (!current.attempt || !current.workflowTask) {
throw new RecoverySnapshotStaleError();
}
const recovery = buildPluginPackageWorkflowTaskRecovery({
admission: current.workflowTask.admission,
run: current.run,
attempt: current.attempt,
stepRun: current.workflowTask.stepRun,
reason: action.reason,
observedAtMs: observation,
});
const releasedLeaseVersion = await releaseExpiredDispatchLease(
client,
current.attempt,
observation,
);
const recoveredAttempt = withReleasedLeaseVersion(
recovery.attempt,
releasedLeaseVersion,
);
if (
!(await compareAndSetWorkflowRun(
client,
current.run,
recovery.run,
)) ||
!(await runs.compareAndSetAttempt(recoveredAttempt, {
status: current.attempt.status,
callbackSequence: current.attempt.callbackSequence,
}))
) {
throw new RecoverySnapshotStaleError();
}
await runs.appendEvent(recovery.attemptEvent);
for (const mutation of recovery.stepMutations) {
await updateWorkflowStepRun(client, mutation);
await appendWorkflowStepMutation(
client,
mutation,
observation,
);
}
return 'applied';
}
if (current.workflowTask) {
throw new RecoverySnapshotStaleError();
}
const transition = buildClusterControlRecoveryLostTransition(
current.run,
current.attempt,
action,
observation,
);
let persistedRun = current.run;
if (transition.attempt) {
if (!current.attempt) throw new RecoverySnapshotStaleError();
const releasedLeaseVersion = await releaseExpiredDispatchLease(
client,
current.attempt,
observation,
);
const recoveredAttempt = withReleasedLeaseVersion(
transition.attempt.attempt,
releasedLeaseVersion,
);
if (
!(await runs.compareAndSetRun(
transition.attempt.run,
persistedRun.version,
)) ||
!(await runs.compareAndSetAttempt(recoveredAttempt, {
status: current.attempt.status,
callbackSequence: current.attempt.callbackSequence,
}))
) {
throw new RecoverySnapshotStaleError();
}
await runs.appendEvent(
eventRecord(
eventId(this.createEventId),
claim.ownerId,
observation,
transition.attempt.event,
),
);
persistedRun = transition.attempt.run;
}
if (transition.run) {
if (
!(await runs.compareAndSetRun(
transition.run.run,
persistedRun.version,
))
) {
throw new RecoverySnapshotStaleError();
}
await runs.appendEvent(
eventRecord(
eventId(this.createEventId),
claim.ownerId,
observation,
transition.run.event,
),
);
}
return 'applied';
});
} catch (error) {
if (error instanceof RecoverySnapshotStaleError) return 'stale';
throw error;
}
}
private async transaction<T>(
work: (client: PostgresClient, runs: PostgresRunTransaction) => Promise<T>,
): Promise<T> {
const client = await this.pool.connect().catch((error: unknown) => {
throw new ClusterControlRecoveryStoreError(error);
});
let began = false;
try {
await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
began = true;
await client.query(`SELECT set_config('statement_timeout', $1, true)`, [
`${TRANSACTION_STATEMENT_TIMEOUT_MS}ms`,
]);
await client.query(`SELECT set_config('lock_timeout', $1, true)`, [
`${TRANSACTION_LOCK_TIMEOUT_MS}ms`,
]);
await client.query(
`SELECT set_config('idle_in_transaction_session_timeout', $1, true)`,
[`${TRANSACTION_IDLE_TIMEOUT_MS}ms`],
);
const result = await work(client, new PostgresRunTransaction(client));
await client.query('COMMIT');
began = false;
return result;
} catch (error) {
if (began) {
try {
await client.query('ROLLBACK');
} catch {
// Preserve the originating failure; release discards broken clients.
}
}
if (error instanceof RecoverySnapshotStaleError) throw error;
if (error instanceof ClusterControlRecoveryStoreError) throw error;
throw new ClusterControlRecoveryStoreError(error);
} finally {
client.release();
}
}
}
@@ -0,0 +1,290 @@
// PostgreSQL authority source for outstanding cluster recovery candidates.
import {
MAX_CLUSTER_CONTROL_RECOVERY_PAGE_SIZE,
type ClusterControlRecoveryCandidate,
type ClusterControlRecoveryPage,
type ClusterControlRecoverySource,
type PostgresQueryable,
} from '@qinglong/runtime-core';
type RecoveryRow = Record<string, unknown> & {
observedAtMs: unknown;
kind: unknown;
id: unknown;
runId: unknown;
status: unknown;
createdAtMs: unknown;
};
const ACTIVE_RUN_STATUSES = new Set(['created', 'dispatching', 'running']);
const ACTIVE_ATTEMPT_STATUSES = new Set(['claimed', 'starting', 'running']);
const OUTSTANDING_RECOVERY_SQL = `
WITH observation AS (
SELECT floor(
extract(epoch FROM statement_timestamp()) * 1000
)::bigint AS observed_at_ms
), run_candidates AS (
SELECT
'run'::text AS "kind",
id AS "id",
id AS "runId",
status AS "status",
created_at_ms AS "createdAtMs"
FROM "ql3"."runs"
CROSS JOIN observation
WHERE execution_owner = 'runtime'
AND trigger_type <> 'plugin_package_workflow'
AND (
status = 'created'
OR (
status IN ('dispatching', 'running')
AND NOT EXISTS (
SELECT 1
FROM "ql3"."run_attempts" AS active_attempt
WHERE active_attempt.run_id = "ql3"."runs".id
AND active_attempt.status IN ('claimed', 'starting', 'running')
AND active_attempt.lease_expires_at_ms > observation.observed_at_ms
)
)
)
ORDER BY created_at_ms, id
LIMIT $1
), attempt_candidates AS (
SELECT
'attempt'::text AS "kind",
attempt.id AS "id",
attempt.run_id AS "runId",
attempt.status AS "status",
attempt.created_at_ms AS "createdAtMs"
FROM "ql3"."run_attempts" AS attempt
INNER JOIN "ql3"."runs" AS attempt_run
ON attempt_run.id = attempt.run_id
CROSS JOIN observation
WHERE attempt.status IN ('claimed', 'starting', 'running')
AND (
attempt.lease_expires_at_ms IS NULL
OR attempt.lease_expires_at_ms <= observation.observed_at_ms
)
AND NOT (
attempt_run.execution_owner = 'runtime'
AND attempt_run.status = 'queued'
AND attempt_run.cancel_requested_at_ms IS NULL
AND attempt_run.queued_at_ms IS NOT NULL
AND attempt.status = 'claimed'
AND attempt.executor_type = 'remote_worker'
AND attempt.worker_id IS NULL
AND attempt.worker_session_id IS NULL
AND attempt.worker_generation IS NULL
AND attempt.executor_handle IS NULL
AND attempt.pid IS NULL
AND attempt.log_artifact_id IS NULL
AND attempt.lease_token IS NULL
AND attempt.lease_token_digest IS NULL
AND attempt.lease_generation IS NULL
AND attempt.lease_version IS NULL
AND attempt.lease_expires_at_ms IS NULL
AND attempt.offer_id IS NULL
AND attempt.deadline_at_ms IS NULL
AND attempt.callback_token_hash IS NULL
AND attempt.callback_sequence = 0
AND attempt.started_at_ms IS NULL
AND attempt.finished_at_ms IS NULL
AND attempt.exit_code IS NULL
AND attempt.error_code IS NULL
AND attempt.error_summary IS NULL
AND NOT EXISTS (
SELECT 1
FROM "ql3"."run_attempts" AS newer_attempt
WHERE newer_attempt.run_id = attempt.run_id
AND newer_attempt.attempt > attempt.attempt
)
)
AND NOT (
attempt_run.execution_owner = 'runtime'
AND attempt_run.trigger_type = 'plugin_package_workflow'
AND attempt_run.status = 'running'
AND attempt_run.cancel_requested_at_ms IS NULL
AND attempt.status = 'claimed'
AND attempt.executor_type = 'remote_worker'
AND attempt.worker_id IS NULL
AND attempt.worker_session_id IS NULL
AND attempt.worker_generation IS NULL
AND attempt.executor_handle IS NULL
AND attempt.pid IS NULL
AND attempt.log_artifact_id IS NULL
AND attempt.lease_token IS NULL
AND attempt.lease_token_digest IS NULL
AND attempt.lease_generation IS NULL
AND attempt.lease_version IS NULL
AND attempt.lease_expires_at_ms IS NULL
AND attempt.offer_id IS NULL
AND attempt.deadline_at_ms IS NULL
AND attempt.callback_token_hash IS NULL
AND attempt.callback_sequence = 0
AND attempt.started_at_ms IS NULL
AND attempt.finished_at_ms IS NULL
AND attempt.exit_code IS NULL
AND attempt.error_code IS NULL
AND attempt.error_summary IS NULL
AND EXISTS (
SELECT 1
FROM "ql3"."plugin_package_workflow_task_attempt_admissions"
AS workflow_task
WHERE workflow_task.attempt_id = attempt.id
AND workflow_task.run_id = attempt.run_id
)
)
ORDER BY attempt.created_at_ms, attempt.id
LIMIT $1
), outstanding AS (
SELECT *
FROM (
SELECT * FROM run_candidates
UNION ALL
SELECT * FROM attempt_candidates
) AS combined
ORDER BY "createdAtMs", "kind", "id"
LIMIT $1
)
SELECT
observation.observed_at_ms AS "observedAtMs",
outstanding."kind",
outstanding."id",
outstanding."runId",
outstanding."status",
outstanding."createdAtMs"
FROM observation
LEFT JOIN outstanding ON TRUE
ORDER BY outstanding."createdAtMs", outstanding."kind", outstanding."id"
`.trim();
function positivePageSize(limit: number): number {
if (
!Number.isInteger(limit) ||
limit < 1 ||
limit > MAX_CLUSTER_CONTROL_RECOVERY_PAGE_SIZE
) {
throw new RangeError(
`Cluster-control recovery limit must be between 1 and ${MAX_CLUSTER_CONTROL_RECOVERY_PAGE_SIZE}`,
);
}
return limit;
}
function observationTime(value: unknown): number {
const converted =
typeof value === 'string' && /^[0-9]+$/.test(value) ? Number(value) : value;
if (
typeof converted !== 'number' ||
!Number.isSafeInteger(converted) ||
converted < 0
) {
throw new TypeError('PostgreSQL recovery observedAtMs is invalid');
}
return converted;
}
function nonemptyString(name: string, value: unknown): string {
if (typeof value !== 'string' || value.length === 0) {
throw new TypeError(`PostgreSQL recovery ${name} is invalid`);
}
return value;
}
function createdAtMs(value: unknown): number {
const converted =
typeof value === 'string' && /^[0-9]+$/.test(value) ? Number(value) : value;
if (
typeof converted !== 'number' ||
!Number.isSafeInteger(converted) ||
converted < 0
) {
throw new TypeError('PostgreSQL recovery createdAtMs is invalid');
}
return converted;
}
function recoveryCandidate(row: RecoveryRow): ClusterControlRecoveryCandidate {
const id = nonemptyString('id', row.id);
const runId = nonemptyString('runId', row.runId);
const status = nonemptyString('status', row.status);
const timestamp = createdAtMs(row.createdAtMs);
if (row.kind === 'run' && ACTIVE_RUN_STATUSES.has(status)) {
return Object.freeze({
kind: 'run',
id,
runId,
status: status as Extract<
ClusterControlRecoveryCandidate,
{ kind: 'run' }
>['status'],
createdAtMs: timestamp,
});
}
if (row.kind === 'attempt' && ACTIVE_ATTEMPT_STATUSES.has(status)) {
return Object.freeze({
kind: 'attempt',
id,
runId,
status: status as Extract<
ClusterControlRecoveryCandidate,
{ kind: 'attempt' }
>['status'],
createdAtMs: timestamp,
});
}
throw new TypeError(
'PostgreSQL recovery candidate kind or status is invalid',
);
}
export class PostgresClusterControlRecoverySource
implements ClusterControlRecoverySource
{
constructor(private readonly queryable: PostgresQueryable) {}
async listOutstanding(limit: number): Promise<ClusterControlRecoveryPage> {
const pageSize = positivePageSize(limit);
const fetchSize = pageSize + 1;
const result = await this.queryable.query<RecoveryRow>(
OUTSTANDING_RECOVERY_SQL,
[fetchSize],
);
if (result.rows.length === 0 || result.rows.length > fetchSize) {
throw new TypeError(
'PostgreSQL recovery query violated its bounded result contract',
);
}
const observedAtMs = observationTime(result.rows[0]!.observedAtMs);
if (
result.rows.some(
(row) => observationTime(row.observedAtMs) !== observedAtMs,
)
) {
throw new TypeError(
'PostgreSQL recovery observation changed within a page',
);
}
const empty = result.rows[0]!.kind === null;
if (empty) {
const row = result.rows[0]!;
if (
result.rows.length !== 1 ||
row.id !== null ||
row.runId !== null ||
row.status !== null ||
row.createdAtMs !== null
) {
throw new TypeError('PostgreSQL recovery empty page is invalid');
}
}
const mapped = empty ? [] : result.rows.map(recoveryCandidate);
const candidates = mapped.slice(0, pageSize);
return Object.freeze({
observedAtMs,
candidates: Object.freeze(candidates),
hasMore: mapped.length > pageSize,
});
}
}
@@ -0,0 +1,784 @@
// PostgreSQL authority adapter for cancellation convergence and terminal recovery.
import { createHash } from 'node:crypto';
import type { PostgresClient, PostgresPool } from '@qinglong/runtime-core';
import type {
RunEventRecord,
RunRecord,
} from '@qinglong/runtime-core';
import {
ClusterRunCancellationConvergenceUnavailableError,
normalizeClusterRunCancellationConvergencePageCommand,
normalizeClusterRunCancellationConvergencePageResult,
type ClusterRunCancellationConvergencePageCommand,
type ClusterRunCancellationConvergencePageResult,
type ClusterRunCancellationConvergenceRepository,
} from '@qinglong/runtime-core/cluster-run-cancellation-convergence';
import {
resolvePluginPackageWorkflowCancellation,
type PluginPackageWorkflowCancellationActiveAttempt,
type PluginPackageWorkflowCancellationResolution,
} from '@qinglong/runtime-core/plugin-package-workflow-cancellation-convergence';
import type {
PluginPackageWorkflowTaskAttemptAdmissionReceipt,
} from '@qinglong/runtime-core/plugin-package-workflow-task-attempt-admission';
import type {
StepRunMutation,
StepRunRecord,
} from '@qinglong/runtime-core/step-run';
import { PostgresRunTransaction } from '../run/runRepository';
type Row = Record<string, unknown>;
const NON_EXECUTING_RUN_STATUSES = Object.freeze([
'created',
'queued',
'waiting_approval',
'retry_wait',
'lost',
]);
const TERMINAL_ATTEMPT_STATUSES = new Set([
'succeeded',
'failed',
'cancelled',
'timed_out',
'lost',
]);
const CANCEL_REASONS = new Set([
'user',
'policy',
'shutdown',
'reconcile',
'timeout',
]);
function text(row: Row, key: string): string {
const value = row[key];
if (typeof value !== 'string' || value.length < 1) {
throw new TypeError(`PostgreSQL cancellation convergence ${key} is invalid`);
}
return value;
}
function integer(row: Row, key: string): number {
const raw = row[key];
const value = typeof raw === 'string' && /^(0|[1-9]\d*)$/.test(raw)
? Number(raw)
: raw;
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
throw new TypeError(`PostgreSQL cancellation convergence ${key} is invalid`);
}
return value;
}
function optionalText(row: Row, key: string): string | undefined {
return row[key] === null || row[key] === undefined
? undefined
: text(row, key);
}
function optionalInteger(row: Row, key: string): number | undefined {
return row[key] === null || row[key] === undefined
? undefined
: integer(row, key);
}
function boolean(row: Row, key: string): boolean {
const value = row[key];
if (typeof value !== 'boolean') {
throw new TypeError(`PostgreSQL cancellation convergence ${key} is invalid`);
}
return value;
}
function object(row: Row, key: string): Readonly<Record<string, unknown>> {
const value = row[key];
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new TypeError(`PostgreSQL cancellation convergence ${key} is invalid`);
}
return Object.freeze({ ...(value as Record<string, unknown>) });
}
async function begin(client: PostgresClient): Promise<void> {
await client.query('BEGIN');
await client.query(`SELECT set_config('statement_timeout', $1, true)`, [
'5000ms',
]);
await client.query(`SELECT set_config('lock_timeout', $1, true)`, ['1000ms']);
await client.query(
`SELECT set_config('idle_in_transaction_session_timeout', $1, true)`,
['10000ms'],
);
}
async function rollback(client: PostgresClient): Promise<void> {
try {
await client.query('ROLLBACK');
} catch {
// Preserve the primary transaction failure.
}
}
interface TerminalMapping {
readonly status: 'cancelled' | 'timed_out';
readonly errorCode: 'EXECUTION_CANCELLED' | 'EXECUTION_TIMED_OUT';
readonly errorSummary: string;
}
function mapping(reason: string): Readonly<TerminalMapping> {
if (!CANCEL_REASONS.has(reason)) {
throw new TypeError('PostgreSQL cancellation convergence reason is invalid');
}
return reason === 'timeout'
? Object.freeze({
status: 'timed_out' as const,
errorCode: 'EXECUTION_TIMED_OUT' as const,
errorSummary: 'Execution exceeded its configured timeout',
})
: Object.freeze({
status: 'cancelled' as const,
errorCode: 'EXECUTION_CANCELLED' as const,
errorSummary: 'Execution was cancelled',
});
}
function eventIdentity(
kind: 'attempt' | 'run',
runId: string,
attemptId: string | undefined,
cancelRequestedAtMs: number,
): string {
const digest = createHash('sha256');
for (const value of [
'qinglong/cluster-run-cancellation-convergence-event@v1',
kind,
runId,
attemptId ?? '',
String(cancelRequestedAtMs),
]) {
digest.update(String(Buffer.byteLength(value)));
digest.update(':');
digest.update(value);
}
return `${kind === 'attempt' ? 'qca' : 'qcr'}-${digest.digest('hex').slice(0, 32)}`;
}
async function tryLockAttemptAuthority(
client: PostgresClient,
attemptId: string,
): Promise<boolean> {
const result = await client.query<Row>(
`SELECT pg_try_advisory_xact_lock(
hashtextextended($1, 0)
) AS "locked"`,
[`ql3-attempt-authority:${attemptId}`],
);
return result.rows.length === 1 && boolean(result.rows[0]!, 'locked');
}
async function updateWorkflowStepRun(
client: PostgresClient,
mutation: Readonly<StepRunMutation>,
): Promise<void> {
const stepRun = mutation.stepRun;
const result = await client.query(
`UPDATE "ql3"."step_runs"
SET status = $1, version = $2, attempt_count = $3, output_ref = $4,
approval_request_id = $5, ready_at_ms = $6, started_at_ms = $7,
finished_at_ms = $8, result_code = $9, error_summary = $10,
updated_at_ms = $11, last_mutation_id = $12,
step_run_digest = $13, step_run_json = $14::jsonb
WHERE id = $15 AND run_id = $16 AND version = $17
AND step_run_digest = $18 AND status = $19`,
[
stepRun.status,
stepRun.version,
stepRun.attemptCount,
stepRun.outputRef,
stepRun.approvalRequestId,
stepRun.readyAtMs,
stepRun.startedAtMs,
stepRun.finishedAtMs,
stepRun.resultCode,
stepRun.errorSummary,
stepRun.updatedAtMs,
stepRun.lastMutationId,
stepRun.stepRunDigest,
JSON.stringify(stepRun),
stepRun.id,
stepRun.runId,
mutation.expectedStepRunVersion,
mutation.expectedStepRunDigest,
mutation.previousStatus,
],
);
if ((result.rowCount ?? result.rows.length) !== 1) {
throw new TypeError('PostgreSQL cancellation convergence StepRun fence changed');
}
}
async function appendWorkflowStepMutation(
client: PostgresClient,
mutation: Readonly<StepRunMutation>,
committedAtMs: number,
): Promise<void> {
const event = mutation.event;
await client.query(
`INSERT INTO "ql3"."run_events" (
id, run_id, sequence, type, dedupe_key, actor_type, actor_id,
attempt_id, step_run_id, payload, created_at_ms
) VALUES ($1, $2, $3, $4, $5, $6, $7, NULL, $8, $9::jsonb, $10)`,
[
event.id,
event.runId,
event.sequence,
event.type,
event.dedupeKey ?? null,
event.actorType,
event.actorId ?? null,
mutation.stepRun.id,
JSON.stringify(event.payload),
event.createdAtMs,
],
);
await client.query(
`INSERT INTO "ql3"."step_run_mutations" (
mutation_id, mutation_digest, run_id, step_run_id, step_run_digest,
event_id, event_sequence, run_version, step_run_json, committed_at_ms
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10)`,
[
mutation.mutationId,
mutation.mutationDigest,
mutation.runId,
mutation.stepRun.id,
mutation.stepRun.stepRunDigest,
event.id,
event.sequence,
mutation.expectedRunVersion + 1,
JSON.stringify(mutation.stepRun),
committedAtMs,
],
);
}
async function appendWorkflowEvent(
runs: PostgresRunTransaction,
event: Readonly<RunEventRecord>,
): Promise<void> {
await runs.appendEvent(event);
}
async function compareAndSetWorkflowRun(
client: PostgresClient,
current: Readonly<RunRecord>,
resolution: Readonly<PluginPackageWorkflowCancellationResolution>,
): Promise<void> {
const next = resolution.run;
const result = await client.query(
`UPDATE "ql3"."runs"
SET status = $2, finished_at_ms = $3,
error_code = $4, error_summary = $5,
version = $6, event_sequence = $7
WHERE id = $1 AND status = 'running'
AND execution_owner = 'runtime'
AND trigger_type = 'plugin_package_workflow'
AND cancel_requested_at_ms = $8 AND cancel_reason = $9
AND version = $10 AND event_sequence = $11`,
[
current.id,
next.status,
next.finishedAtMs ?? null,
next.errorCode ?? null,
next.errorSummary ?? null,
next.version,
next.eventSequence,
current.cancelRequestedAtMs,
current.cancelReason,
current.version,
current.eventSequence,
],
);
if ((result.rowCount ?? result.rows.length) !== 1) {
throw new TypeError('PostgreSQL cancellation convergence Workflow fence changed');
}
}
export class PostgresClusterRunCancellationConvergenceRepository
implements ClusterRunCancellationConvergenceRepository
{
constructor(private readonly pool: PostgresPool) {
if (!pool || typeof pool.connect !== 'function') {
throw new TypeError('PostgreSQL cancellation convergence pool is invalid');
}
}
private async convergeWorkflow(
client: PostgresClient,
runId: string,
): Promise<Readonly<{
settledRuns: number;
settledAttempts: number;
blocked: number;
}>> {
const authority = await client.query<Row>(
`SELECT attempt.id AS "attemptId"
FROM "ql3"."run_attempts" AS attempt
JOIN "ql3"."plugin_package_workflow_task_attempt_admissions"
AS admission ON admission.attempt_id = attempt.id
WHERE attempt.run_id = $1
AND attempt.status = ANY($2::text[])
ORDER BY attempt.id`,
[runId, ['claimed', 'starting', 'running']],
);
const authorityIds = authority.rows.map((row) => text(row, 'attemptId'));
for (const attemptId of authorityIds) {
if (!(await tryLockAttemptAuthority(client, attemptId))) {
return Object.freeze({
settledRuns: 0,
settledAttempts: 0,
blocked: 1,
});
}
}
const locked = await client.query<Row>(
`SELECT id AS "runId"
FROM "ql3"."runs"
WHERE id = $1
AND execution_owner = 'runtime'
AND trigger_type = 'plugin_package_workflow'
AND status = 'running'
AND cancel_requested_at_ms IS NOT NULL
FOR UPDATE`,
[runId],
);
if (locked.rows.length === 0) {
return Object.freeze({
settledRuns: 0,
settledAttempts: 0,
blocked: 0,
});
}
if (locked.rows.length !== 1) {
throw new TypeError('PostgreSQL cancellation convergence Workflow duplicated');
}
const runs = new PostgresRunTransaction(client);
const run = await runs.findRunById(runId);
if (!run) {
throw new TypeError('PostgreSQL cancellation convergence Workflow disappeared');
}
const stepResult = await client.query<Row>(
`SELECT step_run_json AS "stepRunJson"
FROM "ql3"."step_runs"
WHERE run_id = $1
ORDER BY step_key, id
FOR UPDATE`,
[runId],
);
const stepRuns = stepResult.rows.map((row) =>
object(row, 'stepRunJson') as unknown as Readonly<StepRunRecord>);
const activeResult = await client.query<Row>(
`SELECT admission.receipt_json AS "admissionJson",
attempt.id AS "attemptId",
lease.status AS "leaseStatus"
FROM "ql3"."plugin_package_workflow_task_attempt_admissions"
AS admission
JOIN "ql3"."run_attempts" AS attempt
ON attempt.id = admission.attempt_id
AND attempt.run_id = admission.run_id
LEFT JOIN "ql3"."run_dispatch_leases" AS lease
ON lease.attempt_id = attempt.id
WHERE admission.run_id = $1
AND attempt.status = ANY($2::text[])
ORDER BY attempt.id
FOR UPDATE OF attempt`,
[runId, ['claimed', 'starting', 'running']],
);
const activeIds = activeResult.rows.map((row) => text(row, 'attemptId'));
if (activeIds.some((attemptId) => !authorityIds.includes(attemptId))) {
throw new TypeError(
'PostgreSQL cancellation convergence acquired incomplete Attempt authority',
);
}
if (activeIds.length > 0) {
await client.query(
`SELECT attempt_id
FROM "ql3"."run_dispatch_leases"
WHERE attempt_id = ANY($1::text[])
ORDER BY attempt_id
FOR UPDATE`,
[activeIds],
);
}
const activeTaskAttempts:
PluginPackageWorkflowCancellationActiveAttempt[] = [];
for (const row of activeResult.rows) {
const attemptId = text(row, 'attemptId');
const attempt = await runs.findAttemptById(attemptId);
if (!attempt) {
throw new TypeError(
'PostgreSQL cancellation convergence Attempt disappeared',
);
}
activeTaskAttempts.push(Object.freeze({
admission:
object(row, 'admissionJson') as unknown as
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>,
attempt,
leaseStatus:
(optionalText(row, 'leaseStatus') ?? null) as
PluginPackageWorkflowCancellationActiveAttempt['leaseStatus'],
}));
}
const observation = await client.query<Row>(
`SELECT floor(
extract(epoch FROM statement_timestamp()) * 1000
)::bigint AS "observedAtMs"`,
);
if (observation.rows.length !== 1) {
throw new TypeError(
'PostgreSQL cancellation convergence Workflow observation is invalid',
);
}
const resolution = resolvePluginPackageWorkflowCancellation({
run,
stepRuns,
activeTaskAttempts,
observedAtMs: integer(observation.rows[0]!, 'observedAtMs'),
});
for (const transition of resolution.attemptTransitions) {
if (
!(await runs.compareAndSetAttempt(transition.attempt, {
status: transition.previousStatus,
callbackSequence: transition.attempt.callbackSequence,
}))
) {
throw new TypeError(
'PostgreSQL cancellation convergence Attempt fence changed',
);
}
await appendWorkflowEvent(runs, transition.event);
}
for (const mutation of resolution.stepMutations) {
await updateWorkflowStepRun(client, mutation);
await appendWorkflowStepMutation(
client,
mutation,
resolution.observedAtMs,
);
}
if (resolution.terminalTransition) {
await appendWorkflowEvent(
runs,
resolution.terminalTransition.event,
);
}
if (
resolution.run.version !== run.version ||
resolution.run.eventSequence !== run.eventSequence ||
resolution.run.status !== run.status
) {
await compareAndSetWorkflowRun(client, run, resolution);
}
return Object.freeze({
settledRuns: resolution.terminalTransition === null ? 0 : 1,
settledAttempts: resolution.attemptTransitions.length,
blocked: resolution.blockedStepRunIds.length === 0 ? 0 : 1,
});
}
async convergePage(
value: Readonly<ClusterRunCancellationConvergencePageCommand>,
): Promise<Readonly<ClusterRunCancellationConvergencePageResult>> {
const command = normalizeClusterRunCancellationConvergencePageCommand(value);
let client: PostgresClient;
try {
client = await this.pool.connect();
} catch (error) {
throw new ClusterRunCancellationConvergenceUnavailableError({ cause: error });
}
try {
await begin(client);
const candidates = await client.query<Row>(
`WITH observation AS MATERIALIZED (
SELECT floor(extract(epoch FROM statement_timestamp()) * 1000)::bigint
AS observed_at_ms
), candidates AS MATERIALIZED (
SELECT run.id
FROM "ql3"."runs" AS run
WHERE run.execution_owner = 'runtime'
AND run.cancel_requested_at_ms IS NOT NULL
AND run.trigger_type <> 'plugin_package_workflow'
AND run.status = ANY($1::text[])
ORDER BY run.cancel_requested_at_ms, run.id
FOR UPDATE OF run SKIP LOCKED
LIMIT $2
)
SELECT observation.observed_at_ms AS "observedAtMs",
run.id AS "runId", run.status AS "runStatus",
run.version AS "runVersion",
run.event_sequence AS "eventSequence",
run.created_at_ms AS "runCreatedAtMs",
run.queued_at_ms AS "runQueuedAtMs",
run.started_at_ms AS "runStartedAtMs",
run.cancel_requested_at_ms AS "cancelRequestedAtMs",
run.cancel_reason AS "cancelReason",
attempt.id AS "attemptId", attempt.status AS "attemptStatus",
attempt.step_run_id AS "stepRunId",
attempt.attempt AS "attemptNumber",
attempt.created_at_ms AS "attemptCreatedAtMs",
attempt.started_at_ms AS "attemptStartedAtMs",
attempt.finished_at_ms AS "attemptFinishedAtMs",
lease.status AS "leaseStatus"
FROM observation
JOIN candidates ON true
JOIN "ql3"."runs" AS run ON run.id = candidates.id
LEFT JOIN LATERAL (
SELECT candidate_attempt.*
FROM "ql3"."run_attempts" AS candidate_attempt
WHERE candidate_attempt.run_id = run.id
ORDER BY candidate_attempt.attempt DESC, candidate_attempt.id DESC
LIMIT 1
) AS attempt ON true
LEFT JOIN "ql3"."run_dispatch_leases" AS lease
ON lease.attempt_id = attempt.id
ORDER BY run.cancel_requested_at_ms, run.id`,
[NON_EXECUTING_RUN_STATUSES, command.limit],
);
let settledRuns = 0;
let settledAttempts = 0;
let blocked = 0;
let scanned = candidates.rows.length;
for (const row of candidates.rows) {
const attemptStatus = optionalText(row, 'attemptStatus');
const leaseStatus = optionalText(row, 'leaseStatus');
if (
attemptStatus === 'starting' ||
attemptStatus === 'running' ||
(attemptStatus === 'claimed' && leaseStatus === 'leased')
) {
blocked += 1;
continue;
}
if (
attemptStatus !== undefined &&
attemptStatus !== 'claimed' &&
!TERMINAL_ATTEMPT_STATUSES.has(attemptStatus)
) {
throw new TypeError('PostgreSQL cancellation convergence Attempt is invalid');
}
const runStatus = text(row, 'runStatus');
if (!NON_EXECUTING_RUN_STATUSES.includes(runStatus)) {
throw new TypeError('PostgreSQL cancellation convergence Run is invalid');
}
const cancelRequestedAtMs = integer(row, 'cancelRequestedAtMs');
const cancelReason = text(row, 'cancelReason');
const terminal = mapping(cancelReason);
const observedAtMs = integer(row, 'observedAtMs');
const finishedAtMs = Math.max(
observedAtMs,
cancelRequestedAtMs,
integer(row, 'runCreatedAtMs'),
optionalInteger(row, 'runQueuedAtMs') ?? 0,
optionalInteger(row, 'runStartedAtMs') ?? 0,
optionalInteger(row, 'attemptCreatedAtMs') ?? 0,
optionalInteger(row, 'attemptStartedAtMs') ?? 0,
optionalInteger(row, 'attemptFinishedAtMs') ?? 0,
);
const runVersion = integer(row, 'runVersion');
const eventSequence = integer(row, 'eventSequence');
const settlesAttempt = attemptStatus === 'claimed';
const eventCount = settlesAttempt ? 2 : 1;
if (
runVersion > 2_147_483_647 - eventCount ||
eventSequence > 2_147_483_647 - eventCount
) {
throw new RangeError('PostgreSQL cancellation convergence counter overflowed');
}
const attemptId = optionalText(row, 'attemptId');
const attemptEventId = eventIdentity(
'attempt',
text(row, 'runId'),
attemptId,
cancelRequestedAtMs,
);
const runEventId = eventIdentity(
'run',
text(row, 'runId'),
attemptId,
cancelRequestedAtMs,
);
let nextSequence = eventSequence;
if (settlesAttempt) {
if (!attemptId) {
throw new TypeError('PostgreSQL cancellation convergence Attempt identity is missing');
}
const attempt = await client.query(
`UPDATE "ql3"."run_attempts"
SET status = $2, finished_at_ms = $3,
error_code = $4, error_summary = $5
WHERE id = $1 AND run_id = $6 AND status = 'claimed'`,
[
attemptId,
terminal.status,
finishedAtMs,
terminal.errorCode,
terminal.errorSummary,
text(row, 'runId'),
],
);
if (attempt.rowCount !== 1) {
throw new TypeError('PostgreSQL cancellation convergence Attempt fence changed');
}
nextSequence += 1;
await client.query(
`INSERT INTO "ql3"."run_events" (
id, run_id, sequence, type, dedupe_key, actor_type, actor_id,
attempt_id, step_run_id, payload, created_at_ms
) VALUES ($1, $2, $3, $4, $5, 'reconciler',
'runtime:cancellation', $6, $7, $8::jsonb, $9)`,
[
attemptEventId,
text(row, 'runId'),
nextSequence,
`attempt.${terminal.status}`,
`cancel-convergence:attempt:${attemptId}:${cancelRequestedAtMs}`,
attemptId,
optionalText(row, 'stepRunId') ?? null,
JSON.stringify({
attempt_id: attemptId,
attempt: integer(row, 'attemptNumber'),
from_status: 'claimed',
to_status: terminal.status,
cancel_reason: cancelReason,
cancel_requested_at_ms: cancelRequestedAtMs,
error_code: terminal.errorCode,
}),
finishedAtMs,
],
);
settledAttempts += 1;
}
nextSequence += 1;
const nextVersion = runVersion + eventCount;
const run = await client.query(
`UPDATE "ql3"."runs"
SET status = $2, finished_at_ms = $3,
error_code = $4, error_summary = $5,
version = $6, event_sequence = $7
WHERE id = $1 AND version = $8 AND status = $9
AND cancel_requested_at_ms = $10 AND cancel_reason = $11
AND execution_owner = 'runtime'`,
[
text(row, 'runId'),
terminal.status,
finishedAtMs,
terminal.errorCode,
terminal.errorSummary,
nextVersion,
nextSequence,
runVersion,
runStatus,
cancelRequestedAtMs,
cancelReason,
],
);
if (run.rowCount !== 1) {
throw new TypeError('PostgreSQL cancellation convergence Run fence changed');
}
await client.query(
`INSERT INTO "ql3"."run_events" (
id, run_id, sequence, type, dedupe_key, actor_type, actor_id,
attempt_id, step_run_id, payload, created_at_ms
) VALUES ($1, $2, $3, $4, $5, 'reconciler',
'runtime:cancellation', $6, NULL, $7::jsonb, $8)`,
[
runEventId,
text(row, 'runId'),
nextSequence,
`run.${terminal.status}`,
`cancel-convergence:run:${text(row, 'runId')}:${cancelRequestedAtMs}`,
attemptId ?? null,
JSON.stringify({
...(attemptId === undefined ? {} : { attempt_id: attemptId }),
from_status: runStatus,
to_status: terminal.status,
version: nextVersion,
cancel_reason: cancelReason,
cancel_requested_at_ms: cancelRequestedAtMs,
error_code: terminal.errorCode,
}),
finishedAtMs,
],
);
settledRuns += 1;
}
const remaining = command.limit - candidates.rows.length;
if (remaining > 0) {
const workflowCandidates = await client.query<Row>(
`SELECT id AS "runId"
FROM "ql3"."runs"
WHERE execution_owner = 'runtime'
AND trigger_type = 'plugin_package_workflow'
AND status = 'running'
AND cancel_requested_at_ms IS NOT NULL
ORDER BY cancel_requested_at_ms, id
LIMIT $1`,
[remaining],
);
for (const row of workflowCandidates.rows) {
const result = await this.convergeWorkflow(
client,
text(row, 'runId'),
);
settledRuns += result.settledRuns;
settledAttempts += result.settledAttempts;
blocked += result.blocked;
}
scanned += workflowCandidates.rows.length;
}
const continuation = await client.query<Row>(
`SELECT EXISTS (
SELECT 1 FROM "ql3"."runs"
WHERE execution_owner = 'runtime'
AND cancel_requested_at_ms IS NOT NULL
AND (
(
trigger_type <> 'plugin_package_workflow'
AND status = ANY($1::text[])
) OR (
trigger_type = 'plugin_package_workflow'
AND status = 'running'
)
)
LIMIT 1
) AS "hasMore"`,
[NON_EXECUTING_RUN_STATUSES],
);
if (continuation.rows.length !== 1) {
throw new TypeError('PostgreSQL cancellation convergence continuation is invalid');
}
const result = normalizeClusterRunCancellationConvergencePageResult({
scanned,
settledRuns,
settledAttempts,
blocked,
hasMore: boolean(continuation.rows[0]!, 'hasMore'),
}, command.limit);
await client.query('COMMIT');
return result;
} catch (error) {
await rollback(client);
if (error instanceof ClusterRunCancellationConvergenceUnavailableError) {
throw error;
}
throw new ClusterRunCancellationConvergenceUnavailableError({ cause: error });
} finally {
client.release();
}
}
}
@@ -0,0 +1,318 @@
// PostgreSQL authority adapter for cluster run cancellation requests.
import type { PostgresClient, PostgresPool } from '@qinglong/runtime-core';
import {
ClusterRunCancellationFenceRejectedError,
ClusterRunCancellationNotFoundError,
ClusterRunCancellationUnavailableError,
InvalidClusterRunCancellationError,
normalizeClusterRunCancellationCommand,
normalizeClusterRunCancellationResult,
type ClusterRunCancellationAllowedRole,
type ClusterRunCancellationCommand,
type ClusterRunCancellationRepository,
type ClusterRunCancellationResult,
} from '@qinglong/runtime-core/cluster-run-cancellation';
import { RUN_STATUSES, type RunStatus } from '@qinglong/runtime-core';
type Row = Record<string, unknown>;
const ALLOWED_ROLES = new Set<ClusterRunCancellationAllowedRole>([
'owner',
'admin',
'operator',
]);
const TERMINAL = new Set<RunStatus>([
'succeeded',
'failed',
'cancelled',
'timed_out',
]);
const CANCEL_REASONS = new Set([
'user',
'policy',
'shutdown',
'reconcile',
'timeout',
]);
function text(row: Row, key: string): string {
const value = row[key];
if (typeof value !== 'string' || value.length < 1) {
throw new TypeError(`PostgreSQL Run cancellation ${key} is invalid`);
}
return value;
}
function integer(row: Row, key: string): number {
const raw = row[key];
const value = typeof raw === 'string' && /^(0|[1-9]\d*)$/.test(raw)
? Number(raw)
: raw;
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < 0
) {
throw new TypeError(`PostgreSQL Run cancellation ${key} is invalid`);
}
return value;
}
function optionalInteger(row: Row, key: string): number | undefined {
return row[key] === null || row[key] === undefined
? undefined
: integer(row, key);
}
function optionalText(row: Row, key: string): string | undefined {
return row[key] === null || row[key] === undefined
? undefined
: text(row, key);
}
function runStatus(row: Row): RunStatus {
const value = text(row, 'runStatus') as RunStatus;
if (!RUN_STATUSES.includes(value)) {
throw new TypeError('PostgreSQL Run cancellation status is invalid');
}
return value;
}
function cancellationResult(
status: ClusterRunCancellationResult['status'],
command: Readonly<ClusterRunCancellationCommand>,
row: Row,
): Readonly<ClusterRunCancellationResult> {
const cancelRequestedAtMs = optionalInteger(row, 'cancelRequestedAtMs');
const cancelReason = optionalText(row, 'cancelReason');
if (
(cancelRequestedAtMs === undefined) !== (cancelReason === undefined) ||
(cancelReason !== undefined && !CANCEL_REASONS.has(cancelReason))
) {
throw new TypeError('PostgreSQL Run cancellation intent is invalid');
}
return normalizeClusterRunCancellationResult({
status,
projectId: command.projectId,
runId: command.runId,
runStatus: runStatus(row),
runVersion: integer(row, 'runVersion'),
eventSequence: integer(row, 'eventSequence'),
...(cancelRequestedAtMs === undefined
? {}
: {
cancelRequestedAtMs,
cancelReason: cancelReason as NonNullable<
ClusterRunCancellationResult['cancelReason']
>,
}),
});
}
async function begin(client: PostgresClient): Promise<void> {
await client.query('BEGIN ISOLATION LEVEL SERIALIZABLE');
await client.query(`SELECT set_config('statement_timeout', $1, true)`, [
'5000ms',
]);
await client.query(`SELECT set_config('lock_timeout', $1, true)`, ['1000ms']);
await client.query(
`SELECT set_config('idle_in_transaction_session_timeout', $1, true)`,
['10000ms'],
);
}
async function databaseNow(client: PostgresClient): Promise<number> {
const result = await client.query<Row>(`
SELECT floor(extract(epoch FROM statement_timestamp()) * 1000)::bigint AS "nowMs"
`);
if (result.rows.length !== 1) {
throw new TypeError('PostgreSQL Run cancellation clock is invalid');
}
return integer(result.rows[0]!, 'nowMs');
}
async function rollback(client: PostgresClient): Promise<void> {
try {
await client.query('ROLLBACK');
} catch {
// Preserve the primary transaction failure.
}
}
export class PostgresClusterRunCancellationRepository
implements ClusterRunCancellationRepository {
constructor(private readonly pool: PostgresPool) {
if (!pool || typeof pool.connect !== 'function') {
throw new TypeError('PostgreSQL Run cancellation pool is invalid');
}
}
async requestUserCancellation(
value: Readonly<ClusterRunCancellationCommand>,
): Promise<Readonly<ClusterRunCancellationResult>> {
const command = normalizeClusterRunCancellationCommand(value);
return this.transaction(async (client) => {
const project = await client.query<Row>(`
SELECT status AS "projectStatus", version AS "projectVersion"
FROM "ql3"."projects" WHERE id = $1 FOR UPDATE
`, [command.projectId]);
if (project.rows.length === 0) {
throw new ClusterRunCancellationNotFoundError();
}
if (project.rows.length !== 1) {
throw new TypeError('PostgreSQL Run cancellation Project is invalid');
}
const binding = await client.query<Row>(`
SELECT version AS "bindingVersion", state AS "bindingState",
role AS "bindingRole"
FROM "ql3"."project_role_bindings"
WHERE project_id = $1 AND subject_type = $2 AND subject_id = $3
ORDER BY version DESC LIMIT 1
`, [
command.projectId,
command.subject.type,
command.subject.id,
]);
const currentProject = project.rows[0]!;
const currentBinding = binding.rows[0];
if (
text(currentProject, 'projectStatus') !== 'active' ||
integer(currentProject, 'projectVersion') !==
command.policyFence.projectVersion ||
!currentBinding ||
integer(currentBinding, 'bindingVersion') !==
command.policyFence.bindingVersion ||
text(currentBinding, 'bindingState') !== 'active' ||
!ALLOWED_ROLES.has(
text(currentBinding, 'bindingRole') as ClusterRunCancellationAllowedRole,
)
) {
throw new ClusterRunCancellationFenceRejectedError(
'authorization_changed',
);
}
const run = await client.query<Row>(`
SELECT project_id AS "projectId", status AS "runStatus",
version AS "runVersion", event_sequence AS "eventSequence",
cancel_requested_at_ms AS "cancelRequestedAtMs",
cancel_reason AS "cancelReason"
FROM "ql3"."runs" WHERE id = $1 FOR UPDATE
`, [command.runId]);
if (run.rows.length === 0 || run.rows[0]?.projectId !== command.projectId) {
throw new ClusterRunCancellationNotFoundError();
}
if (run.rows.length !== 1) {
throw new TypeError('PostgreSQL Run cancellation Run is invalid');
}
if (command.workflowTarget) {
const admission = await client.query<Row>(`
SELECT project_id AS "projectId", package_name AS "packageName",
workflow_id AS "workflowId"
FROM "ql3"."plugin_package_workflow_admissions"
WHERE run_id = $1
`, [command.runId]);
const target = admission.rows[0];
if (
admission.rows.length !== 1 ||
!target ||
text(target, 'projectId') !== command.projectId ||
text(target, 'packageName') !== command.workflowTarget.packageName ||
text(target, 'workflowId') !== command.workflowTarget.workflowId
) {
throw new ClusterRunCancellationNotFoundError();
}
}
const current = run.rows[0]!;
const currentStatus = runStatus(current);
if (TERMINAL.has(currentStatus)) {
return cancellationResult('already_terminal', command, current);
}
if (optionalInteger(current, 'cancelRequestedAtMs') !== undefined) {
return cancellationResult('already_requested', command, current);
}
if (optionalText(current, 'cancelReason') !== undefined) {
throw new TypeError('PostgreSQL Run cancellation intent is invalid');
}
const runVersion = integer(current, 'runVersion');
const eventSequence = integer(current, 'eventSequence');
if (runVersion >= 2_147_483_647 || eventSequence >= 2_147_483_647) {
throw new TypeError('PostgreSQL Run cancellation counter overflowed');
}
const observedAtMs = await databaseNow(client);
const updated = await client.query<Row>(`
UPDATE "ql3"."runs"
SET cancel_requested_at_ms = $2, cancel_reason = 'user',
version = $3, event_sequence = $4
WHERE id = $1 AND version = $5 AND cancel_requested_at_ms IS NULL
RETURNING project_id AS "projectId", status AS "runStatus",
version AS "runVersion", event_sequence AS "eventSequence",
cancel_requested_at_ms AS "cancelRequestedAtMs",
cancel_reason AS "cancelReason"
`, [
command.runId,
observedAtMs,
runVersion + 1,
eventSequence + 1,
runVersion,
]);
if (updated.rows.length !== 1) {
throw new ClusterRunCancellationFenceRejectedError('state_mismatch');
}
await client.query(`
INSERT INTO "ql3"."run_events" (
id, run_id, sequence, type, dedupe_key, actor_type, actor_id,
attempt_id, step_run_id, payload, created_at_ms
) VALUES ($1, $2, $3, 'run.cancel_requested', $4, $5, $6,
NULL, NULL, $7::jsonb, $8)
`, [
command.eventId,
command.runId,
eventSequence + 1,
`user-cancel:${command.mutationId}`,
command.subject.type,
command.subject.id,
JSON.stringify({
reason: 'user',
mutation_id: command.mutationId,
policy_fence: {
project_version: command.policyFence.projectVersion,
binding_version: command.policyFence.bindingVersion,
},
}),
observedAtMs,
]);
return cancellationResult('accepted', command, updated.rows[0]!);
});
}
private async transaction<T>(
work: (client: PostgresClient) => Promise<T>,
): Promise<T> {
let client: PostgresClient;
try {
client = await this.pool.connect();
} catch (error) {
throw new ClusterRunCancellationUnavailableError({ cause: error });
}
try {
await begin(client);
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error) {
await rollback(client);
if (
error instanceof InvalidClusterRunCancellationError ||
error instanceof ClusterRunCancellationNotFoundError ||
error instanceof ClusterRunCancellationFenceRejectedError
) {
throw error;
}
throw new ClusterRunCancellationUnavailableError({ cause: error });
} finally {
client.release();
}
}
}
@@ -0,0 +1,326 @@
// PostgreSQL authority adapter for lost-run retry reconciliation.
import { randomUUID } from 'node:crypto';
import {
ClusterRunLostRetryUnavailableError,
buildClusterRunLostRetryTransition,
normalizeClusterRunLostRetryPageCommand,
normalizeClusterRunLostRetryPageResult,
type ClusterRunLostRetryDisposition,
type ClusterRunLostRetryPageCommand,
type ClusterRunLostRetryPageResult,
type ClusterRunLostRetryRepository,
type PostgresClient,
type PostgresPool,
type RunAttemptRecord,
type RunRecord,
type RunRetryPolicyRecord,
} from '@qinglong/runtime-core';
import { lockAttemptAuthority } from '../run/attemptAuthorityLock';
import { PostgresRunTransaction } from '../run/runRepository';
type Row = Record<string, unknown>;
interface Candidate {
readonly runId: string;
readonly attemptId: string;
}
const TRANSACTION_STATEMENT_TIMEOUT_MS = 5_000;
const TRANSACTION_LOCK_TIMEOUT_MS = 1_000;
const TRANSACTION_IDLE_TIMEOUT_MS = 10_000;
function text(row: Row, key: string): string {
const value = row[key];
if (typeof value !== 'string' || value.length < 1 || value.length > 128) {
throw new TypeError(`PostgreSQL lost retry ${key} is invalid`);
}
return value;
}
function integer(row: Row, key: string): number {
const raw = row[key];
const value =
typeof raw === 'string' && /^(0|[1-9]\d*)$/.test(raw)
? Number(raw)
: raw;
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < 0
) {
throw new TypeError(`PostgreSQL lost retry ${key} is invalid`);
}
return value;
}
function rowCount(result: { readonly rowCount?: number | null; readonly rows: readonly unknown[] }): number {
return result.rowCount ?? result.rows.length;
}
function eventId(factory: () => string): string {
const value = factory();
if (
typeof value !== 'string' ||
value.length < 1 ||
value.length > 36 ||
/[\u0000-\u001f\u007f]/.test(value)
) {
throw new TypeError('PostgreSQL lost retry generated ID is invalid');
}
return value;
}
async function begin(client: PostgresClient): Promise<void> {
await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
await client.query(`SELECT set_config('statement_timeout', $1, true)`, [
`${TRANSACTION_STATEMENT_TIMEOUT_MS}ms`,
]);
await client.query(`SELECT set_config('lock_timeout', $1, true)`, [
`${TRANSACTION_LOCK_TIMEOUT_MS}ms`,
]);
await client.query(
`SELECT set_config('idle_in_transaction_session_timeout', $1, true)`,
[`${TRANSACTION_IDLE_TIMEOUT_MS}ms`],
);
}
async function rollback(client: PostgresClient): Promise<void> {
try {
await client.query('ROLLBACK');
} catch {
// Preserve the primary transaction failure.
}
}
/**
* PostgreSQL owns candidate ordering, aggregate/advisory locks and the atomic
* write bundle. Policy remains in runtime-core's pure transition builder.
*/
export class PostgresClusterRunLostRetryRepository
implements ClusterRunLostRetryRepository
{
constructor(
private readonly pool: PostgresPool,
private readonly createId: () => string = randomUUID,
) {
if (
!pool ||
typeof pool.connect !== 'function' ||
typeof createId !== 'function'
) {
throw new TypeError('PostgreSQL lost retry repository is invalid');
}
}
async reconcilePage(
input: Readonly<ClusterRunLostRetryPageCommand>,
): Promise<Readonly<ClusterRunLostRetryPageResult>> {
const command = normalizeClusterRunLostRetryPageCommand(input);
try {
const candidates = await this.listCandidates(command.limit + 1);
const page = candidates.slice(0, command.limit);
const counts: Record<ClusterRunLostRetryDisposition | 'raced', number> = {
scheduled: 0,
requeued: 0,
failed_disabled: 0,
failed_unsafe: 0,
failed_exhausted: 0,
raced: 0,
};
for (const candidate of page) {
const disposition = await this.reconcileCandidate(candidate);
counts[disposition] += 1;
}
return normalizeClusterRunLostRetryPageResult(
{
scanned: page.length,
scheduled: counts.scheduled,
requeued: counts.requeued,
failed:
counts.failed_disabled +
counts.failed_unsafe +
counts.failed_exhausted,
raced: counts.raced,
hasMore: candidates.length > command.limit,
},
command.limit,
);
} catch (error) {
if (error instanceof ClusterRunLostRetryUnavailableError) throw error;
throw new ClusterRunLostRetryUnavailableError({ cause: error });
}
}
private async listCandidates(limit: number): Promise<readonly Candidate[]> {
const result = await this.pool.query<Row>(
`WITH observation AS MATERIALIZED (
SELECT floor(
extract(epoch FROM statement_timestamp()) * 1000
)::bigint AS observed_at_ms
)
SELECT run.id AS "runId", attempt.id AS "attemptId"
FROM "ql3"."runs" AS run
JOIN LATERAL (
SELECT candidate.id, candidate.status, candidate.attempt
FROM "ql3"."run_attempts" AS candidate
WHERE candidate.run_id = run.id
ORDER BY candidate.attempt DESC, candidate.id DESC
LIMIT 1
) AS attempt ON attempt.status = 'lost'
LEFT JOIN "ql3"."run_retry_policies" AS policy
ON policy.run_id = run.id
CROSS JOIN observation
WHERE run.execution_owner = 'runtime'
AND run.trigger_type <> 'plugin_package_workflow'
AND run.cancel_requested_at_ms IS NULL
AND (
run.status = 'lost'
OR (
run.status = 'retry_wait'
AND policy.next_attempt_at_ms IS NOT NULL
AND policy.next_attempt_at_ms <= observation.observed_at_ms
)
)
ORDER BY
CASE
WHEN run.status = 'lost' THEN 0
ELSE policy.next_attempt_at_ms
END,
run.id
LIMIT $1`,
[limit],
);
if (result.rows.length > limit) {
throw new TypeError('PostgreSQL lost retry exceeded its page size');
}
return Object.freeze(
result.rows.map((row) =>
Object.freeze({
runId: text(row, 'runId'),
attemptId: text(row, 'attemptId'),
}),
),
);
}
private async reconcileCandidate(
candidate: Readonly<Candidate>,
): Promise<ClusterRunLostRetryDisposition | 'raced'> {
const client = await this.pool.connect();
let began = false;
try {
await begin(client);
began = true;
await lockAttemptAuthority(client, candidate.attemptId);
const locked = await client.query<Row>(
`SELECT run.id AS "runId"
FROM "ql3"."runs" AS run
WHERE run.id = $1
AND run.execution_owner = 'runtime'
AND run.trigger_type <> 'plugin_package_workflow'
AND run.cancel_requested_at_ms IS NULL
AND run.status IN ('lost', 'retry_wait')
FOR UPDATE`,
[candidate.runId],
);
if (locked.rows.length === 0) {
await client.query('COMMIT');
began = false;
return 'raced';
}
if (locked.rows.length !== 1) {
throw new TypeError('PostgreSQL lost retry duplicated a Run');
}
const runs = new PostgresRunTransaction(client);
const [run, attempt, policy] = await Promise.all([
runs.findRunById(candidate.runId),
runs.findLatestAttemptByRunId(candidate.runId),
runs.findRetryPolicyByRunId(candidate.runId),
]);
if (
!run ||
!attempt ||
attempt.id !== candidate.attemptId ||
attempt.status !== 'lost'
) {
await client.query('COMMIT');
began = false;
return 'raced';
}
if (policy) {
const policyLock = await client.query<Row>(
`SELECT run_id AS "runId"
FROM "ql3"."run_retry_policies"
WHERE run_id = $1
FOR UPDATE`,
[candidate.runId],
);
if (policyLock.rows.length !== 1) {
throw new TypeError('PostgreSQL lost retry policy disappeared');
}
}
const observation = await client.query<Row>(
`SELECT floor(
extract(epoch FROM statement_timestamp()) * 1000
)::bigint AS "observedAtMs"`,
);
if (observation.rows.length !== 1) {
throw new TypeError('PostgreSQL lost retry observation is invalid');
}
const transition = buildClusterRunLostRetryTransition({
run,
attempt,
policy,
observedAtMs: integer(observation.rows[0]!, 'observedAtMs'),
runEventId: eventId(this.createId),
...(run.status === 'retry_wait'
? {
attemptId: eventId(this.createId),
attemptEventId: eventId(this.createId),
}
: {}),
});
await this.persistTransition(runs, run, policy, transition);
await client.query('COMMIT');
began = false;
return transition.disposition;
} catch (error) {
if (began) await rollback(client);
throw error;
} finally {
client.release();
}
}
private async persistTransition(
runs: PostgresRunTransaction,
currentRun: Readonly<RunRecord>,
currentPolicy: Readonly<RunRetryPolicyRecord> | null,
transition: ReturnType<typeof buildClusterRunLostRetryTransition>,
): Promise<void> {
let version = currentRun.version;
for (const run of transition.runTransitions) {
if (!(await runs.compareAndSetRun(run, version))) {
throw new TypeError('PostgreSQL lost retry Run fence changed');
}
version = run.version;
}
if (transition.policy && transition.policy !== currentPolicy) {
if (
!currentPolicy ||
!(await runs.compareAndSetRetryPolicy(
transition.policy,
currentPolicy.version,
))
) {
throw new TypeError('PostgreSQL lost retry policy fence changed');
}
}
if (transition.attempt) {
await runs.insertAttempt(transition.attempt);
}
for (const event of transition.events) {
await runs.appendEvent(event);
}
}
}
@@ -0,0 +1,142 @@
// PostgreSQL authority source for runtime-level recovery candidates.
import {
MAX_CLUSTER_CONTROL_RECOVERY_PAGE_SIZE,
type ClusterControlRecoveryCandidate,
type ClusterControlRecoveryPage,
type ClusterControlRecoverySource,
type PostgresQueryable,
} from '@qinglong/runtime-core';
type Row = Record<string, unknown>;
function integer(value: unknown, label: string): number {
const normalized =
typeof value === 'string' && /^(0|[1-9]\d*)$/.test(value)
? Number(value)
: value;
if (
typeof normalized !== 'number' ||
!Number.isSafeInteger(normalized) ||
normalized < 0
) {
throw new TypeError(`PostgreSQL runtime recovery ${label} is invalid`);
}
return normalized;
}
function text(value: unknown, label: string): string {
if (typeof value !== 'string' || value.length < 1) {
throw new TypeError(`PostgreSQL runtime recovery ${label} is invalid`);
}
return value;
}
function pageSize(value: number): number {
if (
!Number.isSafeInteger(value) ||
value < 1 ||
value > MAX_CLUSTER_CONTROL_RECOVERY_PAGE_SIZE
) {
throw new RangeError(
`Cluster runtime recovery limit must be between 1 and ${MAX_CLUSTER_CONTROL_RECOVERY_PAGE_SIZE}`,
);
}
return value;
}
/**
* Continuous production recovery source. Unlike the startup source it never
* scans orphaned `created` Runs; one bounded page contains only active
* Attempts whose durable lease is absent or expired.
*/
export class PostgresClusterRuntimeRecoverySource
implements ClusterControlRecoverySource
{
constructor(private readonly queryable: PostgresQueryable) {
if (!queryable || typeof queryable.query !== 'function') {
throw new TypeError('PostgreSQL runtime recovery queryable is invalid');
}
}
async listOutstanding(limit: number): Promise<ClusterControlRecoveryPage> {
const maximum = pageSize(limit);
const result = await this.queryable.query<Row>(
`WITH observation AS MATERIALIZED (
SELECT floor(
extract(epoch FROM statement_timestamp()) * 1000
)::bigint AS observed_at_ms
), candidates AS (
SELECT attempt.id, attempt.run_id, attempt.status,
attempt.created_at_ms
FROM "ql3"."run_attempts" AS attempt
JOIN "ql3"."runs" AS run ON run.id = attempt.run_id
CROSS JOIN observation
WHERE run.execution_owner = 'runtime'
AND run.status IN ('dispatching', 'running', 'lost')
AND attempt.status IN ('claimed', 'starting', 'running')
AND (
attempt.lease_expires_at_ms IS NULL
OR attempt.lease_expires_at_ms <= observation.observed_at_ms
)
AND NOT (
attempt.status = 'claimed'
AND attempt.executor_type = 'remote_worker'
AND attempt.worker_id IS NULL
AND attempt.worker_session_id IS NULL
AND attempt.worker_generation IS NULL
AND attempt.lease_generation IS NULL
AND attempt.lease_version IS NULL
AND attempt.lease_expires_at_ms IS NULL
AND attempt.offer_id IS NULL
AND attempt.started_at_ms IS NULL
)
ORDER BY attempt.lease_expires_at_ms NULLS FIRST,
attempt.created_at_ms, attempt.id
LIMIT $1
)
SELECT observation.observed_at_ms AS "observedAtMs",
candidate.id AS "attemptId",
candidate.run_id AS "runId",
candidate.status,
candidate.created_at_ms AS "createdAtMs"
FROM observation
LEFT JOIN candidates AS candidate ON TRUE
ORDER BY candidate.created_at_ms, candidate.id`,
[maximum + 1],
);
if (result.rows.length < 1 || result.rows.length > maximum + 1) {
throw new TypeError(
'PostgreSQL runtime recovery violated its bounded page',
);
}
const observedAtMs = integer(
result.rows[0]!.observedAtMs,
'observation',
);
const candidates: ClusterControlRecoveryCandidate[] = [];
for (const row of result.rows) {
if (row.attemptId === null || row.attemptId === undefined) continue;
const status = text(row.status, 'Attempt status');
if (!['claimed', 'starting', 'running'].includes(status)) {
throw new TypeError(
'PostgreSQL runtime recovery Attempt status is invalid',
);
}
candidates.push(
Object.freeze({
kind: 'attempt' as const,
id: text(row.attemptId, 'Attempt ID'),
runId: text(row.runId, 'Run ID'),
status: status as 'claimed' | 'starting' | 'running',
createdAtMs: integer(row.createdAtMs, 'creation time'),
}),
);
}
const hasMore = candidates.length > maximum;
return Object.freeze({
observedAtMs,
candidates: Object.freeze(candidates.slice(0, maximum)),
hasMore,
});
}
}