Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(ci): add bun run test:stress, the PR stress gate and the nightly race hunt
garrytande6b41f271bd
diff --git a/.github/workflows/stress.yml b/.github/workflows/stress.ymlnew file mode 100644index 0000000000..c8dc7360e2--- /dev/null+++ b/.github/workflows/stress.yml@@ -0,0 +1,180 @@+name: Stress++# Repeated-run lanes, both driven by `bun run test:stress` (scripts/stress/run.ts)+# and planned and reported by scripts/stress/gate.ts. test.yml calls this+# workflow twice:+# - stress-changed-tests (mode gate): every event, inside test-status. On+# pull_request and merge_group it runs every added or modified test file,+# plus direct importers of changed test/helpers/ files (fan-in rule), 10+# times each; elsewhere it succeeds with "not a PR event". A dispatch with+# stress_files or stress_base/stress_head runs it for real as a diagnostic.+# - race-hunt (mode race-hunt): the nightly Test schedule and a race_hunt+# dispatch only, outside test-status. Every file in test/postgres-unit-arms.txt+# 10 times against Postgres.+# Every database iteration gets a fresh database (CREATE DATABASE … TEMPLATE).+# Shard jobs record results and exit 0 on test failures; the result job alone+# decides, so a known failure with a trusted exemption can pass while any+# other failure, a missing receipt or a failed plan fails it.+# Docs: docs/TESTING.md#stress-gate, docs/TESTING.md#race-hunt.++on:+ workflow_call:+ inputs:+ mode:+ type: string+ required: true+ stress_files:+ type: string+ default: ''+ stress_base:+ type: string+ default: ''+ stress_head:+ type: string+ default: ''++permissions:+ contents: read++jobs:+ plan:+ name: Stress plan+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 10+ outputs:+ run: ${{ steps.plan.outputs.run }}+ matrix: ${{ steps.plan.outputs.matrix }}+ steps:+ # Full history: the gate diffs against the merge base, the race hunt+ # reads which helpers changed on master since the last night.+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ fetch-depth: 0+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.2+ - run: bun install --frozen-lockfile --ignore-scripts+ # Dispatch inputs reach the planner through env only; it validates every+ # path and ref before use. Named exception (docs/TESTING.md#event-parity):+ # the gate plans work only for pull_request, merge_group and a stress+ # dispatch; push and nightly runs execute every file in the full suite.+ - name: Plan+ id: plan+ env:+ MODE: ${{ inputs.mode }}+ EVENT: ${{ github.event_name }}+ BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha }}+ STRESS_FILES: ${{ inputs.stress_files }}+ STRESS_BASE: ${{ inputs.stress_base }}+ STRESS_HEAD: ${{ inputs.stress_head }}+ run: bun scripts/stress/gate.ts plan --mode "$MODE"+ - name: Upload plan+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: stress-plan-${{ inputs.mode }}+ path: ${{ runner.temp }}/stress-plan/plan.json+ retention-days: 14+ overwrite: true++ shards:+ name: ${{ inputs.mode == 'gate' && 'Stress shard' || 'Race hunt shard' }} ${{ matrix.shard }}+ needs: plan+ if: needs.plan.outputs.run == 'true'+ runs-on: ubicloud-standard-4-ubuntu-2404+ # Gate shards are planned under 25 minutes and race-hunt shards under 55;+ # the margin covers checkout, install and the snapshot build.+ timeout-minutes: ${{ fromJSON(inputs.mode == 'gate' && '35' || '65') }}+ strategy:+ fail-fast: false+ # Bounded so a large fix-wave PR queues its shards instead of starving+ # every other job of the shared runner quota.+ max-parallel: 6+ matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}+ services:+ postgres:+ image: pgvector/pgvector:pg16+ env:+ POSTGRES_USER: gbrain_test+ POSTGRES_PASSWORD: gbrain_test+ POSTGRES_DB: gbrain_test+ ports: ['5432:5432']+ options: >-+ --health-cmd "pg_isready -U gbrain_test -d gbrain_test"+ --health-interval 5s --health-timeout 5s --health-retries 20+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.2+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ with:+ path: ~/.bun/install/cache+ key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}+ restore-keys: bun-cache-${{ runner.os }}-+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ with:+ path: |+ test/fixtures/pglite-snapshot.tar+ test/fixtures/pglite-snapshot.version+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}+ - run: bun install --frozen-lockfile+ # Exit 1 means a test failed and the manifest says which; the result job+ # decides. Exit 2 (setup error) or a signal fails the shard, and the+ # result job reports its iterations as missing.+ - name: Run planned iterations+ shell: bash+ env:+ GBRAIN_STRESS_ADMIN_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test+ STRESS_WORK: ${{ matrix.work }}+ run: |+ rc=0+ bun run test:stress --postgres --work "$STRESS_WORK" --out "$RUNNER_TEMP/stress" || rc=$?+ [ "$rc" -le 1 ]+ - name: Upload manifest and receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: stress-${{ inputs.mode }}-shard-${{ matrix.shard }}+ path: ${{ runner.temp }}/stress+ retention-days: 14+ if-no-files-found: warn+ overwrite: true++ result:+ name: ${{ inputs.mode == 'gate' && 'stress-changed-tests result' || 'race-hunt result' }}+ needs: [plan, shards]+ if: always()+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 10+ permissions:+ contents: read+ issues: read+ actions: read+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.2+ - run: bun install --frozen-lockfile --ignore-scripts+ - name: Download plan+ continue-on-error: true+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ with:+ name: stress-plan-${{ inputs.mode }}+ path: ${{ runner.temp }}/plan+ - name: Download shard manifests+ continue-on-error: true+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ with:+ pattern: stress-${{ inputs.mode }}-shard-*+ path: ${{ runner.temp }}/manifests+ # Event parity: GATE_SINCE only dates exemptions (docs/TESTING.md#event-parity).+ - name: Decide+ env:+ MODE: ${{ inputs.mode }}+ PLAN_RESULT: ${{ needs.plan.result }}+ SHARDS_RESULT: ${{ needs.shards.result }}+ GH_TOKEN: ${{ github.token }}+ GATE_SINCE: ${{ github.event.pull_request.created_at || github.event.merge_group.head_commit.timestamp }}+ run: bun scripts/stress/gate.ts report --mode "$MODE" --plan "$RUNNER_TEMP/plan/plan.json" --manifests "$RUNNER_TEMP/manifests"diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 104cad5e7b..17219809a7 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -24,6 +24,29 @@ on:type: booleandefault: falserequired: false+ # Diagnostic modes (docs/TESTING.md#stress-gate, docs/TESTING.md#race-hunt):+ # either one runs only its lane, never the full suite, and its result never+ # opens, updates or closes an issue.+ race_hunt:+ description: Run only the race hunt (every test/postgres-unit-arms.txt file 10 times); diagnostic+ type: boolean+ default: false+ required: false+ stress_files:+ description: Run only the stress gate on these test files (space- or comma-separated test/…/*.test.ts); diagnostic+ type: string+ default: ''+ required: false+ stress_base:+ description: Run only the stress gate on the test files changed versus this ref or SHA; diagnostic+ type: string+ default: ''+ required: false+ stress_head:+ description: Head ref or SHA for stress_base (default HEAD of the dispatched ref)+ type: string+ default: ''+ required: falsepermissions:contents: read@@ -37,7 +60,7 @@ permissions:# Event parity (docs/TESTING.md#event-parity): the event suffixes only separate# runs that must not cancel each other; they change no job, matrix or parameter.concurrency:- group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event_name == 'workflow_dispatch' && inputs.native_only == true && '-native-only' || '' }}${{ github.event_name == 'schedule' && '-nightly' || '' }}+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event_name == 'workflow_dispatch' && inputs.native_only == true && '-native-only' || '' }}${{ github.event_name == 'workflow_dispatch' && (inputs.race_hunt == true || inputs.stress_files != '' || inputs.stress_base != '') && '-diagnostic' || '' }}${{ github.event_name == 'schedule' && '-nightly' || '' }}cancel-in-progress: truejobs:@@ -106,7 +129,7 @@ jobs:# Re-run checks for every event. Only dependencies and PGLite snapshots are cached.gitleaks:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}runs-on: ubicloud-standard-2-ubuntu-2404timeout-minutes: 10steps:@@ -159,7 +182,7 @@ jobs:gitleaks detect --redact --no-banner --log-opts "$RANGE"security-regressions:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}runs-on: ${{ matrix.os == 'ubuntu-latest' && 'ubicloud-standard-2-ubuntu-2404' || matrix.os }}timeout-minutes: 10strategy:@@ -190,13 +213,13 @@ jobs:# package.json dependency field (or carry the `dependency-audit` label).# Elsewhere a new upstream advisory is a warning, so it cannot turn every# open PR red at once; the push and nightly runs still fail on it (B11).- # Named exception with its rule (docs/TESTING.md#dependency-audit-rule): a+ # Named exception with its rule (docs/ci-event-parity.md#dependency-audit-rule): a# push-to-master red from a newly published advisory opens the Test master-red# issue and a scheduled red the nightly-red issue; the repair PR bumps,# overrides, patches or removes the dependency; when no fix exists, an# expiring ignore entry needs Garry's approval.dependency-audit:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}runs-on: ubicloud-standard-2-ubuntu-2404timeout-minutes: 10permissions:@@ -248,7 +271,7 @@ jobs:run: bash scripts/ci-dependency-audit.shverify:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}# Pre-test gates: privacy/jsonb/source-id/etc + typecheck + admin-build.# Lives in its own runner so the matrix shards aren't carrying ~2-3min# of verify work in addition to their test files (the old shape stuffed@@ -331,7 +354,7 @@ jobs:overwrite: trueserial-tests:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}# *.serial.test.ts — one bun process per file (module-registry isolation),# POOLED across files by scripts/run-serial-tests.sh (was strictly# sequential: an 8.5-minute job whose serialization the quarantine@@ -365,9 +388,9 @@ jobs:# not once per job per run. This job SAVES; verify + matrix + slow jobs# restore-only. The key is an approximation on purpose: it only has to# be a superset-trigger of real schema changes.- # HASH INPUTS HAVE 13 HOMES: 11 legacy keys (five here and six in- # e2e.yml) plus two default-profile keys here (slow-brainbench and- # brainbench). Edit all together when schema dependencies change;+ # HASH INPUTS HAVE 14 HOMES: 12 legacy keys (five here, six in+ # e2e.yml, one in stress.yml) plus two default-profile keys here+ # (slow-brainbench and brainbench). Edit all together when schema dependencies change;# profile names stay distinct, and the serial save reuses its restore key.- uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3id: snapshot-cache@@ -421,7 +444,7 @@ jobs:overwrite: trueslow-brainbench-e2e:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}# Dedicated runner for the BrainBench CLI e2e file. At 98s mined it was# the matrix's single heaviest atom (10% of the whole corpus weight) and# the hard floor on shard-count scaling; a Phase-2 rewrite (spawn batching@@ -496,7 +519,7 @@ jobs:overwrite: truebrainbench:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}# BrainBench memory-conformance gate (Cathedral 2). Hermetic: in-memory# PGLite, zero API keys, ~15s for the full 141-fixture × 3-harness run.# Governance (decision 4): compares HEAD's run against MAIN's committed@@ -538,7 +561,7 @@ jobs:fislow-entity-resolve-perf:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}# Dedicated runner for the entity-resolve perf test (~159s, single perf# describe with one test that builds 5000+ pages and asserts the NEW# tryPrefixExpansion shape is 5x faster than the OLD shape — not@@ -620,7 +643,7 @@ jobs:bun run src/cli.ts protocol conformance --synthesizetest:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}# Pure matrix shard — no verify, no serial. Each shard runs its slice# of the unit test set under one `bun test` invocation.#@@ -709,7 +732,7 @@ jobs:# ──────────────────────────────────────────────────────────────────────coverage-report:needs: [serial-tests, slow-entity-resolve-perf, slow-brainbench-e2e, test]- if: ${{ always() && (github.event_name != 'workflow_dispatch' || inputs.native_only != true) }}+ if: ${{ always() && (github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base)) }}runs-on: ubicloud-standard-4-ubuntu-2404timeout-minutes: 10steps:@@ -765,16 +788,51 @@ jobs:native-locks:needs: [changes]+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}uses: ./.github/workflows/native-locks.ymlwith:scope: ${{ needs.changes.outputs.native-scope }}persistence-validation:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}uses: ./.github/workflows/persistence-validation.yml- admin-browser:+ # PR stress gate (docs/TESTING.md#stress-gate): every added or modified test+ # file, plus direct importers of changed test/helpers/ files by the fan-in+ # rule, runs 10 times with a fresh database per iteration. Named exception+ # (docs/TESTING.md#event-parity): outside pull_request and merge_group it+ # succeeds with "not a PR event", since push and nightly runs execute every+ # file. Its conclusion is success or failure, never skipped, so test-status+ # gates on it.+ stress-changed-tests:if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ permissions:+ contents: read+ issues: read+ actions: read+ uses: ./.github/workflows/stress.yml+ with:+ mode: gate+ stress_files: ${{ inputs.stress_files || '' }}+ stress_base: ${{ inputs.stress_base || '' }}+ stress_head: ${{ inputs.stress_head || '' }}++ # Race hunt (docs/TESTING.md#race-hunt): every file in test/postgres-unit-arms.txt+ # 10 times against Postgres. Named exception (docs/TESTING.md#event-parity):+ # the nightly Test schedule and a race_hunt dispatch only, and outside+ # test-status: a red lands in the Test nightly-red issue, one line per file.+ race-hunt:+ if: ${{ github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.race_hunt == true) }}+ permissions:+ contents: read+ issues: read+ actions: read+ uses: ./.github/workflows/stress.yml+ with:+ mode: race-hunt++ admin-browser:+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}runs-on: ubicloud-standard-4-ubuntu-2404timeout-minutes: 12steps:@@ -801,7 +859,7 @@ jobs:retention-days: 7shared-skills-compatibility:- if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}+ if: ${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}runs-on: ubicloud-standard-4-ubuntu-2404timeout-minutes: 10steps:@@ -833,7 +891,7 @@ jobs:# bun scripts/ci-executed-counts.ts --base-run <id> --head-run <id>executed-receipts:needs: [verify, serial-tests, slow-entity-resolve-perf, slow-brainbench-e2e, test, shared-skills-compatibility]- if: ${{ always() && (github.event_name != 'workflow_dispatch' || inputs.native_only != true) }}+ if: ${{ always() && (github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base)) }}runs-on: ubicloud-standard-2-ubuntu-2404timeout-minutes: 10steps:@@ -871,9 +929,9 @@ jobs:# The stable aggregate succeeds only when every required lane ran successfully.# Coverage percentages remain advisory until their separate graduation.test-status:- name: ${{ github.event_name == 'workflow_dispatch' && inputs.native_only == true && 'full-suite-not-run' || 'test-status' }}- needs: [gitleaks, security-regressions, dependency-audit, verify, serial-tests, slow-entity-resolve-perf, slow-brainbench-e2e, brainbench, test, native-locks, persistence-validation, admin-browser, shared-skills-compatibility]- if: ${{ always() && (github.event_name != 'workflow_dispatch' || inputs.native_only != true) }}+ name: ${{ github.event_name == 'workflow_dispatch' && (inputs.native_only == true || inputs.race_hunt == true || inputs.stress_files != '' || inputs.stress_base != '') && 'full-suite-not-run' || 'test-status' }}+ needs: [gitleaks, security-regressions, dependency-audit, verify, serial-tests, slow-entity-resolve-perf, slow-brainbench-e2e, brainbench, test, native-locks, persistence-validation, admin-browser, shared-skills-compatibility, stress-changed-tests]+ if: ${{ always() && (github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base)) }}runs-on: ubicloud-standard-2-ubuntu-2404timeout-minutes: 5steps:@@ -892,9 +950,10 @@ jobs:PERSISTENCE="${{ needs.persistence-validation.result }}"ADMIN_BROWSER="${{ needs.admin-browser.result }}"SKILL_COMPATIBILITY="${{ needs.shared-skills-compatibility.result }}"+ STRESS="${{ needs.stress-changed-tests.result }}"echo "gitleaks=$GITLEAKS security-regressions=$SECURITY dependency-audit=$AUDIT verify=$VERIFY serial-tests=$SERIAL slow-entity-resolve-perf=$SLOW_PERF slow-brainbench-e2e=$SLOW_BRAINBENCH brainbench=$BRAINBENCH test=$TEST native-locks=$NATIVE_LOCKS persistence=$PERSISTENCE admin-browser=$ADMIN_BROWSER"- echo "shared-skills-compatibility=$SKILL_COMPATIBILITY"- for r in "$GITLEAKS" "$SECURITY" "$AUDIT" "$VERIFY" "$SERIAL" "$SLOW_PERF" "$SLOW_BRAINBENCH" "$BRAINBENCH" "$TEST" "$NATIVE_LOCKS" "$PERSISTENCE" "$ADMIN_BROWSER" "$SKILL_COMPATIBILITY"; do+ echo "shared-skills-compatibility=$SKILL_COMPATIBILITY stress-changed-tests=$STRESS"+ for r in "$GITLEAKS" "$SECURITY" "$AUDIT" "$VERIFY" "$SERIAL" "$SLOW_PERF" "$SLOW_BRAINBENCH" "$BRAINBENCH" "$TEST" "$NATIVE_LOCKS" "$PERSISTENCE" "$ADMIN_BROWSER" "$SKILL_COMPATIBILITY" "$STRESS"; doif [ "$r" != "success" ]; thenecho "✗ gated job did not succeed (got $r) — CI fail"exit 1diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 4aa9339c5b..c2d5580ba7 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -76,23 +76,17 @@ the decision rule is critical path first, vCPU-minutes second.`test/scripts/ci-runner-routing.test.ts` pins capacity and platform routing;`.github/actionlint.yaml` declares the exact custom runner labels.-### Pull request, master and nightly scope+### Event parityEvery test file runs on every push to master, on the nightly schedule and on-manual dispatch. Pull requests and merge-queue runs (`merge_group`, which use-the PR profile) run every Bun-version cell of the security and persistence-matrices too; only the rows below are narrower, each a named exception in-[Event parity](#event-parity):--| Lane | Pull request | Push to master, nightly, manual |-| --- | --- | --- |-| Security regressions | Linux, macOS and Windows on Bun 1.4.0 and 1.4.2 | Same |-| Persistence read latency, deployment matrix, unit-lane PostgreSQL arms, soak, crash robot, reconciliation crashes | Bun 1.4.0 and 1.4.2 | Same |-| Persistence soak size | 2,500 writes | 10,000 writes |-| Crash robot budget | 150 s (Postgres skips the lease-waiting seams) | 600 s, every seam |-| Native writer locks, native paths changed | Every target on Bun 1.4.2, musl, both Windows probes, OpenClaw | Every target, musl and Windows probe on Bun 1.4.0 and 1.4.2, OpenClaw |-| Native writer locks, other changes | `linux-x64-glibc / Bun 1.4.2` smoke cell (full native step list) | Same as above |-| `test/export-scale.slow.test.ts` | 10,001 pages | 100,001 pages |+manual dispatch, and pull requests and merge-queue runs (`merge_group`) run+every Bun-version cell too. Each narrower PR behavior (soak and crash-robot+budgets, native-lock scope, export scale, the PR-only stress gate) is a named+exception whose comment beside the condition names the scheduled run that+covers it; `test/scripts/ci-pr-scope.test.ts` fails on an unclassified one.+The table, the dependency-audit rule and the measured cost of parity are in+[docs/ci-event-parity.md](ci-event-parity.md). Required checks stay keyed on+the `test-status` and `e2e-status` aggregators.The `changes` job classifies a pull request's changed files with`scripts/ci-native-scope.sh`: native lock sources, the native toolchain, IPC,@@ -126,73 +120,6 @@ legacy test configuration; ordinary resets preserve that identity.Shared-skills suites, the old-binary compatibility job and the lifecycle benchmark are described in[scripts/shared-skills/README.md](../scripts/shared-skills/README.md#tests-and-ci).-### Event parity--A red that only a push to master can produce is a red no PR could have-caught. So every event-conditional behavior in the workflows is either-parity (pull requests and merge-queue runs do the same work) or a named-exception whose comment, beside the condition, names the scheduled run that-covers it. A condition with no covering scheduled run defaults to parity;-anything else needs a new scheduled run or a decision recorded beside the-condition. `test/scripts/ci-pr-scope.test.ts` fails on an event-conditional-job or block in a test workflow without that comment, and on a Bun-version-cell excluded on any event. Required checks stay keyed on the `test-status`-and `e2e-status` aggregators, never on per-cell matrix names.--| Workflow | Condition | Class | Covered by |-| --- | --- | --- | --- |-| `test.yml` | `security-regressions` Bun matrix | Parity: both Bun versions on every OS, every event | — |-| `test.yml` | `changes` native scope (`smoke`/`primary`/`full`) | Named exception | Every push to master and the nightly Test schedule (`full`) |-| `test.yml` | `gitleaks` commit range by event | Parity: each event scans the range it introduces | — |-| `test.yml` | `dependency-audit` blocking scope | Named exception with a rule ([below](#dependency-audit-rule)) | Every push to master and the nightly Test schedule (always blocking) |-| `test.yml` | `export-scale` pages, 10,001 vs 100,001 | Named exception | Every push to master and the nightly Test schedule |-| `test.yml` | `stress-changed-tests` file set | Named exception: PR-only gate; succeeds with "not a PR event" elsewhere | Push and nightly runs run every file; the nightly race hunt repeats the Postgres arms |-| `test.yml` | `race-hunt` | Named exception: schedule and dispatch only, outside `test-status` | Itself (nightly Test schedule) |-| `test.yml` | `native_only`, `race_hunt`, `stress_*` dispatch inputs; concurrency suffixes | Parity: manual modes and run grouping, never applied to PR, push or schedule events | — |-| `persistence-validation.yml` | Bun matrix of read latency, deployment matrix, unit-lane PostgreSQL arms, soak, crash robot, reconciliation | Parity: both Bun versions on every event | — |-| `persistence-validation.yml` | `SOAK_OPERATIONS` 2,500 vs 10,000 | Named exception | Every push to master and the nightly Test schedule |-| `persistence-validation.yml` | `ROBOT_SECONDS` 150 vs 600 | Named exception | Every push to master and the nightly Test schedule |-| `native-locks.yml` | `inputs.scope` (OpenClaw, musl, Windows probes, Bun 1.4.0 and cross-target cells) | Named exception | Every push to master and the nightly Test schedule (`full`) |-| `e2e.yml` | Doc-only pull request selects no E2E file | Named exception | Every push to master (whole corpus) and the nightly E2E schedule |-| `e2e.yml` | Full-corpus coverage lanes and their `e2e-status` checks | Named exception | Nightly E2E schedule (or a `full_corpus` dispatch) |-| `heavy-tests.yml` | Label-gated jobs on pull requests | Named exception | Nightly Heavy Tests schedule |-| `heavy-tests.yml` | `grok-door` (label or input only) | Recorded decision: no scheduled run until the `XAI_API_KEY` secret exists | None yet, by decision |-| `heavy-tests.yml` | `opencode-door-canary` | Named exception: schedule-only, non-gating canary | Itself |-| `macos-validation.yml` | Label-gated on pull requests | Named exception | Nightly macOS validation schedule |-| `scale-tier.yml` | Path- or label-gated 10k on pull requests | Named exception | Nightly Scale tier schedule (10k-50k) |-| `semgrep.yml` | PR diff scan vs full-tree scan | Named exception | Weekly Semgrep schedule |-| `osv-scanner.yml` | Pull requests scan only on a manifest change | Named exception | Weekly OSV schedule; `dependency-audit` on every PR |-| `nightly-watch.yml` | `workflow_run` event guard | Not a test scope: it files issues from qualifying scheduled and push-to-master runs | — |-| `fix-wave-gate.yml`, `fix-wave-closeout.yml` | Pull-request action and merge state | Not a test scope: merge-process automation | — |--#### Dependency-audit rule--`dependency-audit` blocks on pushes, schedules, manual runs and pull requests-or merge-queue entries that change a dependency manifest or carry the-`dependency-audit` label; on other pull requests a new upstream advisory is a-warning, so one published advisory cannot turn every open PR red at once.-The red it produces lands on master instead, and is handled like any other:-a push-to-master red opens the Test `master-red` issue, a scheduled red the-`nightly-red` issue. The repair PR bumps, overrides, patches or removes the-dependency. When no fix exists, an ignore entry needs Garry's approval and an-expiry date.--#### Cost of parity--Measured from the 15 latest green pull-request Test runs before parity (job-start to finish, PR parameters): the Bun 1.4.0 twins add 14 cells per-`pull_request` run, 55.9 runner-minutes in total: 233 Ubicloud vCPU-minutes-(the two unit-lane PostgreSQL arm shards, 19.8 minutes, are the largest share)-and 2.4 GitHub-hosted minutes (macOS 0.9, Windows 1.5). At the week's 713-completed PR runs that is about 40,000 runner-minutes a week. Wall time does-not grow on an idle pool: on the 10 latest push runs, which already run both-versions, the 1.4.0 cells finished between 2.6 minutes before and 2.1 minutes-after every other job (median 0.1 minutes before), and the PR critical path-stays the unit `test` shards (median 13.9 minutes). A `merge_group` run uses-the same profile and costs the same per run; the merge queue is inert, so it-adds nothing today. If the added median PR wall time exceeds 15 minutes over-a week, the agent on release duty records it on the CI health issue.-### Executed-test receiptsA green job proves only that nothing failed; receipts prove which tests ran.@@ -345,21 +272,29 @@ only where a Postgres lane names it. Those lanes are: a workflow step thatruns with `DATABASE_URL` and names the file, a `test/e2e/` wrapper thatimports it (`registerPostgresTests`), a `tests/heavy/` script that names it,or a row in `scripts/e2e-backend-matrix.txt`. Unit-lane files with no other-Postgres owner are listed in `test/postgres-unit-arms.txt`, one sorted path-per line; adding a file is a one-line edit. Three readers share that list:-`persistence-validation.yml`'s `unit-postgres-arms` job (two shards against a-pgvector service on both supported Bun versions, balanced by-`scripts/postgres-arm-weights.json` through `bun scripts/postgres-unit-arms.ts shard <n> <m>`),-the scheduled [race hunt](#race-hunt) and the lane guard. In the job each file-runs in its own Bun process, so a failing file cannot leak environment or-global state into later files, and each failure prints an `::error file=…`-line with its reproduce command. Refresh the weights from a green run's two-shard logs with `bun scripts/postgres-unit-arms.ts mine <job.log>…`.+Postgres owner are listed in `test/postgres-unit-arms.txt` (one sorted path+per line), read by `persistence-validation.yml`'s `unit-postgres-arms` job (two+shards balanced by `scripts/postgres-arm-weights.json`, both Bun versions), the+[race hunt](#race-hunt) and the lane guard. Each file runs in its own Bun+process and each failure prints an `::error file=…` line with its reproduce command.`bun run check:postgres-lanes` (in `verify`) fails on every arm with no lane-and on a list row that is malformed, duplicated, out of order, missing or has-no gated arm. An arm deliberately left out is an `ALLOWLIST` row in+and on a bad list row. An arm deliberately left out is an `ALLOWLIST` row in`scripts/check-postgres-lane-coverage.ts` naming its reason and TODO; a rowfor a file that is laned, has no arm or is gone fails.+### Stress gate++`stress-changed-tests` (in `test-status`) runs every test file a PR adds or+modifies, plus importers of changed `test/helpers/` files, 10 times with a+fresh database per iteration; a failure must be root-caused in that PR. The+local twin is `bun run test:stress [files…] [--iterations N] [--base <ref>]+[--postgres]`. Profiles, exemptions and replay: [scripts/stress/README.md](../scripts/stress/README.md).++### Race hunt++The nightly `race-hunt` job (outside `test-status`) runs every file in+`test/postgres-unit-arms.txt` 10 times against Postgres and fails with one+`test:stress` reproduce line per failing file ([scripts/stress/README.md](../scripts/stress/README.md#race-hunt)).+### Scale tierThe gate shape and cadence are defined once, by O-CEO-16 (with O-ENG-16 anddiff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.mdindex f2189feb79..e2c714fc25 100644--- a/docs/architecture/key-files/tooling-and-tests.md+++ b/docs/architecture/key-files/tooling-and-tests.md@@ -9,7 +9,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `test/helpers/real-home-guard-preload.ts` — detection-only backstop for changes to the real-home autopilot wrapper, environment file, start script and launchd/systemd units. It compares file metadata before/after tests without reading secret-bearing contents and attributes earlier changes separately. `GBRAIN_TEST_ALLOW_REAL_HOME_WRITES=1` explicitly disarms it with a warning. Installer fixtures set both HOME before Bun startup and GBRAIN_HOME per fixture; `test/real-home-guard-preload.test.ts` verifies fake-live sentinels and the autopilot suite in disposable subprocess homes.-- `.github/workflows/test.yml` — required full validation remains the default for pushes, pull requests and manual runs. Explicit manual `native_only` uses a distinct concurrency group to preserve in-flight full persistence soaks, runs the native matrix, and emits only a scoped native result (`full_ci: false`), never the full-suite aggregate check name. `test/scripts/native-only-workflow.test.ts` evaluates the actual event/input conditions and executes the scope/result scripts; `test/scripts/ci-gates.test.ts` retains all default required-result failures.+- `.github/workflows/test.yml` — required full validation remains the default for pushes, pull requests and manual runs. Explicit manual `native_only` uses a distinct concurrency group to preserve in-flight full persistence soaks, runs the native matrix, and emits only a scoped native result (`full_ci: false`), never the full-suite aggregate check name. The diagnostic dispatch inputs `race_hunt`, `stress_files` and `stress_base`/`stress_head` likewise run only their lane under a `-diagnostic` concurrency group and name the aggregate `full-suite-not-run`. `test-status` also gates `stress-changed-tests`; `race-hunt` runs on the schedule and stays outside it. Every event-conditional behavior carries a parity or named-exception comment (docs/ci-event-parity.md). `test/scripts/native-only-workflow.test.ts` evaluates the actual event/input conditions and executes the scope/result scripts; `test/scripts/ci-pr-scope.test.ts` pins Bun parity and the classification comments; `test/scripts/ci-gates.test.ts` retains all default required-result failures.+- `.github/workflows/stress.yml` + `scripts/stress/run.ts` + `scripts/stress/plan.ts` + `scripts/stress/gate.ts` — repeated-run lanes. `bun run test:stress` (run.ts) runs files N times per execution profile (unit, serial, slow with PR values, both arms of a gated suite, E2E via run-e2e.sh), a fresh `CREATE DATABASE … TEMPLATE` database per database iteration with owned-resource cleanup (exit, signal, next run), a JUnit receipt per iteration, unexpected-skip, zero-executed and arm-never-connected failures, and a credential-free reproduce line. plan.ts: changed files versus the merge base, helper fan-in (25 importers, then a 10-file sample seeded by the head SHA), profiles, measured-weight shards with iteration splitting. gate.ts: `plan`/`report` for the PR gate (`stress-changed-tests`, in `test-status`; "not a PR event" outside PRs; trusted, signature-matched, expiring exemptions from open issues) and the race hunt (test/postgres-unit-arms.txt × 10, 6-12 shards of 55 minutes, depth rotation, "race hunt over budget"). Docs: `scripts/stress/README.md`. Tests: `test/scripts/stress-plan.test.ts`, `test/scripts/stress-gate.test.ts`, `test/scripts/test-stress.test.ts`, `test/scripts/test-stress-postgres.test.ts` (listed in test/postgres-unit-arms.txt).- `.github/workflows/native-locks.yml` — native glibc Linux, macOS and Windows jobs also run publication, Git helper, historical sync-origin and backup portability contracts in separate Bun processes, collecting fatal suite outcomes. macOS/Windows publication fixtures require an actual case-insensitive filesystem. Separate six-cell Windows diagnostic jobs opt into a directory-only hidden-window comparison and file/directory cmdlet-versus-production comparisons after real PGLite setup; neither filters or replaces native acceptance. `test/fixtures/windows-backup-cmdlet-protect.ps1` freezes the old program for A; B forwards the actual production program. The separate read-only `windows-backup-dotnet-inspect.ps1` reports actual owner/SYSTEM, protected-DACL, rights, inheritance and propagation for the independent oracle. The persistence deployment matrix separately executes the publication journal and all three sync-safety suites with PostgreSQL; E2E parity wrappers select them in the local full gate. `test/scripts/data-safety-native-workflow.test.ts` pins mandatory native/database execution without ignored failures and requires both file and directory observations; actual results, not configuration or simulated paths, establish platform coverage.diff --git a/docs/ci-event-parity.md b/docs/ci-event-parity.mdnew file mode 100644index 0000000000..e47ba98199--- /dev/null+++ b/docs/ci-event-parity.md@@ -0,0 +1,70 @@+# CI event parity++The classification table [docs/TESTING.md](TESTING.md#event-parity) links to.++A red that only a push to master can produce is a red no PR could have+caught. So every event-conditional behavior in the workflows is either+parity (pull requests and merge-queue runs do the same work) or a named+exception whose comment, beside the condition, names the scheduled run that+covers it. A condition with no covering scheduled run defaults to parity;+anything else needs a new scheduled run or a decision recorded beside the+condition. `test/scripts/ci-pr-scope.test.ts` fails on an event-conditional+job or block in a test workflow without that comment, and on a Bun-version+cell excluded on any event. Required checks stay keyed on the `test-status`+and `e2e-status` aggregators, never on per-cell matrix names.++## Classification++| Workflow | Condition | Class | Covered by |+| --- | --- | --- | --- |+| `test.yml` | `security-regressions` Bun matrix | Parity: both Bun versions on every OS, every event | — |+| `test.yml` | `changes` native scope (`smoke`/`primary`/`full`) | Named exception | Every push to master and the nightly Test schedule (`full`) |+| `test.yml` | `gitleaks` commit range by event | Parity: each event scans the range it introduces | — |+| `test.yml` | `dependency-audit` blocking scope | Named exception with a rule ([below](#dependency-audit-rule)) | Every push to master and the nightly Test schedule (always blocking) |+| `test.yml` | `export-scale` pages, 10,001 vs 100,001 | Named exception | Every push to master and the nightly Test schedule |+| `test.yml`, `stress.yml` | `stress-changed-tests` file set | Named exception: PR-only gate; succeeds with "not a PR event" elsewhere | Push and nightly runs run every file; the nightly race hunt repeats the Postgres arms |+| `test.yml` | `race-hunt` | Named exception: schedule and dispatch only, outside `test-status` | Itself (nightly Test schedule) |+| `test.yml` | `native_only`, `race_hunt`, `stress_*` dispatch inputs; concurrency suffixes | Parity: manual modes and run grouping, never applied to PR, push or schedule events | — |+| `persistence-validation.yml` | Bun matrix of read latency, deployment matrix, unit-lane PostgreSQL arms, soak, crash robot, reconciliation | Parity: both Bun versions on every event | — |+| `persistence-validation.yml` | `SOAK_OPERATIONS` 2,500 vs 10,000 | Named exception | Every push to master and the nightly Test schedule |+| `persistence-validation.yml` | `ROBOT_SECONDS` 150 vs 600 | Named exception | Every push to master and the nightly Test schedule |+| `native-locks.yml` | `inputs.scope` (OpenClaw, musl, Windows probes, Bun 1.4.0 and cross-target cells) | Named exception | Every push to master and the nightly Test schedule (`full`) |+| `e2e.yml` | Doc-only pull request selects no E2E file | Named exception | Every push to master (whole corpus) and the nightly E2E schedule |+| `e2e.yml` | Full-corpus coverage lanes and their `e2e-status` checks | Named exception | Nightly E2E schedule (or a `full_corpus` dispatch) |+| `heavy-tests.yml` | Label-gated jobs on pull requests | Named exception | Nightly Heavy Tests schedule |+| `heavy-tests.yml` | `grok-door` (label or input only) | Recorded decision: no scheduled run until the `XAI_API_KEY` secret exists | None yet, by decision |+| `heavy-tests.yml` | `opencode-door-canary` | Named exception: schedule-only, non-gating canary | Itself |+| `macos-validation.yml` | Label-gated on pull requests | Named exception | Nightly macOS validation schedule |+| `scale-tier.yml` | Path- or label-gated 10k on pull requests | Named exception | Nightly Scale tier schedule (10k-50k) |+| `semgrep.yml` | PR diff scan vs full-tree scan | Named exception | Weekly Semgrep schedule |+| `osv-scanner.yml` | Pull requests scan only on a manifest change | Named exception | Weekly OSV schedule; `dependency-audit` on every PR |+| `nightly-watch.yml` | `workflow_run` event guard | Not a test scope: it files issues from qualifying scheduled and push-to-master runs | — |+| `fix-wave-gate.yml`, `fix-wave-closeout.yml` | Pull-request action and merge state | Not a test scope: merge-process automation | — |++## Dependency-audit rule++`dependency-audit` blocks on pushes, schedules, manual runs and pull requests+or merge-queue entries that change a dependency manifest or carry the+`dependency-audit` label; on other pull requests a new upstream advisory is a+warning, so one published advisory cannot turn every open PR red at once.+The red it produces lands on master instead, and is handled like any other:+a push-to-master red opens the Test `master-red` issue, a scheduled red the+`nightly-red` issue. The repair PR bumps, overrides, patches or removes the+dependency. When no fix exists, an ignore entry needs Garry's approval and an+expiry date.++## Cost of parity++Measured from the 15 latest green pull-request Test runs before parity (job+start to finish, PR parameters): the Bun 1.4.0 twins add 14 cells per+`pull_request` run, 55.9 runner-minutes in total: 233 Ubicloud vCPU-minutes+(the two unit-lane PostgreSQL arm shards, 19.8 minutes, are the largest share)+and 2.4 GitHub-hosted minutes (macOS 0.9, Windows 1.5). At the week's 713+completed PR runs that is about 40,000 runner-minutes a week. Wall time does+not grow on an idle pool: on the 10 latest push runs, which already run both+versions, the 1.4.0 cells finished between 2.6 minutes before and 2.1 minutes+after every other job (median 0.1 minutes before), and the PR critical path+stays the unit `test` shards (median 13.9 minutes). A `merge_group` run uses+the same profile and costs the same per run; the merge queue is inert, so it+adds nothing today. If the added median PR wall time exceeds 15 minutes over+a week, the agent on release duty records it on the CI health issue.diff --git a/package.json b/package.jsonindex 5c77b8ef0d..93d696408f 100644--- a/package.json+++ b/package.json@@ -87,6 +87,7 @@"test:agent-voice": "bash scripts/test-agent-voice.sh","test:e2e": "bash scripts/run-e2e.sh","test:slow": "bash scripts/run-slow-tests.sh",+ "test:stress": "bun run scripts/stress/run.ts","test:scale": "bun scripts/scale/run.ts","test:heavy": "bash scripts/run-heavy.sh","test:profile": "bash scripts/profile-tests.sh",diff --git a/scripts/stress/README.md b/scripts/stress/README.mdnew file mode 100644index 0000000000..686d66feb9--- /dev/null+++ b/scripts/stress/README.md@@ -0,0 +1,142 @@+# Stress runner, PR stress gate and race hunt++`bun run test:stress` runs test files repeatedly on one checkout to prove they+are deterministic. The same runner drives three callers: local runs, the PR+stress gate (`stress-changed-tests`, inside `test-status`) and the nightly+race hunt (`race-hunt`, outside `test-status`). Both CI lanes live in+`.github/workflows/stress.yml`, called from `test.yml`.++| File | Role |+| --- | --- |+| `scripts/stress/run.ts` | The runner (`bun run test:stress`) |+| `scripts/stress/plan.ts` | Changed files, helper fan-in, profiles, shards, reproduce lines |+| `scripts/stress/gate.ts` | CI planner and reporter for both lanes (`plan`, `report`) |+| `test/postgres-unit-arms.txt` | The race hunt's file list (shared with `unit-postgres-arms`) |++## Running it locally++```bash+bun run test:stress # files changed versus origin/master, 10 iterations+bun run test:stress test/a.test.ts --iterations 20 # explicit files+bun run test:stress --postgres # include PostgreSQL arms and E2E files+bun run test:stress --base <ref> --head <ref> # the files a commit range touched+bun run test:stress --dry-run # print the plan only+```++Without files the runner takes every `test/**/*.test.ts` added or modified+versus the merge base with `origin/master` (renames at the new path,+deletions skipped, working tree and untracked files included), plus direct+importers of changed `test/helpers/` files by the fan-in rule below.+`--postgres` uses the server in `GBRAIN_STRESS_ADMIN_URL`, else a+test-shaped `DATABASE_URL`, else starts `docker-compose.ci.yml`'s+`postgres-1` (the `ci:local` service) under its own compose project and+removes it afterwards.++Every run prints one line per iteration, setup and run time, and for each+failing file a reproduce command plus its context line:++```+FAIL [stress_failure]: test/a.test.ts failed in 2 iteration(s) (first: iteration 7, …)+ bun run test:stress test/a.test.ts --iterations 10 --first-iteration 7 --seed 412207 --postgres+ # sha 1a2b3c4d5e6f, Bun 1.4.2, backend pglite+postgres, profile postgres-arm (database), iteration 7, seed 412213, artifact <run url>+```++The reproduce line is the exact command with the recorded values; database+credentials never appear in it or in any log (`redact()`). The manifest+(`.context/test-stress/stress-manifest.json`) records SHA, Bun version,+backend, profile, iteration, seed and every failure. Exit codes: 0 every file+passed, 1 a failure, 2 a usage or setup error, 130/143 cancelled.++## Execution profiles++| Profile | Files | Command and environment |+| --- | --- | --- |+| `unit` | `*.test.ts` | `bun test --timeout=60000`, `DATABASE_URL` unset |+| `serial` | `*.serial.test.ts` | `bun test --max-concurrency=1 --timeout=120000`, `DATABASE_URL` unset; files run one at a time |+| `slow` | `*.slow.test.ts` | the workflow's pull-request values (`SPECIAL_FILES` in `plan.ts`: export scale at 10,001 pages, the pre-feature executable built for the old-binary suite) |+| `postgres-arm` | a file with a `DATABASE_URL`-gated arm, with `--postgres` | `bun --no-env-file test --timeout=120000` with a fresh `DATABASE_URL`: both arms, as in `unit-postgres-arms` |+| `e2e` | `test/e2e/*.test.ts`, with `--postgres` | `bash scripts/run-e2e.sh <file>` with a fresh `DATABASE_URL` |++Paid-provider files (`*.live.test.ts`, `test/live/`,+`scripts/e2e-live-key-only.txt`) are listed as not stressed. A file whose+every test skips on this platform, or skips without an unavailable secret, is+listed as not stressed with that reason; any other run with zero executed+tests fails.++## Isolation and receipts++Each database iteration gets its own database, `CREATE DATABASE … TEMPLATE`+from a blank template the run creates once. Names carry a `test` segment+(`gbrain_stress_<pid>_<rand>_i<n>_test`). Every database and container the run+creates is recorded under `.context/test-stress/owned/` and dropped after the+iteration, on Ctrl-C (SIGINT/SIGTERM stop the running file first), and by the+next run when the owning process is gone.++Every iteration writes an executed-test receipt (`<out>/receipts/<file>--i<n>/`:+the receipt, its file list and Bun's JUnit report). The first iteration's+executed tests are the expected set: a later iteration that does not run one+of them is an unexpected skip and fails. A `postgres-arm` iteration whose fresh+database served no transaction fails too (the arm never connected). Each+iteration has a 15-minute wall cap (`GBRAIN_STRESS_ITERATION_TIMEOUT_MS`).+Seeds: iteration `n` exports `GBRAIN_TEST_SEED=<base>+n-1`; the base is+`--seed` or a hash of the commit and file, and `--randomize` passes it to+Bun's test-order randomizer.++## PR stress gate++`stress-changed-tests` runs on every event and always concludes success or+failure: outside `pull_request` and `merge_group` it succeeds with "not a PR+event"; if the changed-file list cannot be computed it fails with the fetch+step. Otherwise every changed test file runs 10 times in Postgres-backed+shards.++- **Helper fan-in.** A changed helper with at most 25 direct test importers+ stresses all of them. Above 25 it stresses the helper's own tests and 10+ importers sampled deterministically from the head SHA, and lists the rest;+ their Postgres arms join that night's race hunt. Changed test files are+ never sampled or skipped.+- **Shards.** Work items (a file's iterations, split when ten exceed the+ budget) pack into the fewest shards whose measured estimates stay under 25+ minutes. There is no shard-count cap; `max-parallel: 6` keeps a large PR+ from starving other jobs. Shard jobs record results and exit 0 on test+ failures; the result job decides, so a planned iteration without a receipt+ fails the check as incomplete.+- **Failure.** The result names the file, the failing iteration and the+ reproduce line, and says a flaky touched file must be root-caused in this PR.+- **Exemptions.** A failure passes only when its file, test name, backend and+ failure signature match an unexpired record in an open `master-red`, `flake`+ or `nightly-red` issue that predates the PR and was opened or labeled by the+ nightly-watch bot or a maintainer (write access). Records live in the issue+ body or in a comment by the bot or a maintainer. Any other failure in that+ file, or a new signature, still fails. A GitHub API failure grants nothing.+ There is no override label. Record format:++ ````+ <!-- gbrain-stress-exemption -->+ ```json+ {"file":"test/a.test.ts","test":"suite > case","backend":"pglite+postgres","signature":"<from the manifest>","owner":"@release-duty","expires":"2026-10-20"}+ ```+ ````++- **Dispatch.** `gh workflow run test.yml -f stress_files="test/a.test.ts test/b.test.ts"`+ or `-f stress_base=<ref> [-f stress_head=<ref>]` runs only the gate,+ labeled diagnostic. Inputs reach the planner through `env:` only; paths must+ match `^test/[\w./-]+\.test\.ts$` and refs must pass `git check-ref-format`+ or be 40-hex SHAs.+- **Summary.** Files stressed, not-stressed files with reasons, touched files+ with an open issue, runner-minutes, and p95 queue and completion time of the+ shard jobs.++## Race hunt++The scheduled Test run (and `gh workflow run test.yml -f race_hunt=true`, a+diagnostic) runs every file in `test/postgres-unit-arms.txt` 10 times against+Postgres, plus the Postgres-arm and E2E importers of helpers changed on master+since the previous night that the gate sampled out. Budget: at most 55-minute+shards, 6 by default, growing to 12; past that every file runs at least 3+iterations nightly and the spare capacity rotates by day, so each file still+reaches 10 iterations within the week. Files are never dropped: what does not+fit fails the job with "race hunt over budget" and the unrun files. A red+prints one `::error` line per failing file with its reproduce command, which+the Test nightly-red issue carries; the response is a repair PR, never a+known-red row.diff --git a/scripts/stress/gate.ts b/scripts/stress/gate.tsnew file mode 100644index 0000000000..733f949a52--- /dev/null+++ b/scripts/stress/gate.ts@@ -0,0 +1,474 @@+#!/usr/bin/env bun+/**+ * CI planner and reporter for the PR stress gate (`stress-changed-tests`) and+ * the nightly race hunt (`race-hunt`), both run by+ * .github/workflows/stress.yml through `bun run test:stress`.+ *+ * bun scripts/stress/gate.ts plan --mode gate|race-hunt (env inputs below; writes GITHUB_OUTPUT + plan.json)+ * bun scripts/stress/gate.ts report --mode gate|race-hunt --plan <plan.json> --manifests <dir>+ *+ * Plan env: EVENT, BASE_SHA/HEAD_SHA (pull_request, merge_group),+ * STRESS_FILES or STRESS_BASE/STRESS_HEAD (workflow_dispatch, validated:+ * paths match ^test/[\w./-]+\.test\.ts$, refs pass git check-ref-format or are+ * 40-hex SHAs), GBRAIN_RACE_HUNT_DAY (rotation override, tests only).+ * Report env: PLAN_RESULT, SHARDS_RESULT, GITHUB_REPOSITORY, GITHUB_RUN_ID,+ * GITHUB_RUN_ATTEMPT, GH_TOKEN, GATE_SINCE (exemptions must predate it).+ *+ * The gate's conclusion is always success or failure: outside pull_request+ * and merge_group it succeeds with "not a PR event"; a plan that cannot list+ * the changed files fails with the next step. Docs: docs/TESTING.md#stress-gate,+ * docs/TESTING.md#race-hunt.+ */+import { spawnSync } from 'node:child_process';+import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { inert, restClient, type GitHubClient } from '../lib/gh-issue.ts';+import { postgresArm } from '../check-postgres-lane-coverage.ts';+import { readArmsList } from '../postgres-unit-arms.ts';+import {+ DEFAULT_ITERATIONS, RACE_HUNT_DOCS, STRESS_DOCS, allTestFiles, changedFiles, expandHelper, iterationEstimateMs,+ loadWeights, notStressedReason, parseFileList, planShards, profileFor, redact, reproduceLine, validRef,+ type HelperExpansion, type NotStressed, type ProfileName, type Shard, type Weights,+} from './plan.ts';++const ROOT = resolve(import.meta.dir, '..', '..');+export const GATE_SHARD_BUDGET_MS = 25 * 60_000;+export const RACE_SHARD_BUDGET_MS = 55 * 60_000;+export const RACE_BASE_SHARDS = 6;+export const RACE_MAX_SHARDS = 12;+export const RACE_MIN_ITERATIONS = 3;+export const EXEMPTION_LABELS = ['master-red', 'flake', 'nightly-red'];+const TRUSTED_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);+const BOT = 'github-actions[bot]';++export type Mode = 'gate' | 'race-hunt';++export interface PlanFile { file: string; profile: ProfileName; iterations: number; estimateMs: number }+export interface Plan {+ version: 1; mode: Mode; run: boolean; reason: string; diagnostic: boolean; head: string; base: string;+ files: PlanFile[]; notStressed: NotStressed[]; helpers: HelperExpansion[]; shards: Shard[];+ unrun: string[]; iterations: number; budgetMs: number; estimateMs: number;+}++const emptyPlan = (mode: Mode, reason: string, extra: Partial<Plan> = {}): Plan => ({+ version: 1, mode, run: false, reason, diagnostic: false, head: '', base: '', files: [], notStressed: [], helpers: [], shards: [], unrun: [],+ iterations: DEFAULT_ITERATIONS, budgetMs: mode === 'gate' ? GATE_SHARD_BUDGET_MS : RACE_SHARD_BUDGET_MS, estimateMs: 0, ...extra,+});++function liveKeyOnly(root: string): Set<string> {+ const path = join(root, 'scripts/e2e-live-key-only.txt');+ return new Set(existsSync(path) ? readFileSync(path, 'utf8').split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#')) : []);+}++function classify(root: string, files: string[], weights: Weights): { stress: Array<PlanFile & { perIterationMs: number; setupMs: number }>; notStressed: NotStressed[] } {+ const live = liveKeyOnly(root);+ const stress: Array<PlanFile & { perIterationMs: number; setupMs: number }> = [];+ const notStressed: NotStressed[] = [];+ for (const file of files) {+ if (!existsSync(join(root, file))) { notStressed.push({ file, reason: 'no such file at the head commit' }); continue; }+ const reason = notStressedReason(file, live);+ if (reason) { notStressed.push({ file, reason }); continue; }+ const armed = !file.startsWith('test/e2e/') && postgresArm(join(root, file)) !== null;+ const profile = profileFor(file, { armed, postgres: true });+ const perIterationMs = iterationEstimateMs(file, profile.name, weights);+ stress.push({ file, profile: profile.name, iterations: DEFAULT_ITERATIONS, estimateMs: 0, perIterationMs, setupMs: profile.prereq ? 180_000 : 0 });+ }+ return { stress, notStressed };+}++export interface GatePlanInput { event: string; baseSha?: string; headSha?: string; stressFiles?: string; stressBase?: string; stressHead?: string }++/** The PR gate: every changed test file plus helper importers, ten iterations, shards under the budget. */+export function planGate(root: string, input: GatePlanInput, weights = loadWeights(root)): Plan | { error: string } {+ let files: string[];+ let helpers: HelperExpansion[] = [];+ let base = input.baseSha ?? '';+ let head = input.headSha ?? '';+ let diagnostic = false;+ if (input.event === 'workflow_dispatch' && (input.stressFiles || input.stressBase)) {+ diagnostic = true;+ if (input.stressFiles) {+ const parsed = parseFileList(input.stressFiles);+ if (parsed.invalid.length) return { error: `stress_files has entries that are not repo-relative test files: ${parsed.invalid.map(f => JSON.stringify(f.slice(0, 80))).join(', ')}. Next: pass space- or comma-separated paths matching ^test/[\\w./-]+\\.test\\.ts$` };+ files = parsed.files;+ head = 'HEAD';+ } else {+ base = input.stressBase!;+ head = input.stressHead || 'HEAD';+ if (!validRef(base) || !validRef(head)) return { error: `stress_base/stress_head must be 40-hex SHAs or valid ref names (got ${JSON.stringify(base.slice(0, 80))}, ${JSON.stringify(head.slice(0, 80))}). Next: re-dispatch with e.g. stress_base=origin/master` };+ const changed = changedFiles(root, base, head);+ if (changed.error) return { error: changed.error };+ const tests = changed.helpers.length ? allTestFiles(root) : [];+ helpers = changed.helpers.map(h => expandHelper(root, h, tests, resolveSha(root, head)));+ files = [...new Set([...changed.tests, ...helpers.flatMap(h => h.stressed)])].sort();+ }+ } else if (input.event === 'pull_request' || input.event === 'merge_group') {+ if (!input.baseSha || !input.headSha) return { error: `the ${input.event} payload carried no base/head SHA. Next: re-run the job; if it repeats, report the event payload` };+ const changed = changedFiles(root, input.baseSha, input.headSha);+ if (changed.error) return { error: changed.error };+ const tests = changed.helpers.length ? allTestFiles(root) : [];+ helpers = changed.helpers.map(h => expandHelper(root, h, tests, input.headSha!));+ files = [...new Set([...changed.tests, ...helpers.flatMap(h => h.stressed)])].sort();+ } else {+ return emptyPlan('gate', 'not a PR event');+ }+ const { stress, notStressed } = classify(root, files, weights);+ const shards = planShards(stress, DEFAULT_ITERATIONS, GATE_SHARD_BUDGET_MS);+ return {+ ...emptyPlan('gate', stress.length ? `${stress.length} file(s) × ${DEFAULT_ITERATIONS} iterations` : 'no changed test files to stress'),+ run: stress.length > 0, diagnostic, base, head, helpers, notStressed, shards,+ files: stress.map(({ file, profile }) => ({ file, profile, iterations: DEFAULT_ITERATIONS, estimateMs: estimateOf(shards, file) })),+ estimateMs: shards.reduce((s, x) => s + x.estimateMs, 0),+ };+}++const estimateOf = (shards: Shard[], file: string) => shards.flatMap(s => s.items).filter(i => i.file === file).reduce((s, i) => s + i.estimateMs, 0);++function resolveSha(root: string, ref: string): string {+ return spawnSync('git', ['rev-parse', ref], { cwd: root, encoding: 'utf8' }).stdout.trim() || ref;+}++/** Postgres-arm and E2E importers of helpers changed on master since the last night (the gate sampled them out). */+export function raceHuntHelperImporters(root: string, since = '26 hours ago'): { helpers: string[]; files: string[] } {+ const r = spawnSync('git', ['log', `--since=${since}`, '--name-only', '--format=', 'HEAD', '--', 'test/helpers'], { cwd: root, encoding: 'utf8' });+ const helpers = [...new Set((r.stdout ?? '').split('\n').filter(p => p && !p.endsWith('.test.ts') && existsSync(join(root, p))))].sort();+ if (!helpers.length) return { helpers, files: [] };+ const tests = allTestFiles(root);+ const files = new Set<string>();+ for (const h of helpers) {+ const exp = expandHelper(root, h, tests, 'race-hunt');+ for (const f of exp.listedOnly) if (f.startsWith('test/e2e/') || postgresArm(join(root, f))) files.add(f);+ }+ return { helpers, files: [...files].sort() };+}++/**+ * The race hunt: every listed Postgres arm at 10 iterations within 6 shards+ * of 55 minutes, growing to 12 shards; past that, every file runs at least 3+ * iterations nightly and the spare capacity rotates by day so each file still+ * reaches 10 within the week. Files are never dropped: what does not fit is+ * `unrun` and the job fails "race hunt over budget".+ */+export function planRaceHunt(root: string, opts: { day: number; extra?: string[]; diagnostic?: boolean }, weights = loadWeights(root)): Plan {+ const list = readArmsList(root);+ const files = [...new Set([...list.files, ...(opts.extra ?? [])])].sort();+ const { stress, notStressed } = classify(root, files, weights);+ const capacity = RACE_MAX_SHARDS * RACE_SHARD_BUDGET_MS;+ const per = (f: { perIterationMs: number }) => f.perIterationMs + 3000;+ const onePass = stress.reduce((s, f) => s + per(f), 0);+ let depth = new Map(stress.map(f => [f.file, DEFAULT_ITERATIONS]));+ const unrun: string[] = [];+ if (onePass * DEFAULT_ITERATIONS > capacity) {+ const floor = Math.floor(capacity / Math.max(1, onePass));+ if (floor >= RACE_MIN_ITERATIONS) {+ depth = new Map(stress.map(f => [f.file, Math.min(DEFAULT_ITERATIONS, floor)]));+ let spare = capacity - onePass * Math.min(DEFAULT_ITERATIONS, floor);+ const order = stress.map(f => f.file);+ const offset = order.length ? (opts.day * 7) % order.length : 0;+ for (let k = 0; k < order.length && spare > 0; k++) {+ const f = stress.find(x => x.file === order[(offset + k) % order.length])!;+ const add = Math.min(DEFAULT_ITERATIONS - depth.get(f.file)!, Math.floor(spare / per(f)));+ if (add > 0) { depth.set(f.file, depth.get(f.file)! + add); spare -= add * per(f); }+ }+ } else {+ depth = new Map();+ let used = 0;+ for (const f of stress) {+ if (used + per(f) * RACE_MIN_ITERATIONS <= capacity) { depth.set(f.file, RACE_MIN_ITERATIONS); used += per(f) * RACE_MIN_ITERATIONS; } else unrun.push(f.file);+ }+ }+ }+ const scheduled = stress.filter(f => depth.has(f.file));+ const shards: Shard[] = [];+ for (const iterations of [...new Set(depth.values())]) {+ const group = scheduled.filter(f => depth.get(f.file) === iterations);+ shards.push(...planShards(group, iterations, RACE_SHARD_BUDGET_MS));+ }+ shards.forEach((s, i) => { s.index = i + 1; });+ return {+ ...emptyPlan('race-hunt', `${scheduled.length} Postgres-arm file(s), ${shards.length} shard(s)`),+ run: scheduled.length > 0, diagnostic: !!opts.diagnostic, notStressed, shards, unrun,+ files: scheduled.map(f => ({ file: f.file, profile: f.profile, iterations: depth.get(f.file)!, estimateMs: estimateOf(shards, f.file) })),+ estimateMs: shards.reduce((s, x) => s + x.estimateMs, 0),+ };+}++// ── Exemptions ────────────────────────────────────────────────────────────────++export interface Exemption { file: string; test: string; backend: string; signature: string; owner: string; expires: string; issue: number; url: string }+export interface GhIssue { number: number; html_url?: string; title?: string; body?: string | null; created_at: string; user?: { login: string }; author_association?: string; labels?: Array<{ name: string } | string>; pull_request?: unknown }+interface GhComment { body?: string; user?: { login: string }; author_association?: string }+interface GhEvent { event: string; label?: { name: string }; actor?: { login: string } }++const MARKER = '<!-- gbrain-stress-exemption -->';++/** Every exemption block (`<!-- gbrain-stress-exemption -->` then a ```json object or array) in a text. */+export function parseExemptionBlocks(text: string): Array<Omit<Exemption, 'issue' | 'url'>> {+ const out: Array<Omit<Exemption, 'issue' | 'url'>> = [];+ let at = text.indexOf(MARKER);+ while (at !== -1) {+ const rest = text.slice(at + MARKER.length).trimStart();+ const m = /^```json\n([\s\S]*?)\n```/.exec(rest);+ if (m) {+ try {+ const parsed = JSON.parse(m[1]!) as unknown;+ for (const row of Array.isArray(parsed) ? parsed : [parsed]) {+ const r = row as Record<string, unknown>;+ if (['file', 'test', 'backend', 'signature', 'owner', 'expires'].every(k => typeof r[k] === 'string' && (r[k] as string).length > 0) && /^\d{4}-\d{2}-\d{2}$/.test(r.expires as string)) {+ out.push({ file: r.file as string, test: r.test as string, backend: r.backend as string, signature: r.signature as string, owner: r.owner as string, expires: r.expires as string });+ }+ }+ } catch { /* malformed block grants nothing */ }+ }+ at = text.indexOf(MARKER, at + MARKER.length);+ }+ return out;+}++/**+ * Exemptions from open master-red, flake or nightly-red issues. An issue+ * counts only when the nightly-watch bot or a maintainer opened it or applied+ * one of those labels, and it predates `since`; a block counts from the issue+ * body or a comment by the bot or a maintainer. Any API failure returns+ * `incomplete` and grants nothing.+ */+export async function loadExemptions(client: GitHubClient, since: string): Promise<{ exemptions: Exemption[]; openIssues: GhIssue[]; incomplete?: string }> {+ try {+ const seen = new Map<number, GhIssue>();+ for (const label of EXEMPTION_LABELS) {+ for (let page = 1; page <= 5; page++) {+ const batch = await client.request<GhIssue[]>('GET', `repos/{repo}/issues?state=open&labels=${encodeURIComponent(label)}&per_page=100&page=${page}`);+ for (const i of batch) if (!i.pull_request) seen.set(i.number, i);+ if (batch.length < 100) break;+ }+ }+ const permission = new Map<string, boolean>();+ const maintainer = async (login: string | undefined): Promise<boolean> => {+ if (!login) return false;+ if (login === BOT) return true;+ if (!permission.has(login)) {+ try {+ const r = await client.request<{ permission?: string }>('GET', `repos/{repo}/collaborators/${encodeURIComponent(login)}/permission`);+ permission.set(login, ['admin', 'maintain', 'write'].includes(r.permission ?? ''));+ } catch { permission.set(login, false); }+ }+ return permission.get(login)!;+ };+ const exemptions: Exemption[] = [];+ for (const issue of seen.values()) {+ if (!(Date.parse(issue.created_at) < Date.parse(since))) continue;+ let trusted = issue.user?.login === BOT || TRUSTED_ASSOCIATIONS.has(issue.author_association ?? '');+ if (!trusted) {+ const events = await client.request<GhEvent[]>('GET', `repos/{repo}/issues/${issue.number}/events?per_page=100`);+ for (const e of events) if (e.event === 'labeled' && EXEMPTION_LABELS.includes(e.label?.name ?? '') && await maintainer(e.actor?.login)) { trusted = true; break; }+ }+ if (!trusted) continue;+ const texts = [issue.body ?? ''];+ const comments = await client.request<GhComment[]>('GET', `repos/{repo}/issues/${issue.number}/comments?per_page=100`);+ for (const c of comments) if (c.user?.login === BOT || TRUSTED_ASSOCIATIONS.has(c.author_association ?? '')) texts.push(c.body ?? '');+ for (const block of texts.flatMap(parseExemptionBlocks)) exemptions.push({ ...block, issue: issue.number, url: issue.html_url ?? `#${issue.number}` });+ }+ return { exemptions, openIssues: [...seen.values()] };+ } catch (e) {+ return { exemptions: [], openIssues: [], incomplete: (e as Error).message };+ }+}++export interface StressFailure { file: string; iteration: number; seed: number; test: string; backend: string; signature: string; message: string; reproduce: string; context: string }++/** A failure is exempt only when file, test name, backend and signature all match an unexpired record. */+export function matchExemption(f: StressFailure, exemptions: Exemption[], today: string): Exemption | undefined {+ return exemptions.find(e => e.file === f.file && e.test === f.test && e.backend === f.backend && e.signature === f.signature && e.expires >= today);+}++// ── Report ────────────────────────────────────────────────────────────────────++interface Manifest { sha: string; bun: string; run_id: string; artifact: string; files: Array<{ file: string; status: string; firstIteration: number; iterations: Array<{ index: number }>; reason?: string }>; failures: StressFailure[]; setup_ms: number; run_ms: number }++export function loadManifests(dir: string): Manifest[] {+ const out: Manifest[] = [];+ if (!existsSync(dir)) return out;+ const walk = (d: string) => { for (const e of readdirSync(d)) { const p = join(d, e); if (statSync(p).isDirectory()) walk(p); else if (e === 'stress-manifest.json') out.push(JSON.parse(readFileSync(p, 'utf8'))); } };+ walk(dir);+ return out;+}++/** Planned (file, iteration) pairs no manifest accounts for: an incomplete shard never reads as a pass. */+export function missingWork(plan: Plan, manifests: Manifest[]): string[] {+ const done = new Set<string>();+ for (const m of manifests) for (const f of m.files) {+ if (f.status === 'not-stressed') { for (const s of plan.shards) for (const i of s.items) if (i.file === f.file) for (let k = i.first; k < i.first + i.count; k++) done.add(`${f.file}#${k}`); continue; }+ for (const it of f.iterations) done.add(`${f.file}#${it.index}`);+ }+ const missing: string[] = [];+ for (const s of plan.shards) for (const i of s.items) {+ const absent = Array.from({ length: i.count }, (_, k) => i.first + k).filter(k => !done.has(`${i.file}#${k}`));+ if (absent.length) missing.push(`${i.file} iterations ${absent[0]}-${absent[absent.length - 1]} (shard ${s.index})`);+ }+ return missing;+}++export interface JobTiming { name: string; created_at: string; started_at: string | null; completed_at: string | null }+const p95 = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.min(s.length - 1, Math.ceil(0.95 * s.length) - 1)]! : 0; };++/** p95 queue (created → started) and completion (created → completed) minutes of the shard jobs, and their runner-minutes. */+export function shardTimings(jobs: JobTiming[]): { shards: number; p95QueueMin: number; p95CompletionMin: number; runnerMin: number } {+ const shards = jobs.filter(j => /Stress shard|Race hunt shard/.test(j.name) && j.started_at && j.completed_at);+ const min = (a: string, b: string) => (Date.parse(b) - Date.parse(a)) / 60_000;+ return {+ shards: shards.length,+ p95QueueMin: p95(shards.map(j => min(j.created_at, j.started_at!))),+ p95CompletionMin: p95(shards.map(j => min(j.created_at, j.completed_at!))),+ runnerMin: shards.reduce((s, j) => s + min(j.started_at!, j.completed_at!), 0),+ };+}++export interface ReportInput {+ plan: Plan | undefined; planResult: string; shardsResult: string; manifests: Manifest[];+ exemptions: Awaited<ReturnType<typeof loadExemptions>>; timings?: ReturnType<typeof shardTimings>; today: string; artifact: string;+}++/** Summary markdown, `::error` lines and the exit code. Reproduce commands come from validated fields and are never passed through inert(). */+export function buildReport(r: ReportInput): { summary: string; errors: string[]; exit: number } {+ const mode = r.plan?.mode ?? 'gate';+ const docs = mode === 'gate' ? STRESS_DOCS : RACE_HUNT_DOCS;+ const title = mode === 'gate' ? 'PR stress gate (`stress-changed-tests`)' : 'Race hunt (`race-hunt`)';+ const lines: string[] = [`## ${title}${r.plan?.diagnostic ? ' — diagnostic dispatch (never opens, updates or closes an issue)' : ''}`, ''];+ const errors: string[] = [];+ if (r.planResult !== 'success' || !r.plan) {+ const why = 'the plan job failed, so the set of files to stress is unknown';+ lines.push(`**Failed:** ${why}. Next: read the "Stress plan" job log; if it says the merge base is missing, fetch it (\`git fetch --no-tags origin master\`) and re-run. Docs: ${docs}`);+ errors.push(`stress plan did not succeed (${r.planResult}). Why: ${why}. Next: read the plan job log and re-run. Docs: ${docs}`);+ return { summary: lines.join('\n'), errors, exit: 1 };+ }+ const plan = r.plan;+ if (!plan.run && !plan.unrun.length) {+ lines.push(`**Passed:** ${plan.reason}.`);+ for (const n of plan.notStressed) lines.push(`- not stressed: \`${n.file}\`: ${n.reason}`);+ return { summary: lines.join('\n'), errors, exit: 0 };+ }+ const failures = r.manifests.flatMap(m => m.failures);+ const missing = missingWork(plan, r.manifests);+ const exempt: Array<{ f: StressFailure; e: Exemption }> = [];+ const real: StressFailure[] = [];+ for (const f of failures) {+ const e = mode === 'gate' && !r.exemptions.incomplete ? matchExemption(f, r.exemptions.exemptions, r.today) : undefined;+ if (e) exempt.push({ f, e }); else real.push(f);+ }+ const fileCount = plan.files.length;+ const iterationTotal = plan.files.reduce((s, f) => s + f.iterations, 0);+ lines.push(`${fileCount} file(s), ${iterationTotal} iteration(s) across ${plan.shards.length} shard(s); a fresh database per database iteration.`);+ if (r.timings) lines.push(`Shards: ${r.timings.shards}, runner-minutes ${r.timings.runnerMin.toFixed(1)}, p95 queue ${r.timings.p95QueueMin.toFixed(1)} min, p95 completion ${r.timings.p95CompletionMin.toFixed(1)} min.`);+ lines.push('');+ const byFile = new Map<string, StressFailure[]>();+ for (const f of real) byFile.set(f.file, [...(byFile.get(f.file) ?? []), f]);+ if (byFile.size) {+ lines.push(`### Failed (${byFile.size} file${byFile.size > 1 ? 's' : ''})`, '');+ for (const [file, fs] of byFile) {+ const iterations = [...new Set(fs.map(f => f.iteration))].sort((a, b) => a - b);+ const planned = plan.files.find(p => p.file === file)?.iterations ?? DEFAULT_ITERATIONS;+ const first = fs[0]!;+ const reproduce = reproduceLine({ file, iterations: planned, firstIteration: first.iteration, seed: first.seed - first.iteration + 1, postgres: plan.files.find(p => p.file === file)?.profile === 'postgres-arm' || file.startsWith('test/e2e/') });+ const headline = mode === 'gate'+ ? `failed ${iterations.length} of ${planned} iterations (first: iteration ${first.iteration}). A flaky touched file must be root-caused in this PR`+ : `failed ${iterations.length} of ${planned} iterations (first: iteration ${first.iteration}); open a repair PR that root-causes it`;+ lines.push(`- \`${file}\`: ${headline}.`, ` - test: ${inert(first.test)}; backend ${inert(first.backend)}; ${inert(redact(first.message.split('\n')[0] ?? ''), 300)}`, '', ' ```bash', ` ${reproduce}`, ` # ${inert(redact(first.context), 400)}`, ' ```', '');+ errors.push(`file=${file}::${mode === 'gate' ? 'stress gate' : 'race hunt'}: ${headline}. Why: the same commit passed and failed across iterations. Reproduce: ${reproduce} (${r.artifact || 'see the run artifacts'}). Docs: ${docs}`);+ }+ }+ if (exempt.length) {+ lines.push('### Known failures (exempt)', '');+ for (const { f, e } of exempt) lines.push(`- \`${f.file}\` ${inert(f.test)}: matches the open issue ${e.url} (owner ${inert(e.owner)}, expires ${e.expires}); not counted. Any other failure still fails the check.`);+ lines.push('');+ }+ if (mode === 'gate') {+ const touched = plan.files.map(p => p.file);+ const known = r.exemptions.openIssues.filter(i => touched.some(f => (i.body ?? '').includes(f) || (i.title ?? '').includes(f)));+ if (known.length) { lines.push('### Touched files with an open issue', ''); for (const i of known) lines.push(`- ${i.html_url ?? `#${i.number}`}: ${inert(i.title ?? '')}`); lines.push(''); }+ if (r.exemptions.incomplete) lines.push(`Exemption lookup incomplete (${inert(r.exemptions.incomplete, 200)}): no exemption was granted.`, '');+ }+ if (missing.length) {+ lines.push('### Incomplete', '', `Shards result: ${r.shardsResult}. These planned iterations left no receipt, so the run cannot pass:`, ...missing.map(m => `- ${m}`), '', `Next: open the failed shard's log; re-run the job when the cause is outside the PR. Docs: ${docs}`, '');+ errors.push(`${missing.length} planned work item(s) left no receipt (shards: ${r.shardsResult}). Why: an unrun iteration is not a pass. Next: read the shard logs and re-run. Docs: ${docs}`);+ }+ if (plan.unrun.length) {+ lines.push('### Race hunt over budget', '', `These files did not fit ${RACE_MAX_SHARDS} shards × ${RACE_SHARD_BUDGET_MS / 60_000} minutes at ${RACE_MIN_ITERATIONS} iterations and did not run:`, ...plan.unrun.map(f => `- \`${f}\``), '', `Next: speed up the slowest listed files or split the race hunt into a second scheduled run. Docs: ${docs}`, '');+ errors.push(`race hunt over budget: ${plan.unrun.length} file(s) did not run (${plan.unrun.slice(0, 5).join(', ')}${plan.unrun.length > 5 ? ', …' : ''}). Why: files are never dropped silently. Next: speed up the slowest files or add a second scheduled shard group. Docs: ${docs}`);+ }+ if (plan.notStressed.length) { lines.push('### Not stressed', ''); for (const n of plan.notStressed) lines.push(`- \`${n.file}\`: ${n.reason}`); lines.push(''); }+ const runtimeSkips = r.manifests.flatMap(m => m.files.filter(f => f.status === 'not-stressed'));+ for (const s of runtimeSkips) lines.push(`- not stressed at run time: \`${s.file}\`: ${inert(s.reason ?? '')}`);+ for (const h of plan.helpers) if (h.listedOnly.length) lines.push(`- helper \`${h.helper}\` has ${h.importers} direct importers; stressed ${h.stressed.length} (its own tests and a sample seeded by the head SHA). Not stressed here: ${h.listedOnly.map(f => `\`${f}\``).join(', ')}${h.listedOnly.some(f => f.startsWith('test/e2e/')) ? '; their Postgres arms join that night\'s race hunt' : ''}.`);+ const exit = byFile.size || missing.length || plan.unrun.length ? 1 : 0;+ if (!exit) lines.push('', `**Passed.** Every planned iteration ran and passed.`);+ return { summary: lines.join('\n'), errors, exit };+}++// ── CLI ───────────────────────────────────────────────────────────────────────++function arg(argv: string[], name: string): string | undefined { const i = argv.indexOf(name); return i === -1 ? undefined : argv[i + 1]; }++function writeOutputs(plan: Plan) {+ const out = process.env.GITHUB_OUTPUT;+ const matrix = { include: plan.shards.map(s => ({ shard: s.index, work: JSON.stringify(s.items.map(({ file, first, count }) => ({ file, first, count }))) })) };+ const lines = [`run=${plan.run}`, `count=${plan.shards.length}`, `matrix=${JSON.stringify(matrix)}`, `reason=${plan.reason.replace(/\n/g, ' ')}`];+ if (out) appendFileSync(out, `${lines.join('\n')}\n`);+}++async function main(argv: string[]): Promise<number> {+ const [command] = argv;+ const mode = (arg(argv, '--mode') ?? 'gate') as Mode;+ if (!['gate', 'race-hunt'].includes(mode)) { console.error('usage: scripts/stress/gate.ts plan|report --mode gate|race-hunt'); return 2; }+ if (command === 'plan') {+ const env = process.env;+ let plan: Plan;+ if (mode === 'gate') {+ const result = planGate(ROOT, { event: env.EVENT ?? '', baseSha: env.BASE_SHA, headSha: env.HEAD_SHA, stressFiles: env.STRESS_FILES, stressBase: env.STRESS_BASE, stressHead: env.STRESS_HEAD });+ if ('error' in result) {+ console.error(`::error::stress gate: the changed-file list could not be computed: ${result.error}. Why: the gate stresses every test file the diff touches, so a guessed list could skip one. Docs: ${STRESS_DOCS}`);+ return 1;+ }+ plan = result;+ } else {+ const day = Number(env.GBRAIN_RACE_HUNT_DAY ?? Math.floor((Date.now() - Date.UTC(new Date().getUTCFullYear(), 0, 1)) / 86_400_000));+ const extra = raceHuntHelperImporters(ROOT);+ plan = planRaceHunt(ROOT, { day, extra: extra.files, diagnostic: env.EVENT === 'workflow_dispatch' });+ if (extra.files.length) console.log(`race hunt: added ${extra.files.length} Postgres-arm importer(s) of ${extra.helpers.join(', ')} (changed on master since the last night)`);+ }+ const dir = join(env.RUNNER_TEMP ?? join(ROOT, '.context'), 'stress-plan');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'plan.json'), `${JSON.stringify(plan, null, 2)}\n`);+ writeOutputs(plan);+ console.log(`${mode}: ${plan.reason}; ${plan.shards.length} shard(s), estimate ${(plan.estimateMs / 60_000).toFixed(1)} runner-minutes of tests${plan.unrun.length ? `; ${plan.unrun.length} file(s) over budget` : ''}`);+ for (const s of plan.shards) console.log(` shard ${s.index}: ${(s.estimateMs / 60_000).toFixed(1)} min, ${s.items.map(i => `${i.file}[${i.first}..${i.first + i.count - 1}]`).join(' ')}`);+ return 0;+ }+ if (command === 'report') {+ const planPath = arg(argv, '--plan');+ const plan = planPath && existsSync(planPath) ? JSON.parse(readFileSync(planPath, 'utf8')) as Plan : undefined;+ const manifests = loadManifests(arg(argv, '--manifests') ?? '');+ const repo = process.env.GITHUB_REPOSITORY ?? '';+ const client = repo ? restClient(repo) : undefined;+ const since = process.env.GATE_SINCE || new Date().toISOString();+ const exemptions = mode === 'gate' && plan?.run && client ? await loadExemptions(client, since) : { exemptions: [], openIssues: [] };+ let timings: ReturnType<typeof shardTimings> | undefined;+ if (client && process.env.GITHUB_RUN_ID) {+ try {+ const jobs = await client.request<{ jobs: JobTiming[] }>('GET', `repos/{repo}/actions/runs/${process.env.GITHUB_RUN_ID}/attempts/${process.env.GITHUB_RUN_ATTEMPT ?? 1}/jobs?per_page=100`);+ timings = shardTimings(jobs.jobs);+ } catch { /* timings are informational */ }+ }+ const artifact = process.env.GITHUB_SERVER_URL && repo && process.env.GITHUB_RUN_ID ? `${process.env.GITHUB_SERVER_URL}/${repo}/actions/runs/${process.env.GITHUB_RUN_ID}` : '';+ const report = buildReport({ plan, planResult: process.env.PLAN_RESULT ?? 'success', shardsResult: process.env.SHARDS_RESULT ?? 'success', manifests, exemptions, timings, today: new Date().toISOString().slice(0, 10), artifact });+ console.log(report.summary);+ for (const e of report.errors) console.log(e.startsWith('file=') ? `::error ${e}` : `::error::${e}`);+ if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${report.summary}\n`);+ const result = arg(argv, '--json');+ if (result) { mkdirSync(dirname(result), { recursive: true }); writeFileSync(result, JSON.stringify({ exit: report.exit, errors: report.errors, timings }, null, 2)); }+ return report.exit;+ }+ console.error('usage: bun scripts/stress/gate.ts plan|report --mode gate|race-hunt [--plan <plan.json>] [--manifests <dir>] [--json <out>]');+ return 2;+}++if (import.meta.main) process.exit(await main(process.argv.slice(2)));diff --git a/scripts/stress/plan.ts b/scripts/stress/plan.tsnew file mode 100644index 0000000000..7b8c8bd3d9--- /dev/null+++ b/scripts/stress/plan.ts@@ -0,0 +1,283 @@+/**+ * Planning half of `bun run test:stress` (scripts/stress/run.ts) and of the+ * CI stress gate and race hunt (scripts/stress/gate.ts): which files a diff+ * touches, which execution profile each file needs, what a run costs, how+ * work splits into shards, and the replayable reproduce line.+ *+ * Pure except for the git helpers, which take an explicit cwd.+ * Docs: docs/TESTING.md#stress-gate and docs/TESTING.md#race-hunt.+ */+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { dirname, join, normalize, relative } from 'node:path';++export const STRESS_DOCS = 'docs/TESTING.md#stress-gate';+export const RACE_HUNT_DOCS = 'docs/TESTING.md#race-hunt';+export const TEST_PATH_RE = /^test\/[\w./-]+\.test\.ts$/;+export const DEFAULT_ITERATIONS = 10;+/** Helpers with more direct test importers than this are sampled (Eng fan-in rule). */+export const HELPER_FAN_IN_LIMIT = 25;+export const HELPER_SAMPLE = 10;+/** Estimated per-iteration overhead beyond a file's measured time: Bun startup plus database creation. */+export const ITERATION_OVERHEAD_MS = 3000;++export type ProfileName = 'unit' | 'serial' | 'slow' | 'postgres-arm' | 'e2e';++export interface Profile {+ name: ProfileName;+ /** `database` runs get a fresh database per iteration; `no-database` runs have DATABASE_URL unset. */+ env: 'database' | 'no-database';+ /** Backend arm recorded in receipts and failure identities. */+ arm: 'pglite' | 'pglite+postgres' | 'postgres';+ timeoutMs: number;+ /** Extra environment, mirroring the workflow's pull-request values. */+ vars: Record<string, string>;+ /** A prerequisite the runner builds once before the first iteration. */+ prereq?: 'old-binary';+}++export interface NotStressed { file: string; reason: string }++/**+ * Per-file execution specifics that differ from the suffix default. Values+ * mirror test.yml / persistence-validation.yml on pull requests; a test pins+ * the export-scale and old-binary rows to the workflow.+ */+export const SPECIAL_FILES: Record<string, Partial<Profile>> = {+ 'test/export-scale.slow.test.ts': { timeoutMs: 900_000, vars: { GBRAIN_TEST_EXPORT_SCALE_PAGES: '10001' } },+ 'test/entity-resolve-perf.slow.test.ts': { timeoutMs: 300_000 },+ 'test/entity-card-perf.slow.test.ts': { timeoutMs: 300_000 },+ 'test/eval-brainbench-e2e.slow.test.ts': { timeoutMs: 300_000 },+ 'test/persistence-skill-old-binary.slow.test.ts': { timeoutMs: 180_000, prereq: 'old-binary' },+ 'test/reconcile-crash.slow.test.ts': { timeoutMs: 180_000 },+ 'test/persistence-crash-robot.slow.test.ts': { timeoutMs: 300_000 },+};++/** Files no stress run can execute here, with the reason the summary prints. */+export function notStressedReason(file: string, liveKeyOnly: Set<string>): string | null {+ if (/\.live\.test\.ts$/.test(file) || file.startsWith('test/live/')) return 'paid-provider test (needs live model keys); not stressed';+ if (liveKeyOnly.has(file)) return 'needs provider keys no CI job supplies (scripts/e2e-live-key-only.txt); not stressed';+ return null;+}++/**+ * The execution profile for one file. A file with a DATABASE_URL-gated arm+ * runs both arms against a fresh database when Postgres is available, exactly+ * like persistence-validation's unit-postgres-arms job; otherwise it runs its+ * suffix lane with DATABASE_URL unset.+ */+export function profileFor(file: string, opts: { armed: boolean; postgres: boolean }): Profile {+ const special = SPECIAL_FILES[file] ?? {};+ let base: Profile;+ if (file.startsWith('test/e2e/')) base = { name: 'e2e', env: 'database', arm: 'postgres', timeoutMs: 60_000, vars: {} };+ else if (opts.armed && opts.postgres) base = { name: 'postgres-arm', env: 'database', arm: 'pglite+postgres', timeoutMs: 120_000, vars: {} };+ else if (file.endsWith('.serial.test.ts')) base = { name: 'serial', env: 'no-database', arm: 'pglite', timeoutMs: 120_000, vars: {} };+ else if (file.endsWith('.slow.test.ts')) base = { name: 'slow', env: 'no-database', arm: 'pglite', timeoutMs: 120_000, vars: {} };+ else base = { name: 'unit', env: 'no-database', arm: 'pglite', timeoutMs: 60_000, vars: {} };+ return { ...base, ...special, vars: { ...base.vars, ...(special.vars ?? {}) }, name: base.name, env: base.env, arm: base.arm };+}++/** Database URLs and tokens never reach a printed line. */+export function redact(text: string): string {+ return text+ .replace(/\b(postgres(?:ql)?:\/\/[^:/@\s]+):[^@\s]*@/gi, '$1:***@')+ .replace(/\b(PGPASSWORD|[A-Z_]*(?:TOKEN|API_KEY|SECRET))=\S+/g, '$1=***');+}++export interface ReproduceInput {+ file: string; iterations: number; firstIteration: number; seed: number;+ postgres: boolean; randomize?: boolean;+}++/** The exact local command that replays a stress context. Never carries a credential. */+export function reproduceLine(r: ReproduceInput): string {+ const parts = ['bun run test:stress', r.file, '--iterations', String(r.iterations)];+ if (r.firstIteration !== 1) parts.push('--first-iteration', String(r.firstIteration));+ parts.push('--seed', String(r.seed));+ if (r.postgres) parts.push('--postgres');+ if (r.randomize) parts.push('--randomize');+ return redact(parts.join(' '));+}++/** Deterministic base seed for a file at a commit, so a replay without --seed repeats the CI seeds. */+export function defaultSeed(sha: string, file: string): number {+ return parseInt(createHash('sha256').update(`${sha}\0${file}`).digest('hex').slice(0, 8), 16) % 1_000_000;+}++/** A ref from a dispatch input: a 40-hex SHA or a name `git check-ref-format --allow-onelevel` accepts. */+export function validRef(ref: string): boolean {+ if (/^[0-9a-f]{40}$/.test(ref)) return true;+ if (!/^[\w./-]+$/.test(ref) || ref.startsWith('-')) return false;+ return spawnSync('git', ['check-ref-format', '--allow-onelevel', ref], { encoding: 'utf8' }).status === 0;+}++/** Split a dispatch `stress_files` value; every entry must be a repo-relative test path. */+export function parseFileList(value: string): { files: string[]; invalid: string[] } {+ const entries = value.split(/[\s,]+/).filter(Boolean);+ return { files: [...new Set(entries.filter(f => TEST_PATH_RE.test(f) && !f.includes('..')))], invalid: entries.filter(f => !TEST_PATH_RE.test(f) || f.includes('..')) };+}++function git(cwd: string, args: string[]): { ok: boolean; out: string; err: string } {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });+ return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? '').trim() };+}++export interface ChangedFiles { tests: string[]; helpers: string[]; mergeBase: string; error?: string }++/**+ * Test files and test helpers added or modified versus the merge base of+ * `base` and `head` (renames at their new path, deletions skipped). Without+ * `head`, the working tree and untracked files count, for local runs.+ */+export function changedFiles(cwd: string, base: string, head?: string): ChangedFiles {+ const mb = git(cwd, ['merge-base', base, head ?? 'HEAD']);+ if (!mb.ok) {+ return { tests: [], helpers: [], mergeBase: '', error: `cannot compute the merge base of ${base} and ${head ?? 'HEAD'} (${mb.err || 'no common history'}). Next: git fetch --no-tags origin ${base.replace(/^origin\//, '')} and fetch enough history for both commits (actions/checkout fetch-depth: 0), then re-run` };+ }+ const mergeBase = mb.out.trim();+ const diff = git(cwd, ['diff', '--name-status', '-M', '--no-color', mergeBase, ...(head ? [head] : [])]);+ if (!diff.ok) return { tests: [], helpers: [], mergeBase, error: `git diff against ${mergeBase} failed (${diff.err}). Next: fetch both commits and re-run` };+ const paths: string[] = [];+ for (const line of diff.out.split('\n')) {+ const cols = line.split('\t');+ const status = cols[0] ?? '';+ if (!status || status.startsWith('D')) continue;+ paths.push(status.startsWith('R') || status.startsWith('C') ? cols[2]! : cols[1]!);+ }+ if (!head) {+ const untracked = git(cwd, ['ls-files', '--others', '--exclude-standard']);+ if (untracked.ok) paths.push(...untracked.out.split('\n').filter(Boolean));+ }+ const unique = [...new Set(paths)].sort();+ return {+ tests: unique.filter(p => TEST_PATH_RE.test(p) && !p.startsWith('test/fixtures/')),+ helpers: unique.filter(p => p.startsWith('test/helpers/') && /\.(ts|js|mjs)$/.test(p) && !p.endsWith('.test.ts')),+ mergeBase,+ };+}++/** Every `*.test.ts` under test/ (fixtures excluded), repo-relative and sorted. */+export function allTestFiles(root: string): string[] {+ const out: string[] = [];+ const walk = (dir: string) => {+ if (!existsSync(dir)) return;+ for (const entry of readdirSync(dir).sort()) {+ const full = join(dir, entry);+ const rel = relative(root, full).replace(/\\/g, '/');+ if (rel === 'test/fixtures' || entry === 'node_modules') continue;+ if (statSync(full).isDirectory()) walk(full);+ else if (TEST_PATH_RE.test(rel)) out.push(rel);+ }+ };+ walk(join(root, 'test'));+ return out;+}++const IMPORT_RE = /(?:\bfrom\s+|\bimport\s*\(\s*|\brequire\s*\(\s*|^\s*import\s+)['"](\.{1,2}\/[^'"]+)['"]/gm;++/** Test files that import `helper` directly (relative specifiers, with or without the extension). */+export function directImporters(root: string, helper: string, tests: string[]): string[] {+ const target = helper.replace(/\.(ts|js|mjs)$/, '');+ return tests.filter(test => {+ const text = readFileSync(join(root, test), 'utf8');+ for (const [, spec] of text.matchAll(IMPORT_RE)) {+ const resolved = normalize(join(dirname(test), spec!)).replace(/\\/g, '/').replace(/\.(ts|js|mjs)$/, '').replace(/\/index$/, '');+ if (resolved === target) return true;+ }+ return false;+ });+}++/** Seeded Fisher-Yates over a sorted copy: the same head SHA always samples the same importers. */+export function seededSample<T>(items: T[], count: number, seed: string): T[] {+ let state = parseInt(createHash('sha256').update(seed).digest('hex').slice(0, 8), 16) || 1;+ const next = () => { state = (state + 0x6d2b79f5) | 0; let t = Math.imul(state ^ (state >>> 15), 1 | state); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };+ const copy = [...items];+ for (let i = copy.length - 1; i > 0; i--) { const j = Math.floor(next() * (i + 1)); [copy[i], copy[j]] = [copy[j]!, copy[i]!]; }+ return copy.slice(0, count);+}++export interface HelperExpansion {+ helper: string;+ importers: number;+ /** Files the gate stresses because of this helper. */+ stressed: string[];+ /** Importers left out by the fan-in rule, listed in the summary. */+ listedOnly: string[];+ mode: 'all-importers' | 'sampled';+}++/**+ * Eng fan-in rule: a changed helper with at most 25 direct test importers+ * stresses all of them; above 25, its own tests plus a deterministic sample of+ * 10 importers seeded by the head SHA, and the rest are listed. Changed test+ * files are added by the caller and are never sampled.+ */+export function expandHelper(root: string, helper: string, tests: string[], headSha: string): HelperExpansion {+ const importers = directImporters(root, helper, tests);+ if (importers.length <= HELPER_FAN_IN_LIMIT) return { helper, importers: importers.length, stressed: importers, listedOnly: [], mode: 'all-importers' };+ const stem = helper.split('/').pop()!.replace(/\.(ts|js|mjs)$/, '');+ const own = tests.filter(t => t.split('/').pop()!.replace(/(\.(serial|slow|unit))?\.test\.ts$/, '') === stem);+ const sample = seededSample(importers.filter(f => !own.includes(f)), HELPER_SAMPLE, `${headSha}\0${helper}`);+ const stressed = [...new Set([...own, ...sample])].sort();+ return { helper, importers: importers.length, stressed, listedOnly: importers.filter(f => !stressed.includes(f)), mode: 'sampled' };+}++export interface WorkItem { file: string; first: number; count: number; estimateMs: number }+export interface Shard { index: number; items: WorkItem[]; estimateMs: number }++/**+ * Split files into work items (a file's iterations are chunked when ten of+ * them exceed the budget) and pack them into the fewest shards whose+ * estimates stay within `budgetMs`. No shard-count cap: runners queue.+ */+export function planShards(files: Array<{ file: string; perIterationMs: number; setupMs?: number }>, iterations: number, budgetMs: number, firstIteration = 1): Shard[] {+ const items: WorkItem[] = [];+ for (const f of files) {+ const per = f.perIterationMs + ITERATION_OVERHEAD_MS;+ const chunk = Math.max(1, Math.min(iterations, Math.floor((budgetMs - (f.setupMs ?? 0)) / per)));+ for (let first = 0; first < iterations; first += chunk) {+ const count = Math.min(chunk, iterations - first);+ items.push({ file: f.file, first: firstIteration + first, count, estimateMs: (f.setupMs ?? 0) + per * count });+ }+ }+ if (!items.length) return [];+ items.sort((a, b) => b.estimateMs - a.estimateMs || (a.file < b.file ? -1 : a.file > b.file ? 1 : a.first - b.first));+ const total = items.reduce((s, i) => s + i.estimateMs, 0);+ for (let n = Math.max(1, Math.ceil(total / budgetMs)); ; n++) {+ const shards: Shard[] = Array.from({ length: n }, (_, i) => ({ index: i + 1, items: [], estimateMs: 0 }));+ for (const item of items) {+ const target = shards.reduce((min, s) => (s.estimateMs < min.estimateMs ? s : min));+ target.items.push(item);+ target.estimateMs += item.estimateMs;+ }+ if (shards.every(s => s.estimateMs <= budgetMs) || n >= items.length) return shards.filter(s => s.items.length);+ }+}++export interface Weights { unit: Map<string, number>; serialSeconds: Map<string, number>; e2e: Map<string, number>; arms: Map<string, number> }++const loadMap = (path: string): Map<string, number> => (existsSync(path) ? new Map(Object.entries(JSON.parse(readFileSync(path, 'utf8')) as Record<string, number>)) : new Map());++export function loadWeights(root: string): Weights {+ return {+ unit: loadMap(join(root, 'scripts/test-weights.json')),+ serialSeconds: loadMap(join(root, 'scripts/serial-weights.json')),+ e2e: loadMap(join(root, 'scripts/e2e-weights.json')),+ arms: loadMap(join(root, 'scripts/postgres-arm-weights.json')),+ };+}++const p75 = (values: number[]) => { const s = [...values].sort((a, b) => a - b); return s.length ? s[Math.min(s.length - 1, Math.ceil(0.75 * s.length) - 1)]! : 30_000; };++/** Measured milliseconds for one iteration of `file` in `profile`, or the lane's p75 for an unmeasured file. */+export function iterationEstimateMs(file: string, profile: ProfileName, w: Weights): number {+ switch (profile) {+ case 'postgres-arm': return w.arms.get(file) ?? p75([...w.arms.values()]);+ case 'e2e': return w.e2e.get(file) ?? p75([...w.e2e.values()]);+ case 'serial': return (w.serialSeconds.get(file) ?? p75([...w.serialSeconds.values()])) * 1000;+ case 'slow': return w.unit.get(file) ?? 120_000;+ default: return w.unit.get(file) ?? p75([...w.unit.values()]);+ }+}diff --git a/scripts/stress/run.ts b/scripts/stress/run.tsnew file mode 100644index 0000000000..634f326819--- /dev/null+++ b/scripts/stress/run.ts@@ -0,0 +1,542 @@+#!/usr/bin/env bun+/**+ * bun run test:stress (scripts/stress/run.ts) — run test files repeatedly to prove they are+ * deterministic. The one runner behind the PR stress gate, the nightly race+ * hunt and local runs (scripts/stress/README.md, docs/TESTING.md#stress-gate).+ *+ * bun run test:stress [files…] [--iterations N] [--base <ref>] [--head <ref>]+ * [--postgres] [--seed N] [--first-iteration N] [--randomize]+ * [--work <json>] [--out <dir>] [--dry-run]+ *+ * Files default to the test files changed versus the merge base with+ * origin/master (plus direct importers of changed test/helpers/ files, by the+ * fan-in rule). Each file runs in its own execution profile (unit, serial,+ * slow with the workflow's pull-request values, both arms of a+ * DATABASE_URL-gated suite, or E2E through scripts/run-e2e.sh). With+ * --postgres every database iteration gets a fresh database cloned with+ * CREATE DATABASE … TEMPLATE on the server named by GBRAIN_STRESS_ADMIN_URL or+ * a test-shaped DATABASE_URL, or on a pgvector container started from+ * docker-compose.ci.yml (the ci:local service); databases and containers it+ * creates are tracked under .context/test-stress/owned/ and removed on exit,+ * on Ctrl-C and by the next run after a crash.+ *+ * Every iteration writes an executed-test receipt (JUnit) and must execute the+ * same tests as the first; zero executed tests or an unexpected skip fails the+ * run. Output: one line per iteration, a summary with the reproduce command+ * for each failure, and a manifest (<out>/stress-manifest.json).+ * Exit: 0 every file passed, 1 a failure, 2 usage or setup error, 130/143 cancelled.+ */+import { spawn, spawnSync } from 'node:child_process';+import { createServer } from 'node:net';+import { randomBytes } from 'node:crypto';+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import postgres from '#postgres';+import { parseJUnit, type TestCase } from '../ci-executed-counts.ts';+import { postgresArm } from '../check-postgres-lane-coverage.ts';+import {+ DEFAULT_ITERATIONS, STRESS_DOCS, TEST_PATH_RE, allTestFiles, changedFiles, defaultSeed, expandHelper,+ notStressedReason, parseFileList, profileFor, redact, reproduceLine, validRef, type HelperExpansion, type Profile,+} from './plan.ts';++/** GBRAIN_STRESS_ROOT is a test seam: a fixture tree whose test files the runner executes. */+const ROOT = process.env.GBRAIN_STRESS_ROOT ? resolve(process.env.GBRAIN_STRESS_ROOT) : resolve(import.meta.dir, '..', '..');+const ITERATION_CAP_MS = Number(process.env.GBRAIN_STRESS_ITERATION_TIMEOUT_MS ?? 15 * 60_000);++export interface Args {+ files: string[]; iterations: number; firstIteration: number; base: string; head?: string;+ postgres: boolean; seed?: number; randomize: boolean; out: string; dryRun: boolean;+ work?: Array<{ file: string; first: number; count: number }>;+}++export function parseArgs(argv: string[]): Args | string {+ const a: Args = { files: [], iterations: DEFAULT_ITERATIONS, firstIteration: 1, base: 'origin/master', postgres: false, randomize: false, out: '.context/test-stress', dryRun: false };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i]!;+ const value = () => { const v = argv[++i]; if (v === undefined) throw new Error(`${arg} needs a value`); return v; };+ try {+ switch (arg) {+ case '--iterations': a.iterations = Number(value()); break;+ case '--first-iteration': a.firstIteration = Number(value()); break;+ case '--base': a.base = value(); break;+ case '--head': a.head = value(); break;+ case '--seed': a.seed = Number(value()); break;+ case '--out': a.out = value(); break;+ case '--work': a.work = JSON.parse(value()); break;+ case '--postgres': a.postgres = true; break;+ case '--randomize': a.randomize = true; break;+ case '--dry-run': a.dryRun = true; break;+ case '-h': case '--help': return 'help';+ default:+ if (arg.startsWith('-')) return `unknown flag ${arg}`;+ a.files.push(arg.replace(/^\.\//, ''));+ }+ } catch (e) { return (e as Error).message; }+ }+ if (!Number.isInteger(a.iterations) || a.iterations < 1) return '--iterations must be a positive integer';+ if (!Number.isInteger(a.firstIteration) || a.firstIteration < 1) return '--first-iteration must be a positive integer';+ if (a.seed !== undefined && (!Number.isInteger(a.seed) || a.seed < 0)) return '--seed must be a non-negative integer';+ if (!validRef(a.base) || (a.head && !validRef(a.head))) return '--base/--head must be a 40-hex SHA or a valid ref name';+ const bad = parseFileList(a.files.join(' ')).invalid;+ if (bad.length) return `not a repo-relative test file: ${bad.join(', ')} (expected test/…/*.test.ts)`;+ if (a.work) {+ if (!Array.isArray(a.work) || a.work.some(w => !w || typeof w.file !== 'string' || !TEST_PATH_RE.test(w.file) || w.file.includes('..') || !Number.isInteger(w.first) || w.first < 1 || !Number.isInteger(w.count) || w.count < 1)) {+ return '--work must be a JSON array of {"file":"test/…/*.test.ts","first":N,"count":N}';+ }+ }+ return a;+}++// ── Postgres: an admin connection, a template and owned databases ─────────────++interface Owned { pid: number; server: string; databases: string[]; compose?: string }+const OWNED_DIR = join(ROOT, '.context', 'test-stress', 'owned');++class PgServer {+ readonly tag = `${process.pid}_${randomBytes(2).toString('hex')}`;+ private owned: Owned;+ private template = '';+ constructor(readonly adminUrl: string, readonly origin: string, compose?: string) {+ const u = new URL(adminUrl);+ this.owned = { pid: process.pid, server: `${u.hostname}:${u.port || '5432'}`, databases: [], compose };+ this.save();+ }+ private save() { mkdirSync(OWNED_DIR, { recursive: true }); writeFileSync(join(OWNED_DIR, `${this.tag}.json`), JSON.stringify(this.owned)); }+ urlFor(db: string): string { const u = new URL(this.adminUrl); u.pathname = `/${db}`; return u.toString(); }+ private async sql<T>(fn: (sql: ReturnType<typeof postgres>) => Promise<T>): Promise<T> {+ const sql = postgres(this.adminUrl, { max: 1, onnotice: () => {}, connect_timeout: 10 });+ try { return await fn(sql); } finally { await sql.end({ timeout: 5 }); }+ }+ async create(index: number): Promise<string> {+ if (!this.template) {+ this.template = `gbrain_stress_${this.tag}_tmpl_test`;+ this.owned.databases.push(this.template); this.save();+ await this.sql(sql => sql.unsafe(`CREATE DATABASE "${this.template}"`));+ }+ const name = `gbrain_stress_${this.tag}_i${index}_test`;+ this.owned.databases.push(name); this.save();+ await this.sql(sql => sql.unsafe(`CREATE DATABASE "${name}" TEMPLATE "${this.template}"`));+ return name;+ }+ /**+ * Transactions the iteration's own database served. A fresh clone starts at+ * zero, so a positive count proves the PostgreSQL arm connected. Backends+ * flush their counters when they exit, just after the test process closes+ * them, so this waits up to 10 s for a nonzero count before reporting zero.+ */+ async activity(name: string): Promise<number> {+ return this.sql(async sql => {+ for (let waited = 0; ; waited += 250) {+ const [row] = await sql`SELECT (xact_commit + xact_rollback)::int AS n FROM pg_stat_database WHERE datname = ${name}`;+ const n = Number(row?.n ?? 0);+ if (n > 0 || waited >= 10_000) return n;+ await Bun.sleep(250);+ }+ });+ }+ async drop(name: string): Promise<void> {+ await this.sql(sql => sql.unsafe(`DROP DATABASE IF EXISTS "${name}" WITH (FORCE)`));+ this.owned.databases = this.owned.databases.filter(d => d !== name); this.save();+ }+ async close(): Promise<void> {+ for (const db of [...this.owned.databases]) await this.drop(db).catch(() => {});+ if (this.owned.compose) composeDown(this.owned.compose);+ rmSync(join(OWNED_DIR, `${this.tag}.json`), { force: true });+ }+}++function composeDown(project: string) {+ spawnSync('docker', ['compose', '-p', project, '-f', join(ROOT, 'docker-compose.ci.yml'), 'down', '-v', '--remove-orphans'], { stdio: 'ignore' });+}++const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };++/** Remove databases and containers a crashed earlier run left behind (its pid is gone). */+async function sweepOwned(adminUrl?: string): Promise<string[]> {+ if (!existsSync(OWNED_DIR)) return [];+ const swept: string[] = [];+ for (const entry of readdirSync(OWNED_DIR)) {+ const path = join(OWNED_DIR, entry);+ let owned: Owned;+ try { owned = JSON.parse(readFileSync(path, 'utf8')); } catch { rmSync(path, { force: true }); continue; }+ if (alive(owned.pid)) continue;+ if (owned.compose) { composeDown(owned.compose); swept.push(`container project ${owned.compose}`); rmSync(path, { force: true }); continue; }+ if (!adminUrl) continue;+ const u = new URL(adminUrl);+ if (`${u.hostname}:${u.port || '5432'}` !== owned.server) continue;+ const sql = postgres(adminUrl, { max: 1, onnotice: () => {}, connect_timeout: 10 });+ try { for (const db of owned.databases) { await sql.unsafe(`DROP DATABASE IF EXISTS "${db}" WITH (FORCE)`); swept.push(db); } } finally { await sql.end({ timeout: 5 }); }+ rmSync(path, { force: true });+ }+ return swept;+}++const testShaped = (url: string) => { try { return /(^|[_-])test([_-]|$)/i.test(decodeURIComponent(new URL(url).pathname.slice(1))); } catch { return false; } };++async function freePort(): Promise<number> {+ return new Promise((res, rej) => { const s = createServer(); s.once('error', rej); s.listen(0, '127.0.0.1', () => { const port = (s.address() as { port: number }).port; s.close(() => res(port)); }); });+}++async function provisionPostgres(): Promise<PgServer> {+ const explicit = process.env.GBRAIN_STRESS_ADMIN_URL || process.env.DATABASE_URL;+ if (explicit) {+ if (!testShaped(explicit)) {+ throw new Error(`refusing ${redact(explicit)}: the admin database name must carry a "test" segment (e.g. gbrain_test). Why: stress databases are created and dropped on that server. Fix: point GBRAIN_STRESS_ADMIN_URL at a disposable test server, or unset DATABASE_URL to let --postgres start a container`);+ }+ await sweepOwned(explicit);+ return new PgServer(explicit, process.env.GBRAIN_STRESS_ADMIN_URL ? 'GBRAIN_STRESS_ADMIN_URL' : 'DATABASE_URL');+ }+ if (spawnSync('docker', ['info'], { stdio: 'ignore' }).status !== 0) {+ throw new Error('--postgres needs a database server: Docker is not available and neither GBRAIN_STRESS_ADMIN_URL nor DATABASE_URL is set. Fix: start Docker (the run uses docker-compose.ci.yml postgres-1), or export GBRAIN_STRESS_ADMIN_URL=postgres://postgres:postgres@localhost:5434/gbrain_test');+ }+ await sweepOwned();+ const project = `gbrain-stress-${process.pid}`;+ const port = await freePort();+ const env = { ...process.env, GBRAIN_CI_PG_PORT: String(port) };+ const compose = ['compose', '-p', project, '-f', join(ROOT, 'docker-compose.ci.yml')];+ const server = new PgServer(`postgres://postgres:[email protected]:${port}/gbrain_test`, `docker-compose.ci.yml postgres-1 (project ${project})`, project);+ const up = spawnSync('docker', [...compose, 'up', '-d', 'postgres-1'], { env, encoding: 'utf8' });+ if (up.status !== 0) { await server.close(); throw new Error(`docker compose up postgres-1 failed: ${up.stderr.trim().split('\n').pop()}. Fix: check Docker, or set GBRAIN_STRESS_ADMIN_URL`); }+ for (let i = 0; i < 60; i++) {+ if (spawnSync('docker', [...compose, 'exec', '-T', 'postgres-1', 'pg_isready', '-U', 'postgres', '-d', 'gbrain_test'], { env, stdio: 'ignore' }).status === 0) return server;+ await Bun.sleep(1000);+ }+ await server.close();+ throw new Error('the stress Postgres container did not become ready within 60 s. Fix: run `docker compose -f docker-compose.ci.yml logs postgres-1`, or set GBRAIN_STRESS_ADMIN_URL');+}++// ── One iteration ─────────────────────────────────────────────────────────────++export interface Failure { test: string; signature: string; message: string }+export interface IterationResult {+ index: number; seed: number; exit: number; durationMs: number; executed: number; skipped: number;+ failures: Failure[]; missing: string[]; timedOut: boolean; receipt: string;+ /** Transactions the iteration database served; -1 without a database. */+ databaseActivity: number;+}++/** Stable failure signature: the first lines of the message with numbers, temp paths and UUIDs masked. */+export function failureSignature(message: string): string {+ return message.replace(/\x1b\[[0-9;]*m/g, '').split('\n').map(l => l.trim()).filter(Boolean).slice(0, 4).join(' ')+ .replace(/\/(?:private\/)?(?:tmp|var\/folders)\/\S+/g, '<tmp>')+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, '<uuid>')+ .replace(/\b\d+(?:\.\d+)?\b/g, 'N').replace(/\s+/g, ' ').slice(0, 200);+}++const ENTITY: Record<string, string> = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" };+const decode = (t: string) => t.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (w, r: string) => r[0] === '#' ? String.fromCodePoint(r[1] === 'x' ? parseInt(r.slice(2), 16) : Number(r.slice(1))) : ENTITY[r] ?? w);++/** Executed cases plus the failure message of each failing case, in report order. */+export function readReport(xml: string): { cases: TestCase[]; messages: string[] } {+ const cases = parseJUnit(xml);+ const messages: string[] = [];+ for (const [, body] of xml.matchAll(/<testcase\b[^>]*?(?:\/>|>([\s\S]*?)<\/testcase>)/g)) {+ const m = /<(?:failure|error)\b[^>]*?message="([^"]*)"/.exec(body ?? '');+ if (m || /<(?:failure|error)\b/.test(body ?? '')) messages.push(decode(m?.[1] ?? 'failure without a message'));+ }+ return { cases, messages };+}++const slug = (file: string) => file.replace(/^test\//, '').replace(/[^\w.-]+/g, '_');++interface RunContext { args: Args; sha: string; bun: string; pg?: PgServer; snapshot?: string; oldBinary?: string; out: string; child?: ReturnType<typeof spawn> }++function childEnv(ctx: RunContext, profile: Profile, seed: number): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;+ for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_TEST_RECEIPT_DIR', 'GBRAIN_TEST_RECEIPT_LANE', 'GBRAIN_STRESS_ADMIN_URL', 'GBRAIN_TEST_ALLOW_DATABASE_URL', 'GBRAIN_STRESS_ROOT']) delete env[k];+ if (ctx.snapshot) env.GBRAIN_PGLITE_SNAPSHOT = ctx.snapshot;+ if (ctx.oldBinary) env.GBRAIN_TEST_OLD_BINARY = ctx.oldBinary;+ env.GBRAIN_TEST_SEED = String(seed);+ return { ...env, ...profile.vars };+}++async function runIteration(ctx: RunContext, file: string, profile: Profile, index: number, seed: number, withDatabase: boolean): Promise<IterationResult> {+ const dir = join(ctx.out, 'receipts', `${slug(file)}--i${index}`);+ rmSync(dir, { recursive: true, force: true });+ mkdirSync(dir, { recursive: true });+ const env = childEnv(ctx, profile, seed);+ let db = '';+ if (withDatabase) {+ db = await ctx.pg!.create(index);+ env.DATABASE_URL = ctx.pg!.urlFor(db);+ env.GBRAIN_TEST_ALLOW_DATABASE_URL = '1';+ }+ const junit = join(dir, 'stress.junit.xml');+ let cmd: string[];+ if (profile.name === 'e2e') {+ env.GBRAIN_TEST_RECEIPT_DIR = dir;+ env.GBRAIN_TEST_RECEIPT_LANE = 'stress-e2e';+ cmd = ['bash', 'scripts/run-e2e.sh', file];+ } else {+ cmd = ['bun', ...(withDatabase ? ['--no-env-file'] : []), 'test', `--timeout=${profile.timeoutMs}`,+ ...(profile.name === 'serial' ? ['--max-concurrency=1'] : []),+ ...(ctx.args.randomize ? ['--randomize', `--seed=${seed}`] : []),+ '--reporter=junit', `--reporter-outfile=${junit}`, file];+ }+ const started = Date.now();+ const log = join(dir, 'output.log');+ let timedOut = false;+ const exit = await new Promise<number>(res => {+ const child = spawn(cmd[0]!, cmd.slice(1), { cwd: ROOT, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ ctx.child = child;+ const chunks: Buffer[] = [];+ child.stdout!.on('data', c => chunks.push(c));+ child.stderr!.on('data', c => chunks.push(c));+ const timer = setTimeout(() => { timedOut = true; killTree(child.pid!); }, ITERATION_CAP_MS);+ child.on('close', code => { clearTimeout(timer); ctx.child = undefined; writeFileSync(log, redact(Buffer.concat(chunks).toString('utf8'))); res(code ?? 1); });+ });+ const durationMs = Date.now() - started;+ const databaseActivity = db ? await ctx.pg!.activity(db).catch(() => 0) : -1;+ if (db) await ctx.pg!.drop(db).catch(() => {});+ if (!withDatabase || profile.name !== 'e2e') {+ const receipt = [`version=1`, `lane=stress`, `kind=primary`, `tag=${slug(file)}-i${index}`, `shard=`, `of=`, `arm=${withDatabase ? profile.arm : 'pglite'}`,+ `sha=${ctx.sha}`, `root=${ROOT}`, `run_id=${process.env.GITHUB_RUN_ID ?? ''}`, `run_attempt=${process.env.GITHUB_RUN_ATTEMPT ?? ''}`,+ `job=${process.env.GITHUB_JOB ?? ''}`, `started=${Math.floor(started / 1000)}`, `exit=${exit}`].join('\n');+ if (profile.name !== 'e2e') {+ writeFileSync(join(dir, `stress--${slug(file)}-i${index}--primary.receipt`), `${receipt}\n`);+ writeFileSync(join(dir, `stress--${slug(file)}-i${index}--primary.files`), `${file}\n`);+ }+ }+ const report = profile.name === 'e2e' ? readdirSync(dir).find(f => f.endsWith('.junit.xml')) : existsSync(junit) ? 'stress.junit.xml' : undefined;+ let cases: TestCase[] = [];+ let messages: string[] = [];+ let reportError = '';+ if (report) {+ try { ({ cases, messages } = readReport(readFileSync(join(dir, report), 'utf8'))); } catch (e) { reportError = (e as Error).message; }+ } else reportError = 'no JUnit report was written';+ const failed = cases.filter(c => c.status === 'fail');+ const failures: Failure[] = failed.map((c, i) => ({ test: c.test, message: redact(messages[i] ?? ''), signature: failureSignature(messages[i] ?? '') }));+ if (exit !== 0 && !failures.length) {+ const tail = readFileSync(log, 'utf8').split('\n').filter(l => l.trim()).slice(-40);+ const first = tail.find(l => /error|Error|FAIL|timed out|panic/.test(l)) ?? tail[tail.length - 1] ?? `exit ${exit}`;+ const why = timedOut ? `iteration exceeded the ${Math.round(ITERATION_CAP_MS / 60000)}-minute iteration cap and was killed` : reportError ? `${first} (${reportError})` : first;+ failures.push({ test: '(file-level)', message: redact(why), signature: failureSignature(why) });+ }+ return {+ index, seed, exit, durationMs, timedOut, receipt: relativeToRoot(dir), databaseActivity,+ executed: cases.filter(c => c.status === 'pass' || c.status === 'fail').length,+ skipped: cases.filter(c => c.status === 'skip' || c.status === 'todo').length,+ failures, missing: [],+ };+}++const relativeToRoot = (p: string) => p.startsWith(ROOT) ? p.slice(ROOT.length + 1) : p;+function killTree(pid: number) { try { process.kill(-pid, 'SIGTERM'); } catch { /* gone */ } setTimeout(() => { try { process.kill(-pid, 'SIGKILL'); } catch { /* gone */ } }, 5000).unref(); }++function executedIdentities(dir: string): string[] {+ const full = join(ROOT, dir);+ const report = readdirSync(full).find(f => f.endsWith('.junit.xml'));+ if (!report) return [];+ try { return parseJUnit(readFileSync(join(full, report), 'utf8')).filter(c => c.status === 'pass' || c.status === 'fail').map(c => c.test); } catch { return []; }+}++// ── One file ──────────────────────────────────────────────────────────────────++export interface FileResult {+ file: string; profile: Profile['name']; env: Profile['env']; arm: string; status: 'pass' | 'fail' | 'not-stressed';+ reason?: string; seedBase: number; firstIteration: number; iterations: IterationResult[]; reproduce: string;+}++function skipReason(file: string): string | null {+ const text = readFileSync(join(ROOT, file), 'utf8');+ if (/process\.platform/.test(text)) return `every test skipped on ${process.platform}: platform-only tests, run by their owning native lane; not stressed`;+ const keys = [...new Set([...text.matchAll(/process\.env\.([A-Z0-9_]*(?:API_KEY|TOKEN|SECRET))/g)].map(m => m[1]!))];+ if (keys.length) return `every test skipped without ${keys.join(', ')} (secret not available here); not stressed`;+ return null;+}++async function stressFile(ctx: RunContext, file: string, profile: Profile, first: number, count: number): Promise<FileResult> {+ const { args } = ctx;+ const seedBase = args.seed ?? defaultSeed(ctx.sha, file);+ const database = profile.env === 'database';+ const result: FileResult = {+ file, profile: profile.name, env: profile.env, arm: profile.arm, status: 'pass', seedBase, firstIteration: first, iterations: [],+ reproduce: reproduceLine({ file, iterations: count, firstIteration: first, seed: seedBase, postgres: database, randomize: args.randomize }),+ };+ let expected: string[] | undefined;+ for (let index = first; index < first + count; index++) {+ const seed = seedBase + index - 1;+ const it = await runIteration(ctx, file, profile, index, seed, database);+ if (!it.failures.length && database && it.databaseActivity === 0) {+ it.failures.push({ test: '(file-level)', message: 'the PostgreSQL arm never connected: its fresh database served no transaction', signature: 'postgres arm executed no tests' });+ }+ if (!it.failures.length) {+ const ids = executedIdentities(it.receipt);+ if (index === first) {+ if (it.executed === 0) {+ const reason = skipReason(file);+ if (reason) { result.status = 'not-stressed'; result.reason = reason; result.iterations.push(it); log(` - ${file} ${reason}`); return result; }+ it.failures.push({ test: '(file-level)', message: 'zero tests executed', signature: 'zero tests executed' });+ }+ expected = ids;+ } else if (expected) {+ const seen = new Set(ids);+ it.missing = expected.filter(t => !seen.has(t));+ if (it.missing.length) it.failures.push({ test: '(file-level)', message: `unexpected skip: ${it.missing.length} test(s) that ran in iteration ${first} did not run: ${it.missing.slice(0, 3).join('; ')}`, signature: 'unexpected skip' });+ }+ }+ result.iterations.push(it);+ const mark = it.failures.length ? '✗' : '✓';+ log(` ${mark} ${file} iteration ${index} (seed ${seed}) ${(it.durationMs / 1000).toFixed(1)}s, ${it.executed} executed${it.failures.length ? `: ${it.failures[0]!.test}: ${it.failures[0]!.message.split('\n')[0]}` : ''}`);+ if (it.failures.length) result.status = 'fail';+ }+ return result;+}++const log = (line: string) => console.log(line);++// ── Main ──────────────────────────────────────────────────────────────────────++const USAGE = `usage: bun run test:stress [files…] [--iterations N] [--base <ref>] [--head <ref>] [--postgres]+ [--seed N] [--first-iteration N] [--randomize] [--work <json>] [--out <dir>] [--dry-run]+Docs: ${STRESS_DOCS}`;++export interface Selection { files: string[]; helpers: HelperExpansion[]; mergeBase?: string; error?: string }++/** The files a run stresses: explicit files, or changed tests plus helper importers versus the merge base. */+export function selectFiles(args: Args, sha: string): Selection {+ if (args.work) return { files: [...new Set(args.work.map(w => w.file))], helpers: [] };+ if (args.files.length) return { files: args.files, helpers: [] };+ const changed = changedFiles(ROOT, args.base, args.head);+ if (changed.error) return { files: [], helpers: [], error: changed.error };+ const tests = changed.helpers.length ? allTestFiles(ROOT) : [];+ const helpers = changed.helpers.map(h => expandHelper(ROOT, h, tests, sha));+ return { files: [...new Set([...changed.tests, ...helpers.flatMap(h => h.stressed)])].sort(), helpers, mergeBase: changed.mergeBase };+}++async function main(argv: string[]): Promise<number> {+ const parsed = parseArgs(argv);+ if (parsed === 'help') { console.log(USAGE); return 0; }+ if (typeof parsed === 'string') { console.error(`test:stress: ${parsed}\n${USAGE}`); return 2; }+ const args = parsed;+ const sha = process.env.GITHUB_SHA || spawnSync('git', ['rev-parse', 'HEAD'], { cwd: ROOT, encoding: 'utf8' }).stdout.trim() || 'unknown';+ const bun = Bun.version;+ const setupStarted = Date.now();+ const selection = selectFiles(args, sha);+ if (selection.error) {+ console.error(`test:stress: the changed-file list could not be computed: ${selection.error}\n Why: the stress set is every test file the diff touches; a guessed list could skip one.\n Docs: ${STRESS_DOCS}`);+ return 2;+ }+ const livePath = join(ROOT, 'scripts/e2e-live-key-only.txt');+ const liveKeyOnly = new Set(existsSync(livePath) ? readFileSync(livePath, 'utf8').split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#')) : []);+ const missing = selection.files.filter(f => !existsSync(join(ROOT, f)));+ if (missing.length) { console.error(`test:stress: no such file: ${missing.join(', ')}. Fix: pass repo-relative paths of existing test files. Docs: ${STRESS_DOCS}`); return 2; }+ const plan = selection.files.map(file => {+ const reason = notStressedReason(file, liveKeyOnly);+ const armed = !file.startsWith('test/e2e/') && postgresArm(join(ROOT, file)) !== null;+ return { file, reason, armed, profile: profileFor(file, { armed, postgres: args.postgres }) };+ });+ const needsDb = plan.filter(p => !p.reason && p.profile.env === 'database');+ for (const p of plan) {+ if (!p.reason && p.profile.name === 'e2e' && !args.postgres) p.reason = 'E2E file needs Postgres; re-run with --postgres; not stressed';+ }+ const unarmedNotice = plan.filter(p => p.armed && !args.postgres && !p.reason);+ log(`test:stress: ${plan.length} file(s) × ${args.work ? 'planned' : args.iterations} iteration(s) at ${sha.slice(0, 12)} on Bun ${bun}${selection.mergeBase ? `, changed versus ${selection.mergeBase.slice(0, 12)}` : ''}`);+ for (const h of selection.helpers) log(` helper ${h.helper}: ${h.importers} direct importer(s), ${h.mode === 'sampled' ? `stressing its own tests and a sample of ${h.stressed.length}; ${h.listedOnly.length} listed only` : 'stressing all'}`);+ for (const p of plan) log(` ${p.reason ? 'skip' : p.profile.name.padEnd(12)} ${p.file}${p.reason ? ` (${p.reason})` : ''}`);+ for (const p of unarmedNotice) log(` note: ${p.file} has a DATABASE_URL-gated PostgreSQL arm; add --postgres to stress it too`);+ if (args.dryRun) return 0;+ if (!plan.length) { log(`test:stress: no changed test files; nothing to stress. Pass files explicitly or --base <ref>. Docs: ${STRESS_DOCS}`); return 0; }++ const out = resolve(ROOT, args.out);+ mkdirSync(out, { recursive: true });+ const ctx: RunContext = { args, sha, bun, out };+ let cancelled = 0;+ const onSignal = (code: number) => async () => {+ if (cancelled) return;+ cancelled = code;+ log(`\ntest:stress: interrupted; stopping the running file and removing owned databases and containers`);+ if (ctx.child?.pid) killTree(ctx.child.pid);+ await ctx.pg?.close().catch(() => {});+ process.exit(code);+ };+ process.on('SIGINT', onSignal(130));+ process.on('SIGTERM', onSignal(143));++ const results: FileResult[] = [];+ try {+ if (needsDb.length) {+ if (!args.postgres) {+ for (const p of needsDb) p.reason = p.reason ?? 'needs Postgres; re-run with --postgres; not stressed';+ } else {+ ctx.pg = await provisionPostgres();+ log(` postgres: ${ctx.pg.origin}, a fresh database per iteration (CREATE DATABASE … TEMPLATE)`);+ }+ }+ if (spawnSync('bun', ['run', 'build:pglite-snapshot'], { cwd: ROOT, stdio: 'ignore' }).status === 0) ctx.snapshot = join(ROOT, 'test/fixtures/pglite-snapshot.tar');+ if (plan.some(p => !p.reason && p.profile.prereq === 'old-binary')) {+ const bin = join(out, 'gbrain-before-shared-skills');+ const built = spawnSync('bash', ['scripts/build-shared-skills-baseline.sh', bin], { cwd: ROOT, encoding: 'utf8' });+ if (built.status !== 0) throw new Error(`building the pre-feature executable failed (scripts/build-shared-skills-baseline.sh): ${built.stderr.trim().split('\n').pop()}`);+ ctx.oldBinary = bin;+ }+ const setupMs = Date.now() - setupStarted;+ log(` setup ${(setupMs / 1000).toFixed(1)}s`);+ const runStarted = Date.now();+ for (const p of plan) {+ if (p.reason) { results.push({ file: p.file, profile: p.profile.name, env: p.profile.env, arm: p.profile.arm, status: 'not-stressed', reason: p.reason, seedBase: 0, firstIteration: 1, iterations: [], reproduce: '' }); continue; }+ const items = args.work ? args.work.filter(w => w.file === p.file) : [{ file: p.file, first: args.firstIteration, count: args.iterations }];+ for (const item of items) results.push(await stressFile(ctx, p.file, p.profile, item.first, item.count));+ }+ const runMs = Date.now() - runStarted;+ const manifest = writeManifest(ctx, results, selection, setupMs, runMs);+ return summarize(results, manifest, setupMs, runMs);+ } catch (e) {+ console.error(`test:stress: ${(e as Error).message}\n Docs: ${STRESS_DOCS}`);+ return 2;+ } finally {+ await ctx.pg?.close().catch(() => {});+ }+}++function artifactUrl(): string {+ const { GITHUB_SERVER_URL: server, GITHUB_REPOSITORY: repo, GITHUB_RUN_ID: run } = process.env;+ return process.env.GBRAIN_STRESS_ARTIFACT_URL || (server && repo && run ? `${server}/${repo}/actions/runs/${run}` : '');+}++/** The context line printed under every reproduce command. */+export function contextLine(ctx: { sha: string; bun: string }, r: FileResult, it: IterationResult, artifact: string): string {+ return `sha ${ctx.sha.slice(0, 12)}, Bun ${ctx.bun}, backend ${r.arm}, profile ${r.profile} (${r.env}), iteration ${it.index}, seed ${it.seed}${artifact ? `, artifact ${artifact}` : ''}`;+}++function writeManifest(ctx: RunContext, results: FileResult[], selection: Selection, setupMs: number, runMs: number): string {+ const artifact = artifactUrl();+ const failures = results.flatMap(r => r.iterations.flatMap(it => it.failures.map(f => ({+ file: r.file, iteration: it.index, seed: it.seed, test: f.test, backend: r.arm, signature: f.signature, message: f.message,+ reproduce: reproduceLine({ file: r.file, iterations: Math.max(1, r.iterations.length), firstIteration: it.index, seed: r.seedBase, postgres: r.env === 'database', randomize: ctx.args.randomize }),+ context: contextLine(ctx, r, it, artifact),+ }))));+ const manifest = {+ version: 1, kind: 'gbrain-stress-manifest', sha: ctx.sha, bun: ctx.bun, randomize: ctx.args.randomize,+ run_id: process.env.GITHUB_RUN_ID ?? '', run_attempt: process.env.GITHUB_RUN_ATTEMPT ?? '', artifact,+ setup_ms: setupMs, run_ms: runMs, helpers: selection.helpers,+ files: results.map(r => ({ ...r, iterations: r.iterations.map(({ receipt, ...it }) => ({ ...it, receipt })) })),+ not_stressed: results.filter(r => r.status === 'not-stressed').map(r => ({ file: r.file, reason: r.reason })),+ failures,+ };+ const path = join(ctx.out, 'stress-manifest.json');+ writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\n`);+ return path;+}++function summarize(results: FileResult[], manifestPath: string, setupMs: number, runMs: number): number {+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { failures: Array<{ file: string; iteration: number; test: string; message: string; reproduce: string; context: string }> };+ const failedFiles = [...new Set(results.filter(r => r.status === 'fail').map(r => r.file))];+ log(`\ntest:stress: ${results.filter(r => r.status === 'pass').length} passed, ${failedFiles.length} failed, ${results.filter(r => r.status === 'not-stressed').length} not stressed (setup ${(setupMs / 1000).toFixed(1)}s, run ${(runMs / 1000).toFixed(1)}s). Manifest: ${relativeToRoot(manifestPath)}`);+ if (!failedFiles.length) return 0;+ for (const file of failedFiles) {+ const fs = manifest.failures.filter(f => f.file === file);+ const iterations = [...new Set(fs.map(f => f.iteration))];+ const first = fs[0]!;+ log(`\nFAIL [stress_failure]: ${file} failed in ${iterations.length} iteration(s) (first: iteration ${first.iteration}, ${first.test}: ${first.message.split('\n')[0]})`);+ log(` Why: the same checkout passed and failed across iterations, so the file is nondeterministic (or broken).`);+ log(` Fix: root-cause the race in the product or the test; never widen a timeout or weaken an assertion. Replay:`);+ log(` ${first.reproduce}`);+ log(` # ${first.context}`);+ log(` Docs: ${STRESS_DOCS}`);+ }+ return 1;+}++if (import.meta.main) process.exit(await main(process.argv.slice(2)));diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 295cb8c9c3..a2767b153e 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -262,7 +262,7 @@ test/scripts/ci-local-rendering.test.ts ci-local execution coverage 5 readFileSytest/scripts/ci-local-rendering.test.ts local test configuration through run-e2e 2 readFileSynctest/scripts/ci-local-rendering.test.ts required PgBouncer execution through run-e2e 1 readFileSynctest/scripts/ci-manifest-diff.test.ts test.yml dependency-audit scope 2 readFileSync-test/scripts/ci-pr-scope.test.ts pull-request CI scope 9 readFileSync+test/scripts/ci-pr-scope.test.ts pull-request CI scope 11 readFileSynctest/scripts/ci-runner-routing.test.ts CI runner routing 7 readFileSynctest/scripts/classify-tests.test.ts classify-tests detectors 23 bun-file,doctor-source-helper,exec-scan,readFileSync,source-surface-helpertest/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSync@@ -279,10 +279,13 @@ test/scripts/native-lock-prebuilds.test.ts native lock distribution integrity 2test/scripts/nightly-e2e.test.ts nightly E2E scheduling 4 readFileSynctest/scripts/nightly-issue.test.ts .github/nightly-known-red.tsv 2 readFileSynctest/scripts/nightly-issue.test.ts nightly-watch incidents 9 readFileSync-test/scripts/postgres-lane-coverage.test.ts check-postgres-lane-coverage.ts 6 readFileSync+test/scripts/postgres-lane-coverage.test.ts check-postgres-lane-coverage.ts 9 readFileSynctest/scripts/regen-all.test.ts regen:all 4 readFileSynctest/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSynctest/scripts/serial-files.test.ts scripts/serial-files.tsv (serial lane manifest) 5 readFileSync+test/scripts/stress-gate.test.ts docs anchors 1 readFileSync+test/scripts/stress-gate.test.ts gate plan 5 readFileSync+test/scripts/stress-plan.test.ts execution profiles 3 readFileSynctest/scripts/test-env-opt-ins-guard.test.ts check-test-env-opt-ins 2 readFileSynctest/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSynctest/scripts/test-shard.slow.test.ts test-shard.sh — exclusion contract 7 readFileSyncdiff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 9295e98d90..eebf82d8f9 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -69,6 +69,7 @@ test/persistence-sync-holds.test.tstest/persistence-writer-fences.test.tstest/repair-embedding-effects.test.tstest/repair-frontmatter.test.ts+test/scripts/test-stress-postgres.test.tstest/shared-content-freshness.test.tstest/shared-skills-catalog.test.tstest/shared-skills-retention-capacity.test.tsdiff --git a/test/scripts/ci-gates.test.ts b/test/scripts/ci-gates.test.tsindex c8c4a7a86a..4b063ba44f 100644--- a/test/scripts/ci-gates.test.ts+++ b/test/scripts/ci-gates.test.ts@@ -37,7 +37,7 @@ describe('CI execution evidence', () => {}for (const name of ['gitleaks', 'verify']) {expect(unit.jobs[name].needs).toBeUndefined();- expect(unit.jobs[name].if).toBe("${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}");+ expect(unit.jobs[name].if).toBe("${{ github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base) }}");}expect(e2e.jobs.tier2.needs).toBe('jsonb-parity');expect(e2e.jobs.tier2.if).toBeUndefined();@@ -50,11 +50,11 @@ describe('CI execution evidence', () => {});test('unit aggregate rejects failed, cancelled or skipped required jobs', () => {- expect(unit.jobs['test-status'].if).toBe("${{ always() && (github.event_name != 'workflow_dispatch' || inputs.native_only != true) }}");+ expect(unit.jobs['test-status'].if).toBe("${{ always() && (github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base)) }}");expect(unit.jobs['test-status'].needs).toEqual(['gitleaks', 'security-regressions', 'dependency-audit', 'verify', 'serial-tests','slow-entity-resolve-perf', 'slow-brainbench-e2e', 'brainbench', 'test', 'native-locks', 'persistence-validation',- 'admin-browser', 'shared-skills-compatibility',+ 'admin-browser', 'shared-skills-compatibility', 'stress-changed-tests',]);expect(aggregate(unit, 'test-status', 'pull_request', {})).toBe(0);for (const job of unit.jobs['test-status'].needs as string[]) {diff --git a/test/scripts/ci-pr-scope.test.ts b/test/scripts/ci-pr-scope.test.tsindex d2ebbc47c0..47aea5f23b 100644--- a/test/scripts/ci-pr-scope.test.ts+++ b/test/scripts/ci-pr-scope.test.ts@@ -167,13 +167,13 @@ esac// Every event-conditional behavior in a test workflow is classified beside// the condition: parity, or a named exception naming its covering scheduled- // run (docs/TESTING.md#event-parity). The native_only dispatch mode is the- // documented manual mode and is stripped before scanning.+ // run (docs/TESTING.md#event-parity). Manual dispatch modes are documented+ // at test.yml's inputs and stripped before scanning.test('every event-conditional job or block in a test workflow carries its event-parity classification', () => {const conditional = /github\.event_name|github\.event\.(?:pull_request|merge_group|action)|inputs\.scope|"\$EVENT"|\$EVENT\b/;- const dispatchMode = /github\.event_name\s*(?:!=|==)\s*'workflow_dispatch'\s*(?:\|\||&&)\s*inputs\.native_only\s*(?:!=|==)\s*true/g;+ const dispatchMode = /github\.event_name\s*(?:!=|==)\s*'workflow_dispatch'/g;const unclassified: string[] = [];- for (const name of ['test', 'persistence-validation', 'native-locks', 'e2e', 'heavy-tests', 'macos-validation', 'scale-tier', 'semgrep']) {+ for (const name of ['test', 'stress', 'persistence-validation', 'native-locks', 'e2e', 'heavy-tests', 'macos-validation', 'scale-tier', 'semgrep']) {const lines = readFileSync(join(root, '.github/workflows', `${name}.yml`), 'utf8').split('\n');// Blocks: each job (from the comments directly above its key to the next job) and the top-level preamble.const starts = lines.flatMap((line, i) => (/^ [\w-]+:\s*$/.test(line) && lines.slice(0, i).some(l => l === 'jobs:') ? [i] : []));@@ -186,19 +186,20 @@ esacconst text = lines.slice(block.from, block.to);const code = text.filter(l => !/^\s*#/.test(l)).join('\n').replace(dispatchMode, '');if (!conditional.test(code)) continue;- if (!text.some(l => /^\s*#.*docs\/TESTING\.md#(?:event-parity|dependency-audit-rule)/.test(l) || /^\s*#\s*Event parity/.test(l))) unclassified.push(`${name}.yml › ${block.label}`);+ if (!text.some(l => /^\s*#.*docs\/(?:TESTING\.md#event-parity|ci-event-parity\.md#dependency-audit-rule)/.test(l) || /^\s*#\s*Event parity/.test(l))) unclassified.push(`${name}.yml › ${block.label}`);}}expect(unclassified).toEqual([]);});- test('the docs event-parity table lists every classified workflow', () => {- const docs = readFileSync(join(root, 'docs/TESTING.md'), 'utf8');- const section = docs.slice(docs.indexOf('### Event parity'), docs.indexOf('\n### ', docs.indexOf('### Event parity') + 5));- for (const name of ['test', 'persistence-validation', 'native-locks', 'e2e', 'heavy-tests', 'macos-validation', 'scale-tier', 'semgrep', 'osv-scanner', 'nightly-watch']) {+ test('the event-parity table lists every classified workflow', () => {+ expect(readFileSync(join(root, 'docs/TESTING.md'), 'utf8')).toContain('### Event parity');+ const docs = readFileSync(join(root, 'docs/ci-event-parity.md'), 'utf8');+ const section = docs.slice(docs.indexOf('## Classification'), docs.indexOf('## Dependency-audit rule'));+ for (const name of ['test', 'stress', 'persistence-validation', 'native-locks', 'e2e', 'heavy-tests', 'macos-validation', 'scale-tier', 'semgrep', 'osv-scanner', 'nightly-watch']) {expect(section, name).toContain(`${name}.yml`);}- expect(docs).toContain('#### Dependency-audit rule');+ expect(docs).toContain('## Dependency-audit rule');});test('export scale runs 10,001 pages on pull requests and 100,001 everywhere else', () => {diff --git a/test/scripts/native-only-workflow.test.ts b/test/scripts/native-only-workflow.test.tsindex 54ea4650af..a917fa8004 100644--- a/test/scripts/native-only-workflow.test.ts+++ b/test/scripts/native-only-workflow.test.ts@@ -8,42 +8,70 @@ import { safeLoad } from 'js-yaml';type Job = { if?: string; name?: string; needs?: string[]; uses?: string; steps?: Array<{ name: string; run?: string }> };const workflow = safeLoad(readFileSync(join(import.meta.dir, '../../.github/workflows/test.yml'), 'utf8')) as {- on: { workflow_dispatch: { inputs: { native_only: { type: string; default: boolean } } } };+ on: { workflow_dispatch: { inputs: Record<string, { type: string; default: boolean | string }> } };concurrency: { group: string; 'cancel-in-progress': boolean }; jobs: Record<string, Job>;};-function context(event: string, flag?: boolean) {+type Diagnostic = { race_hunt?: boolean; stress_files?: string; stress_base?: string };+function context(event: string, flag?: boolean, diagnostic: Diagnostic = {}) {+ // Dispatch inputs carry their declared defaults; other events have no inputs.+ const inputs = event === 'workflow_dispatch' ? { native_only: flag, race_hunt: false, stress_files: '', stress_base: '', stress_head: '', ...diagnostic } : {};return { github: { workflow: 'Test', event_name: event, ref: 'refs/heads/example', event: { pull_request: event === 'pull_request' ? { number: 123 } : {} } },- inputs: { native_only: flag }, always: () => true };+ inputs, always: () => true };}-function evaluate(expression: string, event: string, flag?: boolean): unknown {- return runInNewContext(expression.replace(/^\$\{\{\s*|\s*\}\}$/g, ''), context(event, flag), { timeout: 100 });+function evaluate(expression: string, event: string, flag?: boolean, diagnostic?: Diagnostic): unknown {+ return runInNewContext(expression.replace(/^\$\{\{\s*|\s*\}\}$/g, ''), context(event, flag, diagnostic), { timeout: 100 });}-function template(value: string, event: string, flag?: boolean): string {- return value.replace(/\$\{\{(.*?)\}\}/g, (_, expression) => String(evaluate(expression.trim(), event, flag)));+function template(value: string, event: string, flag?: boolean, diagnostic?: Diagnostic): string {+ return value.replace(/\$\{\{(.*?)\}\}/g, (_, expression) => String(evaluate(expression.trim(), event, flag, diagnostic)));}describe('native-only CI remains separate from full validation', () => {test('only an explicit manual boolean skips full jobs; default and PR/push gates stay required', () => {expect(workflow.on.workflow_dispatch.inputs.native_only).toMatchObject({ type: 'boolean', default: false });expect(workflow.jobs['native-locks'].uses).toBe('./.github/workflows/native-locks.yml');- expect(workflow.jobs['native-locks'].if).toBeUndefined();expect(workflow.jobs.changes.if).toBeUndefined();expect(workflow.jobs['native-locks'].needs).toEqual(['changes']);+ const ownModes = new Set(['native-locks', 'changes', 'stress-changed-tests', 'race-hunt']);for (const [name, job] of Object.entries(workflow.jobs)) {- if (name === 'native-locks' || name === 'changes') continue;+ if (ownModes.has(name)) continue;expect(job.if).toBeDefined();const nativeStatus = name === 'native-only-status';for (const event of ['push', 'pull_request', 'workflow_dispatch']) {for (const flag of [undefined, false, true]) {const nativeOnly = event === 'workflow_dispatch' && flag === true;- expect(evaluate(job.if!, event, flag), `${name}/${event}/${flag}`).toBe(nativeStatus ? nativeOnly : !nativeOnly);+ expect(Boolean(evaluate(job.if!, event, flag)), `${name}/${event}/${flag}`).toBe(nativeStatus ? nativeOnly : !nativeOnly);}}}+ // native-locks runs in every full or native-only run and skips only in a diagnostic dispatch.+ for (const event of ['push', 'pull_request', 'schedule']) expect(Boolean(evaluate(workflow.jobs['native-locks'].if!, event))).toBe(true);+ expect(Boolean(evaluate(workflow.jobs['native-locks'].if!, 'workflow_dispatch', true))).toBe(true);expect(workflow.jobs['test-status'].needs).toContain('native-locks');expect(workflow.jobs['test-status'].needs).toContain('persistence-validation');});+ test('a diagnostic dispatch (race_hunt or stress inputs) runs only its lane and never emits test-status', () => {+ for (const input of ['race_hunt', 'stress_files', 'stress_base'] as const) {+ expect(workflow.on.workflow_dispatch.inputs[input]).toBeDefined();+ const diagnostic: Diagnostic = input === 'race_hunt' ? { race_hunt: true } : { [input]: input === 'stress_files' ? 'test/a.test.ts' : 'origin/master' };+ for (const [name, job] of Object.entries(workflow.jobs)) {+ if (name === 'changes') continue;+ const runs = Boolean(evaluate(job.if!, 'workflow_dispatch', false, diagnostic));+ const expected = name === 'stress-changed-tests' || (name === 'race-hunt' && input === 'race_hunt');+ expect(runs, `${name} under ${input}`).toBe(expected);+ }+ expect(template(workflow.jobs['test-status'].name!, 'workflow_dispatch', false, diagnostic)).toBe('full-suite-not-run');+ expect(template(workflow.concurrency.group, 'workflow_dispatch', false, diagnostic)).toBe('Test-refs/heads/example-diagnostic');+ }+ // Outside dispatch the gate always runs (and decides "not a PR event" itself); the race hunt runs only on schedule.+ for (const event of ['push', 'pull_request', 'merge_group', 'schedule']) {+ expect(Boolean(evaluate(workflow.jobs['stress-changed-tests'].if!, event))).toBe(true);+ expect(Boolean(evaluate(workflow.jobs['race-hunt'].if!, event))).toBe(event === 'schedule');+ }+ expect(workflow.jobs['test-status'].needs).toContain('stress-changed-tests');+ expect(workflow.jobs['test-status'].needs).not.toContain('race-hunt');+ });+test('a native retry cannot cancel a full run or emit its required aggregate check name', () => {const full = template(workflow.concurrency.group, 'workflow_dispatch', false);expect(full).toBe('Test-refs/heads/example');diff --git a/test/scripts/stress-gate.test.ts b/test/scripts/stress-gate.test.tsnew file mode 100644index 0000000000..923f498389--- /dev/null+++ b/test/scripts/stress-gate.test.ts@@ -0,0 +1,240 @@+/**+ * scripts/stress/gate.ts: the PR stress gate and race-hunt planner and+ * reporter (docs/TESTING.md#stress-gate, docs/TESTING.md#race-hunt).+ * GitHub calls go through a recorded fake client.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { GitHubClient } from '../../scripts/lib/gh-issue.ts';+import {+ RACE_MAX_SHARDS, RACE_MIN_ITERATIONS, RACE_SHARD_BUDGET_MS, buildReport, loadExemptions, matchExemption, missingWork,+ parseExemptionBlocks, planGate, planRaceHunt, shardTimings, type GhIssue, type Plan, type StressFailure,+} from '../../scripts/stress/gate.ts';+import type { Weights } from '../../scripts/stress/plan.ts';++const REPO = join(import.meta.dir, '..', '..');+const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function repo(files: Record<string, string>): { root: string; base: string } {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-stress-gate-'));+ dirs.push(root);+ const git = (...args: string[]) => spawnSync('git', args, { cwd: root, encoding: 'utf8' }).stdout.trim();+ git('init', '-q', '-b', 'master'); git('config', 'user.email', '[email protected]'); git('config', 'user.name', 's'); git('config', 'commit.gpgsign', 'false');+ for (const [rel, body] of Object.entries(files)) { mkdirSync(join(root, rel, '..'), { recursive: true }); writeFileSync(join(root, rel), body); }+ git('add', '-A'); git('commit', '-qm', 'base');+ return { root, base: git('rev-parse', 'HEAD') };+}+const commit = (root: string, files: Record<string, string>) => {+ for (const [rel, body] of Object.entries(files)) { mkdirSync(join(root, rel, '..'), { recursive: true }); writeFileSync(join(root, rel), body); }+ spawnSync('git', ['add', '-A'], { cwd: root }); spawnSync('git', ['commit', '-qm', 'pr'], { cwd: root });+ return spawnSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).stdout.trim();+};+const weights = (arms: Record<string, number> = {}): Weights => ({ unit: new Map(), serialSeconds: new Map(), e2e: new Map(), arms: new Map(Object.entries(arms)) });+const isPlan = (p: Plan | { error: string }): Plan => { if ('error' in p) throw new Error(p.error); return p; };++describe('gate plan', () => {+ test('outside pull_request and merge_group the gate succeeds with "not a PR event"', () => {+ for (const event of ['push', 'schedule', 'workflow_dispatch']) {+ const plan = isPlan(planGate(REPO, { event }, weights()));+ expect(plan).toMatchObject({ run: false, reason: 'not a PR event' });+ const report = buildReport({ plan, planResult: 'success', shardsResult: 'skipped', manifests: [], exemptions: { exemptions: [], openIssues: [] }, today: '2026-10-05', artifact: '' });+ expect(report.exit).toBe(0);+ expect(report.summary).toContain('**Passed:** not a PR event.');+ }+ });++ test('a pull request plans every changed test file at 10 iterations, and lists paid-provider files as not stressed', () => {+ const { root, base } = repo({ 'test/a.test.ts': "test('a', () => {});\n", 'test/b.test.ts': "test('b', () => {});\n" });+ const head = commit(root, { 'test/a.test.ts': "test('a2', () => {});\n", 'test/e2e/x.live.test.ts': "test('paid', () => {});\n", 'test/c.serial.test.ts': "test('c', () => {});\n" });+ const plan = isPlan(planGate(root, { event: 'pull_request', baseSha: base, headSha: head }, weights()));+ expect(plan.run).toBe(true);+ expect(plan.files.map(f => [f.file, f.profile, f.iterations])).toEqual([['test/a.test.ts', 'unit', 10], ['test/c.serial.test.ts', 'serial', 10]]);+ expect(plan.notStressed).toEqual([{ file: 'test/e2e/x.live.test.ts', reason: expect.stringContaining('paid-provider') }]);+ expect(plan.shards.flatMap(s => s.items).reduce((n, i) => n + i.count, 0)).toBe(20);+ });++ test('a missing merge base fails the plan with the fetch next step', () => {+ const { root } = repo({ 'test/a.test.ts': '' });+ const result = planGate(root, { event: 'merge_group', baseSha: 'f'.repeat(40), headSha: 'HEAD' }, weights());+ expect('error' in result && result.error).toContain('Next: git fetch');+ const report = buildReport({ plan: undefined, planResult: 'failure', shardsResult: 'skipped', manifests: [], exemptions: { exemptions: [], openIssues: [] }, today: '2026-10-05', artifact: '' });+ expect(report.exit).toBe(1);+ expect(report.summary).toContain('fetch it (`git fetch --no-tags origin master`)');+ });++ test('dispatch inputs are validated before use and the run is labeled diagnostic', () => {+ expect(planGate(REPO, { event: 'workflow_dispatch', stressFiles: 'test/a.test.ts $(curl x)' }, weights())).toMatchObject({ error: expect.stringContaining('not repo-relative test files') });+ expect(planGate(REPO, { event: 'workflow_dispatch', stressBase: 'master;id' }, weights())).toMatchObject({ error: expect.stringContaining('must be 40-hex SHAs or valid ref names') });+ const plan = isPlan(planGate(REPO, { event: 'workflow_dispatch', stressFiles: 'test/scripts/stress-plan.test.ts' }, weights()));+ expect(plan).toMatchObject({ run: true, diagnostic: true });+ const workflow = readFileSync(join(REPO, '.github/workflows/stress.yml'), 'utf8');+ expect(workflow).not.toMatch(/run:[^\n]*\$\{\{\s*inputs\./);+ });+});++describe('race hunt plan', () => {+ const list = (n: number) => Array.from({ length: n }, (_, i) => `test/arm-${String(i).padStart(2, '0')}.test.ts`);+ function armsRepo(n: number) {+ const files: Record<string, string> = { 'test/postgres-unit-arms.txt': `${list(n).join('\n')}\n` };+ for (const f of list(n)) files[f] = "for (const b of testBackends()) describe(b, () => { test('x', () => {}); });\n";+ return repo(files).root;+ }++ test('every listed file runs 10 iterations when the set fits 12 shards of 55 minutes', () => {+ const root = armsRepo(20);+ const plan = planRaceHunt(root, { day: 3 }, weights(Object.fromEntries(list(20).map(f => [f, 60_000]))));+ expect(plan.files.every(f => f.iterations === 10 && f.profile === 'postgres-arm')).toBe(true);+ expect(plan.unrun).toEqual([]);+ expect(plan.shards.length).toBeLessThanOrEqual(RACE_MAX_SHARDS);+ expect(plan.shards.every(s => s.estimateMs <= RACE_SHARD_BUDGET_MS)).toBe(true);+ });++ test('past 12 shards depth drops to no fewer than 3 nightly and the spare capacity rotates by day', () => {+ const root = armsRepo(30);+ const w = weights(Object.fromEntries(list(30).map(f => [f, 4 * 60_000])));+ const monday = planRaceHunt(root, { day: 1 }, w);+ const tuesday = planRaceHunt(root, { day: 2 }, w);+ expect(monday.unrun).toEqual([]);+ expect(monday.files.every(f => f.iterations >= RACE_MIN_ITERATIONS && f.iterations <= 10)).toBe(true);+ expect(monday.files.length).toBe(30);+ const deep = (p: Plan) => p.files.filter(f => f.iterations > Math.min(...p.files.map(x => x.iterations))).map(f => f.file);+ expect(deep(monday)).not.toEqual(deep(tuesday));+ expect(monday.shards.every(s => s.estimateMs <= RACE_SHARD_BUDGET_MS)).toBe(true);+ });++ test('a set that does not fit at 3 iterations fails "race hunt over budget" naming the unrun files', () => {+ const root = armsRepo(10);+ const plan = planRaceHunt(root, { day: 0 }, weights(Object.fromEntries(list(10).map(f => [f, 40 * 60_000]))));+ expect(plan.unrun.length).toBeGreaterThan(0);+ const report = buildReport({ plan, planResult: 'success', shardsResult: 'success', manifests: [], exemptions: { exemptions: [], openIssues: [] }, today: '2026-10-05', artifact: '' });+ expect(report.exit).toBe(1);+ expect(report.summary).toContain('### Race hunt over budget');+ expect(report.errors.join('\n')).toContain('race hunt over budget');+ for (const f of plan.unrun) expect(report.summary).toContain(f);+ });+});++const failure = (over: Partial<StressFailure> = {}): StressFailure => ({+ file: 'test/a.test.ts', iteration: 3, seed: 12, test: 'suite > counts', backend: 'pglite+postgres', signature: 'expect(received).toBe(expected) Expected: N Received: N',+ message: 'expect(received).toBe(expected)\n\nExpected: 7\nReceived: 6', reproduce: 'bun run test:stress test/a.test.ts --iterations 10 --first-iteration 3 --seed 10 --postgres',+ context: 'sha abc, Bun 1.4.2, backend pglite+postgres, profile postgres-arm (database), iteration 3, seed 12', ...over,+});+const gatePlan = (files: string[]): Plan => ({+ version: 1, mode: 'gate', run: true, reason: 'x', diagnostic: false, head: 'h', base: 'b', notStressed: [], helpers: [], unrun: [], iterations: 10, budgetMs: 1, estimateMs: 1,+ files: files.map(file => ({ file, profile: 'postgres-arm', iterations: 10, estimateMs: 1 })),+ shards: [{ index: 1, estimateMs: 1, items: files.map(file => ({ file, first: 1, count: 10, estimateMs: 1 })) }],+});+const manifest = (files: string[], failures: StressFailure[]) => ({+ sha: 'abc', bun: '1.4.2', run_id: '1', artifact: '', setup_ms: 0, run_ms: 0, failures,+ files: files.map(file => ({ file, status: failures.some(f => f.file === file) ? 'fail' : 'pass', firstIteration: 1, iterations: Array.from({ length: 10 }, (_, i) => ({ index: i + 1 })) })),+});++describe('report', () => {+ test('a failure fails the check with file, iteration, reproduce line and the root-cause rule; credentials never print', () => {+ const plan = gatePlan(['test/a.test.ts']);+ const report = buildReport({ plan, planResult: 'success', shardsResult: 'success', manifests: [manifest(['test/a.test.ts'], [failure({ message: 'connect postgres://gbrain_test:[email protected]/gbrain_test refused' })])], exemptions: { exemptions: [], openIssues: [] }, today: '2026-10-05', artifact: 'https://example.invalid/run/1' });+ expect(report.exit).toBe(1);+ expect(report.summary).toContain('A flaky touched file must be root-caused in this PR');+ expect(report.summary).toContain('bun run test:stress test/a.test.ts --iterations 10 --first-iteration 3 --seed 10 --postgres');+ expect(report.summary).not.toContain('hunter2');+ expect(report.errors[0]).toMatch(/^file=test\/a\.test\.ts::stress gate: failed 1 of 10 iterations \(first: iteration 3\)/);+ expect(report.errors[0]).toContain('Docs: docs/TESTING.md#stress-gate');+ });++ test('more than three failing files are each listed', () => {+ const files = ['test/a.test.ts', 'test/b.test.ts', 'test/c.test.ts', 'test/d.test.ts', 'test/e.test.ts'];+ const report = buildReport({ plan: gatePlan(files), planResult: 'success', shardsResult: 'success', manifests: [manifest(files, files.map(file => failure({ file })))], exemptions: { exemptions: [], openIssues: [] }, today: '2026-10-05', artifact: '' });+ expect(report.errors).toHaveLength(5);+ for (const f of files) expect(report.summary).toContain(`\`${f}\``);+ });++ test('a matching unexpired exemption passes that failure only; a new signature still fails', () => {+ const plan = gatePlan(['test/a.test.ts']);+ const ex = { file: 'test/a.test.ts', test: 'suite > counts', backend: 'pglite+postgres', signature: failure().signature, owner: '@release-duty', expires: '2026-10-20', issue: 7, url: 'https://example.invalid/issues/7' };+ const known = buildReport({ plan, planResult: 'success', shardsResult: 'success', manifests: [manifest(['test/a.test.ts'], [failure()])], exemptions: { exemptions: [ex], openIssues: [] }, today: '2026-10-05', artifact: '' });+ expect(known.exit).toBe(0);+ expect(known.summary).toContain('matches the open issue https://example.invalid/issues/7');+ const fresh = buildReport({ plan, planResult: 'success', shardsResult: 'success', manifests: [manifest(['test/a.test.ts'], [failure(), failure({ signature: 'TypeError: x is undefined', iteration: 5 })])], exemptions: { exemptions: [ex], openIssues: [] }, today: '2026-10-05', artifact: '' });+ expect(fresh.exit).toBe(1);+ expect(matchExemption(failure(), [{ ...ex, expires: '2026-10-04' }], '2026-10-05')).toBeUndefined();+ expect(matchExemption(failure({ backend: 'pglite' }), [ex], '2026-10-05')).toBeUndefined();+ });++ test('an iteration without a receipt is incomplete and fails, never a pass', () => {+ const plan = gatePlan(['test/a.test.ts', 'test/b.test.ts']);+ const m = manifest(['test/a.test.ts'], []);+ expect(missingWork(plan, [m])).toEqual(['test/b.test.ts iterations 1-10 (shard 1)']);+ const report = buildReport({ plan, planResult: 'success', shardsResult: 'failure', manifests: [m], exemptions: { exemptions: [], openIssues: [] }, today: '2026-10-05', artifact: '' });+ expect(report.exit).toBe(1);+ expect(report.summary).toContain('### Incomplete');+ });++ test('p95 queue and completion come from the shard jobs only', () => {+ const t = (name: string, c: number, s: number, e: number) => ({ name, created_at: new Date(c * 60_000).toISOString(), started_at: new Date(s * 60_000).toISOString(), completed_at: new Date(e * 60_000).toISOString() });+ const timings = shardTimings([t('stress-changed-tests / Stress shard 1', 0, 1, 11), t('stress-changed-tests / Stress shard 2', 0, 3, 23), t('test (1)', 0, 0, 99)]);+ expect(timings).toEqual({ shards: 2, p95QueueMin: 3, p95CompletionMin: 23, runnerMin: 30 });+ });+});++describe('exemption trust', () => {+ const block = (row: Record<string, string>) => `<!-- gbrain-stress-exemption -->\n\`\`\`json\n${JSON.stringify(row)}\n\`\`\``;+ const row = { file: 'test/a.test.ts', test: 'suite > counts', backend: 'pglite+postgres', signature: 'sig', owner: '@duty', expires: '2026-10-20' };+ function client(issues: Record<string, GhIssue[]>, extras: Record<string, unknown> = {}): GitHubClient {+ return { async request<T>(_m: string, path: string): Promise<T> {+ const label = /labels=([^&]+)/.exec(path)?.[1];+ if (label) return (issues[decodeURIComponent(label)] ?? []) as T;+ for (const [k, v] of Object.entries(extras)) if (path.includes(k)) { if (v instanceof Error) throw v; return v as T; }+ return [] as T;+ } };+ }++ test('blocks parse from issue bodies; malformed or incomplete rows grant nothing', () => {+ expect(parseExemptionBlocks(`x\n${block(row)}\n${block({ ...row, expires: 'soon' })}\n<!-- gbrain-stress-exemption -->\n\`\`\`json\n{oops\n\`\`\``)).toEqual([row]);+ });++ test('bot- or maintainer-opened issues that predate the PR exempt; a forged flake issue from a non-maintainer does not', async () => {+ const issues: Record<string, GhIssue[]> = {+ flake: [+ { number: 1, created_at: '2026-10-01T00:00:00Z', user: { login: 'github-actions[bot]' }, author_association: 'NONE', body: block(row) },+ { number: 2, created_at: '2026-10-01T00:00:00Z', user: { login: 'drive-by' }, author_association: 'NONE', body: block({ ...row, test: 'forged' }) },+ { number: 3, created_at: '2026-10-09T00:00:00Z', user: { login: 'maintainer' }, author_association: 'MEMBER', body: block({ ...row, test: 'too new' }) },+ ],+ };+ const r = await loadExemptions(client(issues, { 'issues/2/events': [{ event: 'labeled', label: { name: 'flake' }, actor: { login: 'drive-by' } }], 'collaborators/drive-by/permission': { permission: 'read' } }), '2026-10-05T00:00:00Z');+ expect(r.incomplete).toBeUndefined();+ expect(r.exemptions.map(e => [e.issue, e.test])).toEqual([[1, 'suite > counts']]);+ });++ test('a maintainer label makes a contributor-opened issue count; a non-maintainer comment block is ignored', async () => {+ const issues: Record<string, GhIssue[]> = { 'master-red': [{ number: 4, created_at: '2026-10-01T00:00:00Z', user: { login: 'contrib' }, author_association: 'CONTRIBUTOR', body: '' }] };+ const r = await loadExemptions(client(issues, {+ 'issues/4/events': [{ event: 'labeled', label: { name: 'master-red' }, actor: { login: 'lead' } }],+ 'collaborators/lead/permission': { permission: 'admin' },+ 'issues/4/comments': [{ user: { login: 'lead' }, author_association: 'OWNER', body: block(row) }, { user: { login: 'contrib' }, author_association: 'CONTRIBUTOR', body: block({ ...row, test: 'forged' }) }],+ }), '2026-10-05T00:00:00Z');+ expect(r.exemptions.map(e => e.test)).toEqual(['suite > counts']);+ });++ test('an API failure is incomplete evidence and grants no exemption', async () => {+ const failing: GitHubClient = { async request() { throw new Error('HTTP 502'); } };+ const r = await loadExemptions(failing, '2026-10-05T00:00:00Z');+ expect(r).toMatchObject({ exemptions: [], incomplete: 'HTTP 502' });+ const report = buildReport({ plan: gatePlan(['test/a.test.ts']), planResult: 'success', shardsResult: 'success', manifests: [manifest(['test/a.test.ts'], [failure()])], exemptions: r, today: '2026-10-05', artifact: '' });+ expect(report.exit).toBe(1);+ expect(report.summary).toContain('Exemption lookup incomplete');+ });+});++describe('docs anchors', () => {+ test('every anchor the runner and the gate print resolves', () => {+ const testing = readFileSync(join(REPO, 'docs/TESTING.md'), 'utf8');+ expect(testing).toContain('### Stress gate');+ expect(testing).toContain('### Race hunt');+ expect(testing).toContain('#### Postgres-arm lanes');+ expect(readFileSync(join(REPO, 'scripts/stress/README.md'), 'utf8')).toContain('## Race hunt');+ });+});diff --git a/test/scripts/stress-plan.test.ts b/test/scripts/stress-plan.test.tsnew file mode 100644index 0000000000..9b4b067d56--- /dev/null+++ b/test/scripts/stress-plan.test.ts@@ -0,0 +1,175 @@+/**+ * scripts/stress/plan.ts: the planning half of `bun run test:stress`, the+ * PR stress gate and the race hunt (docs/TESTING.md#stress-gate).+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runInNewContext } from 'node:vm';+import { safeLoad } from 'js-yaml';+import {+ HELPER_FAN_IN_LIMIT, SPECIAL_FILES, allTestFiles, changedFiles, defaultSeed, directImporters, expandHelper,+ notStressedReason, parseFileList, planShards, profileFor, redact, reproduceLine, seededSample, validRef,+} from '../../scripts/stress/plan.ts';++const REPO = join(import.meta.dir, '..', '..');+const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function repo(files: Record<string, string>): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-stress-plan-'));+ dirs.push(root);+ const git = (...args: string[]) => { const r = spawnSync('git', args, { cwd: root, encoding: 'utf8' }); if (r.status !== 0) throw new Error(r.stderr); return r.stdout.trim(); };+ git('init', '-q', '-b', 'master');+ git('config', 'user.email', '[email protected]');+ git('config', 'user.name', 'stress');+ git('config', 'commit.gpgsign', 'false');+ for (const [rel, body] of Object.entries(files)) { mkdirSync(join(root, rel, '..'), { recursive: true }); writeFileSync(join(root, rel), body); }+ git('add', '-A');+ git('commit', '-qm', 'base');+ return root;+}+const sh = (root: string, ...args: string[]) => spawnSync('git', args, { cwd: root, encoding: 'utf8' }).stdout.trim();++describe('execution profiles', () => {+ test('suffix and location pick the lane; a gated arm with Postgres runs both arms', () => {+ expect(profileFor('test/a.test.ts', { armed: false, postgres: true })).toMatchObject({ name: 'unit', env: 'no-database', arm: 'pglite', timeoutMs: 60_000 });+ expect(profileFor('test/a.serial.test.ts', { armed: false, postgres: true })).toMatchObject({ name: 'serial', env: 'no-database', timeoutMs: 120_000 });+ expect(profileFor('test/a.slow.test.ts', { armed: false, postgres: false })).toMatchObject({ name: 'slow', env: 'no-database' });+ expect(profileFor('test/e2e/a.test.ts', { armed: false, postgres: false })).toMatchObject({ name: 'e2e', env: 'database', arm: 'postgres' });+ expect(profileFor('test/a.serial.test.ts', { armed: true, postgres: true })).toMatchObject({ name: 'postgres-arm', env: 'database', arm: 'pglite+postgres', timeoutMs: 120_000 });+ expect(profileFor('test/a.test.ts', { armed: true, postgres: false })).toMatchObject({ name: 'unit', env: 'no-database' });+ });++ test('slow-file specifics mirror the workflow values a pull request uses', () => {+ const wf = safeLoad(readFileSync(join(REPO, '.github/workflows/test.yml'), 'utf8')) as { jobs: Record<string, { steps: Array<{ run?: string; env?: Record<string, string> }> }> };+ const exportStep = wf.jobs['slow-entity-resolve-perf']!.steps.find(s => s.run?.includes('test/export-scale.slow.test.ts'))!;+ const pages = runInNewContext(exportStep.env!.GBRAIN_TEST_EXPORT_SCALE_PAGES!.replace(/^\$\{\{\s*|\s*\}\}$/g, ''), { github: { event_name: 'pull_request' } });+ expect(profileFor('test/export-scale.slow.test.ts', { armed: true, postgres: false }).vars).toEqual({ GBRAIN_TEST_EXPORT_SCALE_PAGES: pages });+ expect(exportStep.run).toContain('--timeout=900000');+ expect(SPECIAL_FILES['test/export-scale.slow.test.ts']!.timeoutMs).toBe(900_000);+ const oldBinary = wf.jobs['shared-skills-compatibility']!.steps.find(s => s.run?.includes('test/persistence-skill-old-binary.slow.test.ts'))!;+ expect(Object.keys(oldBinary.env!)).toContain('GBRAIN_TEST_OLD_BINARY');+ expect(oldBinary.run).toContain('--timeout 180000');+ expect(profileFor('test/persistence-skill-old-binary.slow.test.ts', { armed: false, postgres: false })).toMatchObject({ prereq: 'old-binary', timeoutMs: 180_000 });+ });++ test('paid-provider files are listed as not stressed with the reason', () => {+ expect(notStressedReason('test/e2e/x.live.test.ts', new Set())).toContain('paid-provider');+ expect(notStressedReason('test/live/x.test.ts', new Set())).toContain('paid-provider');+ expect(notStressedReason('test/e2e/voyage.test.ts', new Set(['test/e2e/voyage.test.ts']))).toContain('e2e-live-key-only.txt');+ expect(notStressedReason('test/a.test.ts', new Set())).toBeNull();+ });+});++describe('reproduce lines and inputs', () => {+ test('a reproduce line is the local command with every replay value and no credential', () => {+ expect(reproduceLine({ file: 'test/a.test.ts', iterations: 10, firstIteration: 7, seed: 123, postgres: true })).toBe('bun run test:stress test/a.test.ts --iterations 10 --first-iteration 7 --seed 123 --postgres');+ expect(reproduceLine({ file: 'test/a.test.ts', iterations: 3, firstIteration: 1, seed: 5, postgres: false, randomize: true })).toBe('bun run test:stress test/a.test.ts --iterations 3 --seed 5 --randomize');+ expect(redact('DATABASE_URL=postgres://gbrain_test:[email protected]:5432/gbrain_test bun test')).toBe('DATABASE_URL=postgres://gbrain_test:***@127.0.0.1:5432/gbrain_test bun test');+ expect(redact('PGPASSWORD=hunter2 GH_TOKEN=abc')).toBe('PGPASSWORD=*** GH_TOKEN=***');+ expect(defaultSeed('a'.repeat(40), 'test/a.test.ts')).toBe(defaultSeed('a'.repeat(40), 'test/a.test.ts'));+ expect(defaultSeed('a'.repeat(40), 'test/a.test.ts')).not.toBe(defaultSeed('b'.repeat(40), 'test/a.test.ts'));+ });++ test('dispatch values are validated: test paths only, refs by git check-ref-format or 40-hex', () => {+ expect(parseFileList('test/a.test.ts, test/b/c.serial.test.ts test/a.test.ts')).toEqual({ files: ['test/a.test.ts', 'test/b/c.serial.test.ts'], invalid: [] });+ expect(parseFileList('test/a.test.ts;rm -rf / ../x.test.ts test/../etc.test.ts').invalid).toEqual(['test/a.test.ts;rm', '-rf', '/', '../x.test.ts', 'test/../etc.test.ts']);+ expect(validRef('origin/master')).toBe(true);+ expect(validRef('a'.repeat(40))).toBe(true);+ expect(validRef('$(id)')).toBe(false);+ expect(validRef('-x')).toBe(false);+ expect(validRef('a..b')).toBe(false);+ });+});++describe('changed files', () => {+ test('added, modified and renamed tests count at their new path; deletions and fixtures do not', () => {+ const root = repo({ 'test/keep.test.ts': 'a', 'test/old-name.test.ts': 'x'.repeat(200), 'test/gone.test.ts': 'g', 'test/helpers/h.ts': 'h', 'src/a.ts': '1' });+ const base = sh(root, 'rev-parse', 'HEAD');+ writeFileSync(join(root, 'test/keep.test.ts'), 'b');+ spawnSync('git', ['mv', 'test/old-name.test.ts', 'test/new-name.test.ts'], { cwd: root });+ rmSync(join(root, 'test/gone.test.ts'));+ mkdirSync(join(root, 'test/fixtures'), { recursive: true });+ writeFileSync(join(root, 'test/fixtures/f.test.ts'), 'f');+ writeFileSync(join(root, 'test/added.serial.test.ts'), 'n');+ writeFileSync(join(root, 'test/helpers/h.ts'), 'h2');+ spawnSync('git', ['add', '-A'], { cwd: root });+ spawnSync('git', ['commit', '-qm', 'change'], { cwd: root });+ const changed = changedFiles(root, base, 'HEAD');+ expect(changed.error).toBeUndefined();+ expect(changed.tests).toEqual(['test/added.serial.test.ts', 'test/keep.test.ts', 'test/new-name.test.ts']);+ expect(changed.helpers).toEqual(['test/helpers/h.ts']);+ });++ test('a local run without --head includes working-tree and untracked test files', () => {+ const root = repo({ 'test/a.test.ts': 'a' });+ writeFileSync(join(root, 'test/a.test.ts'), 'b');+ writeFileSync(join(root, 'test/new.test.ts'), 'n');+ expect(changedFiles(root, 'master').tests).toEqual(['test/a.test.ts', 'test/new.test.ts']);+ });++ test('an unreachable merge base fails with the next step instead of guessing', () => {+ const root = repo({ 'test/a.test.ts': 'a' });+ const changed = changedFiles(root, 'origin/master', 'HEAD');+ expect(changed.error).toContain('cannot compute the merge base');+ expect(changed.error).toContain('git fetch --no-tags origin master');+ });+});++describe('helper fan-in', () => {+ const importer = (i: number) => [`test/imp-${String(i).padStart(2, '0')}.test.ts`, `import { h } from './helpers/wide.ts';\n`] as const;++ test('direct importers resolve relative specifiers with or without the extension', () => {+ const root = repo({ 'test/helpers/wide.ts': '', 'test/a.test.ts': "import x from './helpers/wide';\n", 'test/sub/b.test.ts': "const m = await import('../helpers/wide.ts');\n", 'test/c.test.ts': "import y from './helpers/other.ts';\n" });+ expect(directImporters(root, 'test/helpers/wide.ts', allTestFiles(root))).toEqual(['test/a.test.ts', 'test/sub/b.test.ts']);+ });++ test('at most 25 importers are all stressed', () => {+ const files = Object.fromEntries([['test/helpers/wide.ts', ''], ...Array.from({ length: HELPER_FAN_IN_LIMIT }, (_, i) => importer(i))]);+ const root = repo(files);+ const exp = expandHelper(root, 'test/helpers/wide.ts', allTestFiles(root), 'a'.repeat(40));+ expect(exp).toMatchObject({ mode: 'all-importers', importers: 25, listedOnly: [] });+ expect(exp.stressed).toHaveLength(25);+ });++ test('above 25: its own tests plus 10 importers sampled by the head SHA, the rest listed', () => {+ const files = Object.fromEntries([['test/helpers/wide.ts', ''], ['test/wide.test.ts', "import { h } from './helpers/wide.ts';\n"], ...Array.from({ length: 40 }, (_, i) => importer(i))]);+ const root = repo(files);+ const tests = allTestFiles(root);+ const a = expandHelper(root, 'test/helpers/wide.ts', tests, 'a'.repeat(40));+ expect(a.mode).toBe('sampled');+ expect(a.importers).toBe(41);+ expect(a.stressed).toContain('test/wide.test.ts');+ expect(a.stressed).toHaveLength(11);+ expect(a.listedOnly).toHaveLength(30);+ expect(expandHelper(root, 'test/helpers/wide.ts', tests, 'a'.repeat(40)).stressed).toEqual(a.stressed);+ expect(expandHelper(root, 'test/helpers/wide.ts', tests, 'b'.repeat(40)).stressed).not.toEqual(a.stressed);+ expect(seededSample([1, 2, 3, 4, 5], 3, 'x')).toEqual(seededSample([1, 2, 3, 4, 5], 3, 'x'));+ });+});++describe('shards', () => {+ test('files pack into the fewest shards under the budget, and every iteration is planned exactly once', () => {+ const shards = planShards([{ file: 'test/a.test.ts', perIterationMs: 57_000 }, { file: 'test/b.test.ts', perIterationMs: 7_000 }, { file: 'test/c.test.ts', perIterationMs: 1_000 }], 10, 25 * 60_000);+ expect(shards.every(s => s.estimateMs <= 25 * 60_000)).toBe(true);+ for (const file of ['test/a.test.ts', 'test/b.test.ts', 'test/c.test.ts']) {+ const its = shards.flatMap(s => s.items).filter(i => i.file === file).flatMap(i => Array.from({ length: i.count }, (_, k) => i.first + k)).sort((x, y) => x - y);+ expect(its).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);+ }+ });++ test('a file whose ten iterations exceed the budget is split by iteration, never skipped', () => {+ const shards = planShards([{ file: 'test/huge.slow.test.ts', perIterationMs: 6 * 60_000 }], 10, 25 * 60_000);+ expect(shards.length).toBeGreaterThan(1);+ expect(shards.every(s => s.estimateMs <= 25 * 60_000)).toBe(true);+ expect(shards.flatMap(s => s.items).reduce((n, i) => n + i.count, 0)).toBe(10);+ });++ test('a single iteration longer than the budget still gets its own shard', () => {+ const shards = planShards([{ file: 'test/giant.slow.test.ts', perIterationMs: 40 * 60_000 }], 2, 25 * 60_000);+ expect(shards).toHaveLength(2);+ });+});diff --git a/test/scripts/test-stress-postgres.test.ts b/test/scripts/test-stress-postgres.test.tsnew file mode 100644index 0000000000..a48d126e63--- /dev/null+++ b/test/scripts/test-stress-postgres.test.ts@@ -0,0 +1,79 @@+/**+ * scripts/stress/run.ts against a real PostgreSQL server: every database+ * iteration gets its own fresh database (CREATE DATABASE … TEMPLATE), a+ * gated arm that never connects fails, and owned databases are dropped after+ * the run and after Ctrl-C. Runs where DATABASE_URL names a test server+ * (test/postgres-unit-arms.txt, docs/TESTING.md#stress-gate).+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawn, spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import postgres from '#postgres';++const REPO = join(import.meta.dir, '..', '..');+const RUNNER = join(REPO, 'scripts', 'stress', 'run.ts');+const DB = process.env.DATABASE_URL;+const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function tree(files: Record<string, string>): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-test-stress-pg-'));+ dirs.push(root);+ for (const [rel, body] of Object.entries(files)) { mkdirSync(join(root, rel, '..'), { recursive: true }); writeFileSync(join(root, rel), body); }+ return root;+}+const runnerEnv = (root: string, extra: Record<string, string> = {}) => {+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_STRESS_ROOT: root, GBRAIN_STRESS_ADMIN_URL: DB, ...extra };+ delete env.DATABASE_URL;+ return env;+};+async function stressDatabases(tag: string): Promise<string[]> {+ const sql = postgres(DB!, { max: 1, onnotice: () => {} });+ try { return (await sql`SELECT datname FROM pg_database WHERE datname LIKE ${`gbrain_stress_${tag}%`}`).map(r => String(r.datname)); } finally { await sql.end({ timeout: 5 }); }+}+const connect = `import postgres from ${JSON.stringify(join(REPO, 'vendor/postgres/src/index.js'))};\nimport { appendFileSync } from 'node:fs';\n`;++describe.skipIf(!DB)('test:stress with a database', () => {+ test('each database iteration gets a fresh database, and every one is dropped afterwards', async () => {+ const root = tree({ 'test/arm.test.ts': `${connect}import { test, expect } from 'bun:test';\ntest.skipIf(!process.env.DATABASE_URL)('postgres arm', async () => {\n const sql = postgres(process.env.DATABASE_URL!, { max: 1 });\n const [{ db }] = await sql\`SELECT current_database() AS db\`;\n await sql\`CREATE TABLE leftover (id int)\`;\n await sql.end();\n appendFileSync(process.env.STRESS_FIXTURE_LOG!, db + '\\n');\n expect(db).toMatch(/^gbrain_stress_.*_test$/);\n});\n` });+ const log = join(root, 'dbs.txt');+ const r = spawnSync(process.execPath, [RUNNER, 'test/arm.test.ts', '--postgres', '--iterations', '3', '--out', join(root, 'out')], { encoding: 'utf8', env: runnerEnv(root, { STRESS_FIXTURE_LOG: log }), timeout: 180_000 });+ expect(r.status, `${r.stdout}\n${r.stderr}`).toBe(0);+ const names = readFileSync(log, 'utf8').trim().split('\n');+ expect(names).toHaveLength(3);+ expect(new Set(names).size).toBe(3);+ const manifest = JSON.parse(readFileSync(join(root, 'out', 'stress-manifest.json'), 'utf8'));+ expect(manifest.files[0]).toMatchObject({ profile: 'postgres-arm', env: 'database', arm: 'pglite+postgres', status: 'pass' });+ for (const it of manifest.files[0].iterations) expect(it.databaseActivity).toBeGreaterThan(0);+ const tag = /^gbrain_stress_(\d+_[0-9a-f]+)_i\d+_test$/.exec(names[0]!)![1]!;+ expect(await stressDatabases(tag)).toEqual([]);+ expect(readdirSync(join(root, '.context', 'test-stress', 'owned'))).toEqual([]);+ }, 200_000);++ test('a gated arm that never reaches its database fails the iteration', () => {+ const root = tree({ 'test/silent.test.ts': "import { test } from 'bun:test';\ntest.skipIf(!process.env.DATABASE_URL)('claims a postgres arm', () => {});\n" });+ const r = spawnSync(process.execPath, [RUNNER, 'test/silent.test.ts', '--postgres', '--iterations', '1', '--out', join(root, 'out')], { encoding: 'utf8', env: runnerEnv(root), timeout: 120_000 });+ expect(r.status, `${r.stdout}\n${r.stderr}`).toBe(1);+ expect(r.stdout).toContain('the PostgreSQL arm never connected');+ }, 150_000);++ test('Ctrl-C stops the running file and drops every database the run created', async () => {+ const root = tree({ 'test/slow.test.ts': `${connect}import { test } from 'bun:test';\ntest.skipIf(!process.env.DATABASE_URL)('holds', async () => {\n appendFileSync(process.env.STRESS_FIXTURE_LOG!, 'started\\n');\n await new Promise(r => setTimeout(r, 60_000));\n}, 120_000);\n` });+ const log = join(root, 'started.txt');+ const child = spawn(process.execPath, [RUNNER, 'test/slow.test.ts', '--postgres', '--iterations', '1', '--out', join(root, 'out')], { env: runnerEnv(root, { STRESS_FIXTURE_LOG: log }), stdio: 'ignore' });+ const exited = new Promise<number | null>(res => child.on('exit', code => res(code)));+ const deadline = Date.now() + 60_000;+ while (!existsSync(log) && Date.now() < deadline) await Bun.sleep(100);+ expect(existsSync(log)).toBe(true);+ const owned = join(root, '.context', 'test-stress', 'owned');+ const record = JSON.parse(readFileSync(join(owned, readdirSync(owned)[0]!), 'utf8')) as { databases: string[] };+ expect(record.databases.length).toBe(2);+ child.kill('SIGINT');+ expect(await exited).toBe(130);+ const tag = /^gbrain_stress_(\d+_[0-9a-f]+)_/.exec(record.databases[0]!)![1]!;+ expect(await stressDatabases(tag)).toEqual([]);+ expect(readdirSync(owned)).toEqual([]);+ }, 120_000);+});diff --git a/test/scripts/test-stress.test.ts b/test/scripts/test-stress.test.tsnew file mode 100644index 0000000000..c0c4efd233--- /dev/null+++ b/test/scripts/test-stress.test.ts@@ -0,0 +1,115 @@+/**+ * scripts/stress/run.ts end to end against fixture trees (GBRAIN_STRESS_ROOT):+ * per-iteration receipts, seeded replay, failure detection with the+ * reproduce line, zero-executed and unexpected-skip failures, and the+ * platform-only "not stressed" path. The Postgres paths live in+ * test/scripts/test-stress-postgres.test.ts.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { failureSignature, parseArgs, readReport } from '../../scripts/stress/run.ts';++const RUNNER = join(import.meta.dir, '..', '..', 'scripts', 'stress', 'run.ts');+const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function tree(files: Record<string, string>): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-test-stress-'));+ dirs.push(root);+ for (const [rel, body] of Object.entries(files)) { mkdirSync(join(root, rel, '..'), { recursive: true }); writeFileSync(join(root, rel), body); }+ return root;+}+function stress(root: string, ...args: string[]) {+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_STRESS_ROOT: root };+ delete env.DATABASE_URL;+ delete env.GITHUB_SHA;+ const r = spawnSync(process.execPath, [RUNNER, ...args, '--out', join(root, 'out')], { encoding: 'utf8', env, timeout: 120_000 });+ const manifestPath = join(root, 'out', 'stress-manifest.json');+ return { code: r.status, out: `${r.stdout}\n${r.stderr}`, manifest: existsSync(manifestPath) ? JSON.parse(readFileSync(manifestPath, 'utf8')) : undefined };+}++describe('test:stress runner', () => {+ test('a stable file passes every iteration and leaves one JUnit receipt per iteration', () => {+ const root = tree({ 'test/stable.test.ts': "import { test, expect } from 'bun:test';\ntest('one', () => expect(1).toBe(1));\ntest('two', () => {});\n" });+ const r = stress(root, 'test/stable.test.ts', '--iterations', '3', '--seed', '40');+ expect(r.code, r.out).toBe(0);+ const file = r.manifest.files[0];+ expect(file).toMatchObject({ file: 'test/stable.test.ts', profile: 'unit', env: 'no-database', status: 'pass', seedBase: 40 });+ expect(file.iterations.map((it: { index: number; seed: number; executed: number }) => [it.index, it.seed, it.executed])).toEqual([[1, 40, 2], [2, 41, 2], [3, 42, 2]]);+ for (const it of file.iterations) {+ const dir = join(root, it.receipt);+ expect(readdirSync(dir).filter(f => f.endsWith('.junit.xml') || f.endsWith('.receipt')).sort()).toEqual(['stress--stable.test.ts-i' + it.index + '--primary.receipt', 'stress.junit.xml']);+ }+ expect(r.out).toContain('setup');+ expect(r.out).toMatch(/run \d+\.\d+s/);+ });++ test('a seed-dependent failure fails the run with its iteration, signature and a replayable reproduce line', () => {+ const root = tree({ 'test/flaky.test.ts': "import { test, expect } from 'bun:test';\ntest('odd seeds only', () => { expect(Number(process.env.GBRAIN_TEST_SEED) % 2).toBe(1); });\n" });+ const r = stress(root, 'test/flaky.test.ts', '--iterations', '4', '--seed', '1');+ expect(r.code, r.out).toBe(1);+ expect(r.manifest.failures.map((f: { iteration: number }) => f.iteration)).toEqual([2, 4]);+ expect(r.manifest.failures[0]).toMatchObject({ test: 'odd seeds only', backend: 'pglite', signature: 'expect(received).toBe(expected) Expected: N Received: N' });+ expect(r.out).toContain('FAIL [stress_failure]: test/flaky.test.ts failed in 2 iteration(s) (first: iteration 2');+ expect(r.out).toContain('bun run test:stress test/flaky.test.ts --iterations 4 --first-iteration 2 --seed 1');+ expect(r.out).toContain('iteration 2, seed 2');+ expect(r.out).toContain('Docs: docs/TESTING.md#stress-gate');+ // Replaying the printed command from the failing iteration fails at once.+ const replay = stress(root, 'test/flaky.test.ts', '--iterations', '1', '--first-iteration', '2', '--seed', '1');+ expect(replay.code).toBe(1);+ });++ test('zero executed tests fails unless the file is platform-only', () => {+ const root = tree({+ 'test/empty.test.ts': "import { test } from 'bun:test';\ntest.skip('never', () => {});\n",+ 'test/platform.test.ts': "import { test } from 'bun:test';\ntest.skipIf(process.platform !== 'aix')('aix only', () => {});\n",+ });+ const r = stress(root, 'test/empty.test.ts', 'test/platform.test.ts', '--iterations', '2');+ expect(r.code, r.out).toBe(1);+ const byFile = Object.fromEntries(r.manifest.files.map((f: { file: string }) => [f.file, f]));+ expect(byFile['test/empty.test.ts'].iterations[0].failures[0].message).toBe('zero tests executed');+ expect(byFile['test/platform.test.ts']).toMatchObject({ status: 'not-stressed', reason: expect.stringContaining('platform-only') });+ expect(r.manifest.not_stressed.map((n: { file: string }) => n.file)).toEqual(['test/platform.test.ts']);+ });++ test('a test that ran in the first iteration and skips later is an unexpected skip', () => {+ const root = tree({ 'test/vanish.test.ts': "import { test } from 'bun:test';\nif (Number(process.env.GBRAIN_TEST_SEED) % 2 === 1) test('sometimes', () => {});\ntest('always', () => {});\n" });+ const r = stress(root, 'test/vanish.test.ts', '--iterations', '2', '--seed', '1');+ expect(r.code, r.out).toBe(1);+ expect(r.manifest.failures[0]).toMatchObject({ iteration: 2, signature: 'unexpected skip' });+ expect(r.manifest.files[0].iterations[1].missing).toEqual(['sometimes']);+ });++ test('an E2E file without --postgres is listed as not stressed with the next step', () => {+ const root = tree({ 'test/e2e/x.test.ts': "import { test } from 'bun:test';\ntest('x', () => {});\n" });+ const r = stress(root, 'test/e2e/x.test.ts', '--iterations', '1');+ expect(r.code, r.out).toBe(0);+ expect(r.manifest.not_stressed[0].reason).toContain('re-run with --postgres');+ });+});++describe('arguments, reports and signatures', () => {+ test('flags are validated before anything runs', () => {+ expect(parseArgs(['test/a.test.ts', '--iterations', '0'])).toBe('--iterations must be a positive integer');+ expect(parseArgs(['../etc/passwd'])).toContain('not a repo-relative test file');+ expect(parseArgs(['--base', '$(id)'])).toContain('--base/--head must be');+ expect(parseArgs(['--work', '[{"file":"test/a.test.ts","first":0,"count":1}]'])).toContain('--work must be');+ expect(parseArgs(['--work', '[{"file":"test/../x.test.ts","first":1,"count":1}]'])).toContain('--work must be');+ expect(parseArgs(['--bogus'])).toBe('unknown flag --bogus');+ expect(parseArgs(['test/a.test.ts', '--postgres', '--seed', '9'])).toMatchObject({ files: ['test/a.test.ts'], postgres: true, seed: 9, iterations: 10, base: 'origin/master' });+ });++ test('failure messages come out of the JUnit report in order', () => {+ const xml = '<?xml version="1.0"?><testsuites tests="2"><testsuite name="a.test.ts" file="a.test.ts" tests="2"><testcase name="ok"/><testcase name="bad"><failure type="AssertionError" message="expect(received).toBe(expected) Expected: 7 Received: 6 ">x</failure></testcase></testsuite></testsuites>';+ const r = readReport(xml);+ expect(r.cases.map(c => [c.test, c.status])).toEqual([['ok', 'pass'], ['bad', 'fail']]);+ expect(r.messages).toEqual(['expect(received).toBe(expected)\n\nExpected: 7\nReceived: 6\n']);+ });++ test('signatures mask numbers, temp paths and UUIDs', () => {+ expect(failureSignature('ENOENT: /tmp/gbrain-x123/a.md at line 42 id 0f8fad5b-d9cb-469f-a165-70867728950e')).toBe('ENOENT: <tmp> at line N id <uuid>');+ });+});diff --git a/test/snapshot-inputs-closure.test.ts b/test/snapshot-inputs-closure.test.tsindex 1d68005604..5eb454042d 100644--- a/test/snapshot-inputs-closure.test.ts+++ b/test/snapshot-inputs-closure.test.ts@@ -114,7 +114,7 @@ describe('snapshot schema hash inputs (EO7)', () => {`FAIL: src/core/${f} is in the static import closure of the PGLite schema roots but computeSnapshotSchemaHash does not hash it.`,'Why: a change to it would leave the test-fixture PGLite snapshot stale.','Fix: make src/core/snapshot-schema-inputs.ts reach it (import form it does not follow?), and cover it in every',- ' pglite-snapshot cache key in .github/workflows/e2e.yml and .github/workflows/test.yml.',+ ' pglite-snapshot cache key in .github/workflows/e2e.yml, test.yml and stress.yml.',SEE,].join('\n')).join('\n'));}@@ -142,10 +142,11 @@ describe('snapshot schema hash inputs (EO7)', () => {describe('pglite-snapshot CI cache keys (DX O7)', () => {const keys = discoverCacheKeys();- test('discovers every key: 13 across e2e.yml and test.yml, two profiles', () => {- expect(keys.length).toBe(13);+ test('discovers every key: 14 across e2e.yml, test.yml and stress.yml, two profiles', () => {+ expect(keys.length).toBe(14);expect(keys.filter((k) => k.file.endsWith('e2e.yml')).length).toBe(6);expect(keys.filter((k) => k.file.endsWith('test.yml')).length).toBe(7);+ expect(keys.filter((k) => k.file.endsWith('stress.yml')).length).toBe(1);expect([...new Set(keys.map((k) => k.namespace))].sort()).toEqual(['pglite-snapshot', 'pglite-snapshot-default']);});@@ -176,7 +177,7 @@ describe('pglite-snapshot CI cache keys (DX O7)', () => {`FAIL: ${f} is a computeSnapshotSchemaHash input but no pglite-snapshot cache key covers it.`,'Why: CI would restore a snapshot baked before the file changed, so the suite runs on a stale schema.',`Fix: add '${f}' (or a glob covering it) to the hashFiles(...) list of all ${keys.length} pglite-snapshot keys in`,- ' .github/workflows/e2e.yml and .github/workflows/test.yml (keep the lists identical).',+ ' .github/workflows/e2e.yml, test.yml and stress.yml (keep the lists identical).',SEE,].join('\n')).join('\n'));}