Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): live legacy refusals name the active ids and the whole live selection (#5157, DX-O15)

garrytanb6cdc5ff486d
diff --git a/src/core/minions/idempotency-coalesce.ts b/src/core/minions/idempotency-coalesce.ts
index 31153e2068..289475d2c4 100644
--- a/src/core/minions/idempotency-coalesce.ts
+++ b/src/core/minions/idempotency-coalesce.ts
@@ -5,9 +5,25 @@
* SQL NULL authority stays distinguishable from JSONB null.
*/
import type { BrainEngine } from '../engine.ts';
-import { LEGACY_AUTHORITY_COLUMN, coalesceDecision, type SubmissionAuthority } from './submission-authority.ts';
+import { ERROR_CATALOGUE } from '../error-catalogue.ts';
+import { OperationError } from '../ops/contract.ts';
+import { LEGACY_AUTHORITY_COLUMN, coalesceDecision, legacyJobAuthorityError, type SubmissionAuthority } from './submission-authority.ts';
import { rowToMinionJob, type MinionJob } from './types.ts';
+/**
+ * `coalesceDecision`, with a legacy refusal's hint naming the active job ids
+ * to cancel first, so the printed recovery runs verbatim.
+ */
+export async function decideCoalesce(tx: BrainEngine, row: Record<string, unknown>, authority: SubmissionAuthority): Promise<'coalesce' | 'release'> {
+ try {
+ return coalesceDecision(row, authority);
+ } catch (error) {
+ if (!(error instanceof OperationError) || error.docs !== ERROR_CATALOGUE.legacy_job_authority.docs) throw error;
+ const active = await tx.executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE status = 'active' ORDER BY id LIMIT 10");
+ throw legacyJobAuthorityError(row, active.map(job => Number(job.id)));
+ }
+}
+
const KEYED_ROW_SQL = `SELECT *, ${LEGACY_AUTHORITY_COLUMN} FROM minion_jobs WHERE idempotency_key = $1`;
function coalescedJob(row: Record<string, unknown>): MinionJob {
@@ -36,7 +52,7 @@ async function releaseIdempotencyKey(tx: BrainEngine, row: Record<string, unknow
export async function coalesceOnIdempotencyKey(tx: BrainEngine, key: string, authority: SubmissionAuthority): Promise<MinionJob | null> {
const [existing] = await tx.executeRaw<Record<string, unknown>>(KEYED_ROW_SQL, [key]);
if (!existing) return null;
- if (coalesceDecision(existing, authority) === 'coalesce') return coalescedJob(existing);
+ if (await decideCoalesce(tx, existing, authority) === 'coalesce') return coalescedJob(existing);
await releaseIdempotencyKey(tx, existing, key);
return null;
}
@@ -53,7 +69,7 @@ export async function insertOrCoalesce(
for (let retried = false; !inserted && key; retried = true) {
const [winner] = await tx.executeRaw<Record<string, unknown>>(KEYED_ROW_SQL, [key]);
if (!winner) throw new Error(`idempotency_key ${key} insert returned no row and no existing row found`);
- if (coalesceDecision(winner, authority) === 'coalesce') return { coalesced: coalescedJob(winner) };
+ if (await decideCoalesce(tx, winner, authority) === 'coalesce') return { coalesced: coalescedJob(winner) };
if (retried) throw new Error(`idempotency_key ${key} was released but the retried insert still conflicted`);
await releaseIdempotencyKey(tx, winner, key);
[inserted] = await tx.executeRaw<Record<string, unknown>>(insertSql, params);
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 88030e8ef9..712459815d 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -8,14 +8,14 @@
* await queue.prune({ olderThan: new Date(Date.now() - 30 * 86400000) });
*/
-import { APPLICATION_AUTHORITY, LEGACY_AUTHORITY_COLUMN, coalesceDecision, assertNoUnreviewedJobs, authorizeJobExecution, currentSubmissionAuthority, parseSubmissionAuthority, type SubmissionAuthority } from './submission-authority.ts';
+import { APPLICATION_AUTHORITY, LEGACY_AUTHORITY_COLUMN, assertNoUnreviewedJobs, authorizeJobExecution, currentSubmissionAuthority, parseSubmissionAuthority, type SubmissionAuthority } from './submission-authority.ts';
import type { BrainEngine } from '../engine.ts';
import type {
MinionJob, MinionJobInput, MinionJobStatus, InboxMessage, TokenUpdate,
MinionQueueOpts, ChildDoneMessage, ChildOutcome, Attachment, AttachmentInput,
} from './types.ts';
import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';
-import { coalesceOnIdempotencyKey, insertOrCoalesce } from './idempotency-coalesce.ts';
+import { coalesceOnIdempotencyKey, decideCoalesce, insertOrCoalesce } from './idempotency-coalesce.ts';
import { validateAttachment } from './attachments.ts';
import { isProtectedJobName } from './protected-names.ts';
import { assertEmbedBackfillQueueAdmission } from './embed-backfill-admission.ts';
@@ -163,13 +163,14 @@ type CoalesceAuditEvent = {
* audit append is filesystem I/O, and doing it while holding the advisory
* lock + a pool connection would let a hung audit volume serialize every
* submission for the scope (adversarial-review finding). */
-function coalesceReturn(
+async function coalesceReturn(
+ tx: BrainEngine,
row: Record<string, unknown>,
audit: Omit<CoalesceAuditEvent, 'returned_job_id'>,
sink: (ev: CoalesceAuditEvent) => void,
authority: SubmissionAuthority,
-): MinionJob {
- if (coalesceDecision(row, authority) !== 'coalesce') throw new Error(`job ${String(row.id)} is ${String(row.status)} and cannot be a coalesce target`);
+): Promise<MinionJob> {
+ if (await decideCoalesce(tx, row, authority) !== 'coalesce') throw new Error(`job ${String(row.id)} is ${String(row.status)} and cannot be a coalesce target`);
const coalesced = rowToMinionJob(row);
coalesced.coalesced = true;
sink({ ...audit, returned_job_id: coalesced.id });
@@ -387,7 +388,7 @@ export class MinionQueue {
matchParams
);
if (match.length > 0) {
- return coalesceReturn(match[0], {
+ return coalesceReturn(tx, match[0], {
queue: admissionQueue,
name: jobName,
param_hash: paramHash,
@@ -496,7 +497,7 @@ export class MinionQueue {
[jobName, backpressureQueue, bpSourceId]
);
if (existingPending.length > 0) {
- return coalesceReturn(existingPending[0], {
+ return coalesceReturn(tx, existingPending[0], {
queue: backpressureQueue,
name: jobName,
pending_count: pendingCount,
@@ -526,7 +527,7 @@ export class MinionQueue {
[jobName, backpressureQueue, bpSourceId]
);
if (existingWaiting.length > 0) {
- return coalesceReturn(existingWaiting[0], {
+ return coalesceReturn(tx, existingWaiting[0], {
queue: backpressureQueue,
name: jobName,
waiting_count: waitingCount,
diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.ts
index 9208fe3e18..cc19b889ec 100644
--- a/src/core/minions/submission-authority.ts
+++ b/src/core/minions/submission-authority.ts
@@ -287,7 +287,7 @@ export const UNREVIEWED_LIVE_JOBS_SQL = `SELECT id, name, status, submission_aut
export const LEGACY_AUTHORITY_COLUMN = 'submission_authority IS NULL AS legacy_authority_is_null';
/** `permission_denied` for a job row whose SQL NULL authority predates the v0.50 cutover. */
-export function legacyJobAuthorityError(row: Record<string, unknown>): OperationError {
+export function legacyJobAuthorityError(row: Record<string, unknown>, activeIds: readonly number[] = []): OperationError {
const id = String(row.id), name = String(row.name), status = String(row.status);
const what = `Queued job authorization: job ${id} (${name}, ${status}) has no submission authority because it predates the upgrade, so it cannot be reused until it is reviewed.`;
if (status === 'completed' || status === 'failed') {
@@ -297,7 +297,8 @@ export function legacyJobAuthorityError(row: Record<string, unknown>): Operation
if (status === 'active') {
return catalogueError('legacy_job_authority', what, `${STOP_PRODUCERS}, then cancel it: gbrain jobs cancel ${id}; run gbrain doctor to review the rest.`);
}
- return catalogueError('legacy_job_authority', what, legacyRecoveryHint([status], [name]));
+ // Name every reviewable live status: one preview and apply then clears the whole SQL NULL population the claim gate blocks on.
+ return catalogueError('legacy_job_authority', what, legacyRecoveryHint(LIVE_JOB_STATUSES, [], activeIds));
}
const RELEASABLE = new Set(['dead', 'cancelled']);
diff --git a/test/serve-http-ingest-legacy.test.ts b/test/serve-http-ingest-legacy.test.ts
index 90319bc664..62a7674193 100644
--- a/test/serve-http-ingest-legacy.test.ts
+++ b/test/serve-http-ingest-legacy.test.ts
@@ -68,7 +68,7 @@ describe('POST /ingest over legacy job authority', () => {
expect(Object.keys(body).sort()).toEqual(['docs_url', 'error', 'hint', 'message']);
expect(body.error).toBe('permission_denied');
expect(body.message).toContain(`job ${id} (ingest_capture, waiting)`);
- expect(body.hint).toContain('gbrain jobs authorize-legacy --select "status=waiting,name=ingest_capture"');
+ expect(body.hint).toContain('gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused"');
expect(body.hint).toContain('--expect <hash> --yes');
expect(body.docs_url).toBe('docs/guides/repair.md#legacy-job-authority');
});