* v0.50.2.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins Closes the critical- and high-severity items from six privately reported advisories (GHSA-548g-mhxp-p66h, GHSA-42r8-3jfh-82vr, GHSA-62gp-q5hj-r9mv, GHSA-q374-hhfh-f79x, GHSA-ghfq-gqmq-7fm4, GHSA-q5p9-qr3g-6v38). Squashed to a single commit so no intermediate revision carries a test-fixture credential shape through the gitleaks range gate. Cluster A — OAuth consent gate (GHSA-548g / -42r8 / -62gp). The v0.50.0.0 owner-approval flow is pinned end to end against a real `serve --http --enable-dcr` process and in-process: anonymous /authorize mints no code, a forged code is rejected at /token, revoked clients are refused at grants.begin, and OAuthGrants.begin() now caps awaiting-decision requests per client_id. Cluster B — DCR scope ceiling (GHSA-q374 defect B, GHSA-548g fix #2). registerClient rejects admin/sources_admin/users_admin/agent with HTTP 400 via scope.ts:dcrScopeViolation; client_credentials DCR clients are read-only. Remote sources_remove is source-fenced like sources_status. doctor's oauth_client_scope_health flags privileged self-registered clients. Cluster C — format-based secret detection (GHSA-ghfq). secret-scan.ts gains jwt/aws(AKIA|ASIA)/google/stripe/sendgrid/twilio/supabase/gitlab/npm/hf plus bearer and db_url_credentials catch-alls; the transcripts lane opts into the digit-gated high-entropy rule; getRawData follows the page soft-delete on both engines; delete_page --purge (local-CLI only) hard-removes a leaked page. Cluster D — cwd .env quarantine (GHSA-q5p9). New env-trust.ts + cli-preflight.ts drop a fixed list of code-loading / exec-target / posture-widening GBRAIN_* variables when a working-directory .env assigns them (key-presence, since Bun expands ${VAR}); the guardrails loader refuses cwd-relative and cwd-.env specs. Release artifacts: VERSION/package.json/three plugin manifests bumped to 0.50.2.0; CHANGELOG entry (reporters credited); SECURITY.md, README, DEPLOY.md, CHATGPT.md, guardrails.md, ENGINES.md and KEY_FILES updated; template + plugin trees, skills.lock, flag registry and llms bundle regenerated; module-size ceilings adjusted with per-row reasons; TODOS follow-ups filed. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix: pre-landing review fixes (v0.50.2.0 security wave) Review cycle 1 of the ship: 6 specialists + red team + coverage audit. Security / red team: - env-trust: parse .env with Bun's line grammar (bare CR terminates a line; BOM/U+2028 cannot hide an assignment); protect the loader / git / node / proxy / AI-CLI variable families a checkout could plant for the programs gbrain spawns; cli-preflight re-execs gbrain once with the sanitized environment so git, the agent CLI and workers inherit the clean view; cwd == ~/.gbrain no longer quarantines the operator's own .env. - guardrails: GBRAIN_GUARDRAILS_MODULE accepts only absolute or ~/ paths (a package name resolves from the cwd's node_modules). - secret-scan: bounded db_url_credentials quantifiers + per-pattern prechecks (linear on long lines), windowed previews that redact every sibling span, single-pass longest-first replacement. - TODOS: follow-up entries reworded to the functional level. API contract / maintainability: - delete_page purge: remote callers get permission_denied; a purged response always carries write_through; get_raw_data description states the soft-delete follow; includeDeleted narrowed to the getRawData signature; client_credentials gate evaluated before the DCR ceiling; doctor privileged set derived from the scope registry; sources_remove / sources_status share assertSourceInCallerScope; shell-job opt-in reaches --job-isolation process children as --allow-shell-jobs; stale help copy. - transcripts ingest: raw-metadata compare uses canonical JSON (JSONB key order made every healthy re-run rewrite unchanged rows). Coverage audit: 5 new test files + 4 extended (25 cases), plus RED-verified pins for every fix above. Docs/KEY_FILES/CHANGELOG/SECURITY updated; llms bundle, flag registry, tool catalog, structural suites regenerated; module-size rows adjusted with reasons. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 2 (v0.50.2.0 security wave) Re-exec redesign (security + red team + adversarial findings): - cli-preflight re-runs gbrain from an empty temporary directory so the sanitized child never reloads the hostile .env: dropped keys are absent, never carried as '' (git and the dynamic loader presence-check GIT_SSL_NO_VERIFY / LD_TRACE_LOADED_OBJECTS; '' broke git ident). - The re-run marker is JSON {cwd, neutral} honoured only when the process provably started in that empty directory — a marker planted via a cwd .env is ignored (the ppid-keyed marker was forgeable under systemd/docker). - SIGINT is delivered by the tty once (wrapper no longer forwards it); SIGTERM/SIGHUP forwarded; execArgv preserved under the dev runtime. - Protected families widened: XDG config roots (git reads $XDG_CONFIG_HOME/git/config as global config), GNUPGHOME, TLS trust stores, EDITOR/VISUAL/PAGER, every provider endpoint variable, the GBRAIN_REMOTE_* / GBRAIN_DIRECT_DATABASE_URL redirects, and the marker. - cwd dotenv parsed once per start; jobs start uses the same '1' literal. secret-scan (cycle-2 findings): - db_url_credentials password class only stops at whitespace, '@' and string delimiters again (unescaped / { } < > | ^ ` \ passwords redact); BEARER uppercase recognized; jwt / high_entropy_assignment / PEM body bounded (adversarial '-eyJ' / '_token' runs and header-only PEM texts were quadratic); incremental PEM line cursor; redactFindings rebuilds the text by span-splice in one pass (was O(unique values x text)). Contract / docs: - delete_page purge responses carry a residuals hint (git history, exports, compiled context, slug-keyed derived rows); CHANGELOG states a single truth for GBRAIN_GUARDRAILS_MODULE (absolute or ~/ only, listed under Changed with a migration note); SECURITY.md / KEY_FILES / docs guides / minion-orchestrator skill describe the new mechanism and the --allow-shell-jobs opt-in; TODOS follow-ups filed; test-reads-source marker on the hook spawn-shape test; new PEM fixtures fragmented. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 3 (v0.50.2.0 security wave) - Compiled binaries: every `bun build --compile` invocation passes `--no-compile-autoload-bunfig`; new `scripts/check-compile-autoload.sh` guard (self-tested, in verify CHECKS) keeps it that way. - cwd `.env` quarantine: `GBRAIN_DATABASE_URL`, `GBRAIN_OAUTH_RELAY_URL`, OpenSSL config/engine/module loaders, temp roots and HOME/USERPROFILE join the protected set; the neutral hop dir is realpath'd; signal handlers are installed before the spawn; non-tty wrappers forward SIGINT once; guardrails fail closed when a dropped GBRAIN_GUARDRAILS_MODULE had a value. - secret-scan: PEM header-line cursor is O(text) on newline-free tails; bounded bearer echo pass redacts bare re-occurrences of claimed tokens. - transcripts ingest: raw-metadata probe reads active rows only. - Tests: afterAll cleanup, execArgv/SIGHUP/chdir-back pins, pty SIGINT, perf pins; docs/CHANGELOG/TODOS/KEY_FILES/SECURITY updated; llms + skills.lock + plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 4 (v0.50.2.0 security wave) Cross-model adversarial pass (Codex) + Claude verifier findings: - env-trust: shell-startup / interpreter-home family (BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH, BASH_FUNC_* prefix) protected; sh `ENV` deliberately excluded. - cli-preflight: config-dir exemption refused when the cwd .env assigns GBRAIN_HOME/HOME/USERPROFILE; wrapper removes pre-existing signal listeners so its exit is always the child's; SIGINT forwarded only without a controlling terminal (/dev/tty probe); a dropped planted HOME is restored from the passwd home; script-mode runs warn once when the cwd bunfig.toml declares a top-level preload. - secret-scan: overlapping matches redact the UNION of matched spans; echo pass covers bearer + high-entropy values (64 unique, <=512 chars) via per-value sweeps over unclaimed gaps only; planRedaction/ applyRedaction share a session-wide echo dictionary in transcripts render. - sources_remove keys on write authority (assertSourceInCallerWriteScope); federated read grants confer no removal right. - delete_page --purge retries the tombstone's file removal and fails closed (storage_error) while the file remains. - Docs: SECURITY.md quarantine example no longer uses the one key that refuses instead of re-running; KEY_FILES/CHANGELOG/TODOS updated; llms. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * v0.50.3.0 chore: re-bump the security wave to 0.50.3.0 (master claimed 0.50.2.0 in #5122) Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header/date + TODOS follow-up refs + bun.lock, template repo and plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 5 — Codex structured-review gate (v0.50.3.0 security wave) - cli-preflight: hop marker carries the wrapper pid; a verified re-run arms an unref'd 1 s watchdog and exits 137 (removing its neutral dir) when the wrapper is force-killed, so supervisor restarts never orphan a worker; relative path-bearing runtime flags (--preload/-r/--require/--import, --config/-c, --env-file, --tsconfig-override) are resolved against the original cwd before the hop. - secret-scan: echo pass is a streaming leftmost-longest merge with O(values) retained state (Codex repro: 64 short claims + 2 MiB repetitive tail went from +233 MiB RSS / 1.4 s to +16 MiB / 140 ms); repetitive tails are now covered wall-to-wall. - Docs: KEY_FILES, SECURITY.md, CHANGELOG; llms regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: update project documentation for v0.50.3.0 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(ci): green the three failing checks on the v0.50.3.0 wave - semgrep: six `nosemgrep` suppressions with justifications for the path-join/resolve and non-literal-RegExp taint heuristics on operator- controlled cwd/flag paths and compile-time pattern sources (no behaviour change). - test (2): the two pty Ctrl-C pins ran the wrapper through `script -c`'s intermediate /bin/sh; on ubuntu-latest that is dash, which re-raises the pty's SIGINT on itself after the child exits (130) instead of relaying the child's 42. The pty command now `exec`s the wrapper so no shell stays in the foreground group; documented in a `ptyCommand` helper. - Selected E2E: with --enable-dcr, OAuth discovery now advertises exactly the self-registration ceiling (`read write`) via `scopesSupportedForDiscovery`, so a connector that copies `scopes_supported` into /register succeeds (master's #5122 pin); without DCR the full operator list minus `agent` is unchanged. Sibling e2e assertions that expected privileged scopes on the DCR-enabled server updated; unit + PGLite e2e pins added; docs/TODOS/CHANGELOG/KEY_FILES updated; llms regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * v0.50.5.0 chore: re-bump the security wave to 0.50.5.0 (master claimed 0.50.4.0 in #5131) Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header + TODOS follow-up refs + bun.lock, template repo and plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
321 lines
14 KiB
TypeScript
321 lines
14 KiB
TypeScript
/**
|
|
* issue #5 — `runJobInChild` against REAL child processes (.mjs harnesses run
|
|
* by process.execPath — the child-worker-supervisor.test.ts pattern).
|
|
*
|
|
* Paths pinned:
|
|
* - success outcome file → resolves with the handler result
|
|
* - error outcome file → throws the reconstructed error class (exit 0!)
|
|
* - exit 1 with no file → generic throw naming the exit (attempt burned)
|
|
* - SIGTERM-ignoring child + aborted signal → group SIGKILL at the injected
|
|
* grace; "terminated after abort" classification
|
|
* - pre-aborted signal → child killed promptly
|
|
* - spawn ENOENT → ChildSpawnInfraError (release, no attempt burned)
|
|
* - worker-shutdown: child finishes + reports during the drain window →
|
|
* normal success; child that can't report → ChildWorkerShutdownError
|
|
* - child env contract (result path, lock token, parent pid, pool bounds)
|
|
*/
|
|
|
|
import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
|
|
import { mkdtempSync, writeFileSync, existsSync, rmSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import {
|
|
runJobInChild,
|
|
ChildSpawnInfraError,
|
|
ChildWorkerShutdownError,
|
|
ChildNotClaimedError,
|
|
} from '../src/core/minions/child-job-runner.ts';
|
|
import { UnrecoverableError } from '../src/core/minions/types.ts';
|
|
import { RateLeaseUnavailableError } from '../src/core/minions/handlers/subagent.ts';
|
|
|
|
const TEST_TIMEOUT_MS = 30_000;
|
|
|
|
let harnessDir: string;
|
|
|
|
function makeHarness(name: string, body: string): string {
|
|
const path = join(harnessDir, `${name}.mjs`);
|
|
writeFileSync(
|
|
path,
|
|
`import { writeFileSync, renameSync } from 'node:fs';\n` +
|
|
`const RESULT = process.env.GBRAIN_JOB_RESULT_PATH;\n` +
|
|
`const writeOutcome = (o) => { writeFileSync(RESULT + '.tmp', JSON.stringify(o)); renameSync(RESULT + '.tmp', RESULT); };\n` +
|
|
body +
|
|
// Readiness handshake LAST (after the body installed its signal
|
|
// handlers): fixed sleeps raced child startup on loaded CI runners —
|
|
// a SIGTERM landing before process.on('SIGTERM') installs takes the
|
|
// default disposition and flips shutdown-semantics assertions
|
|
// (testing specialist). The runner's outcome dir is internal, so the
|
|
// ready path comes from a TEST-provided env var.
|
|
`\nif (process.env.HARNESS_READY_PATH) writeFileSync(process.env.HARNESS_READY_PATH, '1');\n`,
|
|
'utf8',
|
|
);
|
|
return path;
|
|
}
|
|
|
|
/** Make a per-test ready path + the env to hand runJobInChild. */
|
|
function readiness(name: string): { env: Record<string, string | undefined>; wait: () => Promise<void> } {
|
|
const readyPath = join(harnessDir, `${name}.ready`);
|
|
return {
|
|
env: { ...process.env, HARNESS_READY_PATH: readyPath },
|
|
wait: async () => {
|
|
const deadline = Date.now() + 10_000;
|
|
while (Date.now() < deadline) {
|
|
if (existsSync(readyPath)) return;
|
|
await new Promise((r) => setTimeout(r, 25));
|
|
}
|
|
throw new Error('harness never signalled readiness');
|
|
},
|
|
};
|
|
}
|
|
|
|
beforeAll(() => {
|
|
harnessDir = mkdtempSync(join(tmpdir(), 'gbrain-cjr-harness-'));
|
|
});
|
|
|
|
afterAll(() => {
|
|
rmSync(harnessDir, { recursive: true, force: true });
|
|
});
|
|
|
|
function baseOpts(harnessPath: string) {
|
|
return {
|
|
jobId: 77,
|
|
jobName: 'subagent',
|
|
lockToken: 'tok-cjr',
|
|
abortSignal: new AbortController().signal,
|
|
shutdownSignal: new AbortController().signal,
|
|
invocation: { cmd: process.execPath, argsPrefix: [harnessPath] },
|
|
tiniPath: '', // direct spawn in tests; group signaling covers both shapes
|
|
};
|
|
}
|
|
|
|
describe('runJobInChild (real children)', () => {
|
|
test('success outcome resolves with the result; env contract honored', async () => {
|
|
const harness = makeHarness(
|
|
'success',
|
|
`writeOutcome({ outcome: 'success', result: {
|
|
echoedToken: process.env.GBRAIN_JOB_LOCK_TOKEN,
|
|
isChild: process.env.GBRAIN_JOB_CHILD,
|
|
parentPid: process.env.GBRAIN_JOB_PARENT_PID,
|
|
poolSize: process.env.GBRAIN_POOL_SIZE,
|
|
directPoolSize: process.env.GBRAIN_DIRECT_POOL_SIZE,
|
|
argv: process.argv.slice(2),
|
|
}});\n` +
|
|
`process.exit(0);\n`,
|
|
);
|
|
const result = (await runJobInChild(baseOpts(harness))) as Record<string, unknown>;
|
|
expect(result.echoedToken).toBe('tok-cjr');
|
|
expect(result.isChild).toBe('1');
|
|
expect(result.parentPid).toBe(String(process.pid));
|
|
expect(result.poolSize).toBe('3');
|
|
expect(result.directPoolSize).toBe('1'); // codex-2 #6: child direct pool bounded
|
|
expect(result.argv).toEqual(['jobs', 'run-child', '--job-id', '77']);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
// The shell opt-in travels to the isolated child as a FLAG (buildChildArgs):
|
|
// the child re-runs the cwd-.env quarantine in the worker's cwd, so an
|
|
// env-only handoff of GBRAIN_ALLOW_SHELL_JOBS would be dropped again there.
|
|
test('--allow-shell-jobs pass-through: opts.env GBRAIN_ALLOW_SHELL_JOBS=1 appends the flag; any other value does not', async () => {
|
|
const harness = makeHarness(
|
|
'argv-echo',
|
|
`writeOutcome({ outcome: 'success', result: { argv: process.argv.slice(2) } });\n` +
|
|
`process.exit(0);\n`,
|
|
);
|
|
const on = (await runJobInChild({ ...baseOpts(harness), env: { ...process.env, GBRAIN_ALLOW_SHELL_JOBS: '1' } })) as { argv: string[] };
|
|
expect(on.argv).toEqual(['jobs', 'run-child', '--job-id', '77', '--allow-shell-jobs']);
|
|
const off = (await runJobInChild({ ...baseOpts(harness), env: { ...process.env, GBRAIN_ALLOW_SHELL_JOBS: 'true' } })) as { argv: string[] };
|
|
expect(off.argv).toEqual(['jobs', 'run-child', '--job-id', '77']);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('error outcome (exit 0) throws the reconstructed class', async () => {
|
|
const harness = makeHarness(
|
|
'error-unrecoverable',
|
|
`writeOutcome({ outcome: 'error', errorKind: 'unrecoverable', message: 'bad schema, never retry' });\n` +
|
|
`process.exit(0);\n`,
|
|
);
|
|
await expect(runJobInChild(baseOpts(harness))).rejects.toBeInstanceOf(UnrecoverableError);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('rate-lease outcome rebuilds RateLeaseUnavailableError with fields', async () => {
|
|
const harness = makeHarness(
|
|
'error-lease',
|
|
`writeOutcome({ outcome: 'error', errorKind: 'rate_lease', message: 'lease full', lease: { key: 'anthropic', active: 4, max: 4 } });\n` +
|
|
`process.exit(0);\n`,
|
|
);
|
|
try {
|
|
await runJobInChild(baseOpts(harness));
|
|
throw new Error('should have thrown');
|
|
} catch (e) {
|
|
expect(e).toBeInstanceOf(RateLeaseUnavailableError);
|
|
expect((e as RateLeaseUnavailableError).key).toBe('anthropic');
|
|
}
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('exit 1 with no outcome file → generic throw naming the exit code', async () => {
|
|
const harness = makeHarness('crash', `process.exit(1);\n`);
|
|
await expect(runJobInChild(baseOpts(harness))).rejects.toThrow(/exit code=1/);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('SIGTERM-ignoring child: abort → group SIGKILL at the injected grace', async () => {
|
|
const harness = makeHarness(
|
|
'stubborn',
|
|
`process.on('SIGTERM', () => {});\n` +
|
|
`setInterval(() => {}, 1000);\n`, // never exits voluntarily
|
|
);
|
|
const abort = new AbortController();
|
|
const ready = readiness('stubborn');
|
|
const opts = { ...baseOpts(harness), abortSignal: abort.signal, killGraceMs: 400, env: ready.env };
|
|
const p = runJobInChild(opts);
|
|
await ready.wait();
|
|
abort.abort(new Error('timeout'));
|
|
const started = Date.now();
|
|
await expect(p).rejects.toThrow(/terminated after abort/);
|
|
// Died via the SIGKILL escalation, not the 30s force-evict scale.
|
|
expect(Date.now() - started).toBeLessThan(5_000);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('pre-aborted signal: child is terminated promptly', async () => {
|
|
const harness = makeHarness(
|
|
'prekilled',
|
|
`setInterval(() => {}, 1000);\n`,
|
|
);
|
|
const abort = new AbortController();
|
|
abort.abort(new Error('cancel'));
|
|
const opts = { ...baseOpts(harness), abortSignal: abort.signal, killGraceMs: 400 };
|
|
await expect(runJobInChild(opts)).rejects.toThrow(/terminated after abort/);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('spawn ENOENT → ChildSpawnInfraError (infra release, not a job defect)', async () => {
|
|
const opts = {
|
|
...baseOpts('/nonexistent'),
|
|
invocation: { cmd: '/nonexistent/gbrain-binary', argsPrefix: [] },
|
|
};
|
|
await expect(runJobInChild(opts)).rejects.toBeInstanceOf(ChildSpawnInfraError);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('worker shutdown: child finishes + reports during the drain window → normal success', async () => {
|
|
const harness = makeHarness(
|
|
'graceful-drain',
|
|
`let done = false;\n` +
|
|
`process.on('SIGTERM', () => {\n` +
|
|
` writeOutcome({ outcome: 'success', result: { finishedDuringDrain: true } });\n` +
|
|
` done = true; process.exit(0);\n` +
|
|
`});\n` +
|
|
`setInterval(() => {}, 1000);\n`,
|
|
);
|
|
const shutdown = new AbortController();
|
|
const ready = readiness('graceful-drain');
|
|
const opts = { ...baseOpts(harness), shutdownSignal: shutdown.signal, killGraceMs: 5_000, env: ready.env };
|
|
const p = runJobInChild(opts);
|
|
await ready.wait();
|
|
shutdown.abort(new Error('worker-shutdown'));
|
|
const result = (await p) as Record<string, unknown>;
|
|
expect(result.finishedDuringDrain).toBe(true);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('worker shutdown: child that cannot report → ChildWorkerShutdownError (no attempt burned)', async () => {
|
|
const harness = makeHarness(
|
|
'shutdown-stubborn',
|
|
`process.on('SIGTERM', () => {});\n` +
|
|
`setInterval(() => {}, 1000);\n`,
|
|
);
|
|
const shutdown = new AbortController();
|
|
const ready = readiness('shutdown-stubborn');
|
|
const opts = { ...baseOpts(harness), shutdownSignal: shutdown.signal, killGraceMs: 400, env: ready.env };
|
|
const p = runJobInChild(opts);
|
|
await ready.wait();
|
|
shutdown.abort(new Error('worker-shutdown'));
|
|
await expect(p).rejects.toBeInstanceOf(ChildWorkerShutdownError);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('ERROR outcome during worker shutdown → ChildWorkerShutdownError, not a burned attempt (adversarial P2)', async () => {
|
|
// A cooperative handler that bails on shutdown and reports an error must
|
|
// be RELEASED — punishing exactly the well-behaved handlers on every
|
|
// deploy inverts the no-burn guarantee.
|
|
const harness = makeHarness(
|
|
'shutdown-error-report',
|
|
`process.on('SIGTERM', () => {\n` +
|
|
` writeOutcome({ outcome: 'error', errorKind: 'generic', message: 'aborted: shutdown' });\n` +
|
|
` process.exit(0);\n` +
|
|
`});\n` +
|
|
`setInterval(() => {}, 1000);\n`,
|
|
);
|
|
const shutdown = new AbortController();
|
|
const ready = readiness('shutdown-error-report');
|
|
const opts = { ...baseOpts(harness), shutdownSignal: shutdown.signal, killGraceMs: 5_000, env: ready.env };
|
|
const p = runJobInChild(opts);
|
|
await ready.wait();
|
|
shutdown.abort(new Error('worker-shutdown'));
|
|
await expect(p).rejects.toBeInstanceOf(ChildWorkerShutdownError);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('watchdog drain (BOTH signals aborted, non-per-job reason) → shutdown class, not a burned attempt (adversarial P3)', async () => {
|
|
const harness = makeHarness(
|
|
'watchdog-stubborn',
|
|
`process.on('SIGTERM', () => {});\n` +
|
|
`setInterval(() => {}, 1000);\n`,
|
|
);
|
|
const abort = new AbortController();
|
|
const shutdown = new AbortController();
|
|
const ready = readiness('watchdog-stubborn');
|
|
const opts = {
|
|
...baseOpts(harness),
|
|
abortSignal: abort.signal,
|
|
shutdownSignal: shutdown.signal,
|
|
killGraceMs: 400,
|
|
env: ready.env,
|
|
};
|
|
const p = runJobInChild(opts);
|
|
await ready.wait();
|
|
// gracefulShutdown('watchdog') aborts BOTH — shutdown classification must win.
|
|
shutdown.abort(new Error('watchdog'));
|
|
abort.abort(new Error('watchdog'));
|
|
await expect(p).rejects.toBeInstanceOf(ChildWorkerShutdownError);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('per-job reason (timeout) wins over a concurrent shutdown — attempt semantics preserved', async () => {
|
|
const harness = makeHarness(
|
|
'timeout-during-shutdown',
|
|
`process.on('SIGTERM', () => {});\n` +
|
|
`setInterval(() => {}, 1000);\n`,
|
|
);
|
|
const abort = new AbortController();
|
|
const shutdown = new AbortController();
|
|
const ready = readiness('timeout-during-shutdown');
|
|
const opts = {
|
|
...baseOpts(harness),
|
|
abortSignal: abort.signal,
|
|
shutdownSignal: shutdown.signal,
|
|
killGraceMs: 400,
|
|
env: ready.env,
|
|
};
|
|
const p = runJobInChild(opts);
|
|
await ready.wait();
|
|
shutdown.abort(new Error('worker-shutdown'));
|
|
abort.abort(new Error('timeout')); // the JOB was targeted — not shutdown class
|
|
await expect(p).rejects.toThrow(/terminated after abort/);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('bootstrap exit codes: 13 → ChildSpawnInfraError, 14 → ChildNotClaimedError (no burned attempts)', async () => {
|
|
const usage = makeHarness('exit13', `process.exit(13);\n`);
|
|
await expect(runJobInChild(baseOpts(usage))).rejects.toBeInstanceOf(ChildSpawnInfraError);
|
|
|
|
const notClaimed = makeHarness('exit14', `process.exit(14);\n`);
|
|
await expect(runJobInChild(baseOpts(notClaimed))).rejects.toBeInstanceOf(ChildNotClaimedError);
|
|
}, TEST_TIMEOUT_MS);
|
|
|
|
test('child pool-size env: a STRICTER user GBRAIN_POOL_SIZE is respected; explicit child override wins; invalid falls back', async () => {
|
|
const harness = makeHarness(
|
|
'pool-echo',
|
|
`writeOutcome({ outcome: 'success', result: { poolSize: process.env.GBRAIN_POOL_SIZE } });\n` +
|
|
`process.exit(0);\n`,
|
|
);
|
|
const run = (env: Record<string, string | undefined>) =>
|
|
runJobInChild({ ...baseOpts(harness), env: { ...process.env, ...env } }) as Promise<{ poolSize: string }>;
|
|
|
|
expect((await run({ GBRAIN_POOL_SIZE: '2' })).poolSize).toBe('2'); // stricter user tuning respected
|
|
expect((await run({ GBRAIN_POOL_SIZE: '10' })).poolSize).toBe('3'); // never raised above the child default
|
|
expect((await run({ GBRAIN_POOL_SIZE: '2', GBRAIN_JOB_CHILD_POOL_SIZE: '5' })).poolSize).toBe('5'); // explicit knob wins
|
|
expect((await run({ GBRAIN_JOB_CHILD_POOL_SIZE: 'abc' })).poolSize).toBe('3'); // invalid → default
|
|
}, TEST_TIMEOUT_MS);
|
|
});
|