Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(minions): one raw-row coalesce rule for legacy NULL authority on all five paths (#5157, #5114)
garrytanbb71075f9e91
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex f14a2621f4..7a6f4bcd66 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -60,6 +60,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown' | 'wedge_restart' | 'configuration_blocked'`). Single shared point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful, deliberate wedge restarts and configuration blocks are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.+- `src/core/minions/idempotency-coalesce.ts` — the idempotency-key halves of `MinionQueue.add`: `coalesceOnIdempotencyKey` (fast path) and `insertOrCoalesce` (insert race: re-read the winner, release a dead or cancelled key with a CAS update that rechecks key, status and SQL NULL authority, retry the insert once). Both apply `coalesceDecision` from `submission-authority.ts`. Tests: `test/minions-legacy-coalesce.test.ts`.+- `src/core/minions/job-context.ts` — shared `buildJobContext(engine, queue, job, lockToken, signal, shutdownSignal)` (extracted verbatim from executeJob) so inline mode and the run-child child wire identical token-fenced DB callbacks.- `src/core/minions/job-isolation.ts` — per-job process-isolation protocol: atomic outcome-file codec (`writeChildOutcomeFile` tmp+rename, `decodeChildOutcomeFile` with a 32MiB cap that throws `UnrecoverableError` — oversize results die loudly on attempt 1, decode errors report byte counts never content), `encodeHandlerError`/`reconstructHandlerError` preserving `UnrecoverableError`, `RateLeaseUnavailableError`, and allowlisted `LocalConfigurationError` reason codes; configuration messages are reconstructed locally rather than trusting child text, the child argv/env contract (`CHILD_ENV`, `buildChildArgs`), `resolveChildCliInvocation` (explicit `GBRAIN_JOB_CHILD_CLI` override → current worker entrypoint/compiled executable → PATH fallback → null for fail-fast), and the bounded selected-runtime handshake in `child-readiness.ts` (protocol/features plus version-skew reporting; 20s deadline and combined 64KiB stdout/stderr cap; only complete allowlisted replies prove configuration failure). `killProcessGroup(pid, sig)` — children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. Pinned by `test/job-isolation-protocol.test.ts` (incl. real-process grandchild-death). `buildChildArgs(jobId, env = process.env)` appends `--allow-shell-jobs` when `env.GBRAIN_ALLOW_SHELL_JOBS === '1'` (child-job-runner passes its spawning env), because the per-job child re-runs the cwd-.env preflight in the worker's cwd and would otherwise lose the opt-in; `jobs run-child` re-asserts the env from that flag. Pinned by `test/job-isolation-allow-shell-jobs.test.ts`. `child-job-runner.ts` passes `opts.env ?? process.env` as the base env, so `GBRAIN_ALLOW_SHELL_JOBS === '1'` in it appends `--allow-shell-jobs` (any other value does not); pinned by the pass-through case in `test/child-job-runner.test.ts`.diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex c768623b88..fd810e6ef2 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (one implementation for both spawn sites; tini wrapping is testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with `tini -s --` prepended when present, or the bare invocation otherwise. Subreaper mode also serves job children; it does not imply PID 1 or containment of descendants that escape the process group. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).-- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows. `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.+- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `coalesceDecision(rawRow, authority)` is the one coalesce rule for all five `MinionQueue.add` coalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read with `LEGACY_AUTHORITY_COLUMN` so only SQL NULL authority gets the legacy rule (dead/cancelled keys released by a CAS update, completed/failed coalesce for application callers only, live rows refused with the `legacy_job_authority` catalogue error); `UNREVIEWED_LIVE_JOBS_SQL` is the claim gate's query, shared with doctor `legacy_job_authority`. Tests: `test/minions-legacy-coalesce.test.ts` (PGLite) and `test/e2e/minions-legacy-coalesce-postgres.test.ts`, both over `test/helpers/legacy-coalesce-matrix.ts`. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows. `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 26527e0240..e882386380 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -192,6 +192,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {],// Any minions queue/worker/handler change exercises all minion E2E."src/core/minions/**": [+ "test/e2e/minions-legacy-coalesce-postgres.test.ts","test/e2e/worker-readiness-cli.test.ts","test/e2e/worker-configuration-release.test.ts","test/e2e/delegated-grants-withdrawal.test.ts",diff --git a/src/core/minions/idempotency-coalesce.ts b/src/core/minions/idempotency-coalesce.tsnew file mode 100644index 0000000000..31153e2068--- /dev/null+++ b/src/core/minions/idempotency-coalesce.ts@@ -0,0 +1,62 @@+/**+ * The idempotency-key halves of `MinionQueue.add` (#5157 / #5114): the fast+ * path before any other admission work and the insert-race resolution after+ * `ON CONFLICT DO NOTHING`. Both apply `coalesceDecision` to the raw row, so+ * 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 { rowToMinionJob, type MinionJob } from './types.ts';++const KEYED_ROW_SQL = `SELECT *, ${LEGACY_AUTHORITY_COLUMN} FROM minion_jobs WHERE idempotency_key = $1`;++function coalescedJob(row: Record<string, unknown>): MinionJob {+ const job = rowToMinionJob(row);+ job.coalesced = true;+ return job;+}++/**+ * Frees a dead or cancelled row's idempotency key so a fresh attempt can be+ * inserted, keeping the released key in its data for the dream breaker. The+ * update rechecks the key, the terminal status and the SQL NULL-ness of the+ * authority it was decided on, so a row reviewed or resubmitted in between+ * keeps its key and the caller's insert conflicts into the race path instead.+ */+async function releaseIdempotencyKey(tx: BrainEngine, row: Record<string, unknown>, key: string): Promise<void> {+ await tx.executeRaw(+ `UPDATE minion_jobs SET idempotency_key = NULL, data = data || $2::text::jsonb+ WHERE id = $1 AND idempotency_key = $3 AND status IN ('dead','cancelled')+ AND (submission_authority IS NULL) = $4::boolean`,+ [row.id, JSON.stringify({ __released_idempotency_key: key }), key, row.legacy_authority_is_null === true],+ );+}++/** Fast path: the row already holding `key`, coalesced, or null once a releasable key was freed (or none exists). */+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);+ await releaseIdempotencyKey(tx, existing, key);+ return null;+}++/**+ * Runs the INSERT; when `ON CONFLICT DO NOTHING` returns no row, re-reads the+ * winner and applies the same rule. A dead or cancelled winner has its key+ * released and the insert is retried once in the same transaction.+ */+export async function insertOrCoalesce(+ tx: BrainEngine, insertSql: string, params: unknown[], key: string | undefined, authority: SubmissionAuthority,+): Promise<{ inserted: Record<string, unknown> } | { coalesced: MinionJob }> {+ let [inserted] = await tx.executeRaw<Record<string, unknown>>(insertSql, params);+ 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 (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);+ }+ return { inserted: inserted! };+}diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex 89adbabfcb..88030e8ef9 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -8,13 +8,14 @@* await queue.prune({ olderThan: new Date(Date.now() - 30 * 86400000) });*/-import { APPLICATION_AUTHORITY, assertSameAuthority, assertNoUnreviewedJobs, authorizeJobExecution, currentSubmissionAuthority, parseSubmissionAuthority, type SubmissionAuthority } from './submission-authority.ts';+import { APPLICATION_AUTHORITY, LEGACY_AUTHORITY_COLUMN, coalesceDecision, 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 { validateAttachment } from './attachments.ts';import { isProtectedJobName } from './protected-names.ts';import { assertEmbedBackfillQueueAdmission } from './embed-backfill-admission.ts';@@ -168,13 +169,14 @@ function coalesceReturn(sink: (ev: CoalesceAuditEvent) => void,authority: SubmissionAuthority,): MinionJob {- assertSameAuthority(row.submission_authority, authority);+ if (coalesceDecision(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 });return coalesced;}+export class MinionQueue {readonly maxSpawnDepth: number;readonly maxAttachmentBytes: number;@@ -345,23 +347,8 @@ export class MinionQueue {// We NULL the key (preserving the row, with the released key in its// data for the dream breaker) and fall through to the INSERT below.if (opts?.idempotency_key) {- const existing = await tx.executeRaw<Record<string, unknown>>(- `SELECT * FROM minion_jobs WHERE idempotency_key = $1`,- [opts.idempotency_key]- );- if (existing.length > 0) {- const existingJob = rowToMinionJob(existing[0]);- assertSameAuthority(existingJob.submission_authority, authority);- if (existingJob.status === 'dead' || existingJob.status === 'cancelled') {- await tx.executeRaw(- `UPDATE minion_jobs SET idempotency_key = NULL, data = data || $2::text::jsonb WHERE id = $1`,- [existingJob.id, JSON.stringify({ __released_idempotency_key: opts.idempotency_key })]- );- } else {- existingJob.coalesced = true;- return existingJob;- }- }+ const existing = await coalesceOnIdempotencyKey(tx, opts.idempotency_key, authority);+ if (existing) return existing;}// 1a. Param-coalescing (admission): an identical parentless submit —@@ -390,7 +377,7 @@ export class MinionQueue {const matchParams: unknown[] = [jobName, admissionQueue, paramHash];if (ttlHours != null) matchParams.push(ttlHours / 2);const match = await tx.executeRaw<Record<string, unknown>>(- `SELECT * FROM minion_jobs+ `SELECT *, ${LEGACY_AUTHORITY_COLUMN} FROM minion_jobsWHERE name = $1 AND queue = $2 AND status = 'waiting'AND parent_job_id IS NULLAND data->>'__param_hash' = $3@@ -501,7 +488,7 @@ export class MinionQueue {const pendingCount = parseInt(pendingCountRows[0]?.count ?? '0', 10);if (pendingCount >= maxPending) {const existingPending = await tx.executeRaw<Record<string, unknown>>(- `SELECT * FROM minion_jobs+ `SELECT *, ${LEGACY_AUTHORITY_COLUMN} FROM minion_jobsWHERE name = $1 AND queue = $2 AND ${pendingCond}AND ${scopeExact}ORDER BY CASE WHEN status = 'waiting' THEN 0 ELSE 1 END, created_at DESC, id DESC@@ -531,7 +518,7 @@ export class MinionQueue {const waitingCount = parseInt(waitingCountRows[0]?.count ?? '0', 10);if (waitingCount >= maxWaiting) {const existingWaiting = await tx.executeRaw<Record<string, unknown>>(- `SELECT * FROM minion_jobs+ `SELECT *, ${LEGACY_AUTHORITY_COLUMN} FROM minion_jobsWHERE name = $1 AND queue = $2 AND status = 'waiting'AND ${scopeWildcard}ORDER BY created_at DESC, id DESC@@ -660,25 +647,12 @@ export class MinionQueue {];if (hasMaxStalled) params.push(clampedMaxStalled);- const inserted = await tx.executeRaw<Record<string, unknown>>(insertSql, params);-- // ON CONFLICT DO NOTHING returns 0 rows — fall back to SELECT to fetch the- // existing row that won the race.- if (inserted.length === 0 && opts?.idempotency_key) {- const existing = await tx.executeRaw<Record<string, unknown>>(- `SELECT * FROM minion_jobs WHERE idempotency_key = $1`,- [opts.idempotency_key]- );- if (existing.length === 0) {- throw new Error(`idempotency_key ${opts.idempotency_key} insert returned no row and no existing row found`);- }- const raced = rowToMinionJob(existing[0]);- assertSameAuthority(raced.submission_authority, authority);- raced.coalesced = true; // third coalesce path: lost the insert race- return raced;- }+ // ON CONFLICT DO NOTHING returns 0 rows: a concurrent submit won the+ // race, and its row goes through the same coalesce rule (third path).+ const outcome = await insertOrCoalesce(tx, insertSql, params, opts?.idempotency_key, authority);+ if ('coalesced' in outcome) return outcome.coalesced;- const child = rowToMinionJob(inserted[0]);+ const child = rowToMinionJob(outcome.inserted);// 4. Flip parent to waiting-children if this is a fresh child insert.// Only transition from non-terminal, non-already-waiting-children states.diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.tsindex 50506adbb7..a112195a28 100644--- a/src/core/minions/submission-authority.ts+++ b/src/core/minions/submission-authority.ts@@ -5,6 +5,7 @@ import { realpathSync, statSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';import type { AuthInfo, OperationContext } from '../ops/contract.ts';import { OperationError } from '../ops/contract.ts';+import { catalogueError } from '../error-catalogue.ts';import { normalizeSlugPrefix } from '../ops/context.ts';import { hasScope } from '../scope.ts';import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyTokenScope } from '../legacy-token-scope.ts';@@ -266,12 +267,73 @@ export async function assertRemoteJobControl(ctx: OperationContext, job: MinionJawait authorizeJobExecution(ctx.engine, job);}+/** Statuses the claim gate covers: a row in one of them blocks every worker while its authority is unparsable. */+export const LIVE_JOB_STATUSES = ['waiting', 'active', 'delayed', 'waiting-children', 'paused'] as const;++/**+ * The claim gate's candidate rows, shared by `assertNoUnreviewedJobs` and the+ * doctor `legacy_job_authority` check so their counts can never drift. Callers+ * keep the rows `parseSubmissionAuthority` rejects; `legacy_authority_is_null`+ * splits them into authorizable SQL NULL rows and unsupported non-NULL rows.+ */+export const UNREVIEWED_LIVE_JOBS_SQL = `SELECT id, name, status, submission_authority, submission_authority IS NULL AS legacy_authority_is_null+ FROM minion_jobs+ WHERE status IN (${LIVE_JOB_STATUSES.map(s => `'${s}'`).join(',')})+ AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb+ ORDER BY id`;++/** Select-list column every coalesce read adds so SQL NULL stays distinguishable from JSONB null. */+export const LEGACY_AUTHORITY_COLUMN = 'submission_authority IS NULL AS legacy_authority_is_null';++/** The filled `--select` preview that reviews one legacy row's name and status. */+export function legacyAuthorizeCommand(name: string, status: string): string {+ return `gbrain jobs authorize-legacy --select "status=${status},name=${name}"`;+}++/** `permission_denied` for a job row whose SQL NULL authority predates the v0.50 cutover. */+export function legacyJobAuthorityError(row: Record<string, unknown>): 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') {+ return catalogueError('legacy_job_authority', what,+ `Resubmit with a new idempotency key; a local operator can review the old row with ${legacyAuthorizeCommand(name, status)}.`);+ }+ if (status === 'active') {+ return catalogueError('legacy_job_authority', what,+ `Stop producers (gbrain serve, gbrain autopilot) and workers, then cancel it: gbrain jobs cancel ${id}; run gbrain doctor to review the rest.`);+ }+ return catalogueError('legacy_job_authority', what,+ `Stop producers (gbrain serve, gbrain autopilot) and workers, cancel active jobs (gbrain jobs cancel <id>), preview with ${legacyAuthorizeCommand(name, status)}, apply with the printed --expect <hash> --yes, then restart them.`);+}++const RELEASABLE = new Set(['dead', 'cancelled']);++/**+ * The one coalesce rule for `MinionQueue.add` (idempotency fast path, param+ * coalescing, the pending and waiting caps, and the insert race). `row` is a+ * raw `minion_jobs` row selected with `LEGACY_AUTHORITY_COLUMN`.+ *+ * Only SQL NULL authority (rows from before the v0.50 cutover) gets the+ * legacy rule: a dead or cancelled key is released, a completed or failed row+ * coalesces for application callers only, and a live row is refused for every+ * caller because the claim gate keeps workers from ever running it. JSONB+ * null, malformed and future-version authority keep the cross-authority+ * denial, as does any authority that differs from the caller's.+ */+export function coalesceDecision(row: Record<string, unknown>, authority: SubmissionAuthority): 'coalesce' | 'release' {+ const status = String(row.status);+ if (row.legacy_authority_is_null === true) {+ if (RELEASABLE.has(status)) return 'release';+ if ((status === 'completed' || status === 'failed') && authority.kind === 'application') return 'coalesce';+ throw legacyJobAuthorityError(row);+ }+ assertSameAuthority(row.submission_authority, authority);+ return RELEASABLE.has(status) ? 'release' : 'coalesce';+}+/** Startup and claim gate: do not let sweeps silently destroy unresolved legacy dependency graphs. */export async function assertNoUnreviewedJobs(engine: BrainEngine): Promise<void> {- const rows = await engine.executeRaw<{ id: number; submission_authority: unknown }>(- `SELECT id, submission_authority FROM minion_jobs- WHERE status IN ('waiting','active','delayed','waiting-children','paused')- AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb`);+ const rows = await engine.executeRaw<{ id: number; submission_authority: unknown }>(UNREVIEWED_LIVE_JOBS_SQL);const invalid = rows.filter(row => !parseSubmissionAuthority(row.submission_authority));if (invalid.length) deny(`${invalid.length} legacy jobs have missing or unsupported authority; stop producers/workers. Review SQL NULL rows with jobs authorize-legacy --ids ...; unsupported non-NULL authority requires matching application/database versions or explicit local cancellation before workers start`);}diff --git a/test/e2e/minions-legacy-coalesce-postgres.test.ts b/test/e2e/minions-legacy-coalesce-postgres.test.tsnew file mode 100644index 0000000000..0b7dbeb18b--- /dev/null+++ b/test/e2e/minions-legacy-coalesce-postgres.test.ts@@ -0,0 +1,56 @@+/**+ * #5157 / #5114 on real Postgres: the same coalesce matrix the PGLite unit+ * test runs (`test/minions-legacy-coalesce.test.ts`), plus a real concurrent+ * insert race over a released legacy key.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { runMigrations } from '../../src/core/migrate.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { prepareRemoteJob } from '../../src/core/minions/submission-authority.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { PATHS, runCoalesceMatrix } from '../helpers/legacy-coalesce-matrix.ts';+import { withEnv } from '../helpers/with-env.ts';++const suite = hasDatabase() ? describe : describe.skip;+suite('Postgres legacy coalesce rule (#5157)', () => {+ let sandbox: string, root: string;+ const ctx = (): OperationContext => ({+ engine: getEngine(), config: {} as OperationContext['config'], remote: true, sourceId: 'default', dryRun: false,+ logger: { info() {}, warn() {}, error() {} },+ auth: { token: 'test-only', clientId: 'coalesce-test-client', principal: { kind: 'oauth_client', id: 'coalesce-test-client' }, scopes: ['admin'], sourceId: 'default' },+ });+ beforeAll(async () => {+ sandbox = mkdtempSync(join(tmpdir(), 'gbrain-pg-legacy-coalesce-'));+ root = join(sandbox, 'repo'); mkdirSync(root); execFileSync('git', ['init', '-q', root]);+ await withEnv({ GBRAIN_HOME: sandbox }, async () => { await setupDB(); await runMigrations(getEngine()); });+ }, 120_000);+ afterAll(async () => { await teardownDB(); if (sandbox) rmSync(sandbox, { recursive: true, force: true }); });+ beforeEach(async () => {+ await getEngine().executeRaw('DELETE FROM minion_jobs');+ await getEngine().executeRaw("DELETE FROM oauth_clients WHERE client_id = 'coalesce-test-client'");+ await getEngine().executeRaw("UPDATE sources SET local_path = $1, config = '{}'::jsonb, archived = false WHERE id = 'default'", [root]);+ await getEngine().executeRaw("INSERT INTO oauth_clients (client_id, client_secret_hash, client_name, scope, source_id) VALUES ('coalesce-test-client', 'fixture-hash', 'example-client', 'admin', 'default')");+ });++ test('variant x path x status x caller matches PGLite', async () => {+ const cells = await runCoalesceMatrix(getEngine(), () => prepareRemoteJob(ctx(), 'lint', {}));+ expect(cells).toBe(4 * Object.values(PATHS).reduce((n, p) => n + p.statuses.length * p.callers.length, 0));+ }, 300_000);++ test('concurrent resubmissions over one dead legacy key insert exactly one fresh job', async () => {+ const queue = new MinionQueue(getEngine());+ const old = await queue.add('legacy-fixture', { n: 1 }, { idempotency_key: 'dream:synth-v2:race' });+ await getEngine().executeRaw("UPDATE minion_jobs SET status = 'dead', submission_authority = NULL WHERE id = $1", [old.id]);+ const results = await Promise.all(Array.from({ length: 6 }, () => queue.add('legacy-fixture', { n: 1 }, { idempotency_key: 'dream:synth-v2:race' })));+ const ids = new Set(results.map(job => job.id));+ expect(ids.size).toBe(1);+ expect(ids.has(old.id)).toBe(false);+ const rows = await getEngine().executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE idempotency_key = 'dream:synth-v2:race'");+ expect(rows.map(r => r.id)).toEqual([...ids]);+ }, 60_000);+});diff --git a/test/helpers/legacy-coalesce-matrix.ts b/test/helpers/legacy-coalesce-matrix.tsnew file mode 100644index 0000000000..318a283879--- /dev/null+++ b/test/helpers/legacy-coalesce-matrix.ts@@ -0,0 +1,181 @@+/**+ * #5157 / #5114 coalesce matrix, shared by the PGLite unit test and the+ * Postgres E2E test so both engines run the same table.+ *+ * Every case submits once through `MinionQueue.add` to create a row with the+ * right name, payload, hash and key, rewrites that row's status and+ * authority to the case's variant, then submits the same request again on+ * one of the five coalesce paths and checks the outcome.+ */+import { expect } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { APPLICATION_AUTHORITY, coalesceDecision, type SubmissionAuthority } from '../../src/core/minions/submission-authority.ts';+import type { MinionJobInput } from '../../src/core/minions/types.ts';+import { OperationError } from '../../src/core/ops/contract.ts';++export type AuthorityVariant = 'sql_null' | 'jsonb_null' | 'malformed' | 'future';+export type CoalescePath = 'idempotency' | 'param' | 'pending' | 'waiting' | 'race';+export type Outcome = 'coalesce' | 'release' | 'deny-legacy' | 'deny-cross';+export type Caller = 'application' | 'remote';+export interface RemoteSubmission { data: Record<string, unknown>; authority: SubmissionAuthority }++export const AUTHORITY_VARIANTS: Record<AuthorityVariant, string | null> = {+ sql_null: null,+ jsonb_null: 'null',+ malformed: '{"version":1}',+ future: '{"version":2,"kind":"application"}',+};+export const ALL_STATUSES = ['dead', 'cancelled', 'completed', 'failed', 'waiting', 'active', 'delayed', 'waiting-children', 'paused'] as const;+type Status = typeof ALL_STATUSES[number];++/** The statuses each path can select as a coalesce target, and the callers it serves. */+export const PATHS: Record<CoalescePath, { statuses: readonly Status[]; callers: readonly Caller[] }> = {+ idempotency: { statuses: ALL_STATUSES, callers: ['application', 'remote'] },+ race: { statuses: ALL_STATUSES, callers: ['application', 'remote'] },+ // Param coalescing is application-only by design (queue.ts coalesceActive).+ param: { statuses: ['waiting'], callers: ['application'] },+ pending: { statuses: ['waiting', 'active'], callers: ['application', 'remote'] },+ waiting: { statuses: ['waiting'], callers: ['application', 'remote'] },+};++export const LEGACY_DOCS = 'docs/guides/repair.md#legacy-job-authority';++export function expectedOutcome(variant: AuthorityVariant, status: Status, caller: Caller): Outcome {+ if (variant !== 'sql_null') return 'deny-cross';+ if (status === 'dead' || status === 'cancelled') return 'release';+ if ((status === 'completed' || status === 'failed') && caller === 'application') return 'coalesce';+ return 'deny-legacy';+}++/**+ * Hides the first idempotency-key read inside each transaction, so the+ * fast path misses and the INSERT's ON CONFLICT lands on the race path+ * exactly as a concurrent winner would.+ */+export function racingEngine(engine: BrainEngine): BrainEngine {+ const bind = <T extends object>(target: T, prop: string | symbol) => {+ const value = Reflect.get(target, prop);+ return typeof value === 'function' ? value.bind(target) : value;+ };+ return new Proxy(engine, {+ get(target, prop) {+ if (prop !== 'transaction') return bind(target, prop);+ return <T>(fn: (tx: BrainEngine) => Promise<T>) => target.transaction(tx => {+ let hidden = false;+ return fn(new Proxy(tx, {+ get(t, p) {+ if (p !== 'executeRaw') return bind(t, p);+ return (sql: string, params?: unknown[]) => {+ if (!hidden && /FROM minion_jobs WHERE idempotency_key = \$1$/.test(sql.trim())) { hidden = true; return Promise.resolve([]); }+ return t.executeRaw(sql, params);+ };+ },+ }));+ });+ },+ });+}++function optsFor(path: CoalescePath): Partial<MinionJobInput> {+ switch (path) {+ case 'idempotency': case 'race': return { idempotency_key: 'matrix-key' };+ case 'param': return { coalesce_params: true };+ case 'pending': return { maxPending: 1 };+ case 'waiting': return { maxWaiting: 1 };+ }+}++async function setVariant(engine: BrainEngine, id: number, status: Status, variant: AuthorityVariant): Promise<void> {+ // The queue protocol trigger only lets a claim make a row active, and only+ // with authority present, so claim first and rewrite the authority after.+ if (status === 'active') {+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'active', lock_token = 'matrix', lock_until = now() + interval '1 hour',+ claim_generation = claim_generation + 1 WHERE id = $1`, [id]);+ } else {+ await engine.executeRaw('UPDATE minion_jobs SET status = $2 WHERE id = $1', [id, status]);+ }+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = $2::text::jsonb WHERE id = $1', [id, AUTHORITY_VARIANTS[variant]]);+}++async function rejection(fn: () => Promise<unknown>): Promise<OperationError> {+ try { await fn(); } catch (error) { return error as OperationError; }+ throw new Error('expected a refusal');+}++/** Runs one case and asserts its outcome; returns the outcome it observed. */+export async function runCoalesceCase(+ engine: BrainEngine,+ remote: () => Promise<RemoteSubmission>,+ c: { variant: AuthorityVariant; status: Status; caller: Caller; path: CoalescePath },+): Promise<Outcome> {+ await engine.executeRaw('DELETE FROM minion_jobs');+ const submission = c.caller === 'remote' ? await remote() : { data: { matrix: true, sourceId: 'default' }, authority: APPLICATION_AUTHORITY };+ const name = c.caller === 'remote' ? 'lint' : 'matrix-job';+ const opts = optsFor(c.path);+ const trusted = { submissionAuthority: submission.authority };+ const first = await new MinionQueue(engine).add(name, submission.data, opts, trusted);+ await setVariant(engine, first.id, c.status, c.variant);+ const [{ count: before }] = await engine.executeRaw<{ count: string }>('SELECT count(*)::text AS count FROM minion_jobs');+ const queue = new MinionQueue(c.path === 'race' ? racingEngine(engine) : engine);+ const expected = expectedOutcome(c.variant, c.status, c.caller);+ const label = JSON.stringify(c);++ const [raw] = await engine.executeRaw<Record<string, unknown>>(+ 'SELECT *, submission_authority IS NULL AS legacy_authority_is_null FROM minion_jobs WHERE id = $1', [first.id]);+ let decided: Outcome;+ try { decided = coalesceDecision(raw!, submission.authority); }+ catch (error) { decided = (error as OperationError).docs === LEGACY_DOCS ? 'deny-legacy' : 'deny-cross'; }+ expect(decided, `${label} decision`).toBe(expected);++ if (expected === 'deny-legacy' || expected === 'deny-cross') {+ const error = await rejection(() => queue.add(name, submission.data, opts, trusted));+ expect(error, label).toBeInstanceOf(OperationError);+ expect(error.code, label).toBe('permission_denied');+ if (expected === 'deny-legacy') {+ expect(error.docs, label).toBe(LEGACY_DOCS);+ expect(error.suggestion, label).toContain(c.status === 'active' ? `gbrain jobs cancel ${first.id}` : 'gbrain jobs authorize-legacy --select');+ expect(error.message, label).toContain(`job ${first.id} (${name}, ${c.status})`);+ } else {+ expect(error.message, label).toContain('coalescing across');+ expect(error.docs, label).toBeUndefined();+ }+ } else {+ const result = await queue.add(name, submission.data, opts, trusted);+ const [old] = await engine.executeRaw<{ idempotency_key: string | null; data: Record<string, unknown> | string }>(+ 'SELECT idempotency_key, data FROM minion_jobs WHERE id = $1', [first.id]);+ if (expected === 'coalesce') {+ expect(result.id, label).toBe(first.id);+ expect(result.coalesced, label).toBe(true);+ } else {+ expect(result.id, label).not.toBe(first.id);+ expect(result.coalesced, label).toBeFalsy();+ expect(result.submission_authority, label).toEqual(submission.authority);+ const data = typeof old!.data === 'string' ? JSON.parse(old!.data) : old!.data;+ expect(old!.idempotency_key, label).toBeNull();+ expect(data.__released_idempotency_key, label).toBe('matrix-key');+ const [{ count: after }] = await engine.executeRaw<{ count: string }>('SELECT count(*)::text AS count FROM minion_jobs');+ expect(Number(after), label).toBe(Number(before) + 1);+ return expected;+ }+ }+ const [{ count: after }] = await engine.executeRaw<{ count: string }>('SELECT count(*)::text AS count FROM minion_jobs');+ expect(Number(after), `${label} inserted nothing`).toBe(Number(before));+ return expected;+}++/** Every (variant x path x status x caller) cell; returns how many cells ran. */+export async function runCoalesceMatrix(engine: BrainEngine, remote: () => Promise<RemoteSubmission>): Promise<number> {+ let cells = 0;+ for (const variant of Object.keys(AUTHORITY_VARIANTS) as AuthorityVariant[]) {+ for (const [path, spec] of Object.entries(PATHS) as Array<[CoalescePath, typeof PATHS[CoalescePath]]>) {+ for (const status of spec.statuses) {+ for (const caller of spec.callers) {+ await runCoalesceCase(engine, remote, { variant, status, caller, path });+ cells++;+ }+ }+ }+ }+ return cells;+}diff --git a/test/minions-legacy-coalesce.test.ts b/test/minions-legacy-coalesce.test.tsnew file mode 100644index 0000000000..d4abfca63b--- /dev/null+++ b/test/minions-legacy-coalesce.test.ts@@ -0,0 +1,141 @@+/**+ * #5157 / #5114: one coalesce rule on every coalesce path of+ * `MinionQueue.add` (PGLite; Postgres runs the same matrix in+ * `test/e2e/minions-legacy-coalesce-postgres.test.ts`).+ *+ * Only SQL NULL authority (rows from before the v0.50 cutover) gets the+ * legacy rule; JSONB null, malformed and future authority keep the+ * cross-authority denial.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import { APPLICATION_AUTHORITY, assertNoUnreviewedJobs, coalesceDecision, prepareRemoteJob } from '../src/core/minions/submission-authority.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { ALL_STATUSES, LEGACY_DOCS, PATHS, expectedOutcome, racingEngine, runCoalesceMatrix } from './helpers/legacy-coalesce-matrix.ts';+import { withEnv } from './helpers/with-env.ts';++const sandbox = mkdtempSync(join(tmpdir(), 'gbrain-legacy-coalesce-'));+const root = join(sandbox, 'repo');+const brainHome = join(sandbox, 'home');+let engine: PGLiteEngine;++function isolated<T>(fn: () => T | Promise<T>): Promise<T> {+ return withEnv({ GBRAIN_HOME: brainHome, DATABASE_URL: undefined }, fn);+}+function ctx(): OperationContext {+ return {+ engine, config: {} as OperationContext['config'], dryRun: false, remote: true, sourceId: 'default',+ logger: { info() {}, warn() {}, error() {} },+ auth: { token: 'test-only', clientId: 'client-a', principal: { kind: 'oauth_client', id: 'client-a' }, scopes: ['admin'], sourceId: 'default' },+ };+}+const remote = () => prepareRemoteJob(ctx(), 'lint', {});++beforeAll(async () => isolated(async () => {+ mkdirSync(root); mkdirSync(brainHome);+ execFileSync('git', ['init', '-q', root]);+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}), 60_000);+afterAll(async () => { await engine?.disconnect(); rmSync(sandbox, { recursive: true, force: true }); }, 60_000);+beforeEach(async () => isolated(async () => {+ await engine.executeRaw('DELETE FROM minion_jobs');+ await engine.executeRaw('DELETE FROM oauth_clients');+ await engine.executeRaw("UPDATE sources SET config = '{}'::jsonb, archived = false, local_path = $1 WHERE id = 'default'", [root]);+ await engine.executeRaw("INSERT INTO oauth_clients (client_id, client_secret_hash, client_name, scope, source_id) VALUES ('client-a', 'test-only', 'example-client', 'admin', 'default')");+}));++describe('coalesceDecision (raw rows)', () => {+ const remoteAuthority = { version: 1, kind: 'remote_generic', principal: { kind: 'oauth_client', id: 'client-a' } } as never;+ test('SQL NULL gets the legacy rule; JSONB null, malformed and future authority keep the denial', () => {+ for (const status of ALL_STATUSES) {+ for (const [caller, authority] of [['application', APPLICATION_AUTHORITY], ['remote', remoteAuthority]] as const) {+ const legacy = { id: 7, name: 'synthesize', status, submission_authority: null, legacy_authority_is_null: true };+ const expected = expectedOutcome('sql_null', status, caller);+ if (expected === 'deny-legacy') {+ let docs: string | undefined;+ try { coalesceDecision(legacy, authority); } catch (error) { docs = (error as { docs?: string }).docs; }+ expect(docs, `${status}/${caller}`).toBe(LEGACY_DOCS);+ } else {+ expect(coalesceDecision(legacy, authority), `${status}/${caller}`).toBe(expected as 'coalesce' | 'release');+ }+ for (const raw of [null, { version: 1 }, { version: 2, kind: 'application' }]) {+ // A missing marker is never legacy: JSONB null decodes to JS null too.+ for (const marker of [false, undefined]) {+ expect(() => coalesceDecision({ id: 7, name: 'synthesize', status, submission_authority: raw, legacy_authority_is_null: marker }, authority))+ .toThrow('coalescing across');+ }+ }+ }+ }+ });+});++describe('legacy coalesce matrix on every queue path (PGLite)', () => {+ test('variant x path x status x caller', () => isolated(async () => {+ const cells = await runCoalesceMatrix(engine, remote);+ const expectedCells = 4 * Object.values(PATHS).reduce((n, p) => n + p.statuses.length * p.callers.length, 0);+ expect(cells).toBe(expectedCells);+ }), 180_000);++ test('the existing cross-authority denial still holds for remote callers over an application row', () => isolated(async () => {+ const queue = new MinionQueue(engine);+ const accepted = await remote();+ await queue.add('lint', accepted.data, { idempotency_key: 'same-key' });+ const trusted = { submissionAuthority: accepted.authority };+ await expect(queue.add('lint', accepted.data, { idempotency_key: 'same-key' }, trusted)).rejects.toThrow('coalescing across');+ await expect(new MinionQueue(racingEngine(engine)).add('lint', accepted.data, { idempotency_key: 'same-key' }, trusted)).rejects.toThrow('coalescing across');+ }));++ test('resubmission over a dead legacy key inserts a fresh job that a worker runs', () => isolated(async () => {+ const queue = new MinionQueue(engine);+ const old = await queue.add('legacy-fixture', { n: 1 }, { idempotency_key: 'dream:synth-v2:example' });+ await engine.executeRaw("UPDATE minion_jobs SET status = 'dead', submission_authority = NULL WHERE id = $1", [old.id]);+ const fresh = await queue.add('legacy-fixture', { n: 1 }, { idempotency_key: 'dream:synth-v2:example' });+ expect(fresh.id).not.toBe(old.id);+ await assertNoUnreviewedJobs(engine);+ let ran = 0;+ const worker = new MinionWorker(engine, { pollInterval: 10, healthCheckInterval: 0, stalledInterval: 60000 });+ worker.register('legacy-fixture', async () => { ran++; return { ok: true }; });+ const running = worker.start();+ for (let i = 0; i < 200 && (await queue.getJob(fresh.id))?.status !== 'completed'; i++) await new Promise(r => setTimeout(r, 25));+ worker.stop();+ await running;+ expect(ran).toBe(1);+ expect((await queue.getJob(fresh.id))?.status).toBe('completed');+ }), 30_000);++ test('a release that lost its CAS (the row was reviewed in between) coalesces through the race path', () => isolated(async () => {+ const old = await new MinionQueue(engine).add('legacy-fixture', { n: 2 }, { idempotency_key: 'cas-key' });+ await engine.executeRaw("UPDATE minion_jobs SET status = 'cancelled', submission_authority = NULL WHERE id = $1", [old.id]);+ // Between the fast-path read and the release, an operator authorizes the row.+ const reviewing = new Proxy(engine, {+ get(target, prop) {+ if (prop !== 'transaction') { const v = Reflect.get(target, prop); return typeof v === 'function' ? v.bind(target) : v; }+ return <T>(fn: (tx: PGLiteEngine) => Promise<T>) => target.transaction(tx => fn(new Proxy(tx, {+ get(t, p) {+ if (p !== 'executeRaw') { const v = Reflect.get(t, p); return typeof v === 'function' ? v.bind(t) : v; }+ return async (sql: string, params?: unknown[]) => {+ if (sql.includes('SET idempotency_key = NULL')) {+ await t.executeRaw("UPDATE minion_jobs SET status = 'completed', submission_authority = $2::jsonb WHERE id = $1", [old.id, APPLICATION_AUTHORITY]);+ }+ return t.executeRaw(sql, params);+ };+ },+ }) as PGLiteEngine));+ },+ });+ const result = await new MinionQueue(reviewing as PGLiteEngine).add('legacy-fixture', { n: 2 }, { idempotency_key: 'cas-key' });+ expect(result.id).toBe(old.id);+ expect(result.coalesced).toBe(true);+ const [{ count }] = await engine.executeRaw<{ count: string }>('SELECT count(*)::text AS count FROM minion_jobs');+ expect(count).toBe('1');+ }));+});