Trunk flaky-test upload runs after Free Tests, off the pull request's checks (GST-3303) (#4579)

Pull requests no longer wait on the upload that sends Free Tests results
to Trunk. It now runs on its own after Free Tests finishes.

The quick test tier's flaky passes now reach Trunk too, so a test that
fails once and passes on its retry shows up there wherever it ran.

Nothing to do: no required check changes, and the upload still never
affects whether a check passes.

Refs: GST-3303
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p1/red-team#2 reader=red-team
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-20 23:33:09 +00:00
1 parent 92c57ca4ce
commit faae7f725a
12 files changed
+214 -119

No files matched your search

+19 -61
View File
@@ -8,9 +8,9 @@ name: Free Tests
# provider keys at all — least privilege, and fork PRs get real test signal
# here (the eval matrix skips fork PRs because repository secrets can't reach
# them). test/free-tests-workflow-wiring.test.ts fails CI if a secret sneaks in.
# The exceptions are TRUNK_API_TOKEN in the trunk-dynamic-ci observer and
# TRUNK_ORG_API_TOKEN in the trunk-flaky-tests uploader. Each runs no
# pull-request code and nothing depends on it (see those jobs).
# The one exception is TRUNK_API_TOKEN in the trunk-dynamic-ci observer, which
# runs no pull-request code and nothing depends on it (see that job). The Trunk
# Flaky Tests uploader runs after this workflow, in trunk-flaky-tests.yml.
#
# This is a REQUIRED check from day one (branch protection lists it). If it's
# red, fix or quarantine-with-issue — don't make it advisory; an advisory lane
@@ -588,7 +588,21 @@ jobs:
env:
GSTACK_FREE_RETRY_FLAKY: "1"
GSTACK_FLAKE_LEDGER: ${{ runner.temp }}/flake-ledger.jsonl
run: xvfb-run -a bun run test:quick
run: xvfb-run -a bun run test:quick --junit-dir "$RUNNER_TEMP/quick-junit"
# Kept for trunk-flaky-tests.yml, which uploads them to Trunk as the
# bun-default variant after the run, so a flaky pass here reaches Trunk
# as well as the flake ledger (GST-3303).
- name: Upload the quick tier's JUnit reports
if: always()
timeout-minutes: 3
continue-on-error: true
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: quick-junit
path: ${{ runner.temp }}/quick-junit/*.xml
if-no-files-found: ignore
retention-days: 7
# The quick tier retries a failing file once too, so its flaky passes go
# in the same flake-ledger-* series the aggregate summarizes and
@@ -846,7 +860,7 @@ jobs:
if-no-files-found: error
# bun's JUnit report from every child of this shard, the flaky retry
# included. Only trunk-flaky-tests reads it; no verdict does.
# included. Only trunk-flaky-tests.yml reads it; no verdict does.
- name: Upload shard JUnit reports
if: always()
timeout-minutes: 3
@@ -888,62 +902,6 @@ jobs:
include-hidden-files: true
if-no-files-found: ignore
# Trunk Flaky Tests, DETECTION ONLY (GST-1859). Uploads every free-suite
# shard's JUnit reports, failures included, to the Trunk test collection
# 7yDVXXE3 so Trunk can flag tests that fail and then pass on the same code.
# Nothing is quarantined or skipped: the uploader runs with quarantine off,
# the collection has quarantining off, and no job needs this one or reads it,
# so it cannot change which tests gate or turn free-tests red. It is the only
# job that sees TRUNK_ORG_API_TOKEN (Trunk's v1 organization token; the v2 API
# key in TRUNK_API_TOKEN does not work with the uploader), so the token never
# shares a job with pull-request code: it checks out nothing, downloads only
# the XML artifacts and runs one pinned action with no GITHUB_TOKEN scopes.
# The CLI version is pinned and use-cache is off, so the binary always comes
# from Trunk's checksummed release, never from an Actions cache entry that a
# pull-request job could have written.
# Same-repository pull requests, main pushes and dispatch runs (the CI runs
# lanes dispatch on their own branches, which only someone with write access
# can start); a missing token skips both steps. Dispatch runs were left out
# until GST-3303 found a retried flake on one that Trunk never saw. Fail-open at step and job level. Review:
# docs/TESTING_INTERNALS.md.
trunk-flaky-tests:
name: Trunk Flaky Tests (detection only)
needs: free-suite
if: always() && needs.free-suite.result != 'skipped' && ((github.event_name == 'push' && github.ref == 'refs/heads/main') || github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository))
runs-on: ubuntu-24.04
timeout-minutes: 10
continue-on-error: true
permissions: {}
env:
TRUNK_ORG_API_TOKEN: ${{ secrets.TRUNK_ORG_API_TOKEN }}
steps:
- name: Download every shard's JUnit reports
if: env.TRUNK_ORG_API_TOKEN != ''
timeout-minutes: 3
continue-on-error: true
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
with:
pattern: free-junit-*
path: ${{ runner.temp }}/free-junit
- name: Upload them to Trunk Flaky Tests (detection only, quarantine off)
if: env.TRUNK_ORG_API_TOKEN != ''
timeout-minutes: 5
continue-on-error: true
uses: trunk-io/analytics-uploader@9886de74a788c450c793109577a4d97bfb3e799f # v2.1.8
with:
junit-paths: ${{ runner.temp }}/free-junit/**/*.xml
org-slug: garry-tan
token: ${{ env.TRUNK_ORG_API_TOKEN }}
test-collection-id: 7yDVXXE3
cli-version: 0.17.0
use-cache: 'false'
quarantine: 'false'
use-uncloned-repo: 'true'
github-token: ''
gh-repo-url: ${{ github.server_url }}/${{ github.repository }}
gh-repo-head-sha: ${{ github.event.pull_request.head.sha || github.sha }}
gh-repo-head-branch: ${{ github.event.pull_request.head.ref || github.ref_name }}
# Branch protection already requires the `free-tests` context. Keep that
# stable name as an always-running aggregate so every platform-specific CSO
# gate is merge-blocking without a separate branch-protection migration.
+106
View File
@@ -0,0 +1,106 @@
# Trunk Flaky Tests, DETECTION ONLY (GST-1859). After every Free Tests run
# completes, this uploads that run's JUnit reports, failures included, to the
# Trunk test collection 7yDVXXE3 so Trunk can flag tests that fail and then
# pass on the same code: every free-suite shard's reports (free-junit-*), and
# the quick tier's on the install-default Bun (quick-junit) as the separate
# bun-default variant, since the same files also run on the pinned Bun.
#
# It runs from workflow_run instead of as a free-tests.yml job (GST-3303), so a
# pull request's checks no longer wait on it; it was the last job to finish in
# about one Free Tests run in four (61 of 223, 11-06 to 11-20). A workflow_run
# workflow runs from the default branch's copy of this file, never from the
# pull request's.
#
# Nothing is quarantined or skipped: the uploader runs with quarantine off, the
# collection has quarantining off, and nothing reads this workflow's result, so
# it cannot change which tests gate or turn a check red. It is the only job that
# sees TRUNK_ORG_API_TOKEN (Trunk's v1 organization token; the v2 API key in
# TRUNK_API_TOKEN does not work with the uploader). It checks out nothing, runs
# no shell, downloads only the XML artifacts of the run that triggered it, and
# its GITHUB_TOKEN can only read Actions artifacts. The CLI version is pinned
# and use-cache is off, so the binary always comes from Trunk's checksummed
# release, never from an Actions cache entry a pull-request job could write.
# Same-repository pull requests, main pushes and dispatch runs (which only
# someone with write access can start), as before; fork pull requests are
# skipped because workflow_run hands this workflow repository secrets, which
# must never meet a fork's artifacts.
# A missing token skips every step. Fail-open at step and job level. Review:
# docs/TESTING_INTERNALS.md.
name: Trunk Flaky Tests
on:
workflow_run:
workflows: [Free Tests]
types: [completed]
permissions: {}
jobs:
trunk-flaky-tests:
name: Trunk Flaky Tests (detection only)
if: github.event.workflow_run.conclusion != 'skipped' && ((github.event.workflow_run.event == 'push' && github.event.workflow_run.head_branch == 'main') || github.event.workflow_run.event == 'workflow_dispatch' || (github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.head_repository.full_name == github.repository))
runs-on: ubuntu-24.04
timeout-minutes: 10
continue-on-error: true
permissions:
actions: read
env:
TRUNK_ORG_API_TOKEN: ${{ secrets.TRUNK_ORG_API_TOKEN }}
steps:
- name: Download every shard's JUnit reports from the Free Tests run
if: env.TRUNK_ORG_API_TOKEN != ''
timeout-minutes: 3
continue-on-error: true
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
with:
pattern: free-junit-*
path: ${{ github.workspace }}/free-junit
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Download the quick tier's JUnit reports from the Free Tests run
if: env.TRUNK_ORG_API_TOKEN != ''
timeout-minutes: 3
continue-on-error: true
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
with:
name: quick-junit
path: ${{ github.workspace }}/quick-junit
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Upload the shard reports to Trunk Flaky Tests (detection only, quarantine off)
if: env.TRUNK_ORG_API_TOKEN != '' && hashFiles('free-junit/**/*.xml') != ''
timeout-minutes: 5
continue-on-error: true
uses: trunk-io/analytics-uploader@9886de74a788c450c793109577a4d97bfb3e799f # v2.1.8
with:
junit-paths: ${{ github.workspace }}/free-junit/**/*.xml
org-slug: garry-tan
token: ${{ env.TRUNK_ORG_API_TOKEN }}
test-collection-id: 7yDVXXE3
cli-version: 0.17.0
use-cache: 'false'
quarantine: 'false'
use-uncloned-repo: 'true'
github-token: ''
gh-repo-url: ${{ github.server_url }}/${{ github.repository }}
gh-repo-head-sha: ${{ github.event.workflow_run.head_sha }}
gh-repo-head-branch: ${{ github.event.workflow_run.head_branch }}
- name: Upload the quick tier's reports as the bun-default variant (detection only, quarantine off)
if: env.TRUNK_ORG_API_TOKEN != '' && hashFiles('quick-junit/**/*.xml') != ''
timeout-minutes: 5
continue-on-error: true
uses: trunk-io/analytics-uploader@9886de74a788c450c793109577a4d97bfb3e799f # v2.1.8
with:
junit-paths: ${{ github.workspace }}/quick-junit/**/*.xml
org-slug: garry-tan
token: ${{ env.TRUNK_ORG_API_TOKEN }}
test-collection-id: 7yDVXXE3
cli-version: 0.17.0
use-cache: 'false'
quarantine: 'false'
use-uncloned-repo: 'true'
variant: bun-default
github-token: ''
gh-repo-url: ${{ github.server_url }}/${{ github.repository }}
gh-repo-head-sha: ${{ github.event.workflow_run.head_sha }}
gh-repo-head-branch: ${{ github.event.workflow_run.head_branch }}
+1
View File
@@ -0,0 +1 @@
**Pull requests no longer wait on the Trunk flaky-test upload, and the quick tier's flaky passes now reach Trunk.** The upload that sends Free Tests results to Trunk was a job inside Free Tests, so in about one pull request run in four it was the last job to finish: usually by a few seconds, but by about three minutes in the slowest twentieth of those runs and once by more than six. It now runs as its own workflow after Free Tests completes, outside the pull request's check list. The quick tier on the install-default Bun now keeps its JUnit reports too (`bun run test:quick --junit-dir <dir>` is new), and they go to Trunk as the `bun-default` variant, so a test that fails and then passes on its one retry there shows up in Trunk, not only in the flake ledger.
+27 -20
View File
@@ -1751,8 +1751,8 @@ or commit disappears), the observer's own check reports failure, and
if it fails again, delete the job. Fork pull requests, pushes and dispatches
skip the job. A missing token skips only its step, so the job still fetches
the action. Its only secret is `TRUNK_API_TOKEN` (in free-tests.yml only it
and the trunk-flaky-tests uploader, with `TRUNK_ORG_API_TOKEN`, see a secret;
evals.yml's other jobs hold their own), so
sees a secret; the Trunk Flaky Tests uploader in trunk-flaky-tests.yml holds
`TRUNK_ORG_API_TOKEN`, and evals.yml's other jobs hold their own), so
it checks out nothing and runs none of the pull request's code. It holds no GITHUB_TOKEN scopes (`permissions: {}`). At the
pinned commit (`src/config.ts`, `src/changed-files.ts`), the action makes one
network call: a request for verdicts to
@@ -1783,26 +1783,33 @@ skipping is a separate decision for Garry, made after that review.
### Trunk Flaky Tests (detection only)
Since GST-1859, every free-suite shard keeps bun's JUnit report from each of
its children, the flaky retry included (`--junit-dir`), and the
`trunk-flaky-tests` job uploads them, failures included, to the Trunk test
collection `7yDVXXE3` ("gstack free suite") on same-repository pull requests,
main pushes and dispatch runs (dispatch runs joined in GST-3303). Trunk flags a test as flaky when it fails and then passes on
the same code, or keeps failing on main, and lists it under Flaky Tests at
app.trunk.io/garry-tan. That job is detection only: quarantine is off in the
uploader and in the collection, nothing skips a test, no job needs or reads it,
and an upload failure can't turn a check red. A child killed at its wall
timeout, or one that crashes, writes no report, so Trunk sees none of that
child's results, its passing files included. Such a child also skips the
flaky retry, so the flake ledger has no entry for it; the red shard result is
the only record. The quick tier on the install-default Bun
(`quick-bun-default`) retries the same way and uploads its ledger as
`flake-ledger-quick`, but keeps no JUnit report, so its flaky passes reach the
ledger and not Trunk. The uploader job is the only one that sees
`TRUNK_ORG_API_TOKEN` (Trunk's v1 organization token, which the uploader
needs), and it checks out and runs nothing of the pull request's. The [flake
its children, the flaky retry included (`--junit-dir`), and so does the quick
tier on the install-default Bun (`quick-bun-default`, artifact `quick-junit`).
After each Free Tests run completes, `trunk-flaky-tests.yml` (a `workflow_run`
workflow) uploads them, failures included, to the Trunk test collection
`7yDVXXE3` ("gstack free suite") for same-repository pull requests, main pushes
and dispatch runs (dispatch runs joined in GST-3303). The quick tier's reports
go up as the `bun-default` variant, because the same files also run on the
pinned Bun. Trunk flags a test as flaky when it fails and then passes on the
same code, or keeps failing on main, and lists it under Flaky Tests at
app.trunk.io/garry-tan.
The uploader is detection only: quarantine is off in the uploader and in the
collection, nothing skips a test, and nothing reads its result, so an upload
failure can't turn a check red. Since GST-3303 it is no longer a free-tests.yml
job, so a pull request's checks don't wait on it; a `workflow_run` workflow runs
from the default branch's copy of its file, so a change to it takes effect only
once it is on main. It is the only job that sees `TRUNK_ORG_API_TOKEN` (Trunk's
v1 organization token, which the uploader needs). It checks out and runs
nothing, downloads only the triggering run's XML artifacts with a GITHUB_TOKEN
limited to `actions: read`, and skips fork pull requests, whose artifacts must
never meet that token. A child killed at its wall timeout, or one that crashes,
writes no report, so Trunk sees none of that child's results, its passing files
included. Such a child also skips the flaky retry, so the flake ledger has no
entry for it; the red shard result is the only record. The [flake
ledger](#flake-ledger), its one-rerun rule and the daily flaky pass are
unchanged and stay the source of record.
`test/free-tests-workflow-wiring.test.ts` locks the job's shape.
`test/free-tests-workflow-wiring.test.ts` locks both workflows' shape.
### Windows free lane
@@ -1 +1 @@
{"blob":"5fa6f0beccfc08d49513c6cca9b1ae29a09265d8","since":6,"nonBehavioral":"Adds the new Codex hooks workflow to FREE_ONLY_PR_FILES; no paid case reads it, so no eval verdict can change"}
{"blob":"c1d0b8ffabc86df40aa8785a7af87b0dae64f3f2","since":6,"nonBehavioral":"adds the new free-lane-only workflow trunk-flaky-tests.yml to FREE_ONLY_PR_FILES; no eval case reads it and no verdict can change"}
+3 -1
View File
@@ -705,7 +705,7 @@ export function parseCliOptions(argv: string[]): CliOptions {
if (ciModes > 1 || (ciModes && (quick || listOnly || dryRun || recordDurations || attributeHome))) throw new Error('CI modes cannot be combined with other selection modes');
if (paths.ciRun && (shardIndex === null || !paths.result)) throw new Error('--ci-run requires --shard and --result');
if (paths.ciVerify && !paths.results) throw new Error('--ci-verify requires --results');
if (junitDir !== undefined && !paths.ciRun) throw new Error('--junit-dir applies only to --ci-run');
if (junitDir !== undefined && !paths.ciRun && !quick) throw new Error('--junit-dir applies only to --ci-run or --quick');
if (jobs !== undefined && !paths.ciRun) rejectJobsWithoutCiRun();
if (shardJobs !== undefined && !paths.ciPlan) rejectShardJobsWithoutCiPlan();
if (jobSetupSeconds !== undefined && !paths.ciPlan) throw new Error('--job-setup-seconds applies only to --ci-plan');
@@ -2206,6 +2206,7 @@ async function main(): Promise<number> {
? wallTimeoutForPackedShard(packed.predictedMs[index], options.wallTimeoutMs, shardFiles.length)
: shardTimeout(shardFiles.length),
verbose: options.verbose,
...(options.junitDir ? { junitDir: options.junitDir } : {}),
})),
);
const homeChange = phaseHome.verify();
@@ -2216,6 +2217,7 @@ async function main(): Promise<number> {
const exclusiveOutcome = await runFreeShard(exclusive, totalShards, totalShards, {
wallTimeoutMs: shardTimeout(exclusive.length),
verbose: options.verbose,
...(options.junitDir ? { junitDir: options.junitDir } : {}),
});
if (exclusiveOutcome.status !== 'passed') {
// Fixture safety rests on each test restoring default state itself; a
+1
View File
@@ -288,6 +288,7 @@ export const FREE_ONLY_PR_FILES = [
'.github/workflows/scorecard.yml',
'.github/workflows/skill-docs.yml',
'.github/workflows/test-health.yml',
'.github/workflows/trunk-flaky-tests.yml',
'.github/workflows/eval-sweep.yml', // The weekly off-ship sweep on main; no PR-gate case reads it, and it never gates a PR.
'.github/workflows/evals-main-backstop.yml', // The merge-train backstop on main: it dispatches evals.yml after a push to main; no PR-gate case reads it, and it never gates a PR.
'.github/workflows/release-gate.yml', // The 8-hour release gate on main: it dispatches evals.yml on main's head; no PR-gate case reads it, and it never gates a PR.
+4 -5
View File
@@ -19,8 +19,8 @@ const ROOT = path.resolve(import.meta.dir, '..');
const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), 'utf8');
const MAIN_PUSH = "github.event_name == 'push' && github.ref == 'refs/heads/main'";
const FILES = {
'free-tests.yml': { aggregate: 'free-tests', profile: 'ci-reuse/free-tests', plan: 'free-plan', exempt: ['trunk-dynamic-ci', 'trunk-flaky-tests', 'docs-scope', 'docs-lane', 'free-plan'], observer: 'trunk-dynamic-ci', uploader: 'trunk-flaky-tests', manual: false, reuseIf: `(${MAIN_PUSH}) || github.event_name == 'pull_request'`, pullRequest: true, docsScope: true, skip: "steps.route.outputs.skip != 'true'" },
'windows-free-tests.yml': { aggregate: 'windows-free-tests', profile: 'ci-reuse/windows-free-tests', plan: 'windows-plan', exempt: ['windows-record-durations'], observer: null, uploader: null, manual: true, reuseIf: MAIN_PUSH, pullRequest: false, docsScope: false, skip: "steps.route.outputs.reused != 'true'" },
'free-tests.yml': { aggregate: 'free-tests', profile: 'ci-reuse/free-tests', plan: 'free-plan', exempt: ['trunk-dynamic-ci', 'docs-scope', 'docs-lane', 'free-plan'], observer: 'trunk-dynamic-ci', manual: false, reuseIf: `(${MAIN_PUSH}) || github.event_name == 'pull_request'`, pullRequest: true, docsScope: true, skip: "steps.route.outputs.skip != 'true'" },
'windows-free-tests.yml': { aggregate: 'windows-free-tests', profile: 'ci-reuse/windows-free-tests', plan: 'windows-plan', exempt: ['windows-record-durations'], observer: null, manual: true, reuseIf: MAIN_PUSH, pullRequest: false, docsScope: false, skip: "steps.route.outputs.reused != 'true'" },
};
const PROFILES = JSON.parse(read('.gstack/pregate.json')).run_profiles as Record<string, { workflow: string; jobs: string[]; artifact: string; events: string[]; os: string }>;
@@ -47,10 +47,9 @@ for (const [file, spec] of Object.entries(FILES)) {
expect(jobs.reuse.if).toBe(spec.reuseIf);
expect(jobs.reuse.permissions).toEqual({ contents: 'read', actions: 'read' });
expect(wf.permissions).toEqual({ contents: 'read' });
for (const name of Object.keys(jobs).filter(n => n !== 'reuse' && n !== spec.observer && n !== spec.uploader)) expect([name, jobs[name].permissions]).toEqual([name, undefined]);
for (const name of Object.keys(jobs).filter(n => n !== 'reuse' && n !== spec.observer)) expect([name, jobs[name].permissions]).toEqual([name, undefined]);
if (spec.observer) expect([jobs[spec.observer].permissions, jobs[spec.observer].needs, jobs[spec.observer].steps.some((s: any) => s.uses?.startsWith('actions/checkout@'))]).toEqual([{}, undefined, false]);
if (spec.uploader) expect([jobs[spec.uploader].permissions, jobs[spec.uploader].needs, jobs[spec.uploader].steps.some((s: any) => s.uses?.startsWith('actions/checkout@'))]).toEqual([{}, 'free-suite', false]);
expect(source.match(/secrets\s*(?:\.|\[)\s*['"]?[A-Za-z0-9_-]*|toJSON\(\s*secrets\b/gi) ?? []).toEqual(spec.observer ? ['secrets.TRUNK_API_TOKEN', 'secrets.TRUNK_ORG_API_TOKEN'] : []);
expect(source.match(/secrets\s*(?:\.|\[)\s*['"]?[A-Za-z0-9_-]*|toJSON\(\s*secrets\b/gi) ?? []).toEqual(spec.observer ? ['secrets.TRUNK_API_TOKEN'] : []);
expect(source).not.toContain('pull_request_target');
const find = jobs.reuse.steps.find((s: any) => s.id === 'find');
expect(find.env).toEqual({ GH_TOKEN: '${{ github.token }}' });
+1 -1
View File
@@ -403,7 +403,7 @@ describe('CSO runtime staging gates', () => {
const gate = job.steps.find((step: any) => step.run?.trim() === 'bun test --max-concurrency 1 test/cso-docker-integration.test.ts');
expect(gate.env.GSTACK_CSO_DOCKER_TESTS).toBe('1');
expect(JSON.stringify(job)).not.toContain('secrets.');
expect(raw.match(/secrets\s*(?:\.|\[)\s*['"]?[A-Za-z0-9_-]*|toJSON\(\s*secrets\b/gi)).toEqual(['secrets.TRUNK_API_TOKEN', 'secrets.TRUNK_ORG_API_TOKEN']);
expect(raw.match(/secrets\s*(?:\.|\[)\s*['"]?[A-Za-z0-9_-]*|toJSON\(\s*secrets\b/gi)).toEqual(['secrets.TRUNK_API_TOKEN']);
expect(job.steps.map((s: any) => s.run ?? '').join('\n')).toContain('docker --host unix:///var/run/docker.sock info');
expect(job['continue-on-error']).not.toBe(true);
expect(gate['continue-on-error']).not.toBe(true);
+48 -28
View File
@@ -6,11 +6,11 @@
* `bun test <dirs>` glob — the runner owns TEST_ROOTS and strict-output
* classification, so a truncated run can't report green.
* 2. It is SECRETLESS where code runs: free tests make no API calls, and
* keeping keys out means fork PRs get real signal here. The two allowed
* `secrets.` references are TRUNK_API_TOKEN in the learning-only
* trunk-dynamic-ci observer and TRUNK_ORG_API_TOKEN in the detection-only
* trunk-flaky-tests uploader. Neither checks out or runs anything of the
* PR's and no job depends on either; any other reference is a regression.
* keeping keys out means fork PRs get real signal here. The one allowed
* `secrets.` reference is TRUNK_API_TOKEN in the learning-only
* trunk-dynamic-ci observer, which checks out and runs nothing of the
* PR's and no job depends on; any other reference is a regression. The
* detection-only Trunk uploader runs after the run, in trunk-flaky-tests.yml.
* 3. It triggers on `pull_request` (never `pull_request_target`, which
* would hand a fork PR the base repo's context).
*
@@ -39,9 +39,8 @@ describe('free-tests workflow wiring', () => {
test('secretless: no secrets reach the free lane', () => {
const jobs = (Bun.YAML.parse(source) as any).jobs;
expect(source.match(/secrets\s*(?:\.|\[)\s*['"]?[A-Za-z0-9_-]*|toJSON\(\s*secrets\b/gi)).toEqual(['secrets.TRUNK_API_TOKEN', 'secrets.TRUNK_ORG_API_TOKEN']);
expect(source.match(/secrets\s*(?:\.|\[)\s*['"]?[A-Za-z0-9_-]*|toJSON\(\s*secrets\b/gi)).toEqual(['secrets.TRUNK_API_TOKEN']);
expect(jobs['trunk-dynamic-ci'].env).toEqual({ TRUNK_API_TOKEN: '${{ secrets.TRUNK_API_TOKEN }}' });
expect(jobs['trunk-flaky-tests'].env).toEqual({ TRUNK_ORG_API_TOKEN: '${{ secrets.TRUNK_ORG_API_TOKEN }}' });
expect(source).not.toContain('ANTHROPIC_API_KEY');
expect(source).not.toContain('OPENAI_API_KEY');
});
@@ -68,13 +67,12 @@ describe('free-tests workflow wiring', () => {
for (const key of step.with['job-keys'].split(',')) expect(jobs[key], key).toBeDefined();
for (const name of Object.keys(jobs).filter(n => n !== 'trunk-dynamic-ci')) {
expect([name, [jobs[name].needs ?? []].flat()]).not.toEqual([name, expect.arrayContaining(['trunk-dynamic-ci'])]);
if (name === 'trunk-flaky-tests') continue;
expect([name, JSON.stringify(jobs[name])]).not.toEqual([name, expect.stringMatching(/trunk|dynamic-ci/i)]);
}
});
// Value: protects=GST-1859's detection-only contract: Trunk Flaky Tests receives every free-suite shard's JUnit, failures included, and can never quarantine, skip, gate or fail anything, while the token never shares a job with pull-request code; fails_when=the suite stops writing or uploading JUnit, the uploader job checks out or runs code, gains token scopes, is needed or read by any job, loses fail-open or its token skip, turns quarantine on, runs on forks, or either action is unpinned; seam=.github/workflows/free-tests.yml; no_claim=what Trunk flags
test('trunk-flaky-tests is a detection-only uploader: pinned, scope-less, fail-open, quarantine off, read by no job', () => {
test('trunk-flaky-tests.yml is a detection-only uploader after the run: pinned, read-only token, fail-open, quarantine off, never on forks', () => {
const jobs = (Bun.YAML.parse(source) as any).jobs;
const suite = jobs['free-suite'];
expect(suite.steps.find((step: any) => step.name === 'Run free suite').run).toContain('--junit-dir "$RUNNER_TEMP/free-junit"');
@@ -85,32 +83,51 @@ describe('free-tests workflow wiring', () => {
const quick = jobs['quick-bun-default'].steps as any[];
const quickRun = quick.findIndex(step => step.name === 'Run the quick free tier on the install-default Bun');
expect(quick[quickRun].env).toEqual({ GSTACK_FREE_RETRY_FLAKY: '1', GSTACK_FLAKE_LEDGER: '${{ runner.temp }}/flake-ledger.jsonl' });
expect(quick[quickRun].run).toBe('xvfb-run -a bun run test:quick --junit-dir "$RUNNER_TEMP/quick-junit"');
const quickLedger = quick.find(step => step.with?.name === 'flake-ledger-quick');
expect(quick.indexOf(quickLedger)).toBeGreaterThan(quickRun);
expect(quickLedger.if).toBe('always()');
expect(quickLedger.uses).toMatch(/^actions\/upload-artifact@[0-9a-f]{40}$/);
expect(quickLedger.with).toEqual({ name: 'flake-ledger-quick', path: '${{ runner.temp }}/flake-ledger.jsonl', 'if-no-files-found': 'ignore', 'retention-days': 90 });
const flaky = jobs['trunk-flaky-tests'];
expect(flaky.needs).toBe('free-suite');
expect(flaky.if).toBe("always() && needs.free-suite.result != 'skipped' && ((github.event_name == 'push' && github.ref == 'refs/heads/main') || github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository))");
const quickJunit = quick.find(step => step.with?.name === 'quick-junit');
expect(quick.indexOf(quickJunit)).toBeGreaterThan(quickRun);
expect(quickJunit.if).toBe('always()');
expect(quickJunit.uses).toMatch(/^actions\/upload-artifact@[0-9a-f]{40}$/);
expect(quickJunit.with).toEqual({ name: 'quick-junit', path: '${{ runner.temp }}/quick-junit/*.xml', 'if-no-files-found': 'ignore', 'retention-days': 7 });
for (const name of Object.keys(jobs)) expect([name, /TRUNK_ORG_API_TOKEN|analytics-uploader|download-artifact[^"]*"[^}]*free-junit-\*/.test(JSON.stringify(jobs[name]))]).toEqual([name, false]);
const upSource = fs.readFileSync(path.resolve(import.meta.dir, '..', '.github', 'workflows', 'trunk-flaky-tests.yml'), 'utf-8');
const up = Bun.YAML.parse(upSource) as any;
expect(up.on).toEqual({ workflow_run: { workflows: ['Free Tests'], types: ['completed'] } });
expect(up.permissions).toEqual({});
expect(Object.keys(up.jobs)).toEqual(['trunk-flaky-tests']);
expect(upSource.match(/secrets\s*(?:\.|\[)\s*['"]?[A-Za-z0-9_-]*|toJSON\(\s*secrets\b/gi)).toEqual(['secrets.TRUNK_ORG_API_TOKEN']);
expect(upSource).not.toContain('pull_request_target');
const flaky = up.jobs['trunk-flaky-tests'];
expect(flaky.if).toBe("github.event.workflow_run.conclusion != 'skipped' && ((github.event.workflow_run.event == 'push' && github.event.workflow_run.head_branch == 'main') || github.event.workflow_run.event == 'workflow_dispatch' || (github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.head_repository.full_name == github.repository))");
expect(flaky['runs-on']).toBe('ubuntu-24.04');
expect(flaky.permissions).toEqual({});
expect(flaky.permissions).toEqual({ actions: 'read' });
expect(flaky.env).toEqual({ TRUNK_ORG_API_TOKEN: '${{ secrets.TRUNK_ORG_API_TOKEN }}' });
expect(flaky['continue-on-error']).toBe(true);
expect(flaky['timeout-minutes']).toBe(10);
expect(flaky.outputs).toBeUndefined();
expect(flaky.steps).toHaveLength(2);
const [download, upload] = flaky.steps;
expect(flaky.needs).toBeUndefined();
expect(flaky.steps).toHaveLength(4);
const [downloadShards, downloadQuick, uploadShards, uploadQuick] = flaky.steps;
for (const step of flaky.steps) {
expect(step.run).toBeUndefined();
expect(step.if).toBe("env.TRUNK_ORG_API_TOKEN != ''");
expect(step.uses.startsWith('actions/checkout@')).toBe(false);
expect(step['continue-on-error']).toBe(true);
}
expect(download.uses).toMatch(/^actions\/download-artifact@[0-9a-f]{40}$/);
expect(download.with).toEqual({ pattern: 'free-junit-*', path: '${{ runner.temp }}/free-junit' });
expect(upload.uses).toBe('trunk-io/analytics-uploader@9886de74a788c450c793109577a4d97bfb3e799f');
expect(upload['timeout-minutes']).toBe(5);
expect(upload.with).toEqual({
'junit-paths': '${{ runner.temp }}/free-junit/**/*.xml',
const fromRun = { 'run-id': '${{ github.event.workflow_run.id }}', 'github-token': '${{ github.token }}' };
for (const download of [downloadShards, downloadQuick]) {
expect(download.if).toBe("env.TRUNK_ORG_API_TOKEN != ''");
expect(download.uses).toMatch(/^actions\/download-artifact@[0-9a-f]{40}$/);
}
expect(downloadShards.with).toEqual({ pattern: 'free-junit-*', path: '${{ github.workspace }}/free-junit', ...fromRun });
expect(downloadQuick.with).toEqual({ name: 'quick-junit', path: '${{ github.workspace }}/quick-junit', ...fromRun });
const uploaded = (dir: string) => ({
'junit-paths': `\${{ github.workspace }}/${dir}/**/*.xml`,
'org-slug': 'garry-tan',
token: '${{ env.TRUNK_ORG_API_TOKEN }}',
'test-collection-id': '7yDVXXE3',
@@ -120,13 +137,16 @@ describe('free-tests workflow wiring', () => {
'use-uncloned-repo': 'true',
'github-token': '',
'gh-repo-url': '${{ github.server_url }}/${{ github.repository }}',
'gh-repo-head-sha': '${{ github.event.pull_request.head.sha || github.sha }}',
'gh-repo-head-branch': '${{ github.event.pull_request.head.ref || github.ref_name }}',
'gh-repo-head-sha': '${{ github.event.workflow_run.head_sha }}',
'gh-repo-head-branch': '${{ github.event.workflow_run.head_branch }}',
});
for (const name of Object.keys(jobs).filter(n => n !== 'trunk-flaky-tests')) {
expect([name, [jobs[name].needs ?? []].flat().includes('trunk-flaky-tests')]).toEqual([name, false]);
expect([name, /TRUNK_ORG_API_TOKEN|analytics-uploader|free-junit-\*/.test(JSON.stringify(jobs[name]))]).toEqual([name, false]);
for (const [upload, dir] of [[uploadShards, 'free-junit'], [uploadQuick, 'quick-junit']] as const) {
expect(upload.if).toBe(`env.TRUNK_ORG_API_TOKEN != '' && hashFiles('${dir}/**/*.xml') != ''`);
expect(upload.uses).toBe('trunk-io/analytics-uploader@9886de74a788c450c793109577a4d97bfb3e799f');
expect(upload['timeout-minutes']).toBe(5);
}
expect(uploadShards.with).toEqual(uploaded('free-junit'));
expect(uploadQuick.with).toEqual({ ...uploaded('quick-junit'), variant: 'bun-default' });
});
test('pull_request trigger, never pull_request_target', () => {
@@ -247,7 +267,7 @@ describe('free-tests workflow wiring', () => {
}
expect(steps[install]['continue-on-error'], name).toBe(true);
const offline = steps.find((step: any) => step.id === 'apt_offline');
const failOpen = name === 'free-suite' ? [offline, steps[install], steps.find((step: any) => step.name === 'Upload shard JUnit reports')] : [offline, steps[install]];
const failOpen = [offline, steps[install], steps.find((step: any) => step.name === (name === 'free-suite' ? 'Upload shard JUnit reports' : "Upload the quick tier's JUnit reports"))];
expect(steps.filter((step: any) => step['continue-on-error']), name).toEqual(failOpen);
}
});
+2 -1
View File
@@ -480,7 +480,8 @@ describe('per-file test and expect() counts from bun JUnit', () => {
const base = ['--ci-run', 'plan.json', '--shard', '1', '--result', 'r.json'];
expect(parseCliOptions([...base, '--junit-dir', 'junit']).junitDir).toBe('junit');
expect('junitDir' in parseCliOptions(base)).toBe(false);
expect(() => parseCliOptions(['--junit-dir', 'junit'])).toThrow('--junit-dir applies only to --ci-run');
expect(() => parseCliOptions(['--junit-dir', 'junit'])).toThrow('--junit-dir applies only to --ci-run or --quick');
expect(parseCliOptions(['--quick', '--junit-dir', 'junit']).junitDir).toBe('junit');
expect(() => parseCliOptions([...base, '--junit-dir'])).toThrow('Missing path for --junit-dir');
} finally { errors.mockRestore(); fs.rmSync(root, { recursive: true, force: true }); }
}, 60_000);
+1 -1
View File
@@ -52,7 +52,7 @@ describe('Trunk Dynamic CI observers', () => {
for (const [name, job] of Object.entries(wf.jobs as Record<string, any>).filter(([n]) => n !== 'trunk-dynamic-ci')) {
expect([name, [job.needs ?? []].flat().includes('trunk-dynamic-ci')]).toEqual([name, false]);
const text = JSON.stringify(job);
const mentions = name === 'trunk-flaky-tests' && file === 'free-tests.yml' ? /dynamic-ci|TRUNK_API_TOKEN/i.test(text) : /trunk|dynamic-ci|TRUNK_API_TOKEN/i.test(text);
const mentions = /trunk|dynamic-ci|TRUNK_API_TOKEN/i.test(text);
expect([name, mentions]).toEqual([name, false]);
}
const trunkRefs = (JSON.stringify(wf.jobs).match(SECRET_REF) ?? []).filter(ref => ref === 'secrets.TRUNK_API_TOKEN');